@owlmeans/server-payment 0.1.18-rc.8 → 0.1.18

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 (537) hide show
  1. package/README.md +157 -26
  2. package/agent-meta/manifest.json +30 -4
  3. package/agent-meta/skills/server-payment/SKILL.md +613 -54
  4. package/agent-meta/skills/server-payment/parts/reference.md +174 -0
  5. package/build/access/types.d.ts +46 -0
  6. package/build/access/types.d.ts.map +1 -0
  7. package/build/access/types.js +2 -0
  8. package/build/access/types.js.map +1 -0
  9. package/build/access.d.ts +6 -0
  10. package/build/access.d.ts.map +1 -0
  11. package/build/access.js +45 -0
  12. package/build/access.js.map +1 -0
  13. package/build/actions/index.d.ts +1 -0
  14. package/build/actions/index.d.ts.map +1 -1
  15. package/build/actions/index.js +1 -0
  16. package/build/actions/index.js.map +1 -1
  17. package/build/actions/resync-subscriptions.d.ts +3 -0
  18. package/build/actions/resync-subscriptions.d.ts.map +1 -0
  19. package/build/actions/resync-subscriptions.js +7 -0
  20. package/build/actions/resync-subscriptions.js.map +1 -0
  21. package/build/actions/resync.d.ts +6 -1
  22. package/build/actions/resync.d.ts.map +1 -1
  23. package/build/actions/resync.js +15 -5
  24. package/build/actions/resync.js.map +1 -1
  25. package/build/actions/webhook.d.ts +2 -1
  26. package/build/actions/webhook.d.ts.map +1 -1
  27. package/build/actions/webhook.js +10 -4
  28. package/build/actions/webhook.js.map +1 -1
  29. package/build/bootstrap/types.d.ts +16 -0
  30. package/build/bootstrap/types.d.ts.map +1 -0
  31. package/build/bootstrap/types.js +2 -0
  32. package/build/bootstrap/types.js.map +1 -0
  33. package/build/bootstrap.d.ts +6 -0
  34. package/build/bootstrap.d.ts.map +1 -0
  35. package/build/bootstrap.js +26 -0
  36. package/build/bootstrap.js.map +1 -0
  37. package/build/catalogue/types.d.ts +38 -0
  38. package/build/catalogue/types.d.ts.map +1 -0
  39. package/build/catalogue/types.js +2 -0
  40. package/build/catalogue/types.js.map +1 -0
  41. package/build/catalogue.d.ts +6 -0
  42. package/build/catalogue.d.ts.map +1 -0
  43. package/build/catalogue.js +110 -0
  44. package/build/catalogue.js.map +1 -0
  45. package/build/commit/types.d.ts +22 -0
  46. package/build/commit/types.d.ts.map +1 -0
  47. package/build/commit/types.js +2 -0
  48. package/build/commit/types.js.map +1 -0
  49. package/build/commit.d.ts +6 -0
  50. package/build/commit.d.ts.map +1 -0
  51. package/build/commit.js +125 -0
  52. package/build/commit.js.map +1 -0
  53. package/build/config.d.ts +44 -5
  54. package/build/config.d.ts.map +1 -1
  55. package/build/config.js +216 -10
  56. package/build/config.js.map +1 -1
  57. package/build/consts.d.ts +74 -16
  58. package/build/consts.d.ts.map +1 -1
  59. package/build/consts.js +86 -23
  60. package/build/consts.js.map +1 -1
  61. package/build/consts.local.d.ts +94 -0
  62. package/build/consts.local.d.ts.map +1 -0
  63. package/build/consts.local.js +44 -0
  64. package/build/consts.local.js.map +1 -0
  65. package/build/consumer/cancellation/types.d.ts +11 -0
  66. package/build/consumer/cancellation/types.d.ts.map +1 -0
  67. package/build/consumer/cancellation/types.js +2 -0
  68. package/build/consumer/cancellation/types.js.map +1 -0
  69. package/build/consumer/cancellation.d.ts +6 -0
  70. package/build/consumer/cancellation.d.ts.map +1 -0
  71. package/build/consumer/cancellation.js +33 -0
  72. package/build/consumer/cancellation.js.map +1 -0
  73. package/build/consumer/capture/types.d.ts +50 -0
  74. package/build/consumer/capture/types.d.ts.map +1 -0
  75. package/build/consumer/capture/types.js +2 -0
  76. package/build/consumer/capture/types.js.map +1 -0
  77. package/build/consumer/capture.d.ts +6 -0
  78. package/build/consumer/capture.d.ts.map +1 -0
  79. package/build/consumer/capture.js +284 -0
  80. package/build/consumer/capture.js.map +1 -0
  81. package/build/consumer/consts.local.d.ts +10 -0
  82. package/build/consumer/consts.local.d.ts.map +1 -0
  83. package/build/consumer/consts.local.js +11 -0
  84. package/build/consumer/consts.local.js.map +1 -0
  85. package/build/consumer/format/types.d.ts +30 -0
  86. package/build/consumer/format/types.d.ts.map +1 -0
  87. package/build/consumer/format/types.js +2 -0
  88. package/build/consumer/format/types.js.map +1 -0
  89. package/build/consumer/format.d.ts +4 -0
  90. package/build/consumer/format.d.ts.map +1 -0
  91. package/build/consumer/format.js +73 -0
  92. package/build/consumer/format.js.map +1 -0
  93. package/build/consumer/handlers.d.ts +21 -0
  94. package/build/consumer/handlers.d.ts.map +1 -0
  95. package/build/consumer/handlers.js +174 -0
  96. package/build/consumer/handlers.js.map +1 -0
  97. package/build/consumer/index.d.ts +10 -0
  98. package/build/consumer/index.d.ts.map +1 -0
  99. package/build/consumer/index.js +6 -0
  100. package/build/consumer/index.js.map +1 -0
  101. package/build/consumer/mail/types.d.ts +29 -0
  102. package/build/consumer/mail/types.d.ts.map +1 -0
  103. package/build/consumer/mail/types.js +2 -0
  104. package/build/consumer/mail/types.js.map +1 -0
  105. package/build/consumer/mail.d.ts +6 -0
  106. package/build/consumer/mail.d.ts.map +1 -0
  107. package/build/consumer/mail.js +313 -0
  108. package/build/consumer/mail.js.map +1 -0
  109. package/build/consumer/observers/types.d.ts +15 -0
  110. package/build/consumer/observers/types.d.ts.map +1 -0
  111. package/build/consumer/observers/types.js +2 -0
  112. package/build/consumer/observers/types.js.map +1 -0
  113. package/build/consumer/observers.d.ts +6 -0
  114. package/build/consumer/observers.d.ts.map +1 -0
  115. package/build/consumer/observers.js +74 -0
  116. package/build/consumer/observers.js.map +1 -0
  117. package/build/consumer/origin/types.d.ts +17 -0
  118. package/build/consumer/origin/types.d.ts.map +1 -0
  119. package/build/consumer/origin/types.js +2 -0
  120. package/build/consumer/origin/types.js.map +1 -0
  121. package/build/consumer/origin.d.ts +8 -0
  122. package/build/consumer/origin.d.ts.map +1 -0
  123. package/build/consumer/origin.js +43 -0
  124. package/build/consumer/origin.js.map +1 -0
  125. package/build/consumer/reconcile/types.d.ts +13 -0
  126. package/build/consumer/reconcile/types.d.ts.map +1 -0
  127. package/build/consumer/reconcile/types.js +2 -0
  128. package/build/consumer/reconcile/types.js.map +1 -0
  129. package/build/consumer/reconcile.d.ts +5 -0
  130. package/build/consumer/reconcile.d.ts.map +1 -0
  131. package/build/consumer/reconcile.js +320 -0
  132. package/build/consumer/reconcile.js.map +1 -0
  133. package/build/consumer/records/types.d.ts +66 -0
  134. package/build/consumer/records/types.d.ts.map +1 -0
  135. package/build/consumer/records/types.js +2 -0
  136. package/build/consumer/records/types.js.map +1 -0
  137. package/build/consumer/records.d.ts +6 -0
  138. package/build/consumer/records.d.ts.map +1 -0
  139. package/build/consumer/records.js +243 -0
  140. package/build/consumer/records.js.map +1 -0
  141. package/build/consumer/service.d.ts +28 -0
  142. package/build/consumer/service.d.ts.map +1 -0
  143. package/build/consumer/service.js +706 -0
  144. package/build/consumer/service.js.map +1 -0
  145. package/build/consumer/types.d.ts +84 -0
  146. package/build/consumer/types.d.ts.map +1 -0
  147. package/build/consumer/types.js +2 -0
  148. package/build/consumer/types.js.map +1 -0
  149. package/build/consumer/types.local.d.ts +26 -0
  150. package/build/consumer/types.local.d.ts.map +1 -0
  151. package/build/consumer/types.local.js +2 -0
  152. package/build/consumer/types.local.js.map +1 -0
  153. package/build/consumer/withdrawal/types.d.ts +36 -0
  154. package/build/consumer/withdrawal/types.d.ts.map +1 -0
  155. package/build/consumer/withdrawal/types.js +2 -0
  156. package/build/consumer/withdrawal/types.js.map +1 -0
  157. package/build/consumer/withdrawal.d.ts +6 -0
  158. package/build/consumer/withdrawal.d.ts.map +1 -0
  159. package/build/consumer/withdrawal.js +237 -0
  160. package/build/consumer/withdrawal.js.map +1 -0
  161. package/build/entitlement.d.ts +4 -0
  162. package/build/entitlement.d.ts.map +1 -0
  163. package/build/entitlement.js +72 -0
  164. package/build/entitlement.js.map +1 -0
  165. package/build/entrypoints.d.ts +19 -2
  166. package/build/entrypoints.d.ts.map +1 -1
  167. package/build/entrypoints.js +16 -4
  168. package/build/entrypoints.js.map +1 -1
  169. package/build/gate/request.d.ts +4 -0
  170. package/build/gate/request.d.ts.map +1 -0
  171. package/build/gate/request.js +17 -0
  172. package/build/gate/request.js.map +1 -0
  173. package/build/gate/types.d.ts +15 -0
  174. package/build/gate/types.d.ts.map +1 -0
  175. package/build/gate/types.js +2 -0
  176. package/build/gate/types.js.map +1 -0
  177. package/build/gate.d.ts +13 -9
  178. package/build/gate.d.ts.map +1 -1
  179. package/build/gate.js +36 -21
  180. package/build/gate.js.map +1 -1
  181. package/build/index.d.ts +50 -3
  182. package/build/index.d.ts.map +1 -1
  183. package/build/index.js +29 -3
  184. package/build/index.js.map +1 -1
  185. package/build/limit.d.ts +11 -0
  186. package/build/limit.d.ts.map +1 -0
  187. package/build/limit.js +48 -0
  188. package/build/limit.js.map +1 -0
  189. package/build/log.d.ts +3 -0
  190. package/build/log.d.ts.map +1 -0
  191. package/build/log.js +4 -0
  192. package/build/log.js.map +1 -0
  193. package/build/models/declarations/types.d.ts +22 -0
  194. package/build/models/declarations/types.d.ts.map +1 -0
  195. package/build/models/declarations/types.js +2 -0
  196. package/build/models/declarations/types.js.map +1 -0
  197. package/build/models/declarations.d.ts +4 -0
  198. package/build/models/declarations.d.ts.map +1 -0
  199. package/build/models/declarations.js +26 -0
  200. package/build/models/declarations.js.map +1 -0
  201. package/build/models/purchase/types.d.ts +13 -0
  202. package/build/models/purchase/types.d.ts.map +1 -0
  203. package/build/models/purchase/types.js +2 -0
  204. package/build/models/purchase/types.js.map +1 -0
  205. package/build/models/purchase.d.ts +4 -0
  206. package/build/models/purchase.d.ts.map +1 -0
  207. package/build/models/purchase.js +37 -0
  208. package/build/models/purchase.js.map +1 -0
  209. package/build/observer.d.ts +9 -0
  210. package/build/observer.d.ts.map +1 -1
  211. package/build/observer.js +38 -12
  212. package/build/observer.js.map +1 -1
  213. package/build/plan/types.d.ts +21 -0
  214. package/build/plan/types.d.ts.map +1 -0
  215. package/build/plan/types.js +2 -0
  216. package/build/plan/types.js.map +1 -0
  217. package/build/plan.d.ts +7 -0
  218. package/build/plan.d.ts.map +1 -0
  219. package/build/plan.js +29 -0
  220. package/build/plan.js.map +1 -0
  221. package/build/plugins/checkout-plugins/types.d.ts +25 -0
  222. package/build/plugins/checkout-plugins/types.d.ts.map +1 -0
  223. package/build/plugins/checkout-plugins/types.js +2 -0
  224. package/build/plugins/checkout-plugins/types.js.map +1 -0
  225. package/build/plugins/checkout-plugins.d.ts +12 -0
  226. package/build/plugins/checkout-plugins.d.ts.map +1 -0
  227. package/build/plugins/checkout-plugins.js +72 -0
  228. package/build/plugins/checkout-plugins.js.map +1 -0
  229. package/build/plugins/checkout-policy/types.d.ts +18 -0
  230. package/build/plugins/checkout-policy/types.d.ts.map +1 -0
  231. package/build/plugins/checkout-policy/types.js +2 -0
  232. package/build/plugins/checkout-policy/types.js.map +1 -0
  233. package/build/plugins/checkout-policy.d.ts +4 -0
  234. package/build/plugins/checkout-policy.d.ts.map +1 -0
  235. package/build/plugins/checkout-policy.js +26 -0
  236. package/build/plugins/checkout-policy.js.map +1 -0
  237. package/build/plugins/checkout-registry/types.d.ts +7 -0
  238. package/build/plugins/checkout-registry/types.d.ts.map +1 -0
  239. package/build/plugins/checkout-registry/types.js +2 -0
  240. package/build/plugins/checkout-registry/types.js.map +1 -0
  241. package/build/plugins/checkout-registry.d.ts +8 -0
  242. package/build/plugins/checkout-registry.d.ts.map +1 -0
  243. package/build/plugins/checkout-registry.js +21 -0
  244. package/build/plugins/checkout-registry.js.map +1 -0
  245. package/build/plugins/consts.local.d.ts +13 -0
  246. package/build/plugins/consts.local.d.ts.map +1 -0
  247. package/build/plugins/consts.local.js +22 -0
  248. package/build/plugins/consts.local.js.map +1 -0
  249. package/build/plugins/customer-lock/types.d.ts +6 -0
  250. package/build/plugins/customer-lock/types.d.ts.map +1 -0
  251. package/build/plugins/customer-lock/types.js +2 -0
  252. package/build/plugins/customer-lock/types.js.map +1 -0
  253. package/build/plugins/customer-lock.d.ts +5 -0
  254. package/build/plugins/customer-lock.d.ts.map +1 -0
  255. package/build/plugins/customer-lock.js +22 -0
  256. package/build/plugins/customer-lock.js.map +1 -0
  257. package/build/plugins/estimate/cache.d.ts +4 -0
  258. package/build/plugins/estimate/cache.d.ts.map +1 -0
  259. package/build/plugins/estimate/cache.js +7 -0
  260. package/build/plugins/estimate/cache.js.map +1 -0
  261. package/build/plugins/estimate/types.d.ts +27 -0
  262. package/build/plugins/estimate/types.d.ts.map +1 -0
  263. package/build/plugins/estimate/types.js +2 -0
  264. package/build/plugins/estimate/types.js.map +1 -0
  265. package/build/plugins/estimate.d.ts +6 -0
  266. package/build/plugins/estimate.d.ts.map +1 -0
  267. package/build/plugins/estimate.js +271 -0
  268. package/build/plugins/estimate.js.map +1 -0
  269. package/build/plugins/events/types.d.ts +12 -0
  270. package/build/plugins/events/types.d.ts.map +1 -0
  271. package/build/plugins/events/types.js +2 -0
  272. package/build/plugins/events/types.js.map +1 -0
  273. package/build/plugins/events.d.ts +6 -13
  274. package/build/plugins/events.d.ts.map +1 -1
  275. package/build/plugins/events.js +441 -144
  276. package/build/plugins/events.js.map +1 -1
  277. package/build/plugins/fx/types.d.ts +33 -0
  278. package/build/plugins/fx/types.d.ts.map +1 -0
  279. package/build/plugins/fx/types.js +2 -0
  280. package/build/plugins/fx/types.js.map +1 -0
  281. package/build/plugins/fx.d.ts +6 -0
  282. package/build/plugins/fx.d.ts.map +1 -0
  283. package/build/plugins/fx.js +83 -0
  284. package/build/plugins/fx.js.map +1 -0
  285. package/build/plugins/portal/types.d.ts +44 -0
  286. package/build/plugins/portal/types.d.ts.map +1 -0
  287. package/build/plugins/portal/types.js +2 -0
  288. package/build/plugins/portal/types.js.map +1 -0
  289. package/build/plugins/portal.d.ts +6 -0
  290. package/build/plugins/portal.d.ts.map +1 -0
  291. package/build/plugins/portal.js +255 -0
  292. package/build/plugins/portal.js.map +1 -0
  293. package/build/plugins/refunds/types.d.ts +35 -0
  294. package/build/plugins/refunds/types.d.ts.map +1 -0
  295. package/build/plugins/refunds/types.js +2 -0
  296. package/build/plugins/refunds/types.js.map +1 -0
  297. package/build/plugins/refunds.d.ts +6 -0
  298. package/build/plugins/refunds.d.ts.map +1 -0
  299. package/build/plugins/refunds.js +81 -0
  300. package/build/plugins/refunds.js.map +1 -0
  301. package/build/plugins/session/types.d.ts +32 -0
  302. package/build/plugins/session/types.d.ts.map +1 -0
  303. package/build/plugins/session/types.js +2 -0
  304. package/build/plugins/session/types.js.map +1 -0
  305. package/build/plugins/session.d.ts +4 -0
  306. package/build/plugins/session.d.ts.map +1 -0
  307. package/build/plugins/session.js +58 -0
  308. package/build/plugins/session.js.map +1 -0
  309. package/build/plugins/status.d.ts +8 -0
  310. package/build/plugins/status.d.ts.map +1 -0
  311. package/build/plugins/status.js +21 -0
  312. package/build/plugins/status.js.map +1 -0
  313. package/build/plugins/stripe/types.d.ts +20 -0
  314. package/build/plugins/stripe/types.d.ts.map +1 -0
  315. package/build/plugins/stripe/types.js +2 -0
  316. package/build/plugins/stripe/types.js.map +1 -0
  317. package/build/plugins/stripe.d.ts +5 -13
  318. package/build/plugins/stripe.d.ts.map +1 -1
  319. package/build/plugins/stripe.js +481 -129
  320. package/build/plugins/stripe.js.map +1 -1
  321. package/build/plugins/subscriptions/types.d.ts +41 -0
  322. package/build/plugins/subscriptions/types.d.ts.map +1 -0
  323. package/build/plugins/subscriptions/types.js +2 -0
  324. package/build/plugins/subscriptions/types.js.map +1 -0
  325. package/build/plugins/subscriptions.d.ts +6 -0
  326. package/build/plugins/subscriptions.d.ts.map +1 -0
  327. package/build/plugins/subscriptions.js +169 -0
  328. package/build/plugins/subscriptions.js.map +1 -0
  329. package/build/plugins/types.d.ts +7 -0
  330. package/build/plugins/types.d.ts.map +1 -0
  331. package/build/plugins/types.js +2 -0
  332. package/build/plugins/types.js.map +1 -0
  333. package/build/plugins/types.local.d.ts +75 -0
  334. package/build/plugins/types.local.d.ts.map +1 -0
  335. package/build/plugins/types.local.js +2 -0
  336. package/build/plugins/types.local.js.map +1 -0
  337. package/build/plugins/webhook-manager/types.d.ts +62 -0
  338. package/build/plugins/webhook-manager/types.d.ts.map +1 -0
  339. package/build/plugins/webhook-manager/types.js +2 -0
  340. package/build/plugins/webhook-manager/types.js.map +1 -0
  341. package/build/plugins/webhook-manager.d.ts +8 -0
  342. package/build/plugins/webhook-manager.d.ts.map +1 -0
  343. package/build/plugins/webhook-manager.js +245 -0
  344. package/build/plugins/webhook-manager.js.map +1 -0
  345. package/build/protocol.d.ts +13 -0
  346. package/build/protocol.d.ts.map +1 -0
  347. package/build/protocol.js +17 -0
  348. package/build/protocol.js.map +1 -0
  349. package/build/reconcile/types.d.ts +17 -0
  350. package/build/reconcile/types.d.ts.map +1 -0
  351. package/build/reconcile/types.js +2 -0
  352. package/build/reconcile/types.js.map +1 -0
  353. package/build/reconcile.d.ts +12 -0
  354. package/build/reconcile.d.ts.map +1 -0
  355. package/build/reconcile.js +91 -0
  356. package/build/reconcile.js.map +1 -0
  357. package/build/resource.d.ts +12 -1
  358. package/build/resource.d.ts.map +1 -1
  359. package/build/resource.js +97 -6
  360. package/build/resource.js.map +1 -1
  361. package/build/schemas.d.ts +19 -0
  362. package/build/schemas.d.ts.map +1 -0
  363. package/build/schemas.js +244 -0
  364. package/build/schemas.js.map +1 -0
  365. package/build/service.d.ts +28 -3
  366. package/build/service.d.ts.map +1 -1
  367. package/build/service.js +140 -19
  368. package/build/service.js.map +1 -1
  369. package/build/subscription/types.d.ts +21 -0
  370. package/build/subscription/types.d.ts.map +1 -0
  371. package/build/subscription/types.js +2 -0
  372. package/build/subscription/types.js.map +1 -0
  373. package/build/subscription.d.ts +4 -0
  374. package/build/subscription.d.ts.map +1 -0
  375. package/build/subscription.js +84 -0
  376. package/build/subscription.js.map +1 -0
  377. package/build/sync/types.d.ts +25 -0
  378. package/build/sync/types.d.ts.map +1 -0
  379. package/build/sync/types.js +2 -0
  380. package/build/sync/types.js.map +1 -0
  381. package/build/sync.d.ts +4 -3
  382. package/build/sync.d.ts.map +1 -1
  383. package/build/sync.js +231 -79
  384. package/build/sync.js.map +1 -1
  385. package/build/types.d.ts +1258 -36
  386. package/build/types.d.ts.map +1 -1
  387. package/build/types.local.d.ts +22 -0
  388. package/build/types.local.d.ts.map +1 -0
  389. package/build/types.local.js +2 -0
  390. package/build/types.local.js.map +1 -0
  391. package/build/usage/types.d.ts +56 -0
  392. package/build/usage/types.d.ts.map +1 -0
  393. package/build/usage/types.js +2 -0
  394. package/build/usage/types.js.map +1 -0
  395. package/build/usage.d.ts +6 -0
  396. package/build/usage.d.ts.map +1 -0
  397. package/build/usage.js +365 -0
  398. package/build/usage.js.map +1 -0
  399. package/build/utils/types.d.ts +31 -0
  400. package/build/utils/types.d.ts.map +1 -0
  401. package/build/utils/types.js +2 -0
  402. package/build/utils/types.js.map +1 -0
  403. package/build/utils.d.ts +21 -7
  404. package/build/utils.d.ts.map +1 -1
  405. package/build/utils.js +56 -17
  406. package/build/utils.js.map +1 -1
  407. package/package.json +22 -17
  408. package/src/access/types.ts +52 -0
  409. package/src/access.ts +86 -0
  410. package/src/actions/index.ts +1 -0
  411. package/src/actions/resync-subscriptions.ts +10 -0
  412. package/src/actions/resync.ts +14 -5
  413. package/src/actions/webhook.ts +9 -4
  414. package/src/bootstrap/types.ts +16 -0
  415. package/src/bootstrap.ts +31 -0
  416. package/src/catalogue/types.ts +32 -0
  417. package/src/catalogue.ts +135 -0
  418. package/src/commit/types.ts +27 -0
  419. package/src/commit.ts +152 -0
  420. package/src/config.ts +234 -14
  421. package/src/consts.local.ts +62 -0
  422. package/src/consts.ts +100 -36
  423. package/src/consumer/cancellation/types.ts +13 -0
  424. package/src/consumer/cancellation.ts +43 -0
  425. package/src/consumer/capture/types.ts +53 -0
  426. package/src/consumer/capture.ts +321 -0
  427. package/src/consumer/consts.local.ts +18 -0
  428. package/src/consumer/format/types.ts +29 -0
  429. package/src/consumer/format.ts +85 -0
  430. package/src/consumer/handlers.ts +204 -0
  431. package/src/consumer/index.ts +9 -0
  432. package/src/consumer/mail/types.ts +31 -0
  433. package/src/consumer/mail.ts +353 -0
  434. package/src/consumer/observers/types.ts +22 -0
  435. package/src/consumer/observers.ts +97 -0
  436. package/src/consumer/origin/types.ts +17 -0
  437. package/src/consumer/origin.ts +61 -0
  438. package/src/consumer/reconcile/types.ts +13 -0
  439. package/src/consumer/reconcile.ts +330 -0
  440. package/src/consumer/records/types.ts +64 -0
  441. package/src/consumer/records.ts +288 -0
  442. package/src/consumer/service.ts +768 -0
  443. package/src/consumer/types.local.ts +22 -0
  444. package/src/consumer/types.ts +96 -0
  445. package/src/consumer/withdrawal/types.ts +37 -0
  446. package/src/consumer/withdrawal.ts +268 -0
  447. package/src/entitlement.ts +85 -0
  448. package/src/entrypoints.ts +17 -4
  449. package/src/gate/request.ts +24 -0
  450. package/src/gate/types.ts +13 -0
  451. package/src/gate.ts +47 -30
  452. package/src/index.ts +55 -3
  453. package/src/limit.ts +54 -0
  454. package/src/log.ts +4 -0
  455. package/src/models/declarations/types.ts +22 -0
  456. package/src/models/declarations.ts +30 -0
  457. package/src/models/purchase/types.ts +13 -0
  458. package/src/models/purchase.ts +43 -0
  459. package/src/observer.ts +44 -11
  460. package/src/plan/types.ts +21 -0
  461. package/src/plan.ts +46 -0
  462. package/src/plugins/checkout-plugins/types.ts +25 -0
  463. package/src/plugins/checkout-plugins.ts +90 -0
  464. package/src/plugins/checkout-policy/types.ts +18 -0
  465. package/src/plugins/checkout-policy.ts +34 -0
  466. package/src/plugins/checkout-registry/types.ts +7 -0
  467. package/src/plugins/checkout-registry.ts +23 -0
  468. package/src/plugins/consts.local.ts +30 -0
  469. package/src/plugins/customer-lock/types.ts +5 -0
  470. package/src/plugins/customer-lock.ts +25 -0
  471. package/src/plugins/estimate/cache.ts +12 -0
  472. package/src/plugins/estimate/types.ts +28 -0
  473. package/src/plugins/estimate.ts +305 -0
  474. package/src/plugins/events/types.ts +11 -0
  475. package/src/plugins/events.ts +466 -132
  476. package/src/plugins/fx/types.ts +40 -0
  477. package/src/plugins/fx.ts +101 -0
  478. package/src/plugins/portal/types.ts +45 -0
  479. package/src/plugins/portal.ts +284 -0
  480. package/src/plugins/refunds/types.ts +31 -0
  481. package/src/plugins/refunds.ts +95 -0
  482. package/src/plugins/session/types.ts +28 -0
  483. package/src/plugins/session.ts +73 -0
  484. package/src/plugins/status.ts +22 -0
  485. package/src/plugins/stripe/types.ts +20 -0
  486. package/src/plugins/stripe.ts +523 -135
  487. package/src/plugins/subscriptions/types.ts +39 -0
  488. package/src/plugins/subscriptions.ts +195 -0
  489. package/src/plugins/types.local.ts +61 -0
  490. package/src/plugins/types.ts +7 -0
  491. package/src/plugins/webhook-manager/types.ts +63 -0
  492. package/src/plugins/webhook-manager.ts +288 -0
  493. package/src/protocol.ts +29 -0
  494. package/src/reconcile/types.ts +17 -0
  495. package/src/reconcile.ts +110 -0
  496. package/src/resource.ts +158 -11
  497. package/src/schemas.ts +271 -0
  498. package/src/service.ts +161 -19
  499. package/src/subscription/types.ts +23 -0
  500. package/src/subscription.ts +104 -0
  501. package/src/sync/types.ts +25 -0
  502. package/src/sync.ts +255 -72
  503. package/src/types.local.ts +18 -0
  504. package/src/types.ts +1365 -32
  505. package/src/usage/types.ts +51 -0
  506. package/src/usage.ts +432 -0
  507. package/src/utils/types.ts +30 -0
  508. package/src/utils.ts +94 -29
  509. package/tests/checkout-consumer.spec.ts +366 -0
  510. package/tests/checkout-locks.spec.ts +161 -0
  511. package/tests/checkout-plugins.spec.ts +164 -0
  512. package/tests/checkout.spec.ts +209 -93
  513. package/tests/consumer-events.spec.ts +215 -0
  514. package/tests/consumer-fixtures.ts +134 -0
  515. package/tests/consumer-ops.spec.ts +350 -0
  516. package/tests/consumer-rights.integration.spec.ts +147 -0
  517. package/tests/consumer-rights.spec.ts +572 -0
  518. package/tests/context.ts +110 -0
  519. package/tests/entitlement.spec.ts +139 -0
  520. package/tests/estimate.spec.ts +350 -0
  521. package/tests/events.spec.ts +357 -0
  522. package/tests/fake-stripe.ts +981 -0
  523. package/tests/gate-handlers.spec.ts +120 -0
  524. package/tests/gate.spec.ts +63 -72
  525. package/tests/gateway-options.spec.ts +180 -0
  526. package/tests/limit-gate.spec.ts +66 -0
  527. package/tests/portal.spec.ts +202 -0
  528. package/tests/protocol.spec.ts +17 -3
  529. package/tests/sync.spec.ts +114 -0
  530. package/tests/usage.integration.spec.ts +133 -0
  531. package/tests/usage.spec.ts +169 -0
  532. package/tests/webhook-manager.spec.ts +149 -0
  533. package/build/model.d.ts +0 -6
  534. package/build/model.d.ts.map +0 -1
  535. package/build/model.js +0 -33
  536. package/build/model.js.map +0 -1
  537. package/src/model.ts +0 -37
@@ -0,0 +1,22 @@
1
+ import type Stripe from 'stripe'
2
+ import type { AbstractRequest } from '@owlmeans/entrypoint'
3
+ import type { ConsumerRightsOptions } from '../types.js'
4
+
5
+ /** A paragraph, or a labelled link rendered as an anchor in HTML. */
6
+ export type Block = { text: string } | { label: string, url: string }
7
+
8
+ export interface Rendered {
9
+ subject: string
10
+ blocks: Block[]
11
+ }
12
+
13
+ export type Headers = AbstractRequest['headers']
14
+
15
+ /** 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 }
@@ -0,0 +1,96 @@
1
+ import type { ServerProtocolEntrypoint } from '@owlmeans/server-entrypoint'
2
+ import type { EntrypointProtocolDeclaration } from '@owlmeans/entrypoint'
3
+ import type {
4
+ ConsumerRightsAccountProtocols, ConsumerRightsPublicProtocols, WithdrawalEstimate,
5
+ } from '@owlmeans/payment'
6
+ import type { Context as ApiContext } from '@owlmeans/server-api'
7
+ import type Stripe from 'stripe'
8
+ import type {
9
+ PurchaseRecord, BillingProfileRecord, BillingProfileSource, LockOptions, UsageMeter, UsageReading,
10
+ } from '../types.js'
11
+
12
+ /** What a completed Checkout Session says about its buyer and totals. */
13
+ export interface SessionEvidence {
14
+ country?: string
15
+ email?: string
16
+ name?: string
17
+ business?: boolean
18
+ currency: string
19
+ subtotalMinor: number
20
+ taxMinor: number
21
+ totalMinor: number
22
+ presentmentCurrency?: string
23
+ presentmentAmountMinor?: number
24
+ termsAccepted?: boolean
25
+ }
26
+
27
+ /** What an invoice adds to a purchase: its number, its line and the payment behind it. */
28
+ export interface InvoiceEvidence {
29
+ invoiceNumber?: string
30
+ invoiceLineId?: string
31
+ paymentIntentId?: string
32
+ country?: string
33
+ subtotalMinor?: number
34
+ taxMinor?: number
35
+ totalMinor?: number
36
+ currency?: string
37
+ }
38
+
39
+ export interface CapturedPurchase {
40
+ purchase: PurchaseRecord
41
+ created: boolean
42
+ }
43
+
44
+ export type Bound = ServerProtocolEntrypoint<EntrypointProtocolDeclaration>
45
+
46
+ /** The protocol tree `makeConsumerRightsProtocols` builds, with or without its public subtree. */
47
+ export interface ConsumerRightsTree extends ConsumerRightsAccountProtocols { public?: ConsumerRightsPublicProtocols }
48
+
49
+ export interface LockInput extends LockOptions {
50
+ entityId: string
51
+ country: string
52
+ source: BillingProfileSource
53
+ }
54
+
55
+ export interface LockResult {
56
+ record: BillingProfileRecord
57
+ created: boolean
58
+ /** The lock exists with another country: recorded as `lock-mismatch`, never relocked. */
59
+ mismatch: boolean
60
+ }
61
+
62
+ export interface PurchaseDraft extends Omit<PurchaseRecord, 'id' | 'contractRef' | 'createdAt'> {}
63
+
64
+ export interface ConsumerRightsInternals {
65
+ readonly managed: boolean
66
+ meter: () => UsageMeter | null
67
+ stripe: (ctx: ApiContext) => Promise<Stripe>
68
+ }
69
+
70
+ /** Who hands a registration its options: the application itself, or the gateway on its behalf. */
71
+ export type ConsumerRightsRegistrar = 'application' | 'gateway'
72
+
73
+ /** What a withdrawal of one purchase reimburses, as computed at one instant. */
74
+ export interface WithdrawalComputation {
75
+ reading: UsageReading
76
+ /** Gross, tax included — what is refunded. */
77
+ refundMinor: number
78
+ /** Net of tax — the credit note's line amount. */
79
+ netMinor: number
80
+ estimate: WithdrawalEstimate
81
+ /** The units the deduction counts: used after consent, plus settled debt and earlier claw-backs. */
82
+ deducted: number
83
+ /** What the application takes back from the balance: the purchase's units still unused. */
84
+ unitsReturned: number
85
+ }
86
+
87
+ export interface WithdrawalExecution {
88
+ /** Every paygate step succeeded (or had nothing to do). */
89
+ ok: boolean
90
+ refundId?: string
91
+ creditNoteId?: string
92
+ refundedMinor: number
93
+ subscriptionCanceled: boolean
94
+ /** A step can never succeed without an operator (no payment to refund). */
95
+ needsReview: boolean
96
+ }
@@ -0,0 +1,37 @@
1
+ import type Stripe from 'stripe'
2
+ import type { ConsumerDeclarationRecord, PurchaseRecord, UsageMeter } from '../../types.js'
3
+ import type { WithdrawalComputation, WithdrawalExecution } from '../types.js'
4
+
5
+ /** Withdrawals of a context: what they reimburse and their paygate steps. */
6
+ export interface WithdrawalHelper {
7
+ /**
8
+ * The refund of a withdrawal from one purchase, in the consumer's favour (`@owlmeans/payment`
9
+ * calculators). The meter's deduction is `usedAfter + settled + clawed`: units used after consent
10
+ * (before it the consumer bears no cost), units that paid an earlier overdraft, units already
11
+ * refunded by money. A subscription's `time` components count from its start request; without
12
+ * one nothing is deducted for time.
13
+ */
14
+ computeWithdrawal: (meter: UsageMeter, purchase: PurchaseRecord, at: Date) => Promise<WithdrawalComputation>
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):
18
+ *
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.
25
+ *
26
+ * Steps that already succeeded (a recorded `ok` event) are skipped. Every step is an event.
27
+ */
28
+ executeWithdrawal: (
29
+ stripe: Stripe, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
30
+ computation: { refundMinor: number, netMinor: number }, opts?: { attempt?: number },
31
+ ) => Promise<WithdrawalExecution>
32
+ /** Retry a credit note that failed after its refund succeeded. */
33
+ retryCreditNote: (
34
+ stripe: Stripe, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
35
+ netMinor: number, refundId: string, attempt: number,
36
+ ) => Promise<boolean>
37
+ }
@@ -0,0 +1,268 @@
1
+ import type Stripe from 'stripe'
2
+ import { PurchaseKind, type WithdrawalEstimate, consumerCopyHelper, withdrawalRefundHelper } from '@owlmeans/payment'
3
+ import type { Context as ApiContext } from '@owlmeans/server-api'
4
+ import { memoHelper } from '@owlmeans/context'
5
+ import { STRIPE_OWNER_KEY, STRIPE_OWNER_VALUE, STRIPE_PAYGATE_ALIAS } from '../consts.js'
6
+ import type { ConsumerDeclarationRecord, PaymentSubscriptionRecord, PurchaseRecord, UsageMeter } from '../types.js'
7
+ import { DAY_MS } from './consts.local.js'
8
+ import type { WithdrawalComputation, WithdrawalExecution } from './types.js'
9
+ import type { PinnedCreditNoteParams } from './types.local.js'
10
+ import { paymentAccessOf } from '../access.js'
11
+ import { paymentUtils } from '../utils.js'
12
+ import { catalogueOf } from '../catalogue.js'
13
+ import { consumerFormatHelper } from './format.js'
14
+ import { consumerRecordsOf } from './records.js'
15
+ import { makePurchaseModel } from '../models/purchase.js'
16
+ import type { ConsumerEventDraft } from './records/types.js'
17
+ import { captureOf } from './capture.js'
18
+ import type { WithdrawalHelper } from './withdrawal/types.js'
19
+
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
+ /**
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.
27
+ */
28
+ const keyOf = (withdrawalId: string, step: string, attempt: number): Stripe.RequestOptions => ({
29
+ idempotencyKey: attempt > 0 ? `withdrawal:${withdrawalId}:${step}:${attempt}` : `withdrawal:${withdrawalId}:${step}`,
30
+ })
31
+
32
+ export const makeWithdrawalHelper = (ctx: ApiContext): WithdrawalHelper => {
33
+ const access = paymentAccessOf(ctx)
34
+ const records = consumerRecordsOf(ctx)
35
+ const capture = captureOf(ctx)
36
+
37
+ const computeWithdrawal = async (
38
+ meter: UsageMeter, purchase: PurchaseRecord, at: Date,
39
+ ): Promise<WithdrawalComputation> => {
40
+ const reading = await meter.used(ctx, paymentUtils.compact({
41
+ entityId: purchase.entityId, purchase: makePurchaseModel(purchase).ref(),
42
+ after: purchase.consentedAt != null ? new Date(purchase.consentedAt) : undefined, at,
43
+ }))
44
+ const deducted = Math.max(0, reading.usedAfter) + Math.max(0, reading.settled ?? 0) + Math.max(0, reading.clawed ?? 0)
45
+ const unitsReturned = Math.max(0, Math.floor(reading.remaining
46
+ ?? reading.granted - reading.used - (reading.settled ?? 0) - (reading.clawed ?? 0)))
47
+ const paid = purchase.amountTotalMinor
48
+ const refunded = purchase.refundedMinor ?? 0
49
+ const net = purchase.amountSubtotalMinor
50
+ // The earlier refunds' net share, so the credit note never credits more than is left.
51
+ const refundedNet = paid > 0 ? Math.floor(refunded * net / paid) : 0
52
+
53
+ if (purchase.kind === PurchaseKind.TopUp) {
54
+ const gross = withdrawalRefundHelper.oneTimeWithdrawalRefund({ paidMinor: paid, refundedMinor: refunded, unitsGranted: reading.granted, unitsUsed: deducted })
55
+ const netRefund = withdrawalRefundHelper.oneTimeWithdrawalRefund({ paidMinor: net, refundedMinor: refundedNet, unitsGranted: reading.granted, unitsUsed: deducted })
56
+ const open = Math.max(0, paid - refunded)
57
+
58
+ return {
59
+ reading, deducted, unitsReturned,
60
+ refundMinor: gross.refundMinor,
61
+ netMinor: netRefund.refundMinor,
62
+ estimate: {
63
+ refundMinor: gross.refundMinor, currency: purchase.currency, timeDeductionMinor: 0,
64
+ unitsDeductionMinor: Math.max(0, open - gross.refundMinor),
65
+ unitsUsed: Math.min(deducted, reading.granted), unitsGranted: reading.granted,
66
+ },
67
+ }
68
+ }
69
+
70
+ const subscription = purchase.subscriptionId != null
71
+ ? await access.subscriptions().byExternalId(purchase.subscriptionId, STRIPE_PAYGATE_ALIAS) : null
72
+ const plan = purchase.planSku != null ? await catalogueOf(ctx).findPlan(purchase.planSku) : null
73
+ const purchasedAt = new Date(purchase.purchasedAt)
74
+ const periodStart = subscription?.periodStart != null ? new Date(subscription.periodStart) : purchasedAt
75
+ const periodEnd = subscription?.periodEnd != null ? new Date(subscription.periodEnd)
76
+ : new Date(periodStart.getTime() + (plan?.recurring?.interval === 'year' ? 365 : 30) * DAY_MS)
77
+ const result = withdrawalRefundHelper.subscriptionWithdrawalRefund({
78
+ paidMinor: paid, refundedMinor: refunded, netMinor: net,
79
+ components: plan?.withdrawal?.components,
80
+ periodStart, periodEnd,
81
+ servicesRequestedAt: purchase.servicesStartedAt != null ? new Date(purchase.servicesStartedAt) : null,
82
+ withdrawnAt: at,
83
+ units: { granted: reading.granted, used: deducted },
84
+ })
85
+
86
+ return {
87
+ reading, deducted, unitsReturned,
88
+ refundMinor: result.refundMinor,
89
+ netMinor: result.refundNetMinor,
90
+ estimate: paymentUtils.compact({
91
+ refundMinor: result.refundMinor, currency: purchase.currency, timeDeductionMinor: result.timeDeductionMinor,
92
+ unitsDeductionMinor: result.unitsDeductionMinor, elapsedDays: result.elapsedDays, periodDays: result.periodDays,
93
+ unitsUsed: result.unitsUsed, unitsGranted: result.unitsGranted,
94
+ }) as WithdrawalEstimate,
95
+ }
96
+ }
97
+
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
+ }
112
+
113
+ const executeWithdrawal = async (
114
+ stripe: Stripe, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
115
+ computation: { refundMinor: number, netMinor: number }, opts: { attempt?: number } = {},
116
+ ): Promise<WithdrawalExecution> => {
117
+ const withdrawalId = declaration.id as string
118
+ const attempt = opts.attempt ?? 0
119
+ const key = (step: string): Stripe.RequestOptions => keyOf(withdrawalId, step, attempt)
120
+ const event = (action: 'refund' | 'credit-note' | 'subscription-cancel', fields: Record<string, unknown>) =>
121
+ records.recordEvent({
122
+ recordId: withdrawalId, recordKind: 'declaration', entityId: purchase.entityId, action, ok: false, ...fields,
123
+ } as ConsumerEventDraft)
124
+ const outcome: WithdrawalExecution = { ok: true, refundedMinor: 0, subscriptionCanceled: false, needsReview: false }
125
+
126
+ if (purchase.kind === PurchaseKind.Subscription && purchase.subscriptionId != null) {
127
+ if (await records.hasEvent(withdrawalId, 'subscription-cancel', undefined, true)) {
128
+ outcome.subscriptionCanceled = true
129
+ } else {
130
+ try {
131
+ await stripe.subscriptions.cancel(purchase.subscriptionId, {
132
+ prorate: false, invoice_now: false, cancellation_details: { comment: `withdrawal:${withdrawalId}` },
133
+ }, key('subscription-cancel'))
134
+ outcome.subscriptionCanceled = true
135
+ await event('subscription-cancel', { ok: true, externalId: purchase.subscriptionId })
136
+ } 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
+ }
144
+ }
145
+ if (outcome.subscriptionCanceled) {
146
+ const row: PaymentSubscriptionRecord | null = await access.subscriptions().byExternalId(purchase.subscriptionId, STRIPE_PAYGATE_ALIAS)
147
+ if (row != null && row.withdrawnAt == null) {
148
+ await access.subscriptions().update({ ...row, withdrawnAt: new Date(declaration.receivedAt) })
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+ if (await records.hasEvent(withdrawalId, 'refund', undefined, true)) {
155
+ return { ...outcome, refundedMinor: declaration.refundMinor ?? computation.refundMinor }
156
+ }
157
+ if (computation.refundMinor <= 0) {
158
+ return outcome
159
+ }
160
+
161
+ let paymentIntentId = purchase.paymentIntentId
162
+ let invoiceLineId = purchase.invoiceLineId
163
+ if (purchase.invoiceId != null && (paymentIntentId == null || invoiceLineId == null)) {
164
+ const invoice = await capture.invoiceEvidenceOf(stripe, purchase.invoiceId)
165
+ paymentIntentId = paymentIntentId ?? invoice.paymentIntentId
166
+ invoiceLineId = invoiceLineId ?? invoice.invoiceLineId
167
+ await records.patchPurchase(purchase.purchaseId, paymentUtils.compact({
168
+ paymentIntentId, invoiceLineId, invoiceNumber: purchase.invoiceNumber ?? invoice.invoiceNumber,
169
+ }))
170
+ }
171
+ if (paymentIntentId == null) {
172
+ await event('refund', { error: 'no-payment-intent', amountMinor: computation.refundMinor, currency: purchase.currency })
173
+ return { ...outcome, ok: false, needsReview: true }
174
+ }
175
+
176
+ const open = Math.max(0, purchase.amountTotalMinor - (purchase.refundedMinor ?? 0))
177
+ 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 }]
181
+ try {
182
+ const preview = await stripe.creditNotes.preview({ invoice: purchase.invoiceId, lines })
183
+ amount = Math.min(open, preview.total)
184
+ } catch (error) {
185
+ lines = null
186
+ await event('credit-note', { step: 'preview', error: paymentUtils.errorText(error) })
187
+ }
188
+ }
189
+ if (amount <= 0) {
190
+ return outcome
191
+ }
192
+
193
+ let refund: Stripe.Refund
194
+ 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'))
200
+ } catch (error) {
201
+ await event('refund', { error: paymentUtils.errorText(error), amountMinor: amount, currency: purchase.currency })
202
+ return { ...outcome, ok: false }
203
+ }
204
+ await event('refund', { ok: true, externalId: refund.id, amountMinor: refund.amount, currency: refund.currency })
205
+ outcome.refundId = refund.id
206
+ outcome.refundedMinor = refund.amount
207
+
208
+ if (lines != null && purchase.invoiceId != null) {
209
+ 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
+ }),
215
+ metadata: { withdrawalId, purchaseId: purchase.purchaseId },
216
+ } as PinnedCreditNoteParams, key('credit-note'))
217
+ outcome.creditNoteId = note.id
218
+ await event('credit-note', { ok: true, externalId: note.id, amountMinor: note.total, currency: note.currency })
219
+ } catch (error) {
220
+ // The refund stands; the corrective document is retried by reconcile.
221
+ await event('credit-note', { error: paymentUtils.errorText(error), detail: JSON.stringify({ refundId: refund.id }) })
222
+ }
223
+ }
224
+
225
+ return outcome
226
+ }
227
+
228
+ const retryCreditNote = async (
229
+ stripe: Stripe, declaration: ConsumerDeclarationRecord, purchase: PurchaseRecord,
230
+ netMinor: number, refundId: string, attempt: number,
231
+ ): Promise<boolean> => {
232
+ const withdrawalId = declaration.id as string
233
+ let invoiceLineId = purchase.invoiceLineId
234
+ if (invoiceLineId == null && purchase.invoiceId != null) {
235
+ invoiceLineId = (await capture.invoiceEvidenceOf(stripe, purchase.invoiceId)).invoiceLineId
236
+ }
237
+ if (purchase.invoiceId == null || invoiceLineId == null || netMinor <= 0) {
238
+ return false
239
+ }
240
+ 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))
250
+ await records.recordEvent({
251
+ recordId: withdrawalId, recordKind: 'declaration', entityId: purchase.entityId, action: 'credit-note', ok: true,
252
+ externalId: note.id, amountMinor: note.total, currency: note.currency,
253
+ })
254
+ return true
255
+ } catch (error) {
256
+ await records.recordEvent({
257
+ recordId: withdrawalId, recordKind: 'declaration', entityId: purchase.entityId, action: 'credit-note', ok: false,
258
+ error: paymentUtils.errorText(error), detail: JSON.stringify({ refundId }),
259
+ })
260
+ return false
261
+ }
262
+ }
263
+
264
+ return { computeWithdrawal, executeWithdrawal, retryCreditNote }
265
+ }
266
+
267
+ /** The withdrawals of a context — one per context. */
268
+ export const withdrawalOf = memoHelper.oncePer(makeWithdrawalHelper)
@@ -0,0 +1,85 @@
1
+ import { createService } from '@owlmeans/context'
2
+ import { INTERNAL_PAYGATE, SubscriptionStatus, entitlementViewHelper, planLimitHelper } from '@owlmeans/payment'
3
+ import type { EntitlementPlanView, EntitlementView, LimitUsage } from '@owlmeans/payment'
4
+ import type { Context as ApiContext } from '@owlmeans/server-api'
5
+ import { ENTITLEMENT_SERVICE } from './consts.js'
6
+ import type { EffectivePlan, EntitlementService } from './types.js'
7
+ import { paymentAccessOf } from './access.js'
8
+ import { paymentUtils } from './utils.js'
9
+ import { catalogueOf } from './catalogue.js'
10
+ import { planHelper } from './plan.js'
11
+ import { usageOf } from './usage.js'
12
+
13
+ const dateOrUndefined = (value: Date | null | undefined): Date | undefined =>
14
+ value == null ? undefined : new Date(value)
15
+
16
+ /** The plan half of an entitlement view. `subscribedAt` is what a grandfathered promo is measured against. */
17
+ const planViewOf = (effective: EffectivePlan): EntitlementPlanView => {
18
+ const { plan, subscription, fallback } = effective
19
+ const status = subscription?.status ?? SubscriptionStatus.Active
20
+
21
+ return paymentUtils.compact<EntitlementPlanView>({
22
+ sku: plan.sku,
23
+ productSku: plan.productSku,
24
+ title: plan.title,
25
+ rank: planHelper.planRank(plan),
26
+ free: plan.free === true,
27
+ status,
28
+ paygate: subscription?.paygate ?? INTERNAL_PAYGATE,
29
+ subscriptionId: subscription?.externalId ?? undefined,
30
+ subscribedAt: dateOrUndefined(subscription?.createdAt),
31
+ periodStart: dateOrUndefined(subscription?.periodStart),
32
+ periodEnd: dateOrUndefined(subscription?.periodEnd),
33
+ cancelAtPeriodEnd: subscription?.cancelAtPeriodEnd ?? undefined,
34
+ trialEnd: dateOrUndefined(subscription?.trialEnd),
35
+ pausedAt: dateOrUndefined(subscription?.pausedAt),
36
+ pastDue: status === SubscriptionStatus.PastDue,
37
+ fallbackSku: plan.free !== true ? fallback?.sku : undefined,
38
+ })
39
+ }
40
+
41
+ /** Plan resolution, the entitlement view and the usage ledger — Mongo only, never the paygate. */
42
+ export const makeEntitlementService = (alias: string = ENTITLEMENT_SERVICE): EntitlementService => {
43
+ // What an entity may do now: its effective plan, every capability and every limit with its usage.
44
+ const entitlementViewFor = async (entityId: string): Promise<EntitlementView> => {
45
+ const ctx = ctxOf()
46
+ const at = new Date()
47
+ const effective = await catalogueOf(ctx).resolveEffectivePlan(entityId, at)
48
+ const declared = Object.entries(effective.plan.limits ?? {})
49
+ const windows = new Map(declared.map(([key, declaration]) => [
50
+ key, planLimitHelper.windowKeyOf(declaration.kind, declaration.window, at, effective.subscription?.createdAt),
51
+ ]))
52
+ const usage: LimitUsage[] = []
53
+ if (declared.length > 0) {
54
+ const { items } = await paymentAccessOf(ctx).usageCounters().list({
55
+ entityId, limitKey: [...windows.keys()], window: [...new Set(windows.values())],
56
+ }, { size: 0 })
57
+ for (const counter of items) {
58
+ if (windows.get(counter.limitKey) === counter.window) {
59
+ usage.push({ key: counter.limitKey, window: counter.window, used: counter.used })
60
+ }
61
+ }
62
+ }
63
+
64
+ return entitlementViewHelper.entitlementViewOf(effective.plan, planViewOf(effective), usage, at)
65
+ }
66
+
67
+ const service: EntitlementService = createService<EntitlementService>(alias, {
68
+ effectivePlan: async entityId => await catalogueOf(ctxOf()).resolveEffectivePlan(entityId),
69
+ entitlements: async entityId => await entitlementViewFor(entityId),
70
+ hasCapability: async (entityId, param) => planLimitHelper.capabilityOf(await entitlementViewFor(entityId), param),
71
+ limitState: async (entityId, key) => await usageOf(ctxOf()).limitStateOf(entityId, key),
72
+ consume: async req => await usageOf(ctxOf()).consumeLimit(req),
73
+ release: async req => await usageOf(ctxOf()).releaseLimit(req),
74
+ reconcileOccupancy: async (entityId, limitKey, actual) =>
75
+ await usageOf(ctxOf()).reconcileOccupancyOf(entityId, limitKey, actual),
76
+ reconcileCounters: async entityId => await usageOf(ctxOf()).reconcileLedgerCounters(entityId),
77
+ consumption: async (entityId, limitKey, eventKey) =>
78
+ await usageOf(ctxOf()).consumptionOf(entityId, limitKey, eventKey),
79
+ consumptionByRef: async (entityId, limitKey, ref) =>
80
+ await usageOf(ctxOf()).consumptionByRefOf(entityId, limitKey, ref),
81
+ })
82
+ const ctxOf = (): ApiContext => service.assertCtx() as unknown as ApiContext
83
+
84
+ return service
85
+ }
@@ -1,10 +1,23 @@
1
1
  import { bind } from '@owlmeans/server-entrypoint'
2
- import { paymentGate } from './consts.js'
3
- import { resync, webhook } from './actions/index.js'
2
+ import { resync, resyncSubscriptions, webhook } from './actions/index.js'
3
+ import { paymentGate } from './protocol.js'
4
+
5
+ /**
6
+ * The payment gate's action handlers, for an application that declares the gate itself — its own
7
+ * aliases, a route pinned to its own service: `bind(own.webhook, paymentGateHandlers.webhook)`.
8
+ *
9
+ * A handler reads its context from the entrypoint it is bound to, so the application's own
10
+ * declaration is the one registered, mounted and run. That declaration keeps `paymentGate`'s paths
11
+ * (`webhookUrlOf` registers the webhook at `paymentGate`'s path), contracts and guards. Bind each
12
+ * one with `bind` itself: `bindAll` pairs a handler with the declaration it was made for, by object
13
+ * identity, and leaves another declaration without one.
14
+ */
15
+ export const paymentGateHandlers = Object.freeze({ webhook, resync, resyncSubscriptions })
4
16
 
5
17
  /** Runtime-local bindings for the shared immutable payment-gateway protocol tree. */
6
18
  export const paymentGateEntrypoints = [
7
19
  bind(paymentGate.base),
8
- bind(paymentGate.webhook, webhook),
9
- bind(paymentGate.resync, resync),
20
+ bind(paymentGate.webhook, paymentGateHandlers.webhook),
21
+ bind(paymentGate.resync, paymentGateHandlers.resync),
22
+ bind(paymentGate.resyncSubscriptions, paymentGateHandlers.resyncSubscriptions),
10
23
  ]
@@ -0,0 +1,24 @@
1
+ import { AuthForbidden, type Auth, authHelper } from '@owlmeans/auth'
2
+ import type { AbstractRequest } from '@owlmeans/entrypoint'
3
+ import type { EntityResolverOption } from '../types.js'
4
+ import type { GateEntity, GateRequestScope } from './types.js'
5
+
6
+ export const makeGateRequestScope = (req: AbstractRequest): GateRequestScope => {
7
+ const defaultEntity = (): string | null =>
8
+ req.entity?.id ?? authHelper.entitySlugOf(req.auth as Auth | undefined) ?? null
9
+
10
+ const gateEntityOf = (opts?: EntityResolverOption): GateEntity => {
11
+ if (req.auth == null) {
12
+ throw new AuthForbidden('auth')
13
+ }
14
+ const resolve = opts?.resolveEntity
15
+ const entityId = resolve != null ? resolve(req) : defaultEntity()
16
+ if (entityId == null || entityId === '') {
17
+ throw new AuthForbidden('entity')
18
+ }
19
+
20
+ return { auth: req.auth, entityId }
21
+ }
22
+
23
+ return { defaultEntity, gateEntityOf }
24
+ }
@@ -0,0 +1,13 @@
1
+ import type { Auth } from '@owlmeans/auth'
2
+ import type { EntityResolverOption } from '../types.js'
3
+
4
+ /** The authenticated entity a gate asserts for. */
5
+ export interface GateEntity { auth: Auth, entityId: string }
6
+
7
+ /** One request as a payment gate reads it. */
8
+ export interface GateRequestScope {
9
+ /** The entity the request acts for by default: `req.entity.id`, else the token's entity. */
10
+ defaultEntity: () => string | null
11
+ /** Resolve the authenticated entity a gate asserts for, or refuse. @throws AuthForbidden */
12
+ gateEntityOf: (opts?: EntityResolverOption) => GateEntity
13
+ }