@simplelayer/graniteer-core 0.2.2 → 0.2.3

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 (475) hide show
  1. package/dist/adminBookingCredit.d.ts +107 -0
  2. package/dist/adminBookingCredit.js +163 -0
  3. package/dist/agreementCheckout.d.ts +34 -0
  4. package/dist/agreementCheckout.js +211 -0
  5. package/dist/agreementPortalEmail.d.ts +15 -0
  6. package/dist/agreementPortalEmail.js +107 -0
  7. package/dist/availability.d.ts +51 -0
  8. package/dist/availability.js +152 -0
  9. package/dist/billingPortalLinkEmail.d.ts +14 -0
  10. package/dist/billingPortalLinkEmail.js +98 -0
  11. package/dist/bookingAgreementEmail.d.ts +23 -0
  12. package/dist/bookingAgreementEmail.js +116 -0
  13. package/dist/bookingEffects.d.ts +84 -0
  14. package/dist/bookingEffects.js +309 -0
  15. package/dist/bookingHoldReclaim.d.ts +16 -0
  16. package/dist/bookingHoldReclaim.js +74 -0
  17. package/dist/busClient.d.ts +44 -0
  18. package/dist/busClient.js +196 -0
  19. package/dist/busSignature.d.ts +19 -0
  20. package/{src/busSignature.ts → dist/busSignature.js} +64 -71
  21. package/dist/checkoutCoupon.d.ts +156 -0
  22. package/dist/checkoutCoupon.js +369 -0
  23. package/dist/checkoutSessionParams.d.ts +19 -0
  24. package/dist/checkoutSessionParams.js +36 -0
  25. package/dist/commonsContract.d.ts +70 -0
  26. package/dist/commonsContract.js +142 -0
  27. package/dist/commonsDeposit.d.ts +78 -0
  28. package/dist/commonsDeposit.js +199 -0
  29. package/dist/commonsDepositWebhook.d.ts +37 -0
  30. package/dist/commonsDepositWebhook.js +147 -0
  31. package/dist/conductorAdmin.d.ts +76 -0
  32. package/dist/conductorAdmin.js +88 -0
  33. package/dist/dayPassConfirmation.d.ts +17 -0
  34. package/dist/dayPassConfirmation.js +187 -0
  35. package/dist/dunningEmails.d.ts +40 -0
  36. package/dist/dunningEmails.js +174 -0
  37. package/dist/email-templates/brand.d.ts +82 -0
  38. package/dist/email-templates/brand.js +72 -0
  39. package/dist/email-templates/email-change.d.ts +10 -0
  40. package/dist/email-templates/email-change.js +50 -0
  41. package/dist/email-templates/invite.d.ts +8 -0
  42. package/dist/email-templates/invite.js +44 -0
  43. package/dist/email-templates/magic-link.d.ts +10 -0
  44. package/dist/email-templates/magic-link.js +26 -0
  45. package/dist/email-templates/reauthentication.d.ts +6 -0
  46. package/dist/email-templates/reauthentication.js +35 -0
  47. package/dist/email-templates/recovery.d.ts +10 -0
  48. package/dist/email-templates/recovery.js +26 -0
  49. package/dist/email-templates/signup.d.ts +12 -0
  50. package/dist/email-templates/signup.js +30 -0
  51. package/dist/functions/admin-cancel-membership.d.ts +1 -0
  52. package/dist/functions/admin-cancel-membership.js +286 -0
  53. package/dist/functions/admin-change-membership-plan.d.ts +1 -0
  54. package/dist/functions/admin-change-membership-plan.js +281 -0
  55. package/dist/functions/admin-charge-guest-print.d.ts +1 -0
  56. package/dist/functions/admin-charge-guest-print.js +227 -0
  57. package/dist/functions/admin-correct-booking.d.ts +1 -0
  58. package/dist/functions/admin-correct-booking.js +326 -0
  59. package/dist/functions/admin-create-booking.d.ts +43 -0
  60. package/dist/functions/admin-create-booking.js +410 -0
  61. package/dist/functions/admin-create-commons-event.d.ts +1 -0
  62. package/dist/functions/admin-create-commons-event.js +237 -0
  63. package/dist/functions/admin-debug-boldsign-doc.d.ts +1 -0
  64. package/dist/functions/admin-debug-boldsign-doc.js +110 -0
  65. package/dist/functions/admin-door-write.d.ts +1 -0
  66. package/dist/functions/admin-door-write.js +267 -0
  67. package/dist/functions/admin-issue-day-pass.d.ts +14 -0
  68. package/dist/functions/admin-issue-day-pass.js +213 -0
  69. package/dist/functions/admin-mark-booking-paid.d.ts +1 -0
  70. package/dist/functions/admin-mark-booking-paid.js +202 -0
  71. package/dist/functions/admin-mint-billing-portal-link.d.ts +6 -0
  72. package/dist/functions/admin-mint-billing-portal-link.js +159 -0
  73. package/dist/functions/admin-mint-portal-link.d.ts +3 -0
  74. package/dist/functions/admin-mint-portal-link.js +54 -0
  75. package/dist/functions/admin-photo-upload.d.ts +1 -0
  76. package/dist/functions/admin-photo-upload.js +104 -0
  77. package/dist/functions/admin-remove-team-member.d.ts +1 -0
  78. package/dist/functions/admin-remove-team-member.js +140 -0
  79. package/dist/functions/admin-request-trial.d.ts +5 -0
  80. package/dist/functions/admin-request-trial.js +349 -0
  81. package/dist/functions/admin-resend-commons-deposit-link.d.ts +7 -0
  82. package/dist/functions/admin-resend-commons-deposit-link.js +298 -0
  83. package/dist/functions/admin-reset-mfa.d.ts +1 -0
  84. package/dist/functions/admin-reset-mfa.js +129 -0
  85. package/dist/functions/admin-retry-invoice-payment.d.ts +76 -0
  86. package/dist/functions/admin-retry-invoice-payment.js +269 -0
  87. package/dist/functions/admin-reverse-coupon-redemption.d.ts +1 -0
  88. package/dist/functions/admin-reverse-coupon-redemption.js +91 -0
  89. package/dist/functions/admin-revoke-agreement.d.ts +4 -0
  90. package/dist/functions/admin-revoke-agreement.js +410 -0
  91. package/dist/functions/admin-send-commons-agreement.d.ts +1 -0
  92. package/dist/functions/admin-send-commons-agreement.js +212 -0
  93. package/dist/functions/admin-set-credit-amount.d.ts +1 -0
  94. package/dist/functions/admin-set-credit-amount.js +112 -0
  95. package/dist/functions/admin-skip-commons-contract.d.ts +1 -0
  96. package/dist/functions/admin-skip-commons-contract.js +170 -0
  97. package/dist/functions/admin-undo-membership-cancel.d.ts +1 -0
  98. package/dist/functions/admin-undo-membership-cancel.js +135 -0
  99. package/dist/functions/admin-wall-photo-write.d.ts +1 -0
  100. package/dist/functions/admin-wall-photo-write.js +137 -0
  101. package/dist/functions/auth-email-hook.d.ts +20 -0
  102. package/dist/functions/auth-email-hook.js +209 -0
  103. package/dist/functions/boldsign-sender-identity.d.ts +1 -0
  104. package/dist/functions/boldsign-sender-identity.js +109 -0
  105. package/dist/functions/booking-availability.d.ts +1 -0
  106. package/dist/functions/booking-availability.js +355 -0
  107. package/dist/functions/booking-member-preview.d.ts +1 -0
  108. package/dist/functions/booking-member-preview.js +123 -0
  109. package/dist/functions/booking-status.d.ts +3 -0
  110. package/dist/functions/booking-status.js +139 -0
  111. package/dist/functions/conductor.d.ts +3 -0
  112. package/dist/functions/conductor.js +451 -0
  113. package/dist/functions/create-agreement.d.ts +8 -0
  114. package/dist/functions/create-agreement.js +498 -0
  115. package/dist/functions/create-booking.d.ts +44 -0
  116. package/dist/functions/create-booking.js +538 -0
  117. package/dist/functions/create-day-pass-checkout.d.ts +4 -0
  118. package/dist/functions/create-day-pass-checkout.js +196 -0
  119. package/dist/functions/create-portal-session.d.ts +4 -0
  120. package/dist/functions/create-portal-session.js +127 -0
  121. package/dist/functions/create-subscription-checkout.d.ts +4 -0
  122. package/dist/functions/create-subscription-checkout.js +394 -0
  123. package/dist/functions/day-pass-status.d.ts +1 -0
  124. package/dist/functions/day-pass-status.js +70 -0
  125. package/dist/functions/dayStatus.d.ts +15 -0
  126. package/dist/functions/dayStatus.js +59 -0
  127. package/dist/functions/diag-webpush-test.d.ts +1 -0
  128. package/dist/functions/diag-webpush-test.js +42 -0
  129. package/dist/functions/event-access-admin.d.ts +17 -0
  130. package/dist/functions/event-access-admin.js +262 -0
  131. package/dist/functions/event-access-store.d.ts +1 -0
  132. package/dist/functions/event-access-store.js +343 -0
  133. package/dist/functions/ezeep-print-webhook.d.ts +1 -0
  134. package/dist/functions/ezeep-print-webhook.js +160 -0
  135. package/dist/functions/ezeep-usage-reconcile.d.ts +1 -0
  136. package/dist/functions/ezeep-usage-reconcile.js +305 -0
  137. package/dist/functions/fetch-avatar-original.d.ts +3 -0
  138. package/dist/functions/fetch-avatar-original.js +423 -0
  139. package/dist/functions/get-provider-sign-link.d.ts +3 -0
  140. package/dist/functions/get-provider-sign-link.js +146 -0
  141. package/dist/functions/get-signing-link.d.ts +1 -0
  142. package/dist/functions/get-signing-link.js +192 -0
  143. package/dist/functions/guest-print-setup-confirm.d.ts +1 -0
  144. package/dist/functions/guest-print-setup-confirm.js +126 -0
  145. package/dist/functions/guest-print-submit.d.ts +1 -0
  146. package/dist/functions/guest-print-submit.js +145 -0
  147. package/dist/functions/luma-webhook.d.ts +1 -0
  148. package/dist/functions/luma-webhook.js +123 -0
  149. package/dist/functions/manage-booking.d.ts +75 -0
  150. package/dist/functions/manage-booking.js +409 -0
  151. package/dist/functions/mcp.d.ts +16 -0
  152. package/dist/functions/mcp.js +51 -0
  153. package/dist/functions/member-door-action.d.ts +60 -0
  154. package/dist/functions/member-door-action.js +774 -0
  155. package/dist/functions/member-unifi-mapping.d.ts +15 -0
  156. package/dist/functions/member-unifi-mapping.js +198 -0
  157. package/dist/functions/membership-door-sync.d.ts +14 -0
  158. package/dist/functions/membership-door-sync.js +863 -0
  159. package/dist/functions/migration-collision-alert.copy.d.ts +7 -0
  160. package/dist/functions/migration-collision-alert.copy.js +207 -0
  161. package/dist/functions/migration-collision-alert.d.ts +7 -0
  162. package/dist/functions/migration-collision-alert.js +207 -0
  163. package/dist/functions/office-assignment-end.d.ts +12 -0
  164. package/dist/functions/office-assignment-end.js +140 -0
  165. package/dist/functions/portal-booking-access.d.ts +22 -0
  166. package/dist/functions/portal-booking-access.js +163 -0
  167. package/dist/functions/portal-list-invoices.d.ts +1 -0
  168. package/dist/functions/portal-list-invoices.js +90 -0
  169. package/dist/functions/portal-request-login.d.ts +7 -0
  170. package/dist/functions/portal-request-login.js +199 -0
  171. package/dist/functions/portal-resend-invite.d.ts +6 -0
  172. package/dist/functions/portal-resend-invite.js +225 -0
  173. package/dist/functions/portal-submit-event.d.ts +4 -0
  174. package/dist/functions/portal-submit-event.js +152 -0
  175. package/dist/functions/print-billing-recover.d.ts +1 -0
  176. package/dist/functions/print-billing-recover.js +83 -0
  177. package/dist/functions/print-billing-run.d.ts +1 -0
  178. package/dist/functions/print-billing-run.js +153 -0
  179. package/dist/functions/public-facts.d.ts +1 -0
  180. package/dist/functions/public-facts.js +141 -0
  181. package/dist/functions/push-send.d.ts +3 -0
  182. package/dist/functions/push-send.js +297 -0
  183. package/dist/functions/push-test.d.ts +3 -0
  184. package/dist/functions/push-test.js +215 -0
  185. package/dist/functions/request-portal-link.d.ts +7 -0
  186. package/dist/functions/request-portal-link.js +178 -0
  187. package/dist/functions/reschedule-booking.d.ts +50 -0
  188. package/dist/functions/reschedule-booking.js +571 -0
  189. package/dist/functions/review-ratings.d.ts +1 -0
  190. package/dist/functions/review-ratings.js +95 -0
  191. package/dist/functions/space-availability-range.d.ts +1 -0
  192. package/dist/functions/space-availability-range.js +109 -0
  193. package/dist/functions/stripe-db-reconcile.d.ts +3 -0
  194. package/dist/functions/stripe-db-reconcile.js +314 -0
  195. package/dist/functions/stripe-webhook.d.ts +46 -0
  196. package/dist/functions/stripe-webhook.js +2367 -0
  197. package/dist/functions/sync-gcal-blackouts.d.ts +1 -0
  198. package/dist/functions/sync-gcal-blackouts.js +251 -0
  199. package/dist/functions/timetable-event-register.d.ts +1 -0
  200. package/dist/functions/timetable-event-register.js +155 -0
  201. package/dist/functions/timetable-event-status.d.ts +1 -0
  202. package/dist/functions/timetable-event-status.js +86 -0
  203. package/dist/functions/timetable-spaces.d.ts +1 -0
  204. package/dist/functions/timetable-spaces.js +161 -0
  205. package/dist/functions/touch-pass-reconciler.d.ts +1 -0
  206. package/dist/functions/touch-pass-reconciler.js +688 -0
  207. package/dist/functions/touch-pass-signup.d.ts +1 -0
  208. package/dist/functions/touch-pass-signup.js +447 -0
  209. package/dist/functions/upload-booking-display-image.d.ts +4 -0
  210. package/dist/functions/upload-booking-display-image.js +159 -0
  211. package/dist/functions/virtual-onboarding-purge.d.ts +1 -0
  212. package/dist/functions/virtual-onboarding-purge.js +123 -0
  213. package/dist/functions/virtual-onboarding-submit.d.ts +1 -0
  214. package/dist/functions/virtual-onboarding-submit.js +303 -0
  215. package/dist/functions/voice-booking.d.ts +10 -0
  216. package/dist/functions/voice-booking.js +360 -0
  217. package/dist/functions/voice-day-pass.d.ts +15 -0
  218. package/dist/functions/voice-day-pass.js +269 -0
  219. package/dist/functions/voice-inquiry.d.ts +1 -0
  220. package/dist/functions/voice-inquiry.js +156 -0
  221. package/dist/functions/voice-membership-signup.d.ts +15 -0
  222. package/dist/functions/voice-membership-signup.js +273 -0
  223. package/dist/functions/voice-tour-availability.d.ts +1 -0
  224. package/dist/functions/voice-tour-availability.js +179 -0
  225. package/dist/functions/voice-tour-booking.d.ts +21 -0
  226. package/dist/functions/voice-tour-booking.js +308 -0
  227. package/dist/gcalSync.d.ts +29 -0
  228. package/dist/gcalSync.js +119 -0
  229. package/dist/ghlEventInquiry.d.ts +16 -0
  230. package/dist/ghlEventInquiry.js +116 -0
  231. package/dist/ghlNote.d.ts +5 -0
  232. package/dist/ghlNote.js +29 -0
  233. package/dist/ghlTask.d.ts +7 -0
  234. package/dist/ghlTask.js +39 -0
  235. package/dist/ghlVoiceInquiry.d.ts +26 -0
  236. package/dist/ghlVoiceInquiry.js +68 -0
  237. package/dist/guestPrintCapture.d.ts +217 -0
  238. package/dist/guestPrintCapture.js +362 -0
  239. package/dist/index.d.ts +3 -0
  240. package/{index.js → dist/index.js} +3 -2
  241. package/dist/lumaGhl.d.ts +19 -0
  242. package/dist/lumaGhl.js +147 -0
  243. package/dist/mailArrivalEmail.d.ts +15 -0
  244. package/dist/mailArrivalEmail.js +99 -0
  245. package/dist/manageToken.d.ts +64 -0
  246. package/dist/manageToken.js +261 -0
  247. package/dist/membership.d.ts +20 -0
  248. package/dist/membership.js +87 -0
  249. package/dist/membershipBusClient.d.ts +139 -0
  250. package/dist/membershipBusClient.js +443 -0
  251. package/dist/membershipWelcome.d.ts +117 -0
  252. package/dist/membershipWelcome.js +497 -0
  253. package/dist/migrationCheckout.d.ts +169 -0
  254. package/dist/migrationCheckout.js +250 -0
  255. package/dist/money.d.ts +20 -0
  256. package/dist/money.js +35 -0
  257. package/dist/ops.d.ts +27 -0
  258. package/dist/ops.js +87 -0
  259. package/dist/pacificDate.d.ts +8 -0
  260. package/{src/pacificDate.ts → dist/pacificDate.js} +76 -88
  261. package/dist/paymentLinkEmail.d.ts +15 -0
  262. package/dist/paymentLinkEmail.js +102 -0
  263. package/dist/policyAcknowledgment.d.ts +46 -0
  264. package/dist/policyAcknowledgment.js +58 -0
  265. package/dist/portalSession.d.ts +15 -0
  266. package/dist/portalSession.js +31 -0
  267. package/dist/pricing.d.ts +306 -0
  268. package/dist/pricing.js +788 -0
  269. package/dist/printBilling.d.ts +340 -0
  270. package/dist/printBilling.js +619 -0
  271. package/dist/printBillingAdapters.d.ts +29 -0
  272. package/dist/printBillingAdapters.js +130 -0
  273. package/dist/printCorrections.d.ts +175 -0
  274. package/dist/printCorrections.js +328 -0
  275. package/dist/rateLimit.d.ts +20 -0
  276. package/dist/rateLimit.js +70 -0
  277. package/dist/referralCredits.d.ts +5 -0
  278. package/{src/referralCredits.ts → dist/referralCredits.js} +27 -34
  279. package/dist/referralGrant.d.ts +49 -0
  280. package/dist/referralGrant.js +268 -0
  281. package/dist/rescheduleCredit.d.ts +98 -0
  282. package/dist/rescheduleCredit.js +263 -0
  283. package/dist/reservationWifiCode.d.ts +19 -0
  284. package/{src/reservationWifiCode.ts → dist/reservationWifiCode.js} +67 -81
  285. package/dist/retellCallAnalyzed.d.ts +18 -0
  286. package/dist/retellCallAnalyzed.js +91 -0
  287. package/dist/retellSignature.d.ts +14 -0
  288. package/dist/retellSignature.js +60 -0
  289. package/dist/signedUnpaidReminderEmail.d.ts +15 -0
  290. package/dist/signedUnpaidReminderEmail.js +111 -0
  291. package/dist/slackAlert.d.ts +13 -0
  292. package/dist/slackAlert.js +37 -0
  293. package/dist/stripeCoworkingPortal.d.ts +21 -0
  294. package/dist/stripeCoworkingPortal.js +80 -0
  295. package/dist/supabaseTestFakes.d.ts +67 -0
  296. package/dist/supabaseTestFakes.js +79 -0
  297. package/dist/supportTicketEmail.d.ts +16 -0
  298. package/dist/supportTicketEmail.js +98 -0
  299. package/dist/tier1Agreement.d.ts +51 -0
  300. package/dist/tier1Agreement.js +86 -0
  301. package/dist/unifiAccessPolicies.d.ts +36 -0
  302. package/dist/unifiAccessPolicies.js +185 -0
  303. package/dist/unifiGroups.d.ts +26 -0
  304. package/dist/unifiGroups.js +106 -0
  305. package/package.json +645 -169
  306. package/src/adminBookingCredit.test.ts +0 -451
  307. package/src/adminBookingCredit.ts +0 -239
  308. package/src/agreementCheckout.ts +0 -250
  309. package/src/agreementPortalEmail.ts +0 -128
  310. package/src/availability.test.ts +0 -25
  311. package/src/availability.ts +0 -201
  312. package/src/billingPortalLinkEmail.ts +0 -117
  313. package/src/bookingAgreementEmail.ts +0 -149
  314. package/src/bookingEffects.ts +0 -388
  315. package/src/bookingHoldReclaim.ts +0 -94
  316. package/src/busClient.ts +0 -268
  317. package/src/checkoutCoupon.test.ts +0 -675
  318. package/src/checkoutCoupon.ts +0 -455
  319. package/src/checkoutSessionParams.ts +0 -56
  320. package/src/commonsContract.ts +0 -175
  321. package/src/commonsDeposit.ts +0 -298
  322. package/src/commonsDepositWebhook.ts +0 -237
  323. package/src/conductorAdmin.ts +0 -141
  324. package/src/dayPassConfirmation.ts +0 -230
  325. package/src/dunningEmails.test.ts +0 -263
  326. package/src/dunningEmails.ts +0 -203
  327. package/src/email-templates/brand.ts +0 -93
  328. package/src/email-templates/email-change.tsx +0 -92
  329. package/src/email-templates/invite.tsx +0 -79
  330. package/src/email-templates/magic-link.tsx +0 -59
  331. package/src/email-templates/reauthentication.tsx +0 -60
  332. package/src/email-templates/recovery.tsx +0 -59
  333. package/src/email-templates/signup.tsx +0 -67
  334. package/src/functions/admin-cancel-membership.ts +0 -311
  335. package/src/functions/admin-change-membership-plan.ts +0 -312
  336. package/src/functions/admin-charge-guest-print.ts +0 -229
  337. package/src/functions/admin-correct-booking.ts +0 -333
  338. package/src/functions/admin-create-booking.ts +0 -460
  339. package/src/functions/admin-create-commons-event.ts +0 -244
  340. package/src/functions/admin-debug-boldsign-doc.ts +0 -93
  341. package/src/functions/admin-door-write.ts +0 -272
  342. package/src/functions/admin-issue-day-pass.ts +0 -231
  343. package/src/functions/admin-mark-booking-paid.ts +0 -203
  344. package/src/functions/admin-mint-billing-portal-link.ts +0 -168
  345. package/src/functions/admin-mint-portal-link.ts +0 -62
  346. package/src/functions/admin-photo-upload.ts +0 -128
  347. package/src/functions/admin-remove-team-member.ts +0 -150
  348. package/src/functions/admin-request-trial.ts +0 -366
  349. package/src/functions/admin-resend-commons-deposit-link.ts +0 -323
  350. package/src/functions/admin-reset-mfa.ts +0 -138
  351. package/src/functions/admin-retry-invoice-payment.test.ts +0 -567
  352. package/src/functions/admin-retry-invoice-payment.ts +0 -333
  353. package/src/functions/admin-reverse-coupon-redemption.ts +0 -98
  354. package/src/functions/admin-revoke-agreement.ts +0 -467
  355. package/src/functions/admin-send-commons-agreement.ts +0 -214
  356. package/src/functions/admin-set-credit-amount.ts +0 -123
  357. package/src/functions/admin-skip-commons-contract.ts +0 -165
  358. package/src/functions/admin-undo-membership-cancel.ts +0 -144
  359. package/src/functions/admin-wall-photo-write.ts +0 -141
  360. package/src/functions/auth-email-hook.ts +0 -259
  361. package/src/functions/boldsign-sender-identity.ts +0 -114
  362. package/src/functions/booking-availability.ts +0 -419
  363. package/src/functions/booking-member-preview.ts +0 -136
  364. package/src/functions/booking-status.ts +0 -149
  365. package/src/functions/conductor.ts +0 -505
  366. package/src/functions/create-agreement.ts +0 -537
  367. package/src/functions/create-booking.ts +0 -648
  368. package/src/functions/create-day-pass-checkout.ts +0 -218
  369. package/src/functions/create-portal-session.ts +0 -142
  370. package/src/functions/create-subscription-checkout.test.ts +0 -222
  371. package/src/functions/create-subscription-checkout.ts +0 -440
  372. package/src/functions/day-pass-status.ts +0 -89
  373. package/src/functions/dayStatus.ts +0 -71
  374. package/src/functions/diag-webpush-test.ts +0 -45
  375. package/src/functions/event-access-admin.ts +0 -277
  376. package/src/functions/event-access-store.ts +0 -334
  377. package/src/functions/ezeep-print-webhook.ts +0 -213
  378. package/src/functions/ezeep-usage-reconcile.ts +0 -299
  379. package/src/functions/fetch-avatar-original.ts +0 -457
  380. package/src/functions/get-provider-sign-link.ts +0 -155
  381. package/src/functions/get-signing-link.ts +0 -211
  382. package/src/functions/guest-print-setup-confirm.ts +0 -128
  383. package/src/functions/guest-print-submit.ts +0 -149
  384. package/src/functions/luma-webhook.ts +0 -165
  385. package/src/functions/manage-booking.ts +0 -472
  386. package/src/functions/mcp.ts +0 -67
  387. package/src/functions/member-door-action.test.ts +0 -1248
  388. package/src/functions/member-door-action.ts +0 -863
  389. package/src/functions/member-unifi-mapping.test.ts +0 -516
  390. package/src/functions/member-unifi-mapping.ts +0 -206
  391. package/src/functions/membership-door-sync.ts +0 -956
  392. package/src/functions/migration-collision-alert.copy.ts +0 -232
  393. package/src/functions/migration-collision-alert.test.ts +0 -349
  394. package/src/functions/migration-collision-alert.ts +0 -232
  395. package/src/functions/office-assignment-end.ts +0 -146
  396. package/src/functions/portal-booking-access.ts +0 -217
  397. package/src/functions/portal-list-invoices.ts +0 -99
  398. package/src/functions/portal-request-login.ts +0 -219
  399. package/src/functions/portal-resend-invite.ts +0 -248
  400. package/src/functions/portal-submit-event.ts +0 -168
  401. package/src/functions/print-billing-recover.ts +0 -97
  402. package/src/functions/print-billing-run.ts +0 -183
  403. package/src/functions/public-facts.ts +0 -168
  404. package/src/functions/push-send.ts +0 -348
  405. package/src/functions/push-test.ts +0 -234
  406. package/src/functions/request-portal-link.ts +0 -211
  407. package/src/functions/reschedule-booking.ts +0 -649
  408. package/src/functions/review-ratings.ts +0 -113
  409. package/src/functions/space-availability-range.acceptance.test.ts +0 -161
  410. package/src/functions/space-availability-range.ts +0 -142
  411. package/src/functions/stripe-db-reconcile.ts +0 -319
  412. package/src/functions/stripe-webhook.moved-regression.test.ts +0 -78
  413. package/src/functions/stripe-webhook.ts +0 -2595
  414. package/src/functions/sync-gcal-blackouts.ts +0 -298
  415. package/src/functions/timetable-event-register.ts +0 -162
  416. package/src/functions/timetable-event-status.ts +0 -90
  417. package/src/functions/timetable-spaces.ts +0 -219
  418. package/src/functions/touch-pass-reconciler.ts +0 -689
  419. package/src/functions/touch-pass-signup.ts +0 -478
  420. package/src/functions/upload-booking-display-image.ts +0 -179
  421. package/src/functions/virtual-onboarding-purge.ts +0 -134
  422. package/src/functions/virtual-onboarding-submit.ts +0 -315
  423. package/src/functions/voice-booking.ts +0 -453
  424. package/src/functions/voice-day-pass.ts +0 -346
  425. package/src/functions/voice-inquiry.test.ts +0 -301
  426. package/src/functions/voice-inquiry.ts +0 -198
  427. package/src/functions/voice-membership-signup.ts +0 -355
  428. package/src/functions/voice-tour-availability.ts +0 -204
  429. package/src/functions/voice-tour-booking.ts +0 -429
  430. package/src/gcalSync.ts +0 -142
  431. package/src/ghlEventInquiry.ts +0 -143
  432. package/src/ghlNote.ts +0 -34
  433. package/src/ghlTask.ts +0 -48
  434. package/src/ghlVoiceInquiry.ts +0 -90
  435. package/src/guestPrintCapture.test.ts +0 -722
  436. package/src/guestPrintCapture.ts +0 -538
  437. package/src/lumaGhl.ts +0 -195
  438. package/src/mailArrivalEmail.ts +0 -121
  439. package/src/manageToken.ts +0 -363
  440. package/src/membership.ts +0 -109
  441. package/src/membershipBusClient.ts +0 -537
  442. package/src/membershipWelcome.ts +0 -683
  443. package/src/migrationCheckout.ts +0 -366
  444. package/src/money.ts +0 -36
  445. package/src/ops.ts +0 -97
  446. package/src/paymentLinkEmail.ts +0 -123
  447. package/src/policyAcknowledgment.test.ts +0 -50
  448. package/src/policyAcknowledgment.ts +0 -96
  449. package/src/portalSession.ts +0 -46
  450. package/src/pricing.test.ts +0 -660
  451. package/src/pricing.ts +0 -1025
  452. package/src/printBilling.test.ts +0 -750
  453. package/src/printBilling.ts +0 -891
  454. package/src/printBillingAdapters.ts +0 -169
  455. package/src/printCorrections.test.ts +0 -348
  456. package/src/printCorrections.ts +0 -496
  457. package/src/rateLimit.ts +0 -82
  458. package/src/referralCredits.test.ts +0 -31
  459. package/src/referralGrant.ts +0 -321
  460. package/src/rescheduleCredit.test.ts +0 -521
  461. package/src/rescheduleCredit.ts +0 -337
  462. package/src/reservationWifiCode.test.ts +0 -69
  463. package/src/retellCallAnalyzed.test.ts +0 -167
  464. package/src/retellCallAnalyzed.ts +0 -113
  465. package/src/retellSignature.test.ts +0 -137
  466. package/src/retellSignature.ts +0 -82
  467. package/src/signedUnpaidReminderEmail.test.ts +0 -246
  468. package/src/signedUnpaidReminderEmail.ts +0 -132
  469. package/src/slackAlert.ts +0 -38
  470. package/src/stripeCoworkingPortal.ts +0 -91
  471. package/src/supabaseTestFakes.ts +0 -131
  472. package/src/supportTicketEmail.ts +0 -119
  473. package/src/tier1Agreement.ts +0 -125
  474. package/src/unifiAccessPolicies.ts +0 -228
  475. package/src/unifiGroups.ts +0 -129
@@ -0,0 +1,619 @@
1
+ // print-usage-bill P2 — the decision core for `print-billing-run` and
2
+ // `print-billing-recover`.
3
+ //
4
+ // Design: PRINT-USAGE-BILL-DESIGN.md v19, sections 4.2, 4.3, 4.4 and 5.
5
+ //
6
+ // THIS MODULE MAKES NO NETWORK CALLS AND IMPORTS NOTHING. Stripe and the
7
+ // database both arrive as injected, structurally-typed dependencies, so the
8
+ // whole of the money logic is exercisable against hand-rolled stubs. That is
9
+ // deliberate and it is what section 8.5 means by "run it against a mocked Stripe
10
+ // client first"; section 8.5's live half is GATED and is not reachable from here.
11
+ //
12
+ // C-03 is the reason the shape is like this at all: there is no synchronous HTTP
13
+ // extension in this Postgres (pg_net is async, dispatch-after-commit), so a
14
+ // plpgsql function cannot call Stripe and branch on the result. The edge function
15
+ // makes the Stripe calls; the DB does short transactions only.
16
+ // ---------------------------------------------------------------- constants --
17
+ /** C-10 / Stripe's documented minimum. Applied at RUN level only — never per period. */
18
+ export const STRIPE_MIN_CENTS = 50;
19
+ /** R-08, KYLE-RATIFIED 2026-08-22. Strictly greater-than: exactly $75.00 bills. */
20
+ export const HARD_CAP_CENTS = 7500;
21
+ /** R-08, KYLE-RATIFIED. ">= 10x" matches the ratified wording "10x or more". */
22
+ export const ANOMALY_MULTIPLIER = 10;
23
+ /** [RE-DERIVED] — Kyle ratified the multiplier, NOT this threshold. */
24
+ export const MIN_QUALIFYING_PERIODS = 3;
25
+ /** [RE-DERIVED] — window size for the baseline. See R-08's row in section 12. */
26
+ export const BASELINE_WINDOW = 6;
27
+ // Deterministic idempotency keys. R2 found v6's "idempotency key" was a DB
28
+ // uniqueness constraint that was never sent to Stripe. These strings are stored
29
+ // in print_billing_runs.idempotency_key AND sent in the Idempotency-Key header.
30
+ export const runKey = (runId) => `gc-p2-run-${runId}`;
31
+ export const itemKey = (runId, periodId) => `gc-p2-item-${runId}-${periodId}`;
32
+ export const finalizeKey = (runId) => `gc-p2-fin-${runId}`;
33
+ export const creditKey = (correctionId) => `gc-p2-cn-${correctionId}`;
34
+ /** GC001..GC011 are raised by the migrations with `using errcode = ...`.
35
+ * Everything branches on these, never on message text. */
36
+ export function gcCodeOf(e) {
37
+ const anyE = e;
38
+ return anyE?.gcCode ?? anyE?.code ?? null;
39
+ }
40
+ // ------------------------------------------------------- section 4.2 queries --
41
+ /** The eligibility query, verbatim from section 4.2.
42
+ * Note the two DIFFERENT predicates and keep them distinct (v15/S5):
43
+ * - `charge_cents_total > 0` is PER PERIOD and excludes $0.00 lines.
44
+ * - `having sum(...) >= 50` is RUN LEVEL and is the ONLY place the Stripe
45
+ * minimum is applied on this side. v14 also had a per-period `>= 50` inside
46
+ * M-11's claim UPDATE; that predicate is DELETED, because it silently billed
47
+ * a member who owed $9.30 nothing at all, every month (T-85). */
48
+ export const ELIGIBILITY_SQL = `
49
+ select p.membership_id,
50
+ array_agg(p.id order by p.period_month) as period_ids,
51
+ array_agg(distinct p.period_month) as period_months,
52
+ sum(p.charge_cents_total)::integer as amount_cents
53
+ from public.print_usage_periods p
54
+ where p.status = 'pending_bill'
55
+ and p.billing_run_id is null
56
+ and p.billed_run_id is null
57
+ and p.charge_cents_total > 0
58
+ group by p.membership_id
59
+ having sum(p.charge_cents_total) >= ${STRIPE_MIN_CENTS}
60
+ and not exists (
61
+ select 1 from public.print_billing_runs r
62
+ where r.membership_id = p.membership_id
63
+ and r.completed_at is null
64
+ )`;
65
+ /** [v18/B12-1] The baseline query. The ORDER BY and LIMIT MUST live in a
66
+ * subquery: v6..v17 printed an ungrouped avg() with a bare ORDER BY, which
67
+ * PostgreSQL rejects outright with 42803 (T-46), and deleting the ORDER BY to
68
+ * "fix" it silently widens the window to the membership's entire history —
69
+ * a 25x baseline error on the v18 fixture (T-46b). Returns BOTH operands rule 2
70
+ * needs; the old form returned no count at all, so the rule was unimplementable
71
+ * from its own stated input. */
72
+ export const BASELINE_SQL = `
73
+ select coalesce(avg(b.billed_amount_cents), 0)::numeric as baseline_cents,
74
+ count(*)::integer as qualifying_periods
75
+ from (
76
+ select p.billed_amount_cents, p.period_month
77
+ from public.print_usage_periods p
78
+ where p.membership_id = $1
79
+ and p.status = 'billed'
80
+ and p.billed_amount_cents > 0
81
+ order by p.period_month desc
82
+ limit ${BASELINE_WINDOW}
83
+ ) b`;
84
+ /** section 5.3's escalation ladder. A held run gets louder rather than expiring —
85
+ * an automatic expiry that frees the periods is exactly what created the
86
+ * double-charge hole in R7 F4 / R8 F2. */
87
+ export const STUCK_ESCALATION_SQL = `
88
+ insert into public.ops_events (kind, severity, detail, dedupe_key)
89
+ select
90
+ 'print_billing_run_stuck',
91
+ case
92
+ when r.updated_at < now() - interval '7 days' then 'critical'
93
+ when r.updated_at < now() - interval '24 hours' then 'error'
94
+ else 'warning'
95
+ end,
96
+ jsonb_build_object(
97
+ 'run_id', r.id, 'membership_id', r.membership_id, 'status', r.status,
98
+ 'hold_reason', r.hold_reason, 'amount_cents', r.amount_cents,
99
+ 'stripe_invoice_id', r.stripe_invoice_id,
100
+ 'stuck_for', now() - r.updated_at,
101
+ 'blocking_future_runs_for_membership', true),
102
+ 'print_billing_run_stuck:' || r.id::text || ':'
103
+ || (now() at time zone 'UTC')::date::text
104
+ from public.print_billing_runs r
105
+ where r.completed_at is null
106
+ and r.status = 'held'
107
+ on conflict (dedupe_key) where dedupe_key is not null do nothing`;
108
+ /** Rules 1-3 of section 4.2's gate. The two gates are INDEPENDENT and both are
109
+ * evaluated — a run can trip the cap without the ratio and vice versa, and
110
+ * staff need to know which rule caught it, so this never short-circuits. */
111
+ export function evaluateGate(input) {
112
+ const overCap = input.amountCents > HARD_CAP_CENTS;
113
+ // With fewer than 3 qualifying periods the relative check is SKIPPED entirely
114
+ // (R2's finding): a member's first real charge must not trip a ratio against an
115
+ // empty or all-zero history.
116
+ const anomaly = input.qualifyingPeriods >= MIN_QUALIFYING_PERIODS &&
117
+ input.amountCents >= ANOMALY_MULTIPLIER * input.baselineCents;
118
+ return { overCap, anomaly, blocked: overCap || anomaly };
119
+ }
120
+ function isNotFound(e) {
121
+ const anyE = e;
122
+ return anyE?.statusCode === 404 || anyE?.status === 404 || anyE?.code === "resource_missing";
123
+ }
124
+ /**
125
+ * section 4.3.1, in strict order.
126
+ *
127
+ * LAYER 1 is the stored id. A 404 there is NEVER, by itself, evidence that no
128
+ * invoice exists — it is only ever a reason to run LAYER 2 (section 4.3.2, round 8
129
+ * blocking finding 3). A wrong-account key or a corrupted write-back would also
130
+ * 404 a real, live invoice, and the v13 design would have released and re-billed it.
131
+ *
132
+ * LAYER 2 is List Invoices — NOT Search (C-05). Stripe's own docs warn against
133
+ * Search for read-after-write, and the one window where stripe_invoice_id is NULL
134
+ * on an incomplete run is the seconds right after creation, which is Search's
135
+ * worst case. There is deliberately NO status filter: a status=draft filter makes
136
+ * "not found" unsound, because an already-finalized invoice is invisible to it and
137
+ * the not-found branch then draws the stronger "never happened" conclusion.
138
+ */
139
+ export async function runOracle(stripe, input) {
140
+ let via404 = false;
141
+ // ---- LAYER 1 -----------------------------------------------------------
142
+ if (input.storedInvoiceId) {
143
+ try {
144
+ const inv = await stripe.invoices.retrieve(input.storedInvoiceId);
145
+ return { found: "yes", invoice: inv };
146
+ }
147
+ catch (e) {
148
+ if (isNotFound(e)) {
149
+ via404 = true; // fall through to LAYER 2 — do NOT conclude "no invoice"
150
+ }
151
+ else {
152
+ return { found: "unknown" }; // transient; retry next sweep
153
+ }
154
+ }
155
+ }
156
+ // ---- LAYER 2 -----------------------------------------------------------
157
+ const matches = [];
158
+ let startingAfter;
159
+ for (let page = 0; page < 20; page++) {
160
+ let res;
161
+ try {
162
+ res = await stripe.invoices.list({
163
+ customer: input.customerId,
164
+ limit: 100,
165
+ ...(startingAfter ? { starting_after: startingAfter } : {}),
166
+ });
167
+ }
168
+ catch {
169
+ return { found: "unknown" };
170
+ }
171
+ for (const inv of res.data) {
172
+ if (inv.metadata?.gc_run_id === input.runId)
173
+ matches.push(inv);
174
+ }
175
+ if (!res.has_more || res.data.length === 0)
176
+ break;
177
+ startingAfter = res.data[res.data.length - 1].id;
178
+ }
179
+ if (matches.length === 1)
180
+ return { found: "yes", invoice: matches[0] };
181
+ if (matches.length > 1)
182
+ return { found: "conflict" }; // never expected; HOLD
183
+ return { found: "no", via404 };
184
+ }
185
+ const IN_FLIGHT = ["claimed", "invoice_created", "items_posted", "finalizing"];
186
+ export function isInFlight(status) {
187
+ return IN_FLIGHT.includes(status);
188
+ }
189
+ /**
190
+ * section 4.4, encoded. Given a run in this state and this oracle result, do exactly
191
+ * this. `failureOrigin` is deliberately NOT a parameter: it exists only inside one
192
+ * invocation and is gone the moment the process is (section 4.4.1). Every decision
193
+ * below is driven by the ORACLE RESULT and the RUN'S PERSISTED STATUS, both of
194
+ * which survive the process — which is why rows 23-25 (no recorded origin) are the
195
+ * COMMON case and need no separate branch.
196
+ */
197
+ export function decideRecoveryAction(runStatus, storedInvoiceId, oracle) {
198
+ // Rows 19-22: terminal states are no-ops for automation.
199
+ if (!isInFlight(runStatus))
200
+ return { kind: "noop" };
201
+ if (oracle.found === "unknown")
202
+ return { kind: "retry" }; // rows 4, 9, 15
203
+ if (oracle.found === "conflict")
204
+ return { kind: "hold", reason: "duplicate_invoices_for_run" }; // row 5
205
+ if (oracle.found === "no") {
206
+ // section 4.3.2: automatic release is reachable from EXACTLY ONE state —
207
+ // claimed AND no stored id AND LAYER 2 verified empty. Anything else is a
208
+ // data-integrity event, not a routine retry.
209
+ if (runStatus === "claimed" && !storedInvoiceId && !oracle.via404) {
210
+ return { kind: "release_run" }; // row 1
211
+ }
212
+ return { kind: "hold", reason: "invoice_404_unverified" }; // rows 8, 14
213
+ }
214
+ // oracle.found === "yes"
215
+ const st = oracle.invoice.status ?? "draft";
216
+ if (st === "void" || st === "uncollectible") {
217
+ return { kind: "hold", reason: "invoice_terminal_out_of_band" }; // row 13
218
+ }
219
+ if (st === "draft") {
220
+ if (runStatus === "claimed")
221
+ return { kind: "adopt_draft" }; // row 2
222
+ if (runStatus === "invoice_created")
223
+ return { kind: "resume_items" }; // row 6
224
+ return { kind: "refinalize" }; // row 10
225
+ }
226
+ // open / paid — the invoice finalized behind us. Do not post more items.
227
+ return { kind: "adopt_finalized", paid: st === "paid" }; // rows 3, 7, 11, 12
228
+ }
229
+ const MONTHS = ["January", "February", "March", "April", "May", "June", "July",
230
+ "August", "September", "October", "November", "December"];
231
+ export function monthName(periodMonth) {
232
+ const m = Number(periodMonth.slice(5, 7));
233
+ return `${MONTHS[m - 1]} ${periodMonth.slice(0, 4)}`;
234
+ }
235
+ export function itemDescription(p) {
236
+ return `Print & copy usage - ${monthName(p.period_month)} ` +
237
+ `(${p.bw_billable} b/w, ${p.color_pages} color)`;
238
+ }
239
+ /**
240
+ * STEP 0.2 — verify the key's account BEFORE anything else.
241
+ * This is what makes a later 404 interpretable at all (R8 F3): without it,
242
+ * "404" and "we are looking in the wrong Stripe account" are the same observation.
243
+ */
244
+ export async function preflightAccount(stripe, expectedAccountId, expectedLivemode) {
245
+ const acct = await stripe.account.retrieve();
246
+ if (acct.id !== expectedAccountId) {
247
+ return { ok: false, detail: `stripe account mismatch: got ${acct.id}, expected ${expectedAccountId}` };
248
+ }
249
+ if (acct.livemode !== undefined && acct.livemode !== expectedLivemode) {
250
+ return { ok: false, detail: `stripe livemode mismatch: got ${acct.livemode}, expected ${expectedLivemode}` };
251
+ }
252
+ return { ok: true };
253
+ }
254
+ function pmId(ref) {
255
+ if (!ref)
256
+ return null;
257
+ return typeof ref === "string" ? ref : ref.id;
258
+ }
259
+ /**
260
+ * STEP 0.4 / C-13, resolved for real. Standalone customer-scoped invoices do
261
+ * NOT inherit subscription.default_payment_method, and 3 of 20 live
262
+ * subscriptions have a different card there than the customer's own default.
263
+ * Preference order, exactly as the design states it:
264
+ * a) subscription.default_payment_method (if the member has a live sub)
265
+ * b) customer.invoice_settings.default_payment_method
266
+ * c) none -> caller sets nothing on the invoice; it still finalizes and duns.
267
+ *
268
+ * This MUST live here, not in the DB (private.print_billing_resolve_customer):
269
+ * there is no synchronous HTTP extension in this Postgres (C-03), so a SQL/
270
+ * stable function cannot call Stripe to ask a subscription what its payment
271
+ * method is. The DB function resolves identifiers only; this resolves the
272
+ * actual preference order against a live Stripe client.
273
+ *
274
+ * A subscription that fails to retrieve (deleted, canceled and purged, wrong
275
+ * account) falls through to (b) rather than aborting the run — a stale
276
+ * subscription id must not block billing a member who otherwise owes money.
277
+ */
278
+ export async function resolveDefaultPaymentMethod(stripe, resolution) {
279
+ if (resolution.stripeSubscriptionId) {
280
+ try {
281
+ const sub = await stripe.subscriptions.retrieve(resolution.stripeSubscriptionId);
282
+ const fromSub = pmId(sub?.default_payment_method);
283
+ if (fromSub)
284
+ return fromSub;
285
+ }
286
+ catch {
287
+ // fall through to (b) — a bad/stale subscription id must not block billing
288
+ }
289
+ }
290
+ try {
291
+ const cust = await stripe.customers.retrieve(resolution.stripeCustomerId);
292
+ const fromCust = pmId(cust?.invoice_settings?.default_payment_method);
293
+ if (fromCust)
294
+ return fromCust;
295
+ }
296
+ catch {
297
+ // fall through to (c)
298
+ }
299
+ return null;
300
+ }
301
+ /**
302
+ * section 4.2 STEP 1 through STEP 4, with every Stripe failure routed to
303
+ * section 4.3's oracle rather than to "release and retry" (R4).
304
+ */
305
+ export async function executeBillingRun(stripe, db, input) {
306
+ // ---- STEP 0.2 preflight -------------------------------------------------
307
+ const pre = await preflightAccount(stripe, input.expectedAccountId, input.expectedLivemode);
308
+ if (!pre.ok) {
309
+ // Aborts before any claim. Nothing is written. (T-56)
310
+ return { ok: false, exitCode: 1, status: "aborted_preflight", detail: pre.detail };
311
+ }
312
+ // ---- STEP 1: T1 claim ---------------------------------------------------
313
+ let claimed;
314
+ try {
315
+ claimed = await db.claim({
316
+ runId: input.runId,
317
+ periodMonths: input.periodMonths,
318
+ periodIds: input.periodIds,
319
+ customerId: input.customerId,
320
+ amountCents: input.amountCents,
321
+ idempotencyKey: runKey(input.runId),
322
+ });
323
+ }
324
+ catch (e) {
325
+ const code = gcCodeOf(e);
326
+ if (code === "GC002") {
327
+ // Benign: another run is in flight for this membership, or the key was
328
+ // reused. Recovery (section 5) owns the other run.
329
+ return { ok: true, exitCode: 0, status: "already_in_flight" };
330
+ }
331
+ if (code === "GC003") {
332
+ // PARTIAL CLAIM or AMOUNT DRIFT. The transaction rolled back, so nothing
333
+ // exists — this insert happens from OUTSIDE the failed transaction.
334
+ // Handling is identical for both causes DELIBERATELY: both mean "the
335
+ // picture this invocation was working from is no longer true", and the
336
+ // correct next action is to re-derive eligibility on a later invocation,
337
+ // never to patch up the numbers in-process.
338
+ await db.opsEvent("print_billing_partial_claim", "error", {
339
+ run_id: input.runId,
340
+ membership_id: input.membershipId,
341
+ requested: input.periodIds.length,
342
+ amount_cents: input.amountCents,
343
+ sqlerrm: String(e?.message ?? e),
344
+ });
345
+ return { ok: false, exitCode: 1, status: "partial_claim" };
346
+ }
347
+ return { ok: false, exitCode: 1, status: "claim_failed", detail: String(e?.message ?? e) };
348
+ }
349
+ const lease = claimed.lease_token;
350
+ return await driveFromClaimed(stripe, db, input, lease);
351
+ }
352
+ /** STEP 2 onward. Shared by the fresh run and by recovery's resume path. */
353
+ export async function driveFromClaimed(stripe, db, input, lease) {
354
+ // ---- STEP 2: create the draft invoice -----------------------------------
355
+ let attempts;
356
+ try {
357
+ attempts = await db.attemptBump(input.runId, lease);
358
+ }
359
+ catch (e) {
360
+ // GC005 == we lost the lease. EXIT immediately, write nothing (row 18).
361
+ if (gcCodeOf(e) === "GC005")
362
+ return { ok: true, exitCode: 0, status: "lease_lost" };
363
+ throw e;
364
+ }
365
+ if (attempts > 3) {
366
+ await db.hold(input.runId, lease, "attempt_count exceeded before invoice creation");
367
+ return { ok: false, exitCode: 1, status: "held", detail: "attempt_count_exceeded" };
368
+ }
369
+ await db.leaseRenew(input.runId, lease);
370
+ let invoice;
371
+ try {
372
+ invoice = await stripe.invoices.create({
373
+ customer: input.customerId,
374
+ collection_method: "charge_automatically",
375
+ // C-06: NOT true here. Setting auto_advance at creation lets Stripe
376
+ // auto-finalize and charge an incomplete draft on its own after ~1hr,
377
+ // bypassing verification (R3). It is passed to FINALIZE instead.
378
+ auto_advance: false,
379
+ pending_invoice_items_behavior: "exclude",
380
+ ...(input.defaultPaymentMethod ? { default_payment_method: input.defaultPaymentMethod } : {}),
381
+ description: "Print & copy usage",
382
+ metadata: {
383
+ gc_run_id: input.runId,
384
+ gc_feature: "print_usage_bill",
385
+ gc_membership_id: input.membershipId,
386
+ gc_period_ids: input.periodIds.join(","),
387
+ },
388
+ }, { idempotencyKey: runKey(input.runId) });
389
+ }
390
+ catch {
391
+ return await recoveryRoute(stripe, db, input, lease);
392
+ }
393
+ // ---- STEP 2.5: T2 write-back -------------------------------------------
394
+ // [v16/B10-1] NOTE THE EMPTY p_detail AND WHAT M-14 DOES WITH IT. There are no
395
+ // line items yet, but M-14 no longer treats "no detail" as "nothing to stamp":
396
+ // it sets stripe_invoice_id on EVERY period this run claimed, right here,
397
+ // because from this instant a real Stripe object exists and the period-level
398
+ // money guards in M-04 and M-17 must be able to see it. Before v16 they could
399
+ // not, and section 2.3.2 is the double charge that window allowed.
400
+ await db.writeback(input.runId, lease, "invoice_created", invoice.id, {});
401
+ return await postItemsAndFinalize(stripe, db, input, lease, invoice.id);
402
+ }
403
+ /** STEP 3 (items) + STEP 4 (finalize). Also recovery's resume point. */
404
+ export async function postItemsAndFinalize(stripe, db, input, lease, invoiceId,
405
+ /** How many times THIS invocation has already re-entered the item/finalize loop
406
+ * via the recovery route. See the note on `applyRecoveryAction`. */
407
+ depth = 0) {
408
+ for (const periodId of input.periodIds) {
409
+ // ---- STEP 3.1: DB-SIDE dedup (C-17) ----------------------------------
410
+ const p = await db.getPeriod(periodId);
411
+ if (!p) {
412
+ await db.hold(input.runId, lease, `period_missing: ${periodId}`);
413
+ return { ok: false, exitCode: 1, status: "held", detail: "period_missing" };
414
+ }
415
+ // [v16/B10-1] The oracle reads stripe_invoice_ITEM_id (ii_), NOT
416
+ // stripe_invoice_id. That distinction is load-bearing: M-14 now stamps
417
+ // stripe_invoice_id on every claimed period at STEP 2.5, so an oracle keyed
418
+ // on THAT column would report every period as already-posted, skip the whole
419
+ // loop, and finalize a $0.00 invoice. Do not "simplify" this to read
420
+ // stripe_invoice_id. (T-26h)
421
+ if (p.stripe_invoice_item_id)
422
+ continue;
423
+ // [v17/B11-1] THE THIRD LEG OF THE FIX, and the only one standing at the
424
+ // layer where the MONEY actually moves. This loop is driven by the RUN's
425
+ // period_ids snapshot, taken at claim time and never revised. Until v17
426
+ // nothing between that snapshot and POST /v1/invoiceitems re-checked that the
427
+ // period was still ours — so a period released out from under a live run was
428
+ // still invoiced, then missed every one of M-14's `where billing_run_id =
429
+ // p_run_id` write-backs, ending with no Stripe trace and both run ids NULL.
430
+ // HOLD rather than skip: a period vanishing from a live run's claim set is a
431
+ // data-integrity event, not a routine condition.
432
+ if (p.billing_run_id !== input.runId || p.billed_run_id !== input.runId) {
433
+ await db.hold(input.runId, lease, `period_no_longer_claimed_by_this_run: ${periodId}`);
434
+ return { ok: false, exitCode: 1, status: "held", detail: "period_no_longer_claimed_by_this_run" };
435
+ }
436
+ await db.leaseRenew(input.runId, lease);
437
+ let item;
438
+ try {
439
+ item = await stripe.invoiceItems.create({
440
+ customer: input.customerId,
441
+ invoice: invoiceId,
442
+ currency: "usd",
443
+ // [v16/S10-4] THIS VALUE COMES FROM THE ROW RE-READ ABOVE, never from the
444
+ // section 4.2 eligibility snapshot, which was computed in a different
445
+ // transaction and may be minutes old.
446
+ amount: p.charge_cents_total,
447
+ description: itemDescription(p),
448
+ metadata: { gc_period_id: periodId, gc_run_id: input.runId },
449
+ }, { idempotencyKey: itemKey(input.runId, periodId) });
450
+ }
451
+ catch {
452
+ // The run is at `invoice_created` and HAS a stored invoice id. Both must be
453
+ // passed: the oracle keys LAYER 1 on the id, and section 4.4 keys the routing on
454
+ // the status. Defaulting either one turns rows 6-9 into rows 1-5.
455
+ return await recoveryRoute(stripe, db, input, lease, "invoice_created", invoiceId, depth);
456
+ }
457
+ // ---- STEP 3.5: write back the ii_ IMMEDIATELY, not batched -------------
458
+ // The dedup oracle at 3.1 is only sound if this is written before the next
459
+ // call can crash.
460
+ await db.writeback(input.runId, lease, "items_posted", invoiceId, { [periodId]: { item_id: item.id } });
461
+ }
462
+ await db.writeback(input.runId, lease, "items_posted", invoiceId, {});
463
+ // ---- STEP 4: finalize, ONE call (C-06) ---------------------------------
464
+ await db.leaseRenew(input.runId, lease);
465
+ let finalized;
466
+ try {
467
+ finalized = await stripe.invoices.finalize(invoiceId, {
468
+ // Passed DIRECTLY to finalize. Not set at creation (R3), not a second
469
+ // call (R4). With auto_advance:false here Stripe never attempts payment
470
+ // and the run would report success having collected nothing (R1).
471
+ auto_advance: true,
472
+ }, { idempotencyKey: finalizeKey(input.runId) });
473
+ }
474
+ catch {
475
+ // THIS IS THE MOST DANGEROUS BRANCH IN THE SYSTEM. It must never route to
476
+ // "release and let it retry" — R4's finding. It routes to "check what
477
+ // actually happened".
478
+ //
479
+ // Passing the real status AND the real invoice id is what makes that true.
480
+ // With the defaults, the oracle would look for no stored id, LAYER 2 would
481
+ // come back empty for a customer whose invoice is right there, and section 4.4
482
+ // would take row 1 and RELEASE a run that already has a finalized invoice —
483
+ // clearing billed_run_id and re-billing the member next sweep. T-54 is that
484
+ // regression test.
485
+ return await recoveryRoute(stripe, db, input, lease, "items_posted", invoiceId, depth);
486
+ }
487
+ const detail = await resolveLineIds(stripe, db, input, invoiceId);
488
+ await db.writeback(input.runId, lease, "billed", invoiceId, detail);
489
+ return { ok: true, exitCode: 0, status: "billed", invoiceId };
490
+ }
491
+ /**
492
+ * STEP 4.4 — resolve the il_ line ids that section 6 will need.
493
+ * R8 should-fix: a credit note needs an il_, NOT an ii_. The link back to the
494
+ * invoice item lives at line.parent.invoice_item_details.invoice_item, and the
495
+ * invoice-LINE object carries its own (empty) metadata — which is why the
496
+ * Stripe-side diff oracle was unsound (R7 F2) and the DB is the dedup oracle.
497
+ */
498
+ export async function resolveLineIds(stripe, db, input, invoiceId) {
499
+ const detail = {};
500
+ let lines;
501
+ try {
502
+ lines = await stripe.invoices.listLines(invoiceId, { limit: 100 });
503
+ }
504
+ catch {
505
+ return detail; // best effort; section 6 can re-resolve later
506
+ }
507
+ const itemToLine = new Map();
508
+ for (const l of lines.data) {
509
+ const ii = l.parent?.invoice_item_details?.invoice_item;
510
+ if (ii)
511
+ itemToLine.set(ii, l.id);
512
+ }
513
+ for (const periodId of input.periodIds) {
514
+ const p = await db.getPeriod(periodId);
515
+ if (p?.stripe_invoice_item_id) {
516
+ const lineId = itemToLine.get(p.stripe_invoice_item_id);
517
+ if (lineId)
518
+ detail[periodId] = { line_id: lineId };
519
+ }
520
+ }
521
+ return detail;
522
+ }
523
+ /** section 4.3 RECOVERY-ROUTE: consult the oracle, then act per section 4.4. */
524
+ export async function recoveryRoute(stripe, db, input, lease, runStatus = "claimed", storedInvoiceId = null, depth = 0) {
525
+ const oracle = await runOracle(stripe, {
526
+ runId: input.runId,
527
+ customerId: input.customerId,
528
+ storedInvoiceId,
529
+ });
530
+ const action = decideRecoveryAction(runStatus, storedInvoiceId, oracle);
531
+ return await applyRecoveryAction(stripe, db, input, lease, action, oracle, depth);
532
+ }
533
+ /**
534
+ * `depth` bounds re-entry into the item/finalize loop WITHIN A SINGLE INVOCATION.
535
+ *
536
+ * Without it, a persistently failing POST /v1/invoiceitems recurses forever:
537
+ * item fails -> recoveryRoute -> oracle says the draft is still there ->
538
+ * resume_items -> item fails -> ... This is not the production retry path. Each
539
+ * section 5.2 recovery sweep is a SEPARATE invocation five minutes later, and that is
540
+ * where a genuine retry belongs (rows 4/9/15, "retry next sweep"); attempt_count
541
+ * and the lease are what bound it across invocations. Re-entering in-process
542
+ * would also spin against Stripe with no backoff.
543
+ */
544
+ const MAX_RESUME_DEPTH = 1;
545
+ export async function applyRecoveryAction(stripe, db, input, lease, action, oracle, depth = 0) {
546
+ const wouldReenter = action.kind === "adopt_draft" || action.kind === "resume_items" || action.kind === "refinalize";
547
+ if (wouldReenter && depth >= MAX_RESUME_DEPTH) {
548
+ return { ok: true, exitCode: 0, status: "retry_next_sweep" };
549
+ }
550
+ switch (action.kind) {
551
+ case "release_run":
552
+ // The ONLY automatic path that clears billed_run_id (row 1).
553
+ await db.releaseRun(input.runId, lease, "no Stripe object exists: List Invoices by customer returned no match for this run", true);
554
+ return { ok: true, exitCode: 0, status: "released" };
555
+ case "hold":
556
+ await db.hold(input.runId, lease, action.reason);
557
+ return { ok: false, exitCode: 1, status: "held", detail: action.reason };
558
+ case "retry":
559
+ // Transient. Leave it; the next sweep picks it up by lease age.
560
+ return { ok: true, exitCode: 0, status: "retry_next_sweep" };
561
+ case "adopt_draft": {
562
+ const inv = oracle.invoice;
563
+ await db.writeback(input.runId, lease, "invoice_created", inv.id, {});
564
+ return await postItemsAndFinalize(stripe, db, input, lease, inv.id, depth + 1);
565
+ }
566
+ case "resume_items": {
567
+ const inv = oracle.invoice;
568
+ return await postItemsAndFinalize(stripe, db, input, lease, inv.id, depth + 1);
569
+ }
570
+ case "refinalize": {
571
+ const inv = oracle.invoice;
572
+ return await postItemsAndFinalize(stripe, db, input, lease, inv.id, depth + 1);
573
+ }
574
+ case "adopt_finalized": {
575
+ const inv = oracle.invoice;
576
+ const detail = await resolveLineIds(stripe, db, input, inv.id);
577
+ await db.writeback(input.runId, lease, "billed", inv.id, detail);
578
+ if (action.paid)
579
+ await db.paymentStatus(inv.id, "paid");
580
+ return { ok: true, exitCode: 0, status: "billed", invoiceId: inv.id };
581
+ }
582
+ case "noop":
583
+ return { ok: true, exitCode: 0, status: "noop" };
584
+ }
585
+ }
586
+ /**
587
+ * section 5.2. Selects abandoned runs through private.print_billing_recovery_select
588
+ * — a FUNCTION, and that is a fix (v18/B12-2): printed bare, the statement raises
589
+ * 42501 for the actor that actually runs it, because M-08 grants service_role
590
+ * SELECT only and `for update skip locked` needs UPDATE as well. Recovery could
591
+ * not select a single run.
592
+ */
593
+ export async function runRecoverySweep(deps, limit = 50) {
594
+ const pre = await preflightAccount(deps.stripe, deps.expectedAccountId, deps.expectedLivemode);
595
+ if (!pre.ok)
596
+ return [{ ok: false, exitCode: 1, status: "aborted_preflight", detail: pre.detail }];
597
+ const runs = await deps.db.recoverySelect(limit);
598
+ const out = [];
599
+ for (const run of runs) {
600
+ // Acquire the lease. If it returns no row the run was picked up by someone
601
+ // else between the select and the acquire: skip it SILENTLY. Do not treat
602
+ // 0 rows as an error, and do not proceed without a token — that is round 7
603
+ // finding 1's failure shape.
604
+ const lease = await deps.db.leaseAcquire(run.id);
605
+ if (!lease) {
606
+ out.push({ ok: true, exitCode: 0, status: "skipped_not_acquired" });
607
+ continue;
608
+ }
609
+ const input = await deps.loadRunInput(run);
610
+ const oracle = await runOracle(deps.stripe, {
611
+ runId: run.id,
612
+ customerId: run.stripe_customer_id,
613
+ storedInvoiceId: run.stripe_invoice_id,
614
+ });
615
+ const action = decideRecoveryAction(run.status, run.stripe_invoice_id, oracle);
616
+ out.push(await applyRecoveryAction(deps.stripe, deps.db, input, lease.lease_token, action, oracle));
617
+ }
618
+ return out;
619
+ }
@@ -0,0 +1,29 @@
1
+ import type { PrintDbLike, PrintStripeLike } from './printBilling.js';
2
+ interface SupabaseLike {
3
+ rpc(fn: string, args?: Record<string, unknown>): Promise<{
4
+ data: unknown;
5
+ error: {
6
+ message: string;
7
+ code?: string;
8
+ } | null;
9
+ }>;
10
+ from(table: string): {
11
+ select(cols: string): {
12
+ eq(col: string, v: unknown): {
13
+ maybeSingle(): Promise<{
14
+ data: unknown;
15
+ error: unknown;
16
+ }>;
17
+ };
18
+ };
19
+ insert(row: Record<string, unknown>): Promise<{
20
+ error: unknown;
21
+ }>;
22
+ };
23
+ }
24
+ export declare function makeDb(supabase: SupabaseLike): PrintDbLike;
25
+ /** Narrow the Stripe SDK down to the surface the design touches. The method
26
+ * names differ slightly from the SDK's (finalize / listLines), which is
27
+ * deliberate: the core names what it MEANS, and the mapping lives here. */
28
+ export declare function makeStripe(stripe: any): PrintStripeLike;
29
+ export {};