@owlmeans/server-payment 0.1.20-rc.1 → 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
@@ -1,10 +1,9 @@
1
- import type Stripe from 'stripe'
2
1
  import { MAILER_SERVICE } from '@owlmeans/mailer'
3
2
  import {
4
- CancellationStatus, DeclarationKind, ENTITLING_STATUSES, PurchaseKind, WithdrawalStatus,
3
+ CancellationStatus, DeclarationKind, ENTITLING_STATUSES, INTERNAL_PAYGATE, PaygateError, PurchaseKind, WithdrawalStatus,
5
4
  } from '@owlmeans/payment'
6
5
  import type { Context as ApiContext } from '@owlmeans/server-api'
7
- import { PURCHASE_BACKFILL_DAYS, STRIPE_PAYGATE_ALIAS } from '../consts.js'
6
+ import { PURCHASE_BACKFILL_DAYS } from '../consts.js'
8
7
  import type { ConsumerRightsInternals, WithdrawalComputation } from './types.js'
9
8
  import type {
10
9
  ConsumerEventRecord, ConsumerMailKind, ConsumerReconcileOptions, ConsumerReconcileResult, UsageReading,
@@ -12,10 +11,10 @@ import type {
12
11
  import { log } from '../log.js'
13
12
  import { DAY_MS, MAX_ATTEMPTS } from './consts.local.js'
14
13
  import { paymentAccessOf } from '../access.js'
15
- import { paymentUtils } from '../utils.js'
16
14
  import { consumerRecordsOf } from './records.js'
17
15
  import { captureOf } from './capture.js'
18
- import { stripeSessionHelper } from '../plugins/session.js'
16
+ import { checkoutSnapshotHelper } from '../plugins/snapshot.js'
17
+ import { paygatesOf } from '../paygate/registry.js'
19
18
  import { consumerMailOf } from './mail.js'
20
19
  import { consumerObserversOf } from './observers.js'
21
20
  import { cancellationOf } from './cancellation.js'
@@ -74,9 +73,7 @@ export const makeConsumerReconcileHelper = (
74
73
  return pending
75
74
  }
76
75
 
77
- const retryWithdrawals = async (
78
- stripe: Stripe, since: Date, limit: number, result: ConsumerReconcileResult,
79
- ): Promise<void> => {
76
+ const retryWithdrawals = async (since: Date, limit: number, result: ConsumerReconcileResult): Promise<void> => {
80
77
  const { items } = await access.consumerDeclarations().list({
81
78
  kind: DeclarationKind.Withdrawal, status: WithdrawalStatus.Processing, matched: true, receivedAt: { $gte: since },
82
79
  }, { size: limit * 2, sort: [{ field: 'receivedAt', order: 'asc' }] })
@@ -87,6 +84,8 @@ export const makeConsumerReconcileHelper = (
87
84
  const purchase = declaration.purchaseId != null ? await access.purchases().byPurchaseId(declaration.purchaseId) : null
88
85
  // A declaration that lost the race for its purchase is a duplicate — never executed.
89
86
  if (purchase == null || purchase.withdrawalId !== id) continue
87
+ const paygate = paygatesOf(ctx).find(purchase.paygate)
88
+ if (paygate == null) continue
90
89
  const computed = await computedOf(id)
91
90
  const refundDone = (declaration.refundMinor ?? 0) <= 0 || await records.hasEvent(id, 'refund', undefined, true)
92
91
  const cancelDone = purchase.kind !== PurchaseKind.Subscription
@@ -100,7 +99,7 @@ export const makeConsumerReconcileHelper = (
100
99
  if (attempt < MAX_ATTEMPTS) {
101
100
  handled++
102
101
  result.retried++
103
- if (!await withdrawalOf(ctx).retryCreditNote(stripe, declaration, purchase, computed.netMinor, refundEvent.externalId, attempt)) {
102
+ if (!await withdrawalOf(ctx).retryCreditNote(paygate, declaration, purchase, computed.netMinor, refundEvent.externalId, attempt)) {
104
103
  result.failed++
105
104
  }
106
105
  }
@@ -112,7 +111,7 @@ export const makeConsumerReconcileHelper = (
112
111
  handled++
113
112
  result.retried++
114
113
  try {
115
- const execution = await withdrawalOf(ctx).executeWithdrawal(stripe, declaration, purchase, {
114
+ const execution = await withdrawalOf(ctx).executeWithdrawal(paygate, declaration, purchase, {
116
115
  refundMinor: declaration.refundMinor ?? computed?.refundMinor ?? 0, netMinor: computed?.netMinor ?? 0,
117
116
  }, { attempt })
118
117
  if (!execution.ok) {
@@ -129,9 +128,7 @@ export const makeConsumerReconcileHelper = (
129
128
  }
130
129
  }
131
130
 
132
- const retryCancellations = async (
133
- stripe: Stripe, since: Date, limit: number, result: ConsumerReconcileResult,
134
- ): Promise<void> => {
131
+ const retryCancellations = async (since: Date, limit: number, result: ConsumerReconcileResult): Promise<void> => {
135
132
  const { items } = await access.consumerDeclarations().list({
136
133
  kind: DeclarationKind.Cancellation, status: CancellationStatus.Scheduled, matched: true, receivedAt: { $gte: since },
137
134
  }, { size: limit * 2, sort: [{ field: 'receivedAt', order: 'asc' }] })
@@ -142,11 +139,12 @@ export const makeConsumerReconcileHelper = (
142
139
  if (declaration.subscriptionId == null
143
140
  || await records.hasEvent(id, 'cancel-scheduled', undefined, true)) continue
144
141
  const attempt = await failures(id, 'cancel-scheduled')
145
- const row = await access.subscriptions().byExternalId(declaration.subscriptionId, STRIPE_PAYGATE_ALIAS)
146
- if (row == null || attempt >= MAX_ATTEMPTS) continue
142
+ const row = await access.subscriptions().load({ externalId: declaration.subscriptionId, paygate: { $ne: INTERNAL_PAYGATE } })
143
+ const paygate = row != null ? paygatesOf(ctx).find(row.paygate) : null
144
+ if (row == null || paygate == null || attempt >= MAX_ATTEMPTS) continue
147
145
  handled++
148
146
  result.retried++
149
- if (!await cancellationOf(ctx).scheduleCancellation(stripe, declaration, row, attempt)) {
147
+ if (!await cancellationOf(ctx).scheduleCancellation(paygate, declaration, row, attempt)) {
150
148
  result.failed++
151
149
  }
152
150
  }
@@ -215,50 +213,52 @@ export const makeConsumerReconcileHelper = (
215
213
  }
216
214
 
217
215
  /** Completed checkouts of the last days that have no purchase row (records only — no mail). */
218
- const backfillPurchases = async (stripe: Stripe, limit: number, result: ConsumerReconcileResult): Promise<void> => {
219
- const from = Math.floor((Date.now() - PURCHASE_BACKFILL_DAYS * DAY_MS) / 1000)
220
- let startingAfter: string | undefined
221
- let scanned = 0
222
- for (;;) {
223
- const page = await stripe.checkout.sessions.list({
224
- created: { gte: from }, status: 'complete', limit: 100,
225
- ...(startingAfter != null ? { starting_after: startingAfter } : {}),
226
- })
227
- for (const session of page.data) {
228
- scanned++
229
- if (result.backfilled >= limit) return
230
- const metadata = session.metadata ?? {}
231
- if (metadata.entityId == null || metadata.productSku == null) continue
232
- try {
233
- if (stripeSessionHelper.canFulfillPayment(session)) {
234
- if (await access.purchases().load({ sessionId: session.id }) != null) continue
235
- const amount = Number(metadata.amountMinor)
236
- const captured = await captureOf(ctx).capturePaymentPurchase(stripe, session, {
237
- ...(Number.isSafeInteger(amount) && amount > 0 ? { netAmountMinor: amount } : {}),
238
- ...(metadata.amountCurrency != null ? { amountCurrency: metadata.amountCurrency } : {}),
239
- at: new Date(session.created * 1000),
240
- }, { mail: false })
241
- if (captured?.created === true) result.backfilled++
242
- } else if (session.mode === 'subscription') {
243
- const subscriptionId = paymentUtils.idOf(session.subscription)
244
- if (subscriptionId == null
245
- || await access.purchases().byPurchaseId(records.purchaseIdOf(subscriptionId)) != null) continue
246
- const row = await access.subscriptions().byExternalId(subscriptionId, STRIPE_PAYGATE_ALIAS)
247
- if (row == null || !ENTITLING_STATUSES.includes(row.status)) continue
248
- const subscription = await stripe.subscriptions.retrieve(subscriptionId)
249
- const captured = await captureOf(ctx).captureSubscriptionPurchase(stripe, subscription, row)
250
- if (captured != null) {
251
- await captureOf(ctx).completeSubscriptionPurchase(stripe, session, captured.purchase, { mail: false })
252
- if (captured.created) result.backfilled++
216
+ const backfillPurchases = async (limit: number, result: ConsumerReconcileResult): Promise<void> => {
217
+ const from = new Date(Math.floor((Date.now() - PURCHASE_BACKFILL_DAYS * DAY_MS) / 1000) * 1000)
218
+ for (const paygate of paygatesOf(ctx).all()) {
219
+ const listCompleted = paygate.checkout.listCompleted
220
+ if (listCompleted == null) continue
221
+ let cursor: string | undefined
222
+ let scanned = 0
223
+ for (;;) {
224
+ const page = await listCompleted(from, cursor)
225
+ for (const session of page.items) {
226
+ scanned++
227
+ if (result.backfilled >= limit) return
228
+ const metadata = session.metadata ?? {}
229
+ if (metadata.entityId == null || metadata.productSku == null) continue
230
+ try {
231
+ if (checkoutSnapshotHelper.canFulfill(session)) {
232
+ if (await access.purchases().load({ sessionId: session.id }) != null) continue
233
+ const amount = Number(metadata.amountMinor)
234
+ const captured = await captureOf(ctx).capturePaymentPurchase(paygate, session, {
235
+ ...(Number.isSafeInteger(amount) && amount > 0 ? { netAmountMinor: amount } : {}),
236
+ ...(metadata.amountCurrency != null ? { amountCurrency: metadata.amountCurrency } : {}),
237
+ ...(session.createdAt != null ? { at: session.createdAt } : {}),
238
+ }, { mail: false })
239
+ if (captured?.created === true) result.backfilled++
240
+ } else if (session.mode === 'subscription') {
241
+ const subscriptionId = session.subscriptionId
242
+ if (subscriptionId == null
243
+ || await access.purchases().byPurchaseId(records.purchaseIdOf(paygate.id, subscriptionId)) != null) continue
244
+ const row = await access.subscriptions().byExternalId(subscriptionId, paygate.id)
245
+ if (row == null || !ENTITLING_STATUSES.includes(row.status)) continue
246
+ const subscription = paygate.subscriptions != null ? await paygate.subscriptions.retrieve(subscriptionId) : null
247
+ if (subscription == null) throw new PaygateError(`subscription:${subscriptionId}`)
248
+ const captured = await captureOf(ctx).captureSubscriptionPurchase(paygate, subscription, row)
249
+ if (captured != null) {
250
+ await captureOf(ctx).completeSubscriptionPurchase(paygate, session, captured.purchase, { mail: false })
251
+ if (captured.created) result.backfilled++
252
+ }
253
253
  }
254
+ } catch (error) {
255
+ result.failed++
256
+ log.error('Reconcile: purchase backfill failed', { sessionId: session.id, paygate: paygate.id, error })
254
257
  }
255
- } catch (error) {
256
- result.failed++
257
- log.error('Reconcile: purchase backfill failed', { sessionId: session.id, error })
258
258
  }
259
+ if (page.cursor == null || page.items.length === 0 || scanned >= limit * 20) break
260
+ cursor = page.cursor
259
261
  }
260
- if (!page.has_more || page.data.length === 0 || scanned >= limit * 20) return
261
- startingAfter = page.data[page.data.length - 1].id
262
262
  }
263
263
  }
264
264
 
@@ -266,25 +266,26 @@ export const makeConsumerReconcileHelper = (
266
266
  * Organizations that paid before countries were locked: locked from their paygate customer's
267
267
  * address — never one an operator unlocked (its next completed purchase locks it).
268
268
  */
269
- const lockLegacy = async (stripe: Stripe, limit: number, result: ConsumerReconcileResult): Promise<void> => {
269
+ const lockLegacy = async (limit: number, result: ConsumerReconcileResult): Promise<void> => {
270
270
  const policy = await access.payment().consumerRightsPolicy()
271
271
  if (policy?.mechanisms.countryLock !== true) {
272
272
  return
273
273
  }
274
- const { items } = await access.paygateCustomers().list({ paygate: STRIPE_PAYGATE_ALIAS, deletedAt: null }, { size: limit * 4 })
274
+ const { items } = await access.paygateCustomers().list({ paygate: { $ne: INTERNAL_PAYGATE }, deletedAt: null }, { size: limit * 4 })
275
275
  for (const customer of items) {
276
276
  if (result.locked >= limit) return
277
277
  if (customer.entityId == null || await access.billingProfiles().byEntity(customer.entityId) != null) continue
278
278
  if (!await records.hasPaid(customer.entityId) || await records.wasUnlocked(customer.entityId)) continue
279
+ const paygate = paygatesOf(ctx).find(customer.paygate)
280
+ if (paygate == null) continue
279
281
  try {
280
282
  let country = customer.country
281
283
  if (country == null) {
282
- const retrieved = await stripe.customers.retrieve(customer.externalId)
283
- country = (retrieved as Stripe.DeletedCustomer).deleted ? undefined : (retrieved as Stripe.Customer).address?.country ?? undefined
284
+ country = (await paygate.customers.retrieve(customer.externalId))?.country ?? undefined
284
285
  }
285
286
  if (country == null) continue
286
287
  const { created } = await records.lockProfile(policy, {
287
- entityId: customer.entityId, country, source: 'customer', customerId: customer.externalId,
288
+ entityId: customer.entityId, country, source: 'customer', paygate: paygate.id, customerId: customer.externalId,
288
289
  email: customer.email ?? undefined,
289
290
  })
290
291
  if (created) result.locked++
@@ -302,17 +303,17 @@ export const makeConsumerReconcileHelper = (
302
303
  }
303
304
  const limit = Math.max(1, opts.limit ?? 50)
304
305
  const since = opts.since ?? new Date(Date.now() - 30 * DAY_MS)
305
- const stripe = internals.managed ? await internals.stripe(ctx) : null
306
+ const managed = internals.managed
306
307
  const steps: Array<[string, () => Promise<void>]> = [
307
- ...(stripe != null ? [
308
- ['withdrawals', async () => { await retryWithdrawals(stripe, since, limit, result) }],
309
- ['cancellations', async () => { await retryCancellations(stripe, since, limit, result) }],
308
+ ...(managed ? [
309
+ ['withdrawals', async () => { await retryWithdrawals(since, limit, result) }],
310
+ ['cancellations', async () => { await retryCancellations(since, limit, result) }],
310
311
  ] as Array<[string, () => Promise<void>]> : []),
311
312
  ['mails', async () => { await retryMails(since, limit, result) }],
312
313
  ['observers', async () => { await retryObservers(since, limit, result) }],
313
- ...(stripe != null ? [
314
- ['backfill', async () => { await backfillPurchases(stripe, limit, result) }],
315
- ['legacy locks', async () => { await lockLegacy(stripe, limit, result) }],
314
+ ...(managed ? [
315
+ ['backfill', async () => { await backfillPurchases(limit, result) }],
316
+ ['legacy locks', async () => { await lockLegacy(limit, result) }],
316
317
  ] as Array<[string, () => Promise<void>]> : []),
317
318
  ]
318
319
  for (const [name, step] of steps) {
@@ -9,8 +9,8 @@ export interface ConsumerEventDraft extends Omit<ConsumerEventRecord, 'at' | 'id
9
9
 
10
10
  /** The consumer-rights records of a context: purchases, billing profiles and the audit trail. */
11
11
  export interface ConsumerRecords {
12
- /** The purchase id of a paygate checkout session or subscription: `stripe:<id>`. */
13
- purchaseIdOf: (externalId: string) => string
12
+ /** The purchase id of a paygate checkout session or subscription: `<paygate>:<id>`. */
13
+ purchaseIdOf: (paygate: string, externalId: string) => string
14
14
  /** A locked profile as the wire sees it. */
15
15
  profileViewOf: (record: BillingProfileRecord, policy: ConsumerRightsPolicy | null) => BillingProfileView
16
16
  /** No profile yet: nothing locked, the default legal language, an unknown buyer (protected by default). */
@@ -22,8 +22,8 @@ export interface ConsumerRecords {
22
22
  recordEvent: (event: ConsumerEventDraft) => Promise<void>
23
23
  /** Whether a step already succeeded (or a mail was deliberately skipped) for a record. */
24
24
  hasEvent: (recordId: string, action: ConsumerEventRecord['action'], step?: string, ok?: boolean) => Promise<boolean>
25
- /** The entity's highest-ranked entitling Stripe subscription, or `null`. */
26
- entitlingStripeSubscription: (entityId: string) => Promise<PaymentSubscriptionRecord | null>
25
+ /** The entity's highest-ranked entitling paygate subscription (any paygate but the internal one), or `null`. */
26
+ entitlingPaygateSubscription: (entityId: string) => Promise<PaymentSubscriptionRecord | null>
27
27
  /** Whether the entity ever paid through the paygate (a fulfilled checkout or a propagated subscription). */
28
28
  hasPaid: (entityId: string) => Promise<boolean>
29
29
  /**
@@ -1,7 +1,6 @@
1
- import { ConsumerRegion, ConsumerRightsError, ENTITLING_STATUSES, PurchaseKind, type BillingProfileView, type ConsumerRightsPolicy, consumerRegionHelper } from '@owlmeans/payment'
1
+ import { ConsumerRegion, ConsumerRightsError, ENTITLING_STATUSES, INTERNAL_PAYGATE, PurchaseKind, type BillingProfileView, type ConsumerRightsPolicy, consumerRegionHelper } from '@owlmeans/payment'
2
2
  import type { Context as ApiContext } from '@owlmeans/server-api'
3
3
  import { memoHelper } from '@owlmeans/context'
4
- import { PURCHASE_ID_PREFIX, STRIPE_PAYGATE_ALIAS } from '../consts.js'
5
4
  import type {
6
5
  BillingProfileRecord, ConsumerEventRecord, PaymentSubscriptionRecord, PurchaseRecord, UnlockOptions,
7
6
  } from '../types.js'
@@ -11,12 +10,13 @@ import type { LockInput, LockResult, PurchaseDraft } from './types.js'
11
10
  import { paymentAccessOf } from '../access.js'
12
11
  import { paymentUtils } from '../utils.js'
13
12
  import { consumerFormatHelper } from './format.js'
13
+ import { paygatesOf } from '../paygate/registry.js'
14
14
  import type { ConsumerEventDraft, ConsumerRecords } from './records/types.js'
15
15
 
16
16
  export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
17
17
  const access = paymentAccessOf(ctx)
18
18
 
19
- const purchaseIdOf = (externalId: string): string => `${PURCHASE_ID_PREFIX}:${externalId}`
19
+ const purchaseIdOf = (paygate: string, externalId: string): string => `${paygate}:${externalId}`
20
20
 
21
21
  const profileViewOf = (record: BillingProfileRecord, policy: ConsumerRightsPolicy | null): BillingProfileView => ({
22
22
  country: record.country,
@@ -52,24 +52,28 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
52
52
  recordId, action, ...(step != null ? { step } : {}), ...(ok != null ? { ok } : {}),
53
53
  })) != null
54
54
 
55
- /** The currency of the entity's entitling Stripe subscription — two of one customer cannot differ. */
55
+ /** The currency of the entity's entitling paygate subscription — two of one customer cannot differ. */
56
56
  const activeSubscriptionCurrency = async (entityId: string): Promise<string | undefined> => {
57
- const row = await entitlingStripeSubscription(entityId)
57
+ const row = await entitlingPaygateSubscription(entityId)
58
58
 
59
59
  return row?.currency ?? undefined
60
60
  }
61
61
 
62
- const entitlingStripeSubscription = async (
62
+ const entitlingPaygateSubscription = async (
63
63
  entityId: string,
64
64
  ): Promise<PaymentSubscriptionRecord | null> => await access.subscriptions().load(
65
- { entityId, paygate: STRIPE_PAYGATE_ALIAS, status: [...ENTITLING_STATUSES] },
65
+ { entityId, paygate: { $ne: INTERNAL_PAYGATE }, status: [...ENTITLING_STATUSES] },
66
66
  { sort: [{ field: 'rank', order: 'desc' }, { field: 'createdAt', order: 'desc' }] },
67
67
  )
68
68
 
69
69
  const hasPaid = async (entityId: string): Promise<boolean> =>
70
- await access.fulfillments().load({ entityId, paygate: STRIPE_PAYGATE_ALIAS, fulfilledAt: { $exists: true } }) != null
70
+ await access.fulfillments().load({ entityId, paygate: { $ne: INTERNAL_PAYGATE }, fulfilledAt: { $exists: true } }) != null
71
71
  || await access.subscriptions()
72
- .load({ entityId, paygate: STRIPE_PAYGATE_ALIAS, initialPropagatedAt: { $exists: true } }) != null
72
+ .load({ entityId, paygate: { $ne: INTERNAL_PAYGATE }, initialPropagatedAt: { $exists: true } }) != null
73
+
74
+ /** The paygate a lock is recorded for: the one named, else the first registered one. */
75
+ const lockPaygateOf = (paygate: string | undefined): string =>
76
+ paygate ?? paygatesOf(ctx).all()[0]?.id ?? INTERNAL_PAYGATE
73
77
 
74
78
  const lockProfile = async (policy: ConsumerRightsPolicy | null, input: LockInput): Promise<LockResult> => {
75
79
  const country = input.country.trim().toUpperCase()
@@ -84,7 +88,8 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
84
88
  }
85
89
 
86
90
  const region = consumerRegionHelper.regionOf(country, policy) ?? ConsumerRegion.Other
87
- const settlement = (await access.stripePricingConfig())?.settlementCurrency?.toLowerCase()
91
+ const paygate = lockPaygateOf(input.paygate)
92
+ const settlement = (await paygatesOf(ctx).find(paygate)?.settlementCurrency())?.toLowerCase()
88
93
  const currency = (await activeSubscriptionCurrency(input.entityId))
89
94
  ?? (policy?.currencies != null && Object.keys(policy.currencies).length > 0
90
95
  ? consumerRegionHelper.chargeCurrencyOf(region, policy, input.currency ?? settlement ?? 'usd')
@@ -96,7 +101,7 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
96
101
  currency: currency.toLowerCase(),
97
102
  language: input.language ?? consumerRegionHelper.billingLanguageOf(country, policy),
98
103
  source: input.source,
99
- paygate: STRIPE_PAYGATE_ALIAS,
104
+ paygate,
100
105
  customerId: input.customerId,
101
106
  sessionId: input.sessionId,
102
107
  ipCountry: input.ipCountry?.toUpperCase(),
@@ -255,7 +260,7 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
255
260
  if (latest?.email != null && latest.email !== '') {
256
261
  return latest.email
257
262
  }
258
- const customer = await access.paygateCustomers().byEntity(entityId, STRIPE_PAYGATE_ALIAS)
263
+ const customer = await access.paygateCustomers().load({ entityId, paygate: { $ne: INTERNAL_PAYGATE }, email: { $exists: true } })
259
264
 
260
265
  return customer?.email ?? undefined
261
266
  }
@@ -272,13 +277,13 @@ export const makeConsumerRecords = (ctx: ApiContext): ConsumerRecords => {
272
277
  if (consumerFormatHelper.normalizeEmail(profile?.email) === wanted) {
273
278
  return true
274
279
  }
275
- const customer = await access.paygateCustomers().byEntity(purchase.entityId, STRIPE_PAYGATE_ALIAS)
280
+ const customer = await access.paygateCustomers().byEntity(purchase.entityId, purchase.paygate)
276
281
 
277
282
  return consumerFormatHelper.normalizeEmail(customer?.email) === wanted
278
283
  }
279
284
 
280
285
  return {
281
- purchaseIdOf, profileViewOf, unlockedProfileView, recordEvent, hasEvent, entitlingStripeSubscription, hasPaid,
286
+ purchaseIdOf, profileViewOf, unlockedProfileView, recordEvent, hasEvent, entitlingPaygateSubscription, hasPaid,
282
287
  lockProfile, unlockProfile, wasUnlocked, unconsentedWindows, createPurchase, patchPurchase, contactEmailOf,
283
288
  emailMatches,
284
289
  }
@@ -1,9 +1,8 @@
1
- import type Stripe from 'stripe'
2
1
  import { createLazyService } from '@owlmeans/context'
3
2
  import { MAILER_SERVICE } from '@owlmeans/mailer'
4
- import { cancellationEffectiveAt, CancellationKind, CancellationStatus, CancellationUnavailable, CancellationUnavailableReason, ConsentKind, CONSUMER_RIGHTS_COPY_VERSION, ConsumerRightsError, DeclarationChannel, DeclarationKind, ENTITLING_STATUSES, PaygateError, PerformanceConsentRequired, PurchaseKind, SubscriptionStartRequired, TERMINAL_STATUSES, UnknownPlan, WithdrawalStatus, WithdrawalUnavailable, WithdrawalUnavailableReason, type CancellationReceipt, type ConsumerRightsPolicy, type DeclarationReceipt, type PerformanceConsentView, type PurchaseView, type SubscriptionStartView, type WithdrawalCandidate, type WithdrawalReceipt, consumerCopyHelper, consumerRegionHelper, consumerRightsPolicyHelper } from '@owlmeans/payment'
3
+ import { cancellationEffectiveAt, CancellationKind, CancellationStatus, CancellationUnavailable, CancellationUnavailableReason, ConsentKind, CONSUMER_RIGHTS_COPY_VERSION, ConsumerRightsError, DeclarationChannel, DeclarationKind, ENTITLING_STATUSES, INTERNAL_PAYGATE, PaygateError, PerformanceConsentRequired, PurchaseKind, SubscriptionStartRequired, TERMINAL_STATUSES, UnknownPlan, WithdrawalStatus, WithdrawalUnavailable, WithdrawalUnavailableReason, type CancellationReceipt, type ConsumerRightsPolicy, type DeclarationReceipt, type PerformanceConsentView, type PurchaseView, type SubscriptionStartView, type WithdrawalCandidate, type WithdrawalReceipt, consumerCopyHelper, consumerRegionHelper, consumerRightsPolicyHelper } from '@owlmeans/payment'
5
4
  import type { Context as ApiContext } from '@owlmeans/server-api'
6
- import { CONSUMER_RIGHTS_SERVICE, STRIPE_PAYGATE_ALIAS } from '../consts.js'
5
+ import { CONSUMER_RIGHTS_SERVICE } from '../consts.js'
7
6
  import { CONSUMER_RIGHTS_RESOURCE_MAKERS } from '../resource.js'
8
7
  import { makeConsumerReconcileHelper } from './reconcile.js'
9
8
  import type {
@@ -26,6 +25,8 @@ import { consumerMailOf } from './mail.js'
26
25
  import { consumerObserversOf } from './observers.js'
27
26
  import { cancellationOf } from './cancellation.js'
28
27
  import { withdrawalOf } from './withdrawal.js'
28
+ import { paygatesOf } from '../paygate/registry.js'
29
+ import type { Paygate } from '../paygate/types.js'
29
30
 
30
31
  const latestDeadline = (items: Array<{ deadline?: Date | null }>): Date | undefined => {
31
32
  const times = items.map(item => item.deadline != null ? new Date(item.deadline).getTime() : Number.NaN)
@@ -34,6 +35,14 @@ const latestDeadline = (items: Array<{ deadline?: Date | null }>): Date | undefi
34
35
  return times.length > 0 ? new Date(Math.max(...times)) : undefined
35
36
  }
36
37
 
38
+ /**
39
+ * Whether a withdrawal of the purchase can be executed at its paygate: a registered paygate with
40
+ * `payments`, and with `subscriptions` for a subscription purchase — otherwise it is left to an
41
+ * operator (`review`).
42
+ */
43
+ const executable = (paygate: Paygate | null, purchase: PurchaseRecord): boolean =>
44
+ paygate?.payments != null && (purchase.kind !== PurchaseKind.Subscription || paygate.subscriptions != null)
45
+
37
46
  /** Only what a person typed, echoed as the receipt's content — never enriched with a match. */
38
47
  const contentOf = (fields: Record<string, string | undefined | null>): Record<string, string> =>
39
48
  Object.fromEntries(Object.entries(fields).filter((entry): entry is [string, string] =>
@@ -81,14 +90,19 @@ export const makeConsumerRightsService = (
81
90
  let manageGateway: boolean | undefined
82
91
  const isManaged = (): boolean => (manageOwn ?? manageGateway) !== false
83
92
  let meter: UsageMeter | null = opts.usage ?? null
84
- let stripeFactory = opts.stripe
85
93
  let renderer: ConsumerMailRenderer | null = null
86
- const stripeOf = async (ctx: ApiContext): Promise<Stripe> =>
87
- stripeFactory != null ? await stripeFactory(ctx) : await paymentAccessOf(ctx).stripeClient()
88
94
  const internals: ConsumerRightsInternals = {
89
- get managed() { return isManaged() }, meter: () => meter, stripe: stripeOf,
95
+ get managed() { return isManaged() }, meter: () => meter,
90
96
  }
91
97
 
98
+ /** The registered paygate of a record, or `null`. */
99
+ const paygateOf = (ctx: ApiContext, id: string | undefined): Paygate | null =>
100
+ id != null ? paygatesOf(ctx).find(id) : null
101
+
102
+ /** A paygate subscription row by its id, whichever paygate it is of. */
103
+ const subscriptionRow = async (ctx: ApiContext, externalId: string): Promise<PaymentSubscriptionRecord | null> =>
104
+ await paymentAccessOf(ctx).subscriptions().load({ externalId, paygate: { $ne: INTERNAL_PAYGATE } })
105
+
92
106
  const requirePolicy = async (ctx: ApiContext): Promise<ConsumerRightsPolicy> => {
93
107
  const policy = await paymentAccessOf(ctx).payment().consumerRightsPolicy()
94
108
  if (policy == null) {
@@ -126,7 +140,7 @@ export const makeConsumerRightsService = (
126
140
  }
127
141
  // Case-insensitive (`$ilike`, its `%`/`_`/`\` wildcards escaped): a paygate keeps the e-mail as typed.
128
142
  const pattern = wanted.replace(/[\\%_]/g, match => `\\${match}`)
129
- const { items } = await paymentAccessOf(ctx).paygateCustomers().list({ paygate: STRIPE_PAYGATE_ALIAS, email: { $ilike: pattern } }, { size: 20 })
143
+ const { items } = await paymentAccessOf(ctx).paygateCustomers().list({ paygate: { $ne: INTERNAL_PAYGATE }, email: { $ilike: pattern } }, { size: 20 })
130
144
  const entities = [...new Set(items.filter(item => item.deletedAt == null && item.entityId != null).map(item => item.entityId as string))]
131
145
 
132
146
  return entities.length === 1 ? entities[0] : null
@@ -522,7 +536,7 @@ export const makeConsumerRightsService = (
522
536
  status = WithdrawalStatus.Received
523
537
  } else if (purchase.deadline == null || at.getTime() >= new Date(purchase.deadline).getTime()) {
524
538
  status = WithdrawalStatus.Expired
525
- } else if (meter != null && policy.mechanisms.automaticRefunds) {
539
+ } else if (meter != null && policy.mechanisms.automaticRefunds && executable(paygateOf(ctx, purchase.paygate), purchase)) {
526
540
  try {
527
541
  computation = await withdrawalOf(ctx).computeWithdrawal(meter, purchase, at)
528
542
  } catch (error) {
@@ -583,7 +597,7 @@ export const makeConsumerRightsService = (
583
597
  let final: WithdrawalStatus = status
584
598
  let execution: WithdrawalExecution | null = null
585
599
  if (status === WithdrawalStatus.Processing && purchase != null && computation != null) {
586
- execution = await withdrawalOf(ctx).executeWithdrawal(await stripeOf(ctx), declaration, purchase, computation)
600
+ execution = await withdrawalOf(ctx).executeWithdrawal(paygateOf(ctx, purchase.paygate) as Paygate, declaration, purchase, computation)
587
601
  final = execution.needsReview ? WithdrawalStatus.Review : execution.ok ? WithdrawalStatus.Refunded : WithdrawalStatus.Failed
588
602
  }
589
603
  if (purchase != null && (final === WithdrawalStatus.Refunded || final === WithdrawalStatus.Review)
@@ -620,22 +634,22 @@ export const makeConsumerRightsService = (
620
634
  let row: PaymentSubscriptionRecord | null = null
621
635
  if (subject != null) {
622
636
  if (body.subscriptionId != null) {
623
- row = await access.subscriptions().byExternalId(body.subscriptionId, STRIPE_PAYGATE_ALIAS)
637
+ row = await subscriptionRow(ctx, body.subscriptionId)
624
638
  } else if (body.contractRef != null) {
625
639
  purchase = await purchaseByContract(ctx, body.contractRef)
626
640
  if (purchase != null && purchase.entityId === subject.entityId && purchase.subscriptionId != null) {
627
- row = await access.subscriptions().byExternalId(purchase.subscriptionId, STRIPE_PAYGATE_ALIAS)
641
+ row = await access.subscriptions().byExternalId(purchase.subscriptionId, purchase.paygate)
628
642
  }
629
643
  }
630
644
  row = row != null && row.entityId === subject.entityId
631
- ? row : await consumerRecordsOf(ctx).entitlingStripeSubscription(subject.entityId)
645
+ ? row : await consumerRecordsOf(ctx).entitlingPaygateSubscription(subject.entityId)
632
646
  } else {
633
647
  purchase = await matchPublicPurchase(ctx, body.contractRef, body.email)
634
648
  if (purchase?.subscriptionId != null) {
635
- row = await access.subscriptions().byExternalId(purchase.subscriptionId, STRIPE_PAYGATE_ALIAS)
649
+ row = await access.subscriptions().byExternalId(purchase.subscriptionId, purchase.paygate)
636
650
  } else if (purchase == null) {
637
651
  const entityId = await entityByEmail(ctx, body.email)
638
- row = entityId != null ? await consumerRecordsOf(ctx).entitlingStripeSubscription(entityId) : null
652
+ row = entityId != null ? await consumerRecordsOf(ctx).entitlingPaygateSubscription(entityId) : null
639
653
  }
640
654
  }
641
655
  const live = row != null && !TERMINAL_STATUSES.includes(row.status) && ENTITLING_STATUSES.includes(row.status)
@@ -652,7 +666,7 @@ export const makeConsumerRightsService = (
652
666
  if (body.kind === CancellationKind.Extraordinary) {
653
667
  // For cause: recorded and left to an operator — the paygate is not touched.
654
668
  status = CancellationStatus.Review
655
- } else if (row != null && live && row.periodEnd != null) {
669
+ } else if (row != null && live && row.periodEnd != null && paygateOf(ctx, row.paygate)?.subscriptions != null) {
656
670
  effectiveAt = cancellationEffectiveAt(new Date(row.periodEnd), plan?.recurring?.interval ?? 'month',
657
671
  requested != null && !Number.isNaN(requested.getTime()) ? requested : null)
658
672
  status = row.cancelAtPeriodEnd === true && effectiveAt.getTime() === new Date(row.periodEnd).getTime()
@@ -676,7 +690,7 @@ export const makeConsumerRightsService = (
676
690
  }) as ConsumerDeclarationRecord)
677
691
  let final = status
678
692
  if (status === CancellationStatus.Scheduled && row != null) {
679
- final = await cancellationOf(ctx).scheduleCancellation(await stripeOf(ctx), declaration, row)
693
+ final = await cancellationOf(ctx).scheduleCancellation(paygateOf(ctx, row.paygate) as Paygate, declaration, row)
680
694
  ? CancellationStatus.Scheduled : CancellationStatus.Received
681
695
  }
682
696
  if (purchase != null && effectiveAt != null) {
@@ -719,7 +733,6 @@ export const makeConsumerRightsService = (
719
733
  else manageGateway = plumbing.manage
720
734
  }
721
735
  if (plumbing.usage != null) meter = plumbing.usage
722
- if (plumbing.stripe != null) stripeFactory = plumbing.stripe
723
736
  })
724
737
 
725
738
  return service
@@ -728,7 +741,7 @@ export const makeConsumerRightsService = (
728
741
  /**
729
742
  * Register the consumer-rights resources and service (each only when absent), or configure the
730
743
  * service already registered — `from` says who asks. The order of the application's call and the
731
- * gateway's is free: `usage` and `stripe` are installed whenever they come, and the application's
744
+ * gateway's is free: `usage` is installed whenever it comes, and the application's
732
745
  * explicit `manage` wins over the gateway's. The resources keep the first registration's aliases.
733
746
  */
734
747
  export const registerConsumerRights = <C extends Config, T extends Context<C>>(
@@ -743,12 +756,12 @@ export const registerConsumerRights = <C extends Config, T extends Context<C>>(
743
756
  // A lazy service: reachable before the context initializes.
744
757
  let service = ctx.hasService(alias) ? ctx.service<ConsumerRightsService>(alias) : null
745
758
  if (service == null) {
746
- service = makeConsumerRightsService(alias, { ...opts, manage: undefined, usage: undefined, stripe: undefined })
759
+ service = makeConsumerRightsService(alias, { ...opts, manage: undefined, usage: undefined })
747
760
  ctx.registerService(service)
748
761
  }
749
762
  const plumb = plumbers.get(service)
750
763
  if (plumb != null) {
751
- plumb(paymentUtils.compact({ manage: opts.manage, usage: opts.usage, stripe: opts.stripe }), from)
764
+ plumb(paymentUtils.compact({ manage: opts.manage, usage: opts.usage }), from)
752
765
  } else if (opts.usage != null) {
753
766
  // A service made elsewhere: only its public seam.
754
767
  service.useMeter(opts.usage)
@@ -759,7 +772,7 @@ export const registerConsumerRights = <C extends Config, T extends Context<C>>(
759
772
 
760
773
  /**
761
774
  * Register the consumer-rights resources and service, each only when absent — the gateway
762
- * registration does too. Called before or after the gateway, it installs `usage` and `stripe` on
775
+ * registration does too. Called before or after the gateway, it installs `usage` on
763
776
  * the service and its explicit `manage` wins over the gateway's; `useMeter` and `useMailRenderer`
764
777
  * work on the service at any time.
765
778
  */
@@ -1,4 +1,3 @@
1
- import type Stripe from 'stripe'
2
1
  import type { AbstractRequest } from '@owlmeans/entrypoint'
3
2
  import type { ConsumerRightsOptions } from '../types.js'
4
3
 
@@ -13,10 +12,4 @@ export interface Rendered {
13
12
  export type Headers = AbstractRequest['headers']
14
13
 
15
14
  /** What a later registration applies to a service already registered. */
16
- export interface Plumbing extends Pick<ConsumerRightsOptions, 'manage' | 'usage' | 'stripe'> {}
17
-
18
- /**
19
- * A credit note's creation parameters in the API version the client is pinned to: the refund it corrects
20
- * is named by `refund` there, where the installed SDK's types (a newer version) list `refunds`.
21
- */
22
- export interface PinnedCreditNoteParams extends Stripe.CreditNoteCreateParams { refund?: string }
15
+ export interface Plumbing extends Pick<ConsumerRightsOptions, 'manage' | 'usage'> {}
@@ -3,13 +3,11 @@ import type { EntrypointProtocolDeclaration } from '@owlmeans/entrypoint'
3
3
  import type {
4
4
  ConsumerRightsAccountProtocols, ConsumerRightsPublicProtocols, WithdrawalEstimate,
5
5
  } from '@owlmeans/payment'
6
- import type { Context as ApiContext } from '@owlmeans/server-api'
7
- import type Stripe from 'stripe'
8
6
  import type {
9
7
  PurchaseRecord, BillingProfileRecord, BillingProfileSource, LockOptions, UsageMeter, UsageReading,
10
8
  } from '../types.js'
11
9
 
12
- /** What a completed Checkout Session says about its buyer and totals. */
10
+ /** What a completed checkout session says about its buyer and totals. */
13
11
  export interface SessionEvidence {
14
12
  country?: string
15
13
  email?: string
@@ -64,7 +62,6 @@ export interface PurchaseDraft extends Omit<PurchaseRecord, 'id' | 'contractRef'
64
62
  export interface ConsumerRightsInternals {
65
63
  readonly managed: boolean
66
64
  meter: () => UsageMeter | null
67
- stripe: (ctx: ApiContext) => Promise<Stripe>
68
65
  }
69
66
 
70
67
  /** Who hands a registration its options: the application itself, or the gateway on its behalf. */
@@ -1,6 +1,6 @@
1
- import type Stripe from 'stripe'
2
1
  import type { ConsumerDeclarationRecord, PurchaseRecord, UsageMeter } from '../../types.js'
3
2
  import type { WithdrawalComputation, WithdrawalExecution } from '../types.js'
3
+ import type { Paygate } from '../../paygate/types.js'
4
4
 
5
5
  /** Withdrawals of a context: what they reimburse and their paygate steps. */
6
6
  export interface WithdrawalHelper {
@@ -13,25 +13,27 @@ export interface WithdrawalHelper {
13
13
  */
14
14
  computeWithdrawal: (meter: UsageMeter, purchase: PurchaseRecord, at: Date) => Promise<WithdrawalComputation>
15
15
  /**
16
- * Execute a withdrawal at the paygate, the first attempt of every call under the idempotency key
17
- * `withdrawal:<id>:<step>` (a retry by `reconcile` adopts what an earlier attempt made):
16
+ * Execute a withdrawal at the purchase's paygate, the first attempt of every call under the
17
+ * idempotency key `withdrawal:<id>:<step>` (a retry by `reconcile` uses `…:<attempt>` and adopts
18
+ * what an earlier attempt made):
18
19
  *
19
- * 1. a subscription purchase: `subscriptions.cancel` at once, without proration or a final invoice;
20
- * 2. an invoice-backed purchase: `creditNotes.preview` of the invoice line at the net refund, then
21
- * OUR `refunds.create` for the previewed total (metadata `withdrawalId` — the refund webhook then
22
- * tells observers not to claw back), then `creditNotes.create` linking that refund — the
23
- * corrective tax document; a failed credit note keeps the plain refund and is recorded;
24
- * 3. no invoice: a plain proportional refund on the payment intent.
20
+ * 1. a subscription purchase: `subscriptions.cancelNow`, without proration or a final invoice;
21
+ * 2. an invoice-backed purchase (a paygate with `payments.creditNotes`): a credit-note preview of
22
+ * the invoice line at the net refund, then OUR refund for the previewed total (metadata
23
+ * `withdrawalId` — the refund webhook then tells observers not to claw back), then a credit note
24
+ * documenting that refund — the corrective tax document; a failed credit note keeps the plain
25
+ * refund and is recorded;
26
+ * 3. otherwise: a plain proportional refund on the payment.
25
27
  *
26
28
  * Steps that already succeeded (a recorded `ok` event) are skipped. Every step is an event.
27
29
  */
28
30
  executeWithdrawal: (
29
- stripe: Stripe, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
31
+ paygate: Paygate, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
30
32
  computation: { refundMinor: number, netMinor: number }, opts?: { attempt?: number },
31
33
  ) => Promise<WithdrawalExecution>
32
- /** Retry a credit note that failed after its refund succeeded. */
34
+ /** Retry a credit note that failed after its refund succeeded (`false` without `payments.creditNotes`). */
33
35
  retryCreditNote: (
34
- stripe: Stripe, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
36
+ paygate: Paygate, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
35
37
  netMinor: number, refundId: string, attempt: number,
36
38
  ) => Promise<boolean>
37
39
  }