@owlmeans/server-payment 0.1.18-rc.9 → 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,706 @@
1
+ import { createLazyService } from '@owlmeans/context';
2
+ import { MAILER_SERVICE } from '@owlmeans/mailer';
3
+ 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, consumerCopyHelper, consumerRegionHelper, consumerRightsPolicyHelper } from '@owlmeans/payment';
4
+ import { CONSUMER_RIGHTS_SERVICE, STRIPE_PAYGATE_ALIAS } from '../consts.js';
5
+ import { CONSUMER_RIGHTS_RESOURCE_MAKERS } from '../resource.js';
6
+ import { makeConsumerReconcileHelper } from './reconcile.js';
7
+ import { log } from '../log.js';
8
+ import { paymentAccessOf } from '../access.js';
9
+ import { paymentUtils } from '../utils.js';
10
+ import { catalogueOf } from '../catalogue.js';
11
+ import { consumerFormatHelper } from './format.js';
12
+ import { originHelper } from './origin.js';
13
+ import { consumerRecordsOf } from './records.js';
14
+ import { makePurchaseModel } from '../models/purchase.js';
15
+ import { consumerMailOf } from './mail.js';
16
+ import { consumerObserversOf } from './observers.js';
17
+ import { cancellationOf } from './cancellation.js';
18
+ import { withdrawalOf } from './withdrawal.js';
19
+ const latestDeadline = (items) => {
20
+ const times = items.map(item => item.deadline != null ? new Date(item.deadline).getTime() : Number.NaN)
21
+ .filter(time => !Number.isNaN(time));
22
+ return times.length > 0 ? new Date(Math.max(...times)) : undefined;
23
+ };
24
+ /** Only what a person typed, echoed as the receipt's content — never enriched with a match. */
25
+ const contentOf = (fields) => Object.fromEntries(Object.entries(fields).filter((entry) => typeof entry[1] === 'string' && entry[1].trim() !== ''));
26
+ const publicReceipt = (declaration, content, mailed) => ({
27
+ declarationId: declaration.id,
28
+ receivedAt: new Date(declaration.receivedAt),
29
+ content,
30
+ mailed,
31
+ });
32
+ /** An e-mail value safe to prefill a form with. */
33
+ const prefillEmail = (email) => email != null && /^[^\s@]+@[^\s@]+$/.test(email) ? email : undefined;
34
+ /** A withdrawal receipt from its declaration (in-app), `status` as executed so far. */
35
+ const receiptOf = (declaration, content, mailed, status) => paymentUtils.compact({
36
+ ...publicReceipt(declaration, content, mailed),
37
+ status: status ?? declaration.status,
38
+ refundMinor: declaration.refundMinor ?? undefined,
39
+ currency: declaration.currency ?? undefined,
40
+ });
41
+ /** The late-configuration seam of every service `makeConsumerRightsService` made — module-private. */
42
+ const plumbers = new WeakMap();
43
+ /**
44
+ * The consumer-rights service (`CONSUMER_RIGHTS_SERVICE`): the billing profile and its lock,
45
+ * purchases and their withdrawal windows, performance consent and subscription start requests,
46
+ * the withdrawal and cancellation functions with their paygate steps, the durable-medium mails,
47
+ * and `reconcile`. Unmanaged (`manage: false`) it still reads, records consents and asserts them;
48
+ * withdrawing and cancelling need the paygate.
49
+ *
50
+ * A lazy service, like the completion observer: `useMeter` / `useMailRenderer` work while the
51
+ * application is still being wired, before the context initializes.
52
+ */
53
+ export const makeConsumerRightsService = (alias = CONSUMER_RIGHTS_SERVICE, opts = {}) => {
54
+ // `manage` by precedence: the application's own, else the gateway's, else managed.
55
+ let manageOwn = opts.manage;
56
+ let manageGateway;
57
+ const isManaged = () => (manageOwn ?? manageGateway) !== false;
58
+ let meter = opts.usage ?? null;
59
+ let stripeFactory = opts.stripe;
60
+ let renderer = null;
61
+ const stripeOf = async (ctx) => stripeFactory != null ? await stripeFactory(ctx) : await paymentAccessOf(ctx).stripeClient();
62
+ const internals = {
63
+ get managed() { return isManaged(); }, meter: () => meter, stripe: stripeOf,
64
+ };
65
+ const requirePolicy = async (ctx) => {
66
+ const policy = await paymentAccessOf(ctx).payment().consumerRightsPolicy();
67
+ if (policy == null) {
68
+ throw new ConsumerRightsError('policy:none');
69
+ }
70
+ return policy;
71
+ };
72
+ /** A contract a person quoted — a contract reference, else an invoice number. */
73
+ const purchaseByContract = async (ctx, contract) => {
74
+ const access = paymentAccessOf(ctx);
75
+ if (contract == null || contract.trim() === '') {
76
+ return null;
77
+ }
78
+ const reference = consumerFormatHelper.normalizeContractRef(contract);
79
+ return await access.purchases().load({ contractRef: reference })
80
+ ?? await access.purchases().load({ invoiceNumber: contract.trim() })
81
+ ?? await access.purchases().load({ invoiceNumber: contract.trim().toUpperCase() });
82
+ };
83
+ /** Public matching: the quoted contract, and an e-mail that belongs to it. */
84
+ const matchPublicPurchase = async (ctx, contract, email) => {
85
+ const purchase = await purchaseByContract(ctx, contract);
86
+ return purchase != null && await consumerRecordsOf(ctx).emailMatches(purchase, email) ? purchase : null;
87
+ };
88
+ /** The one organization whose paygate customer uses this e-mail — none when several do. */
89
+ const entityByEmail = async (ctx, email) => {
90
+ const wanted = consumerFormatHelper.normalizeEmail(email);
91
+ if (wanted === '') {
92
+ return null;
93
+ }
94
+ // Case-insensitive (`$ilike`, its `%`/`_`/`\` wildcards escaped): a paygate keeps the e-mail as typed.
95
+ const pattern = wanted.replace(/[\\%_]/g, match => `\\${match}`);
96
+ const { items } = await paymentAccessOf(ctx).paygateCustomers().list({ paygate: STRIPE_PAYGATE_ALIAS, email: { $ilike: pattern } }, { size: 20 });
97
+ const entities = [...new Set(items.filter(item => item.deletedAt == null && item.entityId != null).map(item => item.entityId))];
98
+ return entities.length === 1 ? entities[0] : null;
99
+ };
100
+ /**
101
+ * Where a withdrawal stands now: a `processing` declaration is `refunded` once its refund (and its
102
+ * subscription cancel) succeeded, `failed` after a failed attempt, else still `processing`.
103
+ */
104
+ const executedStatusOf = async (ctx, declaration) => {
105
+ const access = paymentAccessOf(ctx);
106
+ if (declaration.status !== WithdrawalStatus.Processing) {
107
+ return declaration.status;
108
+ }
109
+ const id = declaration.id;
110
+ const refunded = (declaration.refundMinor ?? 0) <= 0 || await access.consumerEvents().load({ recordId: id, action: 'refund', ok: true }) != null;
111
+ if (refunded) {
112
+ return WithdrawalStatus.Refunded;
113
+ }
114
+ return await access.consumerEvents().load({ recordId: id, action: 'refund', ok: false }) != null
115
+ ? WithdrawalStatus.Failed : WithdrawalStatus.Processing;
116
+ };
117
+ const bootWarnings = async (ctx, managed, meter) => {
118
+ const access = paymentAccessOf(ctx);
119
+ const policy = await access.payment().consumerRightsPolicy();
120
+ // An unmanaged process (a worker that asserts consent) neither mails nor refunds.
121
+ if (policy == null || !managed) {
122
+ return;
123
+ }
124
+ const { mechanisms } = policy;
125
+ const mailing = mechanisms.purchaseConfirmation || mechanisms.performanceConsent || mechanisms.subscriptionStart
126
+ || mechanisms.withdrawal || mechanisms.cancellation;
127
+ const mail = await access.consumerMailConfig();
128
+ if (mailing) {
129
+ const trader = mail?.trader;
130
+ if (trader?.address == null || trader.email == null) {
131
+ log.warn('Consumer rights: the trader has no postal address or e-mail — the legal mails and the '
132
+ + 'withdrawal information go out without them');
133
+ }
134
+ const alias = mail?.alias ?? MAILER_SERVICE;
135
+ if (ctx.hasService?.(alias) !== true) {
136
+ log.warn('Consumer rights: no mailer — no durable-medium mail is sent', { alias });
137
+ }
138
+ }
139
+ if (managed && mechanisms.withdrawal && mechanisms.automaticRefunds && meter() == null) {
140
+ log.warn('Consumer rights: no usage meter — every withdrawal is left to an operator (review)');
141
+ }
142
+ };
143
+ const service = createLazyService(alias, {
144
+ get managed() { return isManaged(); },
145
+ policy: async () => await paymentAccessOf(service.assertCtx()).payment().consumerRightsPolicy(),
146
+ profile: async (entityId) => {
147
+ const ctx = service.assertCtx();
148
+ const access = paymentAccessOf(ctx);
149
+ const record = await access.billingProfiles().byEntity(entityId);
150
+ return record != null
151
+ ? consumerRecordsOf(ctx).profileViewOf(record, await access.payment().consumerRightsPolicy()) : null;
152
+ },
153
+ lock: async (entityId, country, source, lockOpts = {}) => {
154
+ const ctx = service.assertCtx();
155
+ const policy = await paymentAccessOf(ctx).payment().consumerRightsPolicy();
156
+ const { record } = await consumerRecordsOf(ctx).lockProfile(policy, { ...lockOpts, entityId, country, source });
157
+ return consumerRecordsOf(ctx).profileViewOf(record, policy);
158
+ },
159
+ unlock: async (entityId, unlockOpts = {}) => {
160
+ const ctx = service.assertCtx();
161
+ const record = await consumerRecordsOf(ctx).unlockProfile(entityId, unlockOpts);
162
+ return record != null
163
+ ? consumerRecordsOf(ctx).profileViewOf(record, await paymentAccessOf(ctx).payment().consumerRightsPolicy()) : null;
164
+ },
165
+ purchases: async (entityId, listOpts = {}) => {
166
+ const ctx = service.assertCtx();
167
+ const at = listOpts.at ?? new Date();
168
+ const { items } = await paymentAccessOf(ctx).purchases().list({ entityId }, {
169
+ size: 200, sort: [{ field: 'purchasedAt', order: 'desc' }],
170
+ });
171
+ const views = [];
172
+ for (const purchase of items) {
173
+ const open = makePurchaseModel(purchase).windowOpen(at);
174
+ if (listOpts.open === true && !open)
175
+ continue;
176
+ let withdrawable = open;
177
+ if (open && meter != null && purchase.kind === PurchaseKind.TopUp) {
178
+ try {
179
+ withdrawable = (await withdrawalOf(ctx).computeWithdrawal(meter, purchase, at)).refundMinor > 0;
180
+ }
181
+ catch (error) {
182
+ log.warn('Purchase usage unreadable', { purchaseId: purchase.purchaseId, error });
183
+ }
184
+ }
185
+ views.push(makePurchaseModel(purchase).view(withdrawable));
186
+ }
187
+ return views;
188
+ },
189
+ consentView: async (entityId, at = new Date()) => {
190
+ const ctx = service.assertCtx();
191
+ const access = paymentAccessOf(ctx);
192
+ const policy = await requirePolicy(ctx);
193
+ const profile = await access.billingProfiles().byEntity(entityId);
194
+ const windows = policy.mechanisms.performanceConsent
195
+ ? await consumerRecordsOf(ctx).unconsentedWindows(entityId, at) : [];
196
+ const language = profile?.language ?? windows[0]?.language ?? policy.defaultLanguage;
197
+ const deadline = latestDeadline(windows);
198
+ const view = {
199
+ required: windows.length > 0,
200
+ region: profile?.region ?? windows[0]?.region ?? null,
201
+ country: profile?.country ?? windows[0]?.country ?? null,
202
+ language,
203
+ trader: consumerMailOf(ctx).traderOf(await access.consumerMailConfig()).name,
204
+ ...(policy.consentContext != null ? { context: policy.consentContext } : {}),
205
+ textVersion: policy.textVersion,
206
+ copyVersion: CONSUMER_RIGHTS_COPY_VERSION,
207
+ links: consumerRightsPolicyHelper.linksOf(policy, language),
208
+ purchases: windows.map(window => makePurchaseModel(window).view(true)),
209
+ ...(deadline != null ? { deadline } : {}),
210
+ at,
211
+ };
212
+ return view;
213
+ },
214
+ recordConsent: async (subject, body, origin) => {
215
+ const ctx = service.assertCtx();
216
+ const access = paymentAccessOf(ctx);
217
+ const policy = await requirePolicy(ctx);
218
+ if (!policy.mechanisms.performanceConsent) {
219
+ throw new ConsumerRightsError('mechanism:performance-consent');
220
+ }
221
+ const at = new Date();
222
+ const windows = await consumerRecordsOf(ctx).unconsentedWindows(subject.entityId, at);
223
+ const covered = windows.filter(window => body.purchaseIds.includes(window.purchaseId));
224
+ // A statement of another version, or one that saw none of what is open now, is asked again.
225
+ if (body.textVersion !== policy.textVersion || (covered.length === 0 && windows.length > 0)) {
226
+ throw new PerformanceConsentRequired({ pending: windows.length, ...(latestDeadline(windows) != null ? { deadline: latestDeadline(windows) } : {}) });
227
+ }
228
+ const trader = consumerMailOf(ctx).traderOf(await access.consumerMailConfig());
229
+ const deadline = latestDeadline(covered);
230
+ const consent = await access.consumerConsents().create(paymentUtils.compact({
231
+ kind: ConsentKind.Performance,
232
+ entityId: subject.entityId,
233
+ profileId: subject.profileId,
234
+ name: subject.name,
235
+ email: prefillEmail(subject.email),
236
+ purchaseIds: covered.map(window => window.purchaseId),
237
+ textVersion: policy.textVersion,
238
+ copyVersion: CONSUMER_RIGHTS_COPY_VERSION,
239
+ language: body.language,
240
+ uiLanguage: body.uiLanguage,
241
+ trader: trader.name,
242
+ context: policy.consentContext,
243
+ text: consumerCopyHelper.consentStatementOf(body.language, ConsentKind.Performance, {
244
+ trader: trader.name, context: policy.consentContext,
245
+ }),
246
+ links: consumerRightsPolicyHelper.linksOf(policy, body.language),
247
+ deadline,
248
+ decidedAt: at,
249
+ ...originHelper.originFields(origin),
250
+ }));
251
+ for (const window of covered) {
252
+ await paymentUtils.conditionalSet(access.purchases(), { purchaseId: window.purchaseId, consentedAt: null }, {
253
+ consentedAt: at, consentId: consent.id, updatedAt: at,
254
+ });
255
+ }
256
+ const mailed = covered.length > 0 ? await consumerMailOf(ctx).sendConsumerMail(policy, 'consent', consent.id) : false;
257
+ await consumerObserversOf(ctx).notifyConsent(consent);
258
+ return { consentId: consent.id, consentedAt: at, purchaseIds: [...consent.purchaseIds], mailed };
259
+ },
260
+ assertConsent: async (entityId, at = new Date()) => {
261
+ const ctx = service.assertCtx();
262
+ const policy = await paymentAccessOf(ctx).payment().consumerRightsPolicy();
263
+ if (policy?.mechanisms.performanceConsent !== true) {
264
+ return;
265
+ }
266
+ const windows = await consumerRecordsOf(ctx).unconsentedWindows(entityId, at);
267
+ if (windows.length > 0) {
268
+ const deadline = latestDeadline(windows);
269
+ throw new PerformanceConsentRequired({ pending: windows.length, ...(deadline != null ? { deadline } : {}) });
270
+ }
271
+ },
272
+ startView: async (entityId, planSku, viewOpts = {}) => {
273
+ const ctx = service.assertCtx();
274
+ const access = paymentAccessOf(ctx);
275
+ const policy = await requirePolicy(ctx);
276
+ const profile = await access.billingProfiles().byEntity(entityId);
277
+ const language = viewOpts.language ?? profile?.language ?? policy.defaultLanguage;
278
+ // The statement follows the plan's withdrawal arithmetic — the variant `recordStartRequest` records.
279
+ const context = consumerCopyHelper.startContextOf(await catalogueOf(ctx).findPlan(planSku));
280
+ const view = {
281
+ required: policy.mechanisms.subscriptionStart
282
+ && (profile == null || consumerRegionHelper.inScope(profile.region, profile.country, policy)),
283
+ planSku,
284
+ language,
285
+ trader: consumerMailOf(ctx).traderOf(await access.consumerMailConfig()).name,
286
+ ...(context != null ? { context } : {}),
287
+ textVersion: policy.textVersion,
288
+ copyVersion: CONSUMER_RIGHTS_COPY_VERSION,
289
+ links: consumerRightsPolicyHelper.linksOf(policy, language),
290
+ region: profile?.region ?? null,
291
+ };
292
+ return view;
293
+ },
294
+ recordStartRequest: async (subject, body, origin, startOpts = {}) => {
295
+ const ctx = service.assertCtx();
296
+ const access = paymentAccessOf(ctx);
297
+ const policy = await requirePolicy(ctx);
298
+ if (!policy.mechanisms.subscriptionStart) {
299
+ throw new ConsumerRightsError('mechanism:subscription-start');
300
+ }
301
+ if (body.textVersion !== policy.textVersion) {
302
+ throw new SubscriptionStartRequired(body.planSku);
303
+ }
304
+ const plan = await catalogueOf(ctx).findPlan(body.planSku);
305
+ if (plan == null) {
306
+ throw new UnknownPlan(body.planSku);
307
+ }
308
+ const context = consumerCopyHelper.startContextOf(plan);
309
+ const at = new Date();
310
+ const expiresAt = new Date(at.getTime() + (policy.startRequestTtlSeconds ?? 3600) * 1000);
311
+ const trader = consumerMailOf(ctx).traderOf(await access.consumerMailConfig());
312
+ const planName = startOpts.plan ?? await consumerMailOf(ctx).planTitleOf(body.planSku, body.language);
313
+ const consent = await access.consumerConsents().create(paymentUtils.compact({
314
+ kind: ConsentKind.SubscriptionStart,
315
+ entityId: subject.entityId,
316
+ profileId: subject.profileId,
317
+ name: subject.name,
318
+ email: prefillEmail(subject.email),
319
+ purchaseIds: [],
320
+ planSku: body.planSku,
321
+ planName,
322
+ textVersion: policy.textVersion,
323
+ copyVersion: CONSUMER_RIGHTS_COPY_VERSION,
324
+ language: body.language,
325
+ trader: trader.name,
326
+ context,
327
+ text: consumerCopyHelper.consentStatementOf(body.language, ConsentKind.SubscriptionStart, { trader: trader.name, plan: planName, context }),
328
+ links: consumerRightsPolicyHelper.linksOf(policy, body.language),
329
+ decidedAt: at,
330
+ expiresAt,
331
+ ...originHelper.originFields(origin),
332
+ }));
333
+ await consumerMailOf(ctx).sendConsumerMail(policy, 'start', consent.id);
334
+ await consumerObserversOf(ctx).notifyConsent(consent);
335
+ return { startRequestId: consent.id, requestedAt: at, expiresAt };
336
+ },
337
+ assertStartRequest: async (entityId, planSku, startRequestId) => {
338
+ const ctx = service.assertCtx();
339
+ const access = paymentAccessOf(ctx);
340
+ const policy = await access.payment().consumerRightsPolicy();
341
+ if (policy?.mechanisms.subscriptionStart !== true) {
342
+ return null;
343
+ }
344
+ const profile = await access.billingProfiles().byEntity(entityId);
345
+ // Only an organization already locked outside the territories goes without one: a country
346
+ // picked before checkout may differ from the address typed at the paygate.
347
+ if (profile != null && !consumerRegionHelper.inScope(profile.region, profile.country, policy)) {
348
+ return null;
349
+ }
350
+ const record = startRequestId != null && startRequestId !== ''
351
+ ? await access.consumerConsents().load(startRequestId).catch(() => null) : null;
352
+ if (record == null || record.kind !== ConsentKind.SubscriptionStart || record.entityId !== entityId
353
+ || record.planSku !== planSku || record.textVersion !== policy.textVersion
354
+ || record.expiresAt == null || new Date(record.expiresAt).getTime() <= Date.now()) {
355
+ throw new SubscriptionStartRequired(planSku);
356
+ }
357
+ return record;
358
+ },
359
+ withdrawalCandidates: async (entityId, subject = {}) => {
360
+ const ctx = service.assertCtx();
361
+ const access = paymentAccessOf(ctx);
362
+ const policy = await requirePolicy(ctx);
363
+ const profile = await access.billingProfiles().byEntity(entityId);
364
+ const at = new Date();
365
+ const open = policy.mechanisms.withdrawal
366
+ ? (await access.purchases().list({
367
+ entityId, inScope: true, withdrawnAt: null, refundedAt: null, deadline: { $gt: at },
368
+ }, { size: 100, sort: [{ field: 'purchasedAt', order: 'desc' }] })).items
369
+ : [];
370
+ const candidates = [];
371
+ for (const purchase of open) {
372
+ let estimate = null;
373
+ if (meter != null) {
374
+ try {
375
+ estimate = (await withdrawalOf(ctx).computeWithdrawal(meter, purchase, at)).estimate;
376
+ }
377
+ catch (error) {
378
+ log.warn('Withdrawal estimate failed', { purchaseId: purchase.purchaseId, error });
379
+ }
380
+ }
381
+ // Credits fully used after consent: the right has expired, nothing would be reimbursed.
382
+ if (estimate != null && purchase.kind === PurchaseKind.TopUp && estimate.refundMinor === 0)
383
+ continue;
384
+ candidates.push({
385
+ purchaseId: purchase.purchaseId,
386
+ contractRef: purchase.contractRef,
387
+ kind: purchase.kind,
388
+ purchasedAt: new Date(purchase.purchasedAt),
389
+ deadline: new Date(purchase.deadline),
390
+ amountTotalMinor: purchase.amountTotalMinor,
391
+ currency: purchase.currency,
392
+ estimate,
393
+ automatic: policy.mechanisms.automaticRefunds && meter != null && isManaged(),
394
+ });
395
+ }
396
+ const language = profile?.language ?? open[0]?.language ?? policy.defaultLanguage;
397
+ return paymentUtils.compact({
398
+ candidates, language, links: consumerRightsPolicyHelper.linksOf(policy, language),
399
+ name: subject.name != null && subject.name.trim() !== '' ? subject.name : undefined,
400
+ email: prefillEmail(subject.email),
401
+ });
402
+ },
403
+ withdraw: async (subject, body, origin) => {
404
+ const ctx = service.assertCtx();
405
+ const access = paymentAccessOf(ctx);
406
+ const policy = await requirePolicy(ctx);
407
+ if (!policy.mechanisms.withdrawal) {
408
+ throw new ConsumerRightsError('mechanism:withdrawal');
409
+ }
410
+ if (!isManaged()) {
411
+ throw new PaygateError('unmanaged');
412
+ }
413
+ const at = new Date();
414
+ const channel = subject == null ? DeclarationChannel.Public : subject.channel ?? DeclarationChannel.InApp;
415
+ const disclose = channel === DeclarationChannel.InApp;
416
+ let purchase = null;
417
+ if (subject != null) {
418
+ purchase = body.purchaseId != null ? await access.purchases().byPurchaseId(body.purchaseId)
419
+ : await purchaseByContract(ctx, body.contractRef);
420
+ if (purchase != null && purchase.entityId !== subject.entityId)
421
+ purchase = null;
422
+ }
423
+ else {
424
+ purchase = await matchPublicPurchase(ctx, body.contractRef, body.email);
425
+ }
426
+ if (disclose) {
427
+ if (purchase == null)
428
+ throw new WithdrawalUnavailable(WithdrawalUnavailableReason.Unknown);
429
+ if (!purchase.inScope)
430
+ throw new WithdrawalUnavailable(WithdrawalUnavailableReason.NotInScope);
431
+ if (purchase.withdrawnAt == null && purchase.refundedAt != null) {
432
+ throw new WithdrawalUnavailable(WithdrawalUnavailableReason.Withdrawn);
433
+ }
434
+ }
435
+ const content = contentOf({
436
+ name: body.name, contract: body.contractRef ?? (disclose ? purchase?.contractRef : undefined), email: body.email,
437
+ });
438
+ const profile = purchase != null ? await access.billingProfiles().byEntity(purchase.entityId) : null;
439
+ const language = body.language ?? purchase?.language ?? profile?.language ?? policy.defaultLanguage;
440
+ const declarationBase = {
441
+ kind: DeclarationKind.Withdrawal, channel,
442
+ entityId: purchase?.entityId ?? subject?.entityId,
443
+ purchaseId: purchase?.purchaseId,
444
+ subscriptionId: purchase?.subscriptionId ?? undefined,
445
+ contractRef: body.contractRef ?? purchase?.contractRef,
446
+ name: body.name, email: body.email, language,
447
+ textVersion: policy.textVersion, copyVersion: CONSUMER_RIGHTS_COPY_VERSION,
448
+ receivedAt: at, matched: purchase != null, profileId: subject?.profileId, ...originHelper.originFields(origin),
449
+ };
450
+ // A repeated declaration of a contract already withdrawn from: recorded, answered with the original.
451
+ if (purchase?.withdrawnAt != null) {
452
+ const original = purchase.withdrawalId != null ? await access.consumerDeclarations().load(purchase.withdrawalId).catch(() => null) : null;
453
+ const repeated = await access.consumerDeclarations().create(paymentUtils.compact({
454
+ ...declarationBase, duplicateOf: original?.id, status: original?.status ?? WithdrawalStatus.Received,
455
+ }));
456
+ if (!disclose) {
457
+ return publicReceipt(repeated, content, false);
458
+ }
459
+ const answered = original ?? repeated;
460
+ return receiptOf(answered, content, false, await executedStatusOf(ctx, answered));
461
+ }
462
+ let status;
463
+ let computation = null;
464
+ if (purchase == null || !purchase.inScope || purchase.refundedAt != null) {
465
+ status = WithdrawalStatus.Received;
466
+ }
467
+ else if (purchase.deadline == null || at.getTime() >= new Date(purchase.deadline).getTime()) {
468
+ status = WithdrawalStatus.Expired;
469
+ }
470
+ else if (meter != null && policy.mechanisms.automaticRefunds) {
471
+ try {
472
+ computation = await withdrawalOf(ctx).computeWithdrawal(meter, purchase, at);
473
+ }
474
+ catch (error) {
475
+ await consumerRecordsOf(ctx).recordEvent({
476
+ recordId: purchase.purchaseId, recordKind: 'purchase', entityId: purchase.entityId, action: 'meter', ok: false,
477
+ error: paymentUtils.errorText(error),
478
+ });
479
+ }
480
+ status = computation != null ? WithdrawalStatus.Processing : WithdrawalStatus.Review;
481
+ if (computation != null && purchase.kind === PurchaseKind.TopUp && computation.refundMinor === 0) {
482
+ if (disclose)
483
+ throw new WithdrawalUnavailable(WithdrawalUnavailableReason.Performed);
484
+ computation = null;
485
+ status = WithdrawalStatus.Review;
486
+ }
487
+ }
488
+ else {
489
+ status = WithdrawalStatus.Review;
490
+ }
491
+ const declaration = await access.consumerDeclarations().create(paymentUtils.compact({
492
+ ...declarationBase, status,
493
+ refundMinor: computation?.refundMinor, currency: computation != null ? purchase?.currency : undefined,
494
+ }));
495
+ const withdrawalId = declaration.id;
496
+ if (purchase != null && (status === WithdrawalStatus.Processing || status === WithdrawalStatus.Review)) {
497
+ // The window closes now; only one declaration of a purchase wins it.
498
+ const won = await paymentUtils.conditionalSet(access.purchases(), { purchaseId: purchase.purchaseId, withdrawnAt: null }, {
499
+ withdrawnAt: at, withdrawalId, updatedAt: at,
500
+ });
501
+ if (!won) {
502
+ const winner = await access.purchases().byPurchaseId(purchase.purchaseId);
503
+ await consumerRecordsOf(ctx).recordEvent({
504
+ recordId: withdrawalId, recordKind: 'declaration', entityId: purchase.entityId, action: 'duplicate', ok: true,
505
+ detail: JSON.stringify({ of: winner?.withdrawalId }),
506
+ });
507
+ const original = winner?.withdrawalId != null ? await access.consumerDeclarations().load(winner.withdrawalId).catch(() => null) : null;
508
+ const answered = original ?? declaration;
509
+ return disclose
510
+ ? receiptOf(answered, content, false, await executedStatusOf(ctx, answered))
511
+ : publicReceipt(declaration, content, false);
512
+ }
513
+ purchase = { ...purchase, withdrawnAt: at, withdrawalId };
514
+ }
515
+ if (computation != null && purchase != null) {
516
+ await consumerRecordsOf(ctx).recordEvent({
517
+ recordId: withdrawalId, recordKind: 'declaration', entityId: purchase.entityId, action: 'computed', ok: true,
518
+ amountMinor: computation.refundMinor, currency: purchase.currency,
519
+ detail: JSON.stringify({
520
+ reading: computation.reading, deducted: computation.deducted, netMinor: computation.netMinor,
521
+ unitsReturned: computation.unitsReturned, estimate: computation.estimate,
522
+ }),
523
+ });
524
+ }
525
+ const mailed = await consumerMailOf(ctx).sendConsumerMail(policy, 'withdrawal', withdrawalId);
526
+ let final = status;
527
+ let execution = null;
528
+ if (status === WithdrawalStatus.Processing && purchase != null && computation != null) {
529
+ execution = await withdrawalOf(ctx).executeWithdrawal(await stripeOf(ctx), declaration, purchase, computation);
530
+ final = execution.needsReview ? WithdrawalStatus.Review : execution.ok ? WithdrawalStatus.Refunded : WithdrawalStatus.Failed;
531
+ }
532
+ if (purchase != null && (final === WithdrawalStatus.Refunded || final === WithdrawalStatus.Review)
533
+ && (status === WithdrawalStatus.Processing || status === WithdrawalStatus.Review)) {
534
+ await consumerObserversOf(ctx).notifyWithdrawal(declaration, purchase, final, computation, execution);
535
+ }
536
+ if (!disclose) {
537
+ return publicReceipt(declaration, content, mailed);
538
+ }
539
+ return paymentUtils.compact({
540
+ ...receiptOf(declaration, content, mailed), status: final,
541
+ refundMinor: execution?.refundedMinor ?? computation?.refundMinor,
542
+ subscriptionCanceled: execution?.subscriptionCanceled,
543
+ });
544
+ },
545
+ cancel: async (subject, body, origin) => {
546
+ const ctx = service.assertCtx();
547
+ const access = paymentAccessOf(ctx);
548
+ const policy = await requirePolicy(ctx);
549
+ if (!policy.mechanisms.cancellation) {
550
+ throw new ConsumerRightsError('mechanism:cancellation');
551
+ }
552
+ if (!isManaged()) {
553
+ throw new PaygateError('unmanaged');
554
+ }
555
+ const at = new Date();
556
+ const channel = subject == null ? DeclarationChannel.Public : subject.channel ?? DeclarationChannel.InApp;
557
+ const disclose = channel === DeclarationChannel.InApp;
558
+ let purchase = null;
559
+ let row = null;
560
+ if (subject != null) {
561
+ if (body.subscriptionId != null) {
562
+ row = await access.subscriptions().byExternalId(body.subscriptionId, STRIPE_PAYGATE_ALIAS);
563
+ }
564
+ else if (body.contractRef != null) {
565
+ purchase = await purchaseByContract(ctx, body.contractRef);
566
+ if (purchase != null && purchase.entityId === subject.entityId && purchase.subscriptionId != null) {
567
+ row = await access.subscriptions().byExternalId(purchase.subscriptionId, STRIPE_PAYGATE_ALIAS);
568
+ }
569
+ }
570
+ row = row != null && row.entityId === subject.entityId
571
+ ? row : await consumerRecordsOf(ctx).entitlingStripeSubscription(subject.entityId);
572
+ }
573
+ else {
574
+ purchase = await matchPublicPurchase(ctx, body.contractRef, body.email);
575
+ if (purchase?.subscriptionId != null) {
576
+ row = await access.subscriptions().byExternalId(purchase.subscriptionId, STRIPE_PAYGATE_ALIAS);
577
+ }
578
+ else if (purchase == null) {
579
+ const entityId = await entityByEmail(ctx, body.email);
580
+ row = entityId != null ? await consumerRecordsOf(ctx).entitlingStripeSubscription(entityId) : null;
581
+ }
582
+ }
583
+ const live = row != null && !TERMINAL_STATUSES.includes(row.status) && ENTITLING_STATUSES.includes(row.status);
584
+ if (disclose && row == null)
585
+ throw new CancellationUnavailable(CancellationUnavailableReason.NoSubscription);
586
+ if (disclose && !live)
587
+ throw new CancellationUnavailable(CancellationUnavailableReason.Ended);
588
+ if (row != null && purchase == null) {
589
+ purchase = await access.purchases().load({ subscriptionId: row.externalId });
590
+ }
591
+ const requested = body.effective === 'date' && body.date != null ? new Date(`${body.date}T00:00:00.000Z`) : null;
592
+ const plan = row != null ? await catalogueOf(ctx).findPlan(row.planSku) : null;
593
+ let status;
594
+ let effectiveAt;
595
+ if (body.kind === CancellationKind.Extraordinary) {
596
+ // For cause: recorded and left to an operator — the paygate is not touched.
597
+ status = CancellationStatus.Review;
598
+ }
599
+ else if (row != null && live && row.periodEnd != null) {
600
+ effectiveAt = cancellationEffectiveAt(new Date(row.periodEnd), plan?.recurring?.interval ?? 'month', requested != null && !Number.isNaN(requested.getTime()) ? requested : null);
601
+ status = row.cancelAtPeriodEnd === true && effectiveAt.getTime() === new Date(row.periodEnd).getTime()
602
+ ? CancellationStatus.AlreadyScheduled : CancellationStatus.Scheduled;
603
+ }
604
+ else {
605
+ status = CancellationStatus.Received;
606
+ }
607
+ const profile = row != null ? await access.billingProfiles().byEntity(row.entityId) : null;
608
+ const language = body.language ?? purchase?.language ?? profile?.language ?? policy.defaultLanguage;
609
+ const declaration = await access.consumerDeclarations().create(paymentUtils.compact({
610
+ kind: DeclarationKind.Cancellation, channel,
611
+ entityId: row?.entityId ?? subject?.entityId,
612
+ purchaseId: purchase?.purchaseId,
613
+ subscriptionId: row?.externalId,
614
+ contractRef: body.contractRef ?? purchase?.contractRef,
615
+ name: body.name, email: body.email,
616
+ cancellationKind: body.kind, reason: body.reason, effective: body.effective, requestedDate: body.date,
617
+ language, textVersion: policy.textVersion, copyVersion: CONSUMER_RIGHTS_COPY_VERSION,
618
+ receivedAt: at, matched: row != null && live, profileId: subject?.profileId, status, effectiveAt,
619
+ ...originHelper.originFields(origin),
620
+ }));
621
+ let final = status;
622
+ if (status === CancellationStatus.Scheduled && row != null) {
623
+ final = await cancellationOf(ctx).scheduleCancellation(await stripeOf(ctx), declaration, row)
624
+ ? CancellationStatus.Scheduled : CancellationStatus.Received;
625
+ }
626
+ if (purchase != null && effectiveAt != null) {
627
+ await consumerRecordsOf(ctx).patchPurchase(purchase.purchaseId, {
628
+ cancellationId: declaration.id, cancelEffectiveAt: effectiveAt,
629
+ });
630
+ }
631
+ const mailed = await consumerMailOf(ctx).sendConsumerMail(policy, 'cancellation', declaration.id);
632
+ await consumerObserversOf(ctx).notifyCancellation(declaration, final);
633
+ const content = contentOf({
634
+ name: body.name, contract: body.contractRef ?? (disclose ? purchase?.contractRef ?? row?.externalId : undefined),
635
+ email: body.email, kind: body.kind, reason: body.reason, date: body.effective === 'date' ? body.date : undefined,
636
+ });
637
+ if (!disclose) {
638
+ return publicReceipt(declaration, content, mailed);
639
+ }
640
+ return paymentUtils.compact({
641
+ ...publicReceipt(declaration, content, mailed), status: final, effectiveAt,
642
+ });
643
+ },
644
+ useMeter: next => { meter = next; },
645
+ useMailRenderer: next => { renderer = next; },
646
+ usageMeter: () => meter,
647
+ mailRenderer: () => renderer,
648
+ reconcile: async (reconcileOpts = {}) => await makeConsumerReconcileHelper(service.assertCtx(), internals)
649
+ .reconcile(reconcileOpts),
650
+ }, service => async () => {
651
+ service.initialized = true;
652
+ const ctx = service.assertCtx();
653
+ void ctx.waitForInitialized?.().then(async () => { await bootWarnings(ctx, isManaged(), () => meter); })
654
+ .catch(error => { log.error('Consumer-rights boot check failed', error); });
655
+ });
656
+ plumbers.set(service, (plumbing, from) => {
657
+ if (plumbing.manage != null) {
658
+ if (from === 'application')
659
+ manageOwn = plumbing.manage;
660
+ else
661
+ manageGateway = plumbing.manage;
662
+ }
663
+ if (plumbing.usage != null)
664
+ meter = plumbing.usage;
665
+ if (plumbing.stripe != null)
666
+ stripeFactory = plumbing.stripe;
667
+ });
668
+ return service;
669
+ };
670
+ /**
671
+ * Register the consumer-rights resources and service (each only when absent), or configure the
672
+ * service already registered — `from` says who asks. The order of the application's call and the
673
+ * gateway's is free: `usage` and `stripe` are installed whenever they come, and the application's
674
+ * explicit `manage` wins over the gateway's. The resources keep the first registration's aliases.
675
+ */
676
+ export const registerConsumerRights = (ctx, opts = {}, from = 'application') => {
677
+ for (const [alias, maker] of CONSUMER_RIGHTS_RESOURCE_MAKERS) {
678
+ if (!ctx.hasResource(alias)) {
679
+ ctx.registerResource(maker(opts.dbAlias, opts.serviceAlias));
680
+ }
681
+ }
682
+ const alias = opts.alias ?? CONSUMER_RIGHTS_SERVICE;
683
+ // A lazy service: reachable before the context initializes.
684
+ let service = ctx.hasService(alias) ? ctx.service(alias) : null;
685
+ if (service == null) {
686
+ service = makeConsumerRightsService(alias, { ...opts, manage: undefined, usage: undefined, stripe: undefined });
687
+ ctx.registerService(service);
688
+ }
689
+ const plumb = plumbers.get(service);
690
+ if (plumb != null) {
691
+ plumb(paymentUtils.compact({ manage: opts.manage, usage: opts.usage, stripe: opts.stripe }), from);
692
+ }
693
+ else if (opts.usage != null) {
694
+ // A service made elsewhere: only its public seam.
695
+ service.useMeter(opts.usage);
696
+ }
697
+ return ctx;
698
+ };
699
+ /**
700
+ * Register the consumer-rights resources and service, each only when absent — the gateway
701
+ * registration does too. Called before or after the gateway, it installs `usage` and `stripe` on
702
+ * the service and its explicit `manage` wins over the gateway's; `useMeter` and `useMailRenderer`
703
+ * work on the service at any time.
704
+ */
705
+ export const appendConsumerRights = (ctx, opts = {}) => registerConsumerRights(ctx, opts, 'application');
706
+ //# sourceMappingURL=service.js.map