@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
@@ -1,12 +1,10 @@
1
- import type Stripe from 'stripe'
2
- import { PurchaseKind, type WithdrawalEstimate, consumerCopyHelper, withdrawalRefundHelper } from '@owlmeans/payment'
1
+ import { PaygateError, PurchaseKind, type WithdrawalEstimate, consumerCopyHelper, withdrawalRefundHelper } from '@owlmeans/payment'
3
2
  import type { Context as ApiContext } from '@owlmeans/server-api'
4
3
  import { memoHelper } from '@owlmeans/context'
5
- import { STRIPE_OWNER_KEY, STRIPE_OWNER_VALUE, STRIPE_PAYGATE_ALIAS } from '../consts.js'
6
4
  import type { ConsumerDeclarationRecord, PaymentSubscriptionRecord, PurchaseRecord, UsageMeter } from '../types.js'
7
5
  import { DAY_MS } from './consts.local.js'
8
6
  import type { WithdrawalComputation, WithdrawalExecution } from './types.js'
9
- import type { PinnedCreditNoteParams } from './types.local.js'
7
+ import type { CreditNoteLine, Paygate, PaygateCall, PaygateCreditNote, PaygateRefund } from '../paygate/types.js'
10
8
  import { paymentAccessOf } from '../access.js'
11
9
  import { paymentUtils } from '../utils.js'
12
10
  import { catalogueOf } from '../catalogue.js'
@@ -17,17 +15,12 @@ import type { ConsumerEventDraft } from './records/types.js'
17
15
  import { captureOf } from './capture.js'
18
16
  import type { WithdrawalHelper } from './withdrawal/types.js'
19
17
 
20
- /** A Stripe error that says the subscription is already gone. */
21
- const alreadyCanceled = (error: unknown): boolean => paymentUtils.isMissingObject(error)
22
- || /canceled subscription|already (been )?cancel/i.test((error as { message?: string } | null)?.message ?? '')
23
-
24
18
  /**
25
- * Stripe replays the stored answer of an idempotency key — a failure too — for a day: a retry
26
- * uses a fresh key (`…:<attempt>`) and first adopts what an earlier attempt may have made.
19
+ * A paygate may replay the stored answer of an idempotency key — a failure too: a retry uses a fresh
20
+ * key (`…:<attempt>`) and first adopts what an earlier attempt may have made.
27
21
  */
28
- const keyOf = (withdrawalId: string, step: string, attempt: number): Stripe.RequestOptions => ({
29
- idempotencyKey: attempt > 0 ? `withdrawal:${withdrawalId}:${step}:${attempt}` : `withdrawal:${withdrawalId}:${step}`,
30
- })
22
+ const keyOf = (withdrawalId: string, step: string, attempt: number): string =>
23
+ attempt > 0 ? `withdrawal:${withdrawalId}:${step}:${attempt}` : `withdrawal:${withdrawalId}:${step}`
31
24
 
32
25
  export const makeWithdrawalHelper = (ctx: ApiContext): WithdrawalHelper => {
33
26
  const access = paymentAccessOf(ctx)
@@ -68,7 +61,7 @@ export const makeWithdrawalHelper = (ctx: ApiContext): WithdrawalHelper => {
68
61
  }
69
62
 
70
63
  const subscription = purchase.subscriptionId != null
71
- ? await access.subscriptions().byExternalId(purchase.subscriptionId, STRIPE_PAYGATE_ALIAS) : null
64
+ ? await access.subscriptions().byExternalId(purchase.subscriptionId, purchase.paygate) : null
72
65
  const plan = purchase.planSku != null ? await catalogueOf(ctx).findPlan(purchase.planSku) : null
73
66
  const purchasedAt = new Date(purchase.purchasedAt)
74
67
  const periodStart = subscription?.periodStart != null ? new Date(subscription.periodStart) : purchasedAt
@@ -95,28 +88,20 @@ export const makeWithdrawalHelper = (ctx: ApiContext): WithdrawalHelper => {
95
88
  }
96
89
  }
97
90
 
98
- /** A refund this withdrawal already made (found by its metadata) — what a retry adopts. */
99
- const existingRefund = async (stripe: Stripe, paymentIntentId: string, withdrawalId: string): Promise<Stripe.Refund | null> => {
100
- const { data } = await stripe.refunds.list({ payment_intent: paymentIntentId, limit: 100 })
101
-
102
- return data.find(refund => refund.metadata?.withdrawalId === withdrawalId && refund.status !== 'failed'
103
- && refund.status !== 'canceled') ?? null
104
- }
105
-
106
- /** A credit note this withdrawal already made — what a retry adopts. */
107
- const existingCreditNote = async (stripe: Stripe, invoiceId: string, withdrawalId: string): Promise<Stripe.CreditNote | null> => {
108
- const { data } = await stripe.creditNotes.list({ invoice: invoiceId, limit: 100 })
109
-
110
- return data.find(note => note.metadata?.withdrawalId === withdrawalId && note.status !== 'void') ?? null
111
- }
91
+ const memoOf = (declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord): string =>
92
+ consumerCopyHelper.consumerText(declaration.language, 'credit-note.memo', {
93
+ contractRef: purchase.contractRef, date: consumerFormatHelper.formatDate(new Date(declaration.receivedAt), declaration.language),
94
+ })
112
95
 
113
96
  const executeWithdrawal = async (
114
- stripe: Stripe, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
97
+ paygate: Paygate, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
115
98
  computation: { refundMinor: number, netMinor: number }, opts: { attempt?: number } = {},
116
99
  ): Promise<WithdrawalExecution> => {
117
100
  const withdrawalId = declaration.id as string
118
101
  const attempt = opts.attempt ?? 0
119
- const key = (step: string): Stripe.RequestOptions => keyOf(withdrawalId, step, attempt)
102
+ const call = (step: string, comment?: string): PaygateCall => ({
103
+ idempotencyKey: keyOf(withdrawalId, step, attempt), ...(comment != null ? { comment } : {}),
104
+ })
120
105
  const event = (action: 'refund' | 'credit-note' | 'subscription-cancel', fields: Record<string, unknown>) =>
121
106
  records.recordEvent({
122
107
  recordId: withdrawalId, recordKind: 'declaration', entityId: purchase.entityId, action, ok: false, ...fields,
@@ -128,22 +113,22 @@ export const makeWithdrawalHelper = (ctx: ApiContext): WithdrawalHelper => {
128
113
  outcome.subscriptionCanceled = true
129
114
  } else {
130
115
  try {
131
- await stripe.subscriptions.cancel(purchase.subscriptionId, {
132
- prorate: false, invoice_now: false, cancellation_details: { comment: `withdrawal:${withdrawalId}` },
133
- }, key('subscription-cancel'))
116
+ if (paygate.subscriptions == null) {
117
+ throw new PaygateError(`capability:subscriptions:${paygate.id}`)
118
+ }
119
+ const { alreadyCanceled } = await paygate.subscriptions.cancelNow(
120
+ purchase.subscriptionId, call('subscription-cancel', `withdrawal:${withdrawalId}`),
121
+ )
134
122
  outcome.subscriptionCanceled = true
135
- await event('subscription-cancel', { ok: true, externalId: purchase.subscriptionId })
123
+ await event('subscription-cancel', alreadyCanceled
124
+ ? { ok: true, externalId: purchase.subscriptionId, detail: '{"already":true}' }
125
+ : { ok: true, externalId: purchase.subscriptionId })
136
126
  } catch (error) {
137
- if (alreadyCanceled(error)) {
138
- outcome.subscriptionCanceled = true
139
- await event('subscription-cancel', { ok: true, externalId: purchase.subscriptionId, detail: '{"already":true}' })
140
- } else {
141
- outcome.ok = false
142
- await event('subscription-cancel', { externalId: purchase.subscriptionId, error: paymentUtils.errorText(error) })
143
- }
127
+ outcome.ok = false
128
+ await event('subscription-cancel', { externalId: purchase.subscriptionId, error: paymentUtils.errorText(error) })
144
129
  }
145
130
  if (outcome.subscriptionCanceled) {
146
- const row: PaymentSubscriptionRecord | null = await access.subscriptions().byExternalId(purchase.subscriptionId, STRIPE_PAYGATE_ALIAS)
131
+ const row: PaymentSubscriptionRecord | null = await access.subscriptions().byExternalId(purchase.subscriptionId, purchase.paygate)
147
132
  if (row != null && row.withdrawnAt == null) {
148
133
  await access.subscriptions().update({ ...row, withdrawnAt: new Date(declaration.receivedAt) })
149
134
  }
@@ -157,11 +142,16 @@ export const makeWithdrawalHelper = (ctx: ApiContext): WithdrawalHelper => {
157
142
  if (computation.refundMinor <= 0) {
158
143
  return outcome
159
144
  }
145
+ const payments = paygate.payments
146
+ if (payments == null) {
147
+ await event('refund', { error: `capability:payments:${paygate.id}`, amountMinor: computation.refundMinor, currency: purchase.currency })
148
+ return { ...outcome, ok: false, needsReview: true }
149
+ }
160
150
 
161
151
  let paymentIntentId = purchase.paymentIntentId
162
152
  let invoiceLineId = purchase.invoiceLineId
163
153
  if (purchase.invoiceId != null && (paymentIntentId == null || invoiceLineId == null)) {
164
- const invoice = await capture.invoiceEvidenceOf(stripe, purchase.invoiceId)
154
+ const invoice = await capture.invoiceEvidenceOf(paygate, purchase.invoiceId)
165
155
  paymentIntentId = paymentIntentId ?? invoice.paymentIntentId
166
156
  invoiceLineId = invoiceLineId ?? invoice.invoiceLineId
167
157
  await records.patchPurchase(purchase.purchaseId, paymentUtils.compact({
@@ -175,14 +165,14 @@ export const makeWithdrawalHelper = (ctx: ApiContext): WithdrawalHelper => {
175
165
 
176
166
  const open = Math.max(0, purchase.amountTotalMinor - (purchase.refundedMinor ?? 0))
177
167
  let amount = Math.min(open, computation.refundMinor)
178
- let lines: Stripe.CreditNoteCreateParams.Line[] | null = null
179
- if (purchase.invoiceId != null && invoiceLineId != null && computation.netMinor > 0) {
180
- lines = [{ type: 'invoice_line_item', invoice_line_item: invoiceLineId, amount: computation.netMinor }]
168
+ let line: CreditNoteLine | null = null
169
+ if (payments.creditNotes != null && purchase.invoiceId != null && invoiceLineId != null && computation.netMinor > 0) {
170
+ line = { invoiceId: purchase.invoiceId, lineId: invoiceLineId, amountMinor: computation.netMinor }
181
171
  try {
182
- const preview = await stripe.creditNotes.preview({ invoice: purchase.invoiceId, lines })
183
- amount = Math.min(open, preview.total)
172
+ const preview = await payments.creditNotes.preview(line)
173
+ amount = Math.min(open, preview.totalMinor)
184
174
  } catch (error) {
185
- lines = null
175
+ line = null
186
176
  await event('credit-note', { step: 'preview', error: paymentUtils.errorText(error) })
187
177
  }
188
178
  }
@@ -190,32 +180,27 @@ export const makeWithdrawalHelper = (ctx: ApiContext): WithdrawalHelper => {
190
180
  return outcome
191
181
  }
192
182
 
193
- let refund: Stripe.Refund
183
+ let refund: PaygateRefund
194
184
  try {
195
- refund = (attempt > 0 ? await existingRefund(stripe, paymentIntentId, withdrawalId) : null)
196
- ?? await stripe.refunds.create({
197
- payment_intent: paymentIntentId, amount, reason: 'requested_by_customer',
198
- metadata: { [STRIPE_OWNER_KEY]: STRIPE_OWNER_VALUE, withdrawalId, purchaseId: purchase.purchaseId },
199
- }, key('refund'))
185
+ const metadata = { withdrawalId, purchaseId: purchase.purchaseId }
186
+ refund = (attempt > 0 ? await payments.findRefund(paymentIntentId, { withdrawalId }) : null)
187
+ ?? await payments.refund({ paymentId: paymentIntentId, amountMinor: amount, metadata }, call('refund'))
200
188
  } catch (error) {
201
189
  await event('refund', { error: paymentUtils.errorText(error), amountMinor: amount, currency: purchase.currency })
202
190
  return { ...outcome, ok: false }
203
191
  }
204
- await event('refund', { ok: true, externalId: refund.id, amountMinor: refund.amount, currency: refund.currency })
192
+ await event('refund', { ok: true, externalId: refund.id, amountMinor: refund.amountMinor, currency: refund.currency })
205
193
  outcome.refundId = refund.id
206
- outcome.refundedMinor = refund.amount
194
+ outcome.refundedMinor = refund.amountMinor
207
195
 
208
- if (lines != null && purchase.invoiceId != null) {
196
+ if (line != null && payments.creditNotes != null) {
209
197
  try {
210
- const note = await stripe.creditNotes.create({
211
- invoice: purchase.invoiceId, lines, refund: refund.id,
212
- memo: consumerCopyHelper.consumerText(declaration.language, 'credit-note.memo', {
213
- contractRef: purchase.contractRef, date: consumerFormatHelper.formatDate(new Date(declaration.receivedAt), declaration.language),
214
- }),
198
+ const note = await payments.creditNotes.create({
199
+ ...line, refundId: refund.id, memo: memoOf(declaration, purchase),
215
200
  metadata: { withdrawalId, purchaseId: purchase.purchaseId },
216
- } as PinnedCreditNoteParams, key('credit-note'))
201
+ }, call('credit-note'))
217
202
  outcome.creditNoteId = note.id
218
- await event('credit-note', { ok: true, externalId: note.id, amountMinor: note.total, currency: note.currency })
203
+ await event('credit-note', { ok: true, externalId: note.id, amountMinor: note.totalMinor, currency: note.currency })
219
204
  } catch (error) {
220
205
  // The refund stands; the corrective document is retried by reconcile.
221
206
  await event('credit-note', { error: paymentUtils.errorText(error), detail: JSON.stringify({ refundId: refund.id }) })
@@ -226,30 +211,29 @@ export const makeWithdrawalHelper = (ctx: ApiContext): WithdrawalHelper => {
226
211
  }
227
212
 
228
213
  const retryCreditNote = async (
229
- stripe: Stripe, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
214
+ paygate: Paygate, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
230
215
  netMinor: number, refundId: string, attempt: number,
231
216
  ): Promise<boolean> => {
232
217
  const withdrawalId = declaration.id as string
218
+ const creditNotes = paygate.payments?.creditNotes
219
+ if (creditNotes == null) {
220
+ return false
221
+ }
233
222
  let invoiceLineId = purchase.invoiceLineId
234
223
  if (invoiceLineId == null && purchase.invoiceId != null) {
235
- invoiceLineId = (await capture.invoiceEvidenceOf(stripe, purchase.invoiceId)).invoiceLineId
224
+ invoiceLineId = (await capture.invoiceEvidenceOf(paygate, purchase.invoiceId)).invoiceLineId
236
225
  }
237
226
  if (purchase.invoiceId == null || invoiceLineId == null || netMinor <= 0) {
238
227
  return false
239
228
  }
240
229
  try {
241
- const note = await existingCreditNote(stripe, purchase.invoiceId, withdrawalId) ?? await stripe.creditNotes.create({
242
- invoice: purchase.invoiceId,
243
- lines: [{ type: 'invoice_line_item', invoice_line_item: invoiceLineId, amount: netMinor }],
244
- refund: refundId,
245
- memo: consumerCopyHelper.consumerText(declaration.language, 'credit-note.memo', {
246
- contractRef: purchase.contractRef, date: consumerFormatHelper.formatDate(new Date(declaration.receivedAt), declaration.language),
247
- }),
248
- metadata: { withdrawalId, purchaseId: purchase.purchaseId },
249
- } as PinnedCreditNoteParams, keyOf(withdrawalId, 'credit-note', attempt))
230
+ const note: PaygateCreditNote = await creditNotes.find(purchase.invoiceId, { withdrawalId }) ?? await creditNotes.create({
231
+ invoiceId: purchase.invoiceId, lineId: invoiceLineId, amountMinor: netMinor, refundId,
232
+ memo: memoOf(declaration, purchase), metadata: { withdrawalId, purchaseId: purchase.purchaseId },
233
+ }, { idempotencyKey: keyOf(withdrawalId, 'credit-note', attempt) })
250
234
  await records.recordEvent({
251
235
  recordId: withdrawalId, recordKind: 'declaration', entityId: purchase.entityId, action: 'credit-note', ok: true,
252
- externalId: note.id, amountMinor: note.total, currency: note.currency,
236
+ externalId: note.id, amountMinor: note.totalMinor, currency: note.currency,
253
237
  })
254
238
  return true
255
239
  } catch (error) {
package/src/index.ts CHANGED
@@ -38,10 +38,17 @@ export * from './reconcile.js'
38
38
  export type * from './gate/types.js'
39
39
  export * from './gate/request.js'
40
40
 
41
- export type * from './plugins/session/types.js'
42
- export * from './plugins/session.js'
43
- export type * from './plugins/stripe/types.js'
44
- export * from './plugins/stripe.js'
41
+ export type * from './paygate/types.js'
42
+ export * from './paygate/providers.js'
43
+ export * from './paygate/registry.js'
44
+ export type * from './checkout/types.js'
45
+ export * from './checkout.js'
46
+ export type * from './plugins/snapshot/types.js'
47
+ export * from './plugins/snapshot.js'
48
+ export type * from './plugins/fx/types.js'
49
+ export * from './plugins/fx.js'
50
+ export type * from './plugins/refunds/types.js'
51
+ export * from './plugins/refunds.js'
45
52
  export type * from './plugins/checkout-registry/types.js'
46
53
  export * from './plugins/checkout-registry.js'
47
54
  export type * from './plugins/checkout-plugins/types.js'
@@ -53,7 +60,6 @@ export * from './plugins/estimate/cache.js'
53
60
  export * from './plugins/estimate.js'
54
61
  export type * from './plugins/events/types.js'
55
62
  export * from './plugins/events.js'
56
- export * from './plugins/status.js'
57
63
  export type * from './plugins/subscriptions/types.js'
58
64
  export * from './plugins/subscriptions.js'
59
65
  export type * from './plugins/webhook-manager/types.js'
@@ -64,6 +70,6 @@ export * from './plugins/portal.js'
64
70
  export * from './consumer/index.js'
65
71
 
66
72
  export {
67
- consumerConsents, consumerRightsOf, entitlements, fulfillments, gateway, observer, payment, purchases, stripeClient,
73
+ consumerConsents, consumerRightsOf, entitlements, fulfillments, gateway, observer, payment, paymentUtils, purchases,
68
74
  subscriptions,
69
75
  } from './utils.js'
@@ -0,0 +1,48 @@
1
+ import { createLazyService } from '@owlmeans/context'
2
+ import { PaygateError } from '@owlmeans/payment'
3
+ import { PAYMENT_PROVIDERS } from '../consts.js'
4
+ import type { Config, Context } from '../types.js'
5
+ import type { PaymentProvider, PaymentProvidersService } from './types.js'
6
+
7
+ /**
8
+ * The payment providers of a context — a lazy service, so a provider package registers its provider
9
+ * while the application is wired (its `append…` helper, before or after the gateway). A provider
10
+ * registered under an id already taken replaces the earlier one.
11
+ */
12
+ export const createPaymentProvidersService = (alias: string = PAYMENT_PROVIDERS): PaymentProvidersService => {
13
+ const registered: PaymentProvider[] = []
14
+
15
+ const register = (provider: PaymentProvider): void => {
16
+ if (provider == null || typeof provider.id !== 'string' || provider.id.trim() === '') {
17
+ throw new PaygateError('provider:id')
18
+ }
19
+ const index = registered.findIndex(entry => entry.id === provider.id)
20
+ if (index >= 0) {
21
+ registered[index] = provider
22
+ } else {
23
+ registered.push(provider)
24
+ }
25
+ }
26
+
27
+ return createLazyService<PaymentProvidersService>(alias, {
28
+ register,
29
+ provider: id => registered.find(entry => entry.id === id) ?? null,
30
+ providers: () => [...registered],
31
+ }, service => async () => { service.initialized = true })
32
+ }
33
+
34
+ /** Register the payment providers service, once. */
35
+ export const appendPaymentProviders = <C extends Config, T extends Context<C>>(
36
+ ctx: T, alias: string = PAYMENT_PROVIDERS,
37
+ ): T => {
38
+ if (!ctx.hasService(alias)) {
39
+ ctx.registerService(createPaymentProvidersService(alias))
40
+ }
41
+
42
+ return ctx
43
+ }
44
+
45
+ /** The payment providers service of a context, registered on first use — what a provider's `append…` registers with. */
46
+ export const ensurePaymentProviders = <C extends Config, T extends Context<C>>(
47
+ ctx: T, alias: string = PAYMENT_PROVIDERS,
48
+ ): PaymentProvidersService => appendPaymentProviders(ctx, alias).service<PaymentProvidersService>(alias)
@@ -0,0 +1,53 @@
1
+ import { memoHelper } from '@owlmeans/context'
2
+ import { UnknownPaygate } from '@owlmeans/payment'
3
+ import type { Context as ApiContext } from '@owlmeans/server-api'
4
+ import { PAYMENT_PROVIDERS } from '../consts.js'
5
+ import { planHelper } from '../plan.js'
6
+ import type { PaymentPlan, PaymentProduct } from '../types.js'
7
+ import type { Paygate, PaygateRegistry, PaymentProvider, PaymentProvidersService } from './types.js'
8
+
9
+ export const makePaygateRegistry = (ctx: ApiContext): PaygateRegistry => {
10
+ // One binding per provider instance: a provider replaced under its id is bound anew.
11
+ const bound = new WeakMap<PaymentProvider, Paygate>()
12
+
13
+ const providers = (): readonly PaymentProvider[] =>
14
+ (ctx as unknown as { hasService?: (alias: string) => boolean }).hasService?.(PAYMENT_PROVIDERS) === true
15
+ ? ctx.service<PaymentProvidersService>(PAYMENT_PROVIDERS).providers() : []
16
+
17
+ const paygateOf = (provider: PaymentProvider): Paygate => {
18
+ let paygate = bound.get(provider)
19
+ if (paygate == null) {
20
+ paygate = provider.bind(ctx)
21
+ bound.set(provider, paygate)
22
+ }
23
+
24
+ return paygate
25
+ }
26
+
27
+ const find = (id: string): Paygate | null => {
28
+ const provider = providers().find(entry => entry.id === id)
29
+
30
+ return provider != null ? paygateOf(provider) : null
31
+ }
32
+
33
+ const get = (id: string): Paygate => {
34
+ const paygate = find(id)
35
+ if (paygate == null) {
36
+ throw new UnknownPaygate(id)
37
+ }
38
+
39
+ return paygate
40
+ }
41
+
42
+ const all = (): Paygate[] => providers().map(paygateOf)
43
+
44
+ const forSale = (product: PaymentProduct, plan: PaymentPlan, requested?: string): Paygate[] =>
45
+ all().filter(paygate => (requested == null || paygate.id === requested)
46
+ && planHelper.isSoldThrough(product, plan, paygate.id)
47
+ && (plan.recurring == null || paygate.subscriptions != null))
48
+
49
+ return { find, get, all, forSale }
50
+ }
51
+
52
+ /** The paygates of a context — one registry per context. */
53
+ export const paygatesOf = memoHelper.oncePer(makePaygateRegistry)