@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
@@ -1,2595 +0,0 @@
1
- import { createClient } from 'npm:@supabase/supabase-js@2';
2
- import Stripe from 'npm:stripe@17.5.0';
3
- import { logOps } from '../ops.ts';
4
- import { sendDayPassConfirmation } from '../dayPassConfirmation.ts';
5
- import { isDepositOnly, parseTstzRange, type BookingRow } from '../bookingEffects.ts';
6
- import { extractDoorAccess, type BusBooking, type DoorAccess } from '../busClient.ts';
7
- import {
8
- logWelcomeSkipped,
9
- WELCOME_OK_STATUSES,
10
- type WelcomePlan,
11
- type WelcomeResult,
12
- type PrivateOfficeBilling,
13
- } from '../membershipWelcome.ts';
14
- import { sendDunningEmail } from '../dunningEmails.ts';
15
- import { computeReferralCredits } from '../referralCredits.ts';
16
- import { recordReferralFailure, maybeGrantReferralCredit } from '../referralGrant.ts';
17
-
18
- import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
19
- // deno-lint-ignore no-explicit-any
20
- type SupabaseLike = SupabaseClient<any, 'public', any>;
21
-
22
- interface ReferralClawbackRow {
23
- id: string;
24
- referring_membership_id: string;
25
- referred_membership_id: string;
26
- referrer_credit_cents: number | null;
27
- referred_credit_cents?: number | null;
28
- stripe_balance_txn_id_referrer: string | null;
29
- stripe_balance_txn_id_referred?: string | null;
30
- clawback_eligible_until: string | null;
31
- }
32
-
33
- interface DayPassProvisionOutcome {
34
- status: 'provisioned' | 'dry_run' | 'disabled' | 'failed';
35
- credentialStatus: string | null;
36
- wifiCode: string | null;
37
- wifiValidFromIso: string | null;
38
- wifiValidToIso: string | null;
39
- error: string | null;
40
- }
41
-
42
- export interface StripeWebhookConfig {
43
- systemActorEmail: string;
44
- dayPassPortalRedirectUrl: string;
45
- // Tenant-specific membership_plans.slug values. Sponsored team seats and
46
- // virtual-office plans get their own welcome-email routing (see the
47
- // plan-classification block below) — these must come from config, not a
48
- // hardcoded literal, so a second tenant with different plan slugs doesn't
49
- // silently misclassify (and therefore mischarge/misroute) its members.
50
- teamSeatSlug: string;
51
- virtualOfficeSlug: string;
52
- siteConfig: {
53
- operatorName: string;
54
- operatorShortName: string;
55
- domain: string;
56
- supportEmail: string;
57
- };
58
-
59
- busProvision: (b: BusBooking, supabase: SupabaseLike) => Promise<Record<string, unknown> | null>;
60
- busCancel: (b: BusBooking, supabase: SupabaseLike) => Promise<Record<string, unknown> | null>;
61
-
62
- notifyGhl: (supabase: SupabaseLike, booking: BookingRow, doorAccess?: DoorAccess | null) => Promise<void>;
63
- createCalendarEvent: (supabase: SupabaseLike, booking: BookingRow) => Promise<void>;
64
-
65
- handleCommonsDepositSession: (supabase: SupabaseLike, session: Stripe.Checkout.Session) => Promise<void>;
66
-
67
- sendVirtualOfficeWelcome: (supabase: SupabaseLike, email: string, planId: string | null, plan: WelcomePlan) => Promise<WelcomeResult>;
68
- sendMembershipWelcome: (supabase: SupabaseLike, email: string, planId: string | null, customerName: string | null, status: string | null, plan: WelcomePlan, startsOnIso?: string | null) => Promise<WelcomeResult>;
69
- sendPrivateOfficeWelcome: (supabase: SupabaseLike, email: string, name: string | null, plan: WelcomePlan, billing?: PrivateOfficeBilling | null) => Promise<WelcomeResult>;
70
- loadPrivateOfficeBilling: (supabase: SupabaseLike, subscriptionId: string | null | undefined) => Promise<PrivateOfficeBilling | null>;
71
- sendTeamSeatWelcome: (supabase: SupabaseLike, email: string, name: string | null, companyName: string | null, plan: WelcomePlan) => Promise<WelcomeResult>;
72
-
73
- maybeActivateAgreement: (supabase: SupabaseLike, stripe: Stripe, signatureDocumentId: string) => Promise<void>;
74
- pacificMidnightUtc: (dateStr: string | null | undefined) => Date | null;
75
-
76
- maybeConvertTrialGrant: (supabase: SupabaseLike, membershipId: string | null | undefined, email: string | null | undefined) => Promise<void>;
77
-
78
- provisionDayPass: (supabase: SupabaseLike, bookingId: string, visitDate: string, email: string, name: string) => Promise<DayPassProvisionOutcome>;
79
- cancelDayPass: (supabase: SupabaseLike, bookingId: string) => Promise<{ ok: boolean; error: string | null }>;
80
- }
81
-
82
- export function createStripeWebhookHandler(
83
- config: StripeWebhookConfig,
84
- ): (req: Request) => Promise<Response> {
85
- const {
86
- systemActorEmail,
87
- dayPassPortalRedirectUrl,
88
- teamSeatSlug,
89
- virtualOfficeSlug,
90
- siteConfig,
91
- busProvision,
92
- busCancel,
93
- notifyGhl,
94
- createCalendarEvent,
95
- handleCommonsDepositSession,
96
- sendVirtualOfficeWelcome,
97
- sendMembershipWelcome,
98
- sendPrivateOfficeWelcome,
99
- loadPrivateOfficeBilling,
100
- sendTeamSeatWelcome,
101
- maybeActivateAgreement,
102
- pacificMidnightUtc,
103
- maybeConvertTrialGrant,
104
- provisionDayPass,
105
- cancelDayPass,
106
- } = config;
107
-
108
- // No CORS — this is called by Stripe, not the browser.
109
- return async (req: Request): Promise<Response> => {
110
- if (req.method !== 'POST') {
111
- return new Response('Method not allowed', { status: 405 });
112
- }
113
-
114
- const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
115
- const webhookSecret = Deno.env.get('STRIPE_WEBHOOK_SECRET');
116
- if (!stripeKey || !webhookSecret) {
117
- return new Response('Webhook not configured', { status: 500 });
118
- }
119
-
120
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as any });
121
- const signature = req.headers.get('stripe-signature');
122
- if (!signature) return new Response('Missing signature', { status: 400 });
123
-
124
- const rawBody = await req.text();
125
-
126
- let event: Stripe.Event;
127
- try {
128
- event = await stripe.webhooks.constructEventAsync(rawBody, signature, webhookSecret);
129
- } catch (err) {
130
- console.error('signature verification failed', err);
131
- return new Response('Invalid signature', { status: 400 });
132
- }
133
-
134
- const supabase = createClient(
135
- Deno.env.get('SUPABASE_URL')!,
136
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
137
- );
138
-
139
- // Idempotency ledger — dedupe Stripe redeliveries.
140
- {
141
- const { error: ledgerErr } = await supabase
142
- .from('stripe_events')
143
- .insert({ event_id: event.id, type: event.type });
144
- const code = (ledgerErr as { code?: string } | null)?.code;
145
- if (code === '23505') {
146
- return new Response(JSON.stringify({ received: true, duplicate: true }), {
147
- headers: { 'Content-Type': 'application/json' }, status: 200,
148
- });
149
- }
150
- if (ledgerErr) {
151
- console.error('[stripe-webhook] stripe_events insert failed (continuing)', ledgerErr);
152
- }
153
- }
154
-
155
- async function findBooking(session: Stripe.Checkout.Session) {
156
- const bid = session.metadata?.booking_id;
157
- if (bid) {
158
- const { data } = await supabase.from('bookings').select('id,status').eq('id', bid).maybeSingle();
159
- if (data) return data;
160
- }
161
- const { data } = await supabase
162
- .from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
163
- return data;
164
- }
165
-
166
- // --- Internal coupon helpers (self-serve membership / day-pass checkout) ---
167
- // create-subscription-checkout and create-day-pass-checkout reserve a
168
- // coupon_redemptions row at session-creation time and stamp its id onto the
169
- // session (and subscription) metadata. These two settle that reservation.
170
- //
171
- // Same defensive contract as every other side effect in this file: log and
172
- // continue. A coupon-bookkeeping failure must never stop the membership or
173
- // day-pass activation that already works today, and must never make Stripe
174
- // retry the event.
175
-
176
- /** reserved -> applied. Call only with independent proof the payment landed. */
177
- async function markCouponAppliedFromMetadata(
178
- metadata: Stripe.Metadata | null | undefined,
179
- ctx: Record<string, unknown>,
180
- ) {
181
- const redemptionId = metadata?.coupon_redemption_id;
182
- if (!redemptionId) return;
183
- try {
184
- const { data: redRow, error: readErr } = await supabase
185
- .from('coupon_redemptions')
186
- .select('id,status')
187
- .eq('id', redemptionId)
188
- .maybeSingle();
189
- if (readErr) throw readErr;
190
- if (!redRow) throw new Error('coupon_redemptions row not found');
191
- // Already settled either way -- a redelivery or a manual reversal.
192
- if (redRow.status === 'applied' || redRow.status === 'reversed') return;
193
- const { error: cmErr } = await supabase.rpc('coupon_mark_applied', {
194
- p_redemption_id: redRow.id,
195
- });
196
- if (cmErr) throw cmErr;
197
- } catch (e) {
198
- console.error('[stripe-webhook] coupon_mark_applied failed', e);
199
- await logOps(supabase, 'coupon_mark_applied_failed',
200
- { ...ctx, coupon_redemption_id: redemptionId, message: String(e) },
201
- { severity: 'warning' }).catch(() => {});
202
- }
203
- }
204
-
205
- /** reserved -> reversed, so an abandoned checkout doesn't eat a single-use code. */
206
- async function reverseCouponFromMetadata(
207
- metadata: Stripe.Metadata | null | undefined,
208
- reason: string,
209
- ctx: Record<string, unknown>,
210
- ) {
211
- const redemptionId = metadata?.coupon_redemption_id;
212
- if (!redemptionId) return;
213
- try {
214
- const { data: redRow, error: readErr } = await supabase
215
- .from('coupon_redemptions')
216
- .select('id,status')
217
- .eq('id', redemptionId)
218
- .maybeSingle();
219
- if (readErr) throw readErr;
220
- if (!redRow) throw new Error('coupon_redemptions row not found');
221
- // Never claw back a redemption that already funded a real payment.
222
- if (redRow.status === 'applied' || redRow.status === 'reversed') return;
223
- const { error: cvErr } = await supabase.rpc('coupon_reverse', {
224
- p_redemption_id: redRow.id,
225
- p_reason: reason,
226
- p_actor_email: systemActorEmail,
227
- });
228
- if (cvErr) throw cvErr;
229
- } catch (e) {
230
- console.error('[stripe-webhook] coupon_reverse failed', e);
231
- await logOps(supabase, 'coupon_reverse_failed',
232
- { ...ctx, coupon_redemption_id: redemptionId, reason, message: String(e) },
233
- { severity: 'warning' }).catch(() => {});
234
- }
235
- }
236
-
237
- // --- Membership helpers (subscription lifecycle) ---
238
- // The welcome senders live in _shared/membershipWelcome.ts. They are invoked
239
- // ONLY through maybeSendWelcomes() below, which owns the once-only claim.
240
-
241
- /**
242
- * Welcome-email gate. Safe to call from every path that successfully lands a
243
- * membership row: it decides, once and only once per membership, whether the
244
- * welcome email should go out.
245
- *
246
- * Two Stripe events race for the first INSERT — checkout.session.completed
247
- * (which re-retrieves the subscription and therefore sees 'active') and
248
- * customer.subscription.created (which carries the baked-in 'incomplete').
249
- * Whichever won the insert used to decide forever, because no later event
250
- * ever called a welcome sender. Now every path calls this, and the
251
- * welcome_email_sent_at compare-and-swap is what prevents a double send.
252
- *
253
- * Entirely wrapped in try/catch — it can never throw into the webhook handler
254
- * or make Stripe retry.
255
- */
256
- /**
257
- * Best-effort billing figures for the private-office welcome card.
258
- * Never throws, never blocks the send — null means "plain welcome".
259
- */
260
- async function officeBilling(membershipId: string | null | undefined) {
261
- try {
262
- if (!membershipId) return null;
263
- const { data: m } = await supabase
264
- .from('memberships').select('stripe_subscription_id').eq('id', membershipId).maybeSingle();
265
- return await loadPrivateOfficeBilling(supabase, (m?.stripe_subscription_id ?? null) as string | null);
266
- } catch (e) {
267
- await logOps(supabase, 'private_office_welcome_billing_lookup_failed',
268
- { membership_id: membershipId, message: e instanceof Error ? e.message : String(e) },
269
- { severity: 'warning' }).catch(() => {});
270
- return null;
271
- }
272
- }
273
-
274
- async function maybeSendWelcomes(
275
-
276
- membershipId: string | null | undefined,
277
- email: string | null | undefined,
278
- planId: string | null,
279
- customerName: string | null,
280
- status: string | null,
281
- createdAt?: string | null,
282
- sentAt?: string | null,
283
- startsOnIso?: string | null,
284
- ) {
285
- try {
286
- if (!membershipId || !email) return;
287
-
288
- let created = createdAt ?? null;
289
- let claimed = sentAt ?? null;
290
- if (created === null || sentAt === undefined) {
291
- const { data: row, error: rowErr } = await supabase
292
- .from('memberships')
293
- .select('welcome_email_sent_at,created_at')
294
- .eq('id', membershipId)
295
- .maybeSingle();
296
- if (rowErr) return; // unknown state -> never send
297
- if (row) {
298
- claimed = (row.welcome_email_sent_at as string | null) ?? null;
299
- created = (row.created_at as string | null) ?? null;
300
- }
301
- }
302
-
303
- // Already claimed → renewals are free: no send, no log, for years.
304
- if (claimed) return;
305
-
306
- // Age window, fail CLOSED. A "welcome" six months in is wrong, and an
307
- // unknown created_at must never be treated as "young enough".
308
- const createdMs = created ? Date.parse(created) : NaN;
309
- if (!Number.isFinite(createdMs)) return; // unknown age -> never send
310
- if ((Date.now() - createdMs) > 30 * 24 * 60 * 60 * 1000) return;
311
-
312
- if (!WELCOME_OK_STATUSES.has(String(status))) {
313
- await logWelcomeSkipped(supabase, email, 'status_not_paid', { plan_id: planId, status });
314
- return;
315
- }
316
-
317
- // Resolve the plan ONCE, before the claim. Every failure below returns
318
- // without claiming — nothing outbound has happened yet, so a later event
319
- // inside the 30-day window can still succeed once the cause is fixed.
320
- if (!planId) {
321
- await logWelcomeSkipped(supabase, email, 'no_plan_id', { status });
322
- return;
323
- }
324
- const { data: plan, error: planErr } = await supabase
325
- .from('membership_plans')
326
- .select('slug,name,price_display,unit,unifi_group_ids,wifi_enabled,active,category,is_private_office')
327
- .eq('id', planId)
328
- .maybeSingle();
329
- if (planErr) {
330
- await logWelcomeSkipped(supabase, email, 'plan_lookup_failed',
331
- { plan_id: planId, message: planErr.message });
332
- return;
333
- }
334
- if (!plan) {
335
- await logWelcomeSkipped(supabase, email, 'plan_not_found', { plan_id: planId });
336
- return;
337
- }
338
- // Sponsored team seats sit on the deliberately inactive, category='office'
339
- // plan named by config's teamSeatSlug. They get their own short welcome
340
- // and must bypass both the plan_inactive skip and the private-office
341
- // routing below.
342
- const isTeamSeat = plan.slug === teamSeatSlug;
343
- if (plan.active === false && !isTeamSeat) {
344
- await logWelcomeSkipped(supabase, email, 'plan_inactive',
345
- { plan_id: planId, plan_slug: plan.slug });
346
- return;
347
- }
348
- const isVirtualOffice = plan.slug === virtualOfficeSlug;
349
- const isOffice = plan.is_private_office === true && !isTeamSeat;
350
-
351
-
352
- // Compare-and-swap claim. Conditional update returning rows — never a
353
- // read-then-write; this is the only thing standing between the two racing
354
- // events and a double email.
355
- const claimTs = new Date().toISOString();
356
- const { data: claimRows, error: claimErr } = await supabase
357
- .from('memberships')
358
- .update({ welcome_email_sent_at: claimTs })
359
- .eq('id', membershipId)
360
- .is('welcome_email_sent_at', null)
361
- .select('id');
362
- if (claimErr) {
363
- console.warn('[stripe-webhook] welcome claim failed', claimErr);
364
- return;
365
- }
366
- if (!claimRows || claimRows.length === 0) return; // another event claimed it
367
-
368
- // Exactly one sender runs — routing above makes a double welcome
369
- // structurally impossible.
370
- const result = isVirtualOffice
371
- ? await sendVirtualOfficeWelcome(supabase, email, planId, plan)
372
- : isTeamSeat
373
- ? await sendTeamSeatWelcome(supabase, email, customerName, null, plan)
374
- : isOffice
375
- ? await sendPrivateOfficeWelcome(supabase, email, customerName, plan, await officeBilling(membershipId))
376
-
377
- : await sendMembershipWelcome(supabase, email, planId, customerName, status, plan, startsOnIso ?? null);
378
-
379
-
380
- if (result === 'sent') return;
381
-
382
- if (result === 'skipped') {
383
- // Every remaining 'skipped' returns before any outbound call, so
384
- // releasing the claim cannot duplicate an email. Guarded on the exact
385
- // value we wrote so a concurrent claim can never be clobbered.
386
- const { error: relErr } = await supabase
387
- .from('memberships')
388
- .update({ welcome_email_sent_at: null })
389
- .eq('id', membershipId)
390
- .eq('welcome_email_sent_at', claimTs);
391
- if (relErr) console.warn('[stripe-webhook] welcome claim release failed', relErr);
392
- await logOps(supabase, 'membership_welcome_claim_released',
393
- { email, membership_id: membershipId, plan_id: planId, result },
394
- { severity: 'warning' }).catch(() => {});
395
- return;
396
- }
397
-
398
- // failed_retryable / failed_permanent: the send may genuinely have
399
- // landed, so the claim stays set and this must never retry.
400
- await logOps(supabase, 'membership_welcome_email_burned',
401
- { email, membership_id: membershipId, plan_id: planId, result },
402
- { severity: 'error' }).catch(() => {});
403
- } catch (e) {
404
- console.warn('[stripe-webhook] maybeSendWelcomes failed (ignored)', e);
405
- }
406
- }
407
-
408
- // maybeConvertTrialGrant lives in ../_shared/trialConversion.ts (so it's
409
- // unit-testable without a live network/DB, same convention as
410
- // referralGrant.ts / membershipWelcome.ts) — imported above. Called at the
411
- // exact same call sites as maybeSendWelcomes, alongside it, never instead
412
- // of it.
413
-
414
- function subCurrentPeriodEndISO(sub: Stripe.Subscription): string | null {
415
- // deno-lint-ignore no-explicit-any
416
- const anySub = sub as any;
417
- const top = anySub.current_period_end as number | undefined;
418
- if (typeof top === 'number') return new Date(top * 1000).toISOString();
419
- // Recent Stripe API versions expose the billing period on the subscription item.
420
- const itemCpe = anySub.items?.data?.[0]?.current_period_end as number | undefined;
421
- if (typeof itemCpe === 'number') return new Date(itemCpe * 1000).toISOString();
422
- return null;
423
- }
424
-
425
- async function linkOfficeAssignment(sub: Stripe.Subscription, membershipId: string | null | undefined) {
426
- try {
427
- if (!membershipId) return;
428
- if (sub.metadata?.checkout_type !== 'private_office_agreement') return;
429
- const sigDocId = sub.metadata?.signature_document_id;
430
- if (!sigDocId) return;
431
-
432
- // Which room is this incoming tenant's row for? Needed to decide whether
433
- // the room is still physically occupied by a different active tenant.
434
- const { data: pendingRow, error: pendingErr } = await supabase
435
- .from('office_assignments')
436
- .select('id,room_id')
437
- .eq('signature_document_id', sigDocId)
438
- .eq('status', 'pending_activation')
439
- .maybeSingle();
440
- if (pendingErr) {
441
- await logOps(supabase, 'office_assignment_link_failed',
442
- { subscription_id: sub.id, signature_document_id: sigDocId, membership_id: membershipId, stage: 'lookup', message: pendingErr.message },
443
- { severity: 'error' });
444
- return;
445
- }
446
- if (!pendingRow) {
447
- // Subsequent webhook events (renewals, subscription updates) re-run this
448
- // linker. If the row was already linked previously it now sits in
449
- // 'active' or 'awaiting_handoff' -- that's normal, stay silent.
450
- const { data: linkedRows, error: linkedErr } = await supabase
451
- .from('office_assignments')
452
- .select('id,status')
453
- .eq('signature_document_id', sigDocId)
454
- .in('status', ['active', 'awaiting_handoff'])
455
- .limit(1);
456
- if (!linkedErr && linkedRows && linkedRows.length > 0) return;
457
-
458
- // A paying customer with no office_assignments row at all to flip --
459
- // they can otherwise silently go invisible. Always loud.
460
- await logOps(supabase, 'office_assignment_link_failed',
461
- { subscription_id: sub.id, signature_document_id: sigDocId, membership_id: membershipId, stage: 'no_pending_row', linked_lookup_error: linkedErr?.message ?? null },
462
- { severity: 'error' });
463
- return;
464
- }
465
-
466
-
467
- // Is someone else still actively occupying this room? If so the new
468
- // tenant queues as 'awaiting_handoff' -- never touch the existing active
469
- // row here; that only ends via end_office_assignment_and_promote.
470
- const { data: activeRows, error: activeErr } = await supabase
471
- .from('office_assignments')
472
- .select('id')
473
- .eq('room_id', pendingRow.room_id)
474
- .eq('status', 'active')
475
- .neq('id', pendingRow.id)
476
- .limit(1);
477
- if (activeErr) {
478
- await logOps(supabase, 'office_assignment_link_failed',
479
- { subscription_id: sub.id, signature_document_id: sigDocId, membership_id: membershipId, stage: 'active_check', message: activeErr.message },
480
- { severity: 'error' });
481
- return;
482
- }
483
- const nextStatus = (activeRows && activeRows.length > 0) ? 'awaiting_handoff' : 'active';
484
-
485
- const { data: updated, error } = await supabase
486
- .from('office_assignments')
487
- .update({ membership_id: membershipId, status: nextStatus })
488
- .eq('id', pendingRow.id)
489
- .eq('status', 'pending_activation')
490
- .is('membership_id', null)
491
- .select('id');
492
- if (error || !updated || updated.length === 0) {
493
- await logOps(supabase, 'office_assignment_link_failed',
494
- {
495
- subscription_id: sub.id,
496
- signature_document_id: sigDocId,
497
- membership_id: membershipId,
498
- office_assignment_id: pendingRow.id,
499
- attempted_status: nextStatus,
500
- stage: error ? 'update_error' : 'zero_rows_updated',
501
- message: error?.message ?? null,
502
- },
503
- { severity: 'error' });
504
- return;
505
- }
506
- if (nextStatus === 'awaiting_handoff') {
507
- await logOps(supabase, 'office_assignment_awaiting_handoff',
508
- { subscription_id: sub.id, signature_document_id: sigDocId, office_assignment_id: pendingRow.id, room_id: pendingRow.room_id },
509
- { severity: 'warning' });
510
- }
511
- } catch (e) {
512
- console.warn('[stripe-webhook] linkOfficeAssignment failed (ignored)', e);
513
- }
514
- }
515
-
516
- /**
517
- * D31-follow-up (office downgrade/rejoin gap): a private-office membership
518
- * ending (canceled/unpaid) while its office_assignments row is still
519
- * 'active' is exactly the trap that later stops that row from ever being
520
- * self-serve-adopted -- adoptEligible's encumbrance check above treats a
521
- * still-'active' office_assignments row as proof the room is genuinely
522
- * still occupied, and refuses to adopt. When staff hasn't yet closed out
523
- * the physical move-out (via /admin/offices -> end_office_assignment_and_
524
- * promote), that row is left behind as the OLDEST membership row for this
525
- * email, which is exactly what usePortalAuth.tsx reads by default -- so a
526
- * former office member who later downgrades or rejoins as a plain member
527
- * can portal-side look like they have no current membership even though a
528
- * newer, active row exists. This never auto-ends the assignment (occupancy
529
- * is a staff-confirmed physical fact, not a billing one) -- it only flags
530
- * it, once per membership, so staff have a durable reminder on the admin
531
- * dashboard (see useAttention.ts) instead of relying on remembering to
532
- * close it out at cancellation time. Best-effort: never throws, never
533
- * blocks the webhook.
534
- */
535
- async function flagStaleOfficeAssignmentIfEnded(
536
- membershipId: string | null | undefined,
537
- planId: string | null | undefined,
538
- isEnded: boolean,
539
- ) {
540
- try {
541
- if (!isEnded || !membershipId || !planId) return;
542
- const { data: plan } = await supabase
543
- .from('membership_plans').select('is_private_office').eq('id', planId).maybeSingle();
544
- if (plan?.is_private_office !== true) return;
545
- const { data: assignment } = await supabase
546
- .from('office_assignments')
547
- .select('id,room_id')
548
- .eq('membership_id', membershipId)
549
- .eq('status', 'active')
550
- .maybeSingle();
551
- if (!assignment) return;
552
- await logOps(supabase, 'office_membership_canceled_assignment_open', {
553
- membership_id: membershipId, office_assignment_id: assignment.id, room_id: assignment.room_id,
554
- }, { severity: 'warning', dedupeKey: `office_membership_canceled_assignment_open:${membershipId}` });
555
- } catch (e) {
556
- console.warn('[stripe-webhook] flagStaleOfficeAssignmentIfEnded failed (ignored)', e);
557
- }
558
- }
559
-
560
- /**
561
- * Referral program Phase 1, step 1 (signup capture).
562
- *
563
- * Called ONLY from the true first-time-INSERT branch of
564
- * upsertMembershipFromSubscription -- never on update-by-subscription-id or
565
- * the adopt/resubscribe path, since a referral only makes sense the first
566
- * time this membership row is ever created. `planId` is the caller's
567
- * already-resolved plan id (it has the private-office signature_documents
568
- * fallback baked in), not re-derived from sub.metadata here.
569
- *
570
- * Inserts a 'signed_up' referrals row only -- no credit amounts, no Stripe
571
- * balance calls. Those happen later, at first-invoice-paid (see
572
- * maybeGrantReferralCredit below). We do NOT call computeReferralCredits
573
- * here to "validate" plan.price_cents -- Math.max/Math.round never throw,
574
- * so that validated nothing. Instead we check price_cents directly and
575
- * refuse to insert a referrals row at all if it's missing, rather than
576
- * insert one that will compute NaN credits later.
577
- */
578
- async function maybeRecordReferral(
579
- sub: Stripe.Subscription,
580
- newMembershipId: string | null | undefined,
581
- planId: string | null,
582
- ) {
583
- try {
584
- if (!newMembershipId) return;
585
- const refCode = sub.metadata?.referral_code;
586
- if (!refCode) return; // no referral on this signup -- normal case
587
-
588
- const { data: referrer, error: referrerErr } = await supabase
589
- .from('memberships')
590
- .select('id')
591
- .eq('referral_code', refCode)
592
- .maybeSingle();
593
- if (referrerErr || !referrer) return; // unresolvable code -- silently skip, never block signup
594
- // Self-referral guard on top of the DB's own referrals_no_self_referral
595
- // CHECK constraint -- catch it here so we never even attempt the insert.
596
- if (referrer.id === newMembershipId) return;
597
-
598
- if (!planId) return;
599
- const { data: plan, error: planErr } = await supabase
600
- .from('membership_plans')
601
- .select('price_cents,billing_interval,category,is_private_office')
602
- .eq('id', planId)
603
- .maybeSingle();
604
- if (planErr || !plan) return;
605
- // Day Pass / any one-time plan is NEVER eligible for a referral credit.
606
- if (plan.billing_interval === 'one_time') return;
607
-
608
- // Real validation (per the docstring above): refuse to insert a
609
- // referrals row at all if price_cents is missing/non-positive, rather
610
- // than let it silently compute NaN/zero credits later at grant time.
611
- if (plan.price_cents == null || plan.price_cents <= 0) {
612
- console.warn('[stripe-webhook] maybeRecordReferral: plan missing/invalid price_cents, skipping referral row', {
613
- planId, price_cents: plan.price_cents,
614
- });
615
- return;
616
- }
617
-
618
- const isPrivateOffice = plan.is_private_office === true;
619
-
620
- const { error: refInsErr } = await supabase.from('referrals').insert({
621
- referring_membership_id: referrer.id,
622
- referred_membership_id: newMembershipId,
623
- referral_code_used: refCode,
624
- referred_plan_id: planId,
625
- referred_plan_price_cents: plan.price_cents ?? null,
626
- is_private_office: isPrivateOffice,
627
- });
628
- if (refInsErr) {
629
- console.error('[stripe-webhook] referral insert failed', {
630
- membership_id: newMembershipId, referring_membership_id: referrer.id, message: refInsErr.message,
631
- });
632
- }
633
- } catch (e) {
634
- console.warn('[stripe-webhook] maybeRecordReferral failed (ignored)', e);
635
- }
636
- }
637
-
638
- // recordReferralFailure moved verbatim to ../_shared/referralGrant.ts
639
- // (2026-08-24) so admin-referral-retry can share it too -- imported above.
640
-
641
- // maybeGrantReferralCredit moved verbatim to ../_shared/referralGrant.ts
642
- // (2026-08-24) so admin-referral-retry can call the exact same, already-
643
- // idempotent function on a grant_failed row instead of a second
644
- // hand-written copy of this Stripe balance-transaction logic. Imported
645
- // above; the call site below now passes supabase/stripe explicitly.
646
-
647
- /**
648
- * Referral program Phase 1, step 3 (clawback on fast cancel).
649
- *
650
- * Called from customer.subscription.deleted -- the only genuine
651
- * subscription-cancellation handler in this file (refund/dispute clawback
652
- * is handled separately below, via maybeClawbackReferralCreditForRefundOrDispute).
653
- *
654
- * Window check uses `canceledAtUnixSeconds` (Stripe's sub.canceled_at,
655
- * which reflects the time cancellation was REQUESTED, not -- for a
656
- * cancel_at_period_end subscription -- the later time this delete event
657
- * actually fires at period end) instead of wall-clock arrival time (fix
658
- * #2). Using arrival time made the clawback dead on the default cancel
659
- * path: a monthly plan's cancel_at_period_end delete event fires roughly a
660
- * month after the request, at or past the 30-day window edge, every time.
661
- *
662
- * Only the REFERRER's credit is reversed here (fix #9) -- a departing
663
- * referred member has no future invoice for a reversing debit to apply
664
- * against. Both sides are still reversed on the refund/dispute path below,
665
- * where the underlying payment itself no longer exists.
666
- */
667
- async function maybeClawbackReferralCredit(subId: string, canceledAtUnixSeconds: number | null) {
668
- try {
669
- const { data: membership, error: memErr } = await supabase
670
- .from('memberships')
671
- .select('id')
672
- .eq('stripe_subscription_id', subId)
673
- .maybeSingle();
674
- if (memErr || !membership) return;
675
-
676
- const { data: referral, error: refErr } = await supabase
677
- .from('referrals')
678
- .select(
679
- 'id,referring_membership_id,referred_membership_id,referrer_credit_cents,' +
680
- 'stripe_balance_txn_id_referrer,clawback_eligible_until',
681
- )
682
- .eq('referred_membership_id', membership.id)
683
- .eq('status', 'credited')
684
- .maybeSingle();
685
- if (refErr) {
686
- console.error('[stripe-webhook] referral clawback lookup failed', {
687
- membership_id: membership.id, message: refErr.message,
688
- });
689
- return;
690
- }
691
- if (!referral) return; // nothing credited on this membership -- normal case
692
- const typedReferral = referral as unknown as ReferralClawbackRow;
693
-
694
- const checkTimeMs = canceledAtUnixSeconds != null ? canceledAtUnixSeconds * 1000 : Date.now();
695
- if (!typedReferral.clawback_eligible_until || new Date(typedReferral.clawback_eligible_until).getTime() <= checkTimeMs) {
696
- return; // outside the 30-day clawback window, measured from the cancellation REQUEST
697
- }
698
- if (!typedReferral.referrer_credit_cents) return; // nothing to reverse
699
-
700
- const { data: referrerMembership, error: memErr2 } = await supabase
701
- .from('memberships')
702
- .select('id,stripe_customer_id')
703
- .eq('id', typedReferral.referring_membership_id)
704
- .maybeSingle();
705
- if (memErr2 || !referrerMembership?.stripe_customer_id) {
706
- console.error('[stripe-webhook] referral clawback missing referrer stripe_customer_id', { referral_id: typedReferral.id });
707
- await recordReferralFailure(supabase, typedReferral.id, 'credited', 'clawback_failed', memErr2 ?? new Error('missing referrer stripe_customer_id'));
708
- return;
709
- }
710
-
711
- try {
712
- // POSITIVE amount = reverse the earlier credit (increases what the
713
- // customer owes back by the same magnitude that was credited).
714
- await stripe.customers.createBalanceTransaction(
715
- referrerMembership.stripe_customer_id,
716
- {
717
- amount: typedReferral.referrer_credit_cents,
718
- currency: 'usd',
719
- description:
720
- `Referral clawback: reversing ${typedReferral.stripe_balance_txn_id_referrer ?? 'unknown txn'} ` +
721
- `(referral ${typedReferral.id})`,
722
- },
723
- { idempotencyKey: `ref-${typedReferral.id}-referrer-clawback-cancel` },
724
- );
725
- } catch (e) {
726
- console.error('[stripe-webhook] referral clawback balance transaction failed', {
727
- referral_id: typedReferral.id, message: e instanceof Error ? e.message : String(e),
728
- });
729
- await recordReferralFailure(supabase, typedReferral.id, 'credited', 'clawback_failed', e);
730
- return;
731
- }
732
-
733
- const { error: clawUpdErr } = await supabase
734
- .from('referrals')
735
- .update({ status: 'clawed_back', clawed_back_at: new Date().toISOString() })
736
- .eq('id', typedReferral.id)
737
- .eq('status', 'credited');
738
- if (clawUpdErr) {
739
- console.error('[stripe-webhook] referral clawback row update failed', {
740
- referral_id: typedReferral.id, message: clawUpdErr.message,
741
- });
742
- }
743
- } catch (e) {
744
- console.error('[stripe-webhook] maybeClawbackReferralCredit failed', {
745
- subscription_id: subId, message: e instanceof Error ? e.message : String(e),
746
- });
747
- }
748
- }
749
-
750
- /**
751
- * Referral clawback on refund or dispute (should-fix #7 from the round-2
752
- * review -- spec says clawback triggers on "cancels or refunds", and until
753
- * this existed only cancellation via customer.subscription.deleted ever
754
- * reversed anything). Unlike the cancellation path, this reverses BOTH
755
- * sides when it fires.
756
- *
757
- * Round-3 review finding N2: this has no direct link to WHICH invoice
758
- * funded the credit (the referrals row doesn't store that), so without
759
- * some scope limit, a refund on ANY charge on this membership's
760
- * subscription at ANY point in its life would reverse the referral --
761
- * e.g. a goodwill partial refund at month 14 debiting an uninvolved
762
- * referrer. Two narrowing guards, applied at the call sites below rather
763
- * than in here: (1) `charge.refunded` only calls this for a charge where
764
- * `charge.refunded === true` (a FULLY refunded charge, not partial --
765
- * partial refunds leave that flag false); (2) this function itself still
766
- * enforces `clawback_eligible_until`, computed at event-arrival time (no
767
- * cancel_at_period_end-style skew risk here the way there is on the
768
- * cancellation path) -- a refund/dispute long after the window closed no
769
- * longer reverses anything. Proper invoice-level linkage (storing the
770
- * funding invoice id on the referrals row) is a real follow-up, not done
771
- * in this pass.
772
- *
773
- * Round-3 review finding N3: dispute clawback fires on `charge.dispute.closed`
774
- * with `status === 'lost'` ONLY (never on `.created`, i.e. never while a
775
- * dispute is still open and could be won) -- see the switch-case below.
776
- * This avoids ever debiting a member for a dispute the merchant later wins,
777
- * and avoids needing a separate "restore on won" path entirely.
778
- *
779
- * Not fully atomic across the two Stripe calls the way the grant path is
780
- * (no per-step DB column to persist an in-progress two-sided clawback
781
- * into) -- if the referred-side call fails after the referrer-side one
782
- * succeeds, that's logged with both the referral id and "referrer side
783
- * already reversed", but not separately persisted to the row beyond the
784
- * final clawback_failed status (now recorded via the outer catch too,
785
- * round-3 finding 4a). Flagged for a future pass rather than silently
786
- * accepted.
787
- */
788
- async function maybeClawbackReferralCreditForRefundOrDispute(
789
- referredMembershipId: string,
790
- reasonTag: 'charge_refunded' | 'charge_dispute_closed_lost',
791
- ) {
792
- let referralId: string | null = null;
793
- try {
794
- const { data: referral, error: refErr } = await supabase
795
- .from('referrals')
796
- .select(
797
- 'id,referring_membership_id,referred_membership_id,referrer_credit_cents,referred_credit_cents,' +
798
- 'stripe_balance_txn_id_referrer,stripe_balance_txn_id_referred,clawback_eligible_until',
799
- )
800
- .eq('referred_membership_id', referredMembershipId)
801
- .eq('status', 'credited')
802
- .maybeSingle();
803
- if (refErr) {
804
- console.error('[stripe-webhook] referral refund/dispute clawback lookup failed', {
805
- membership_id: referredMembershipId, message: refErr.message,
806
- });
807
- return;
808
- }
809
- if (!referral) return; // nothing credited on this membership -- normal case
810
- const typedReferral = referral as unknown as ReferralClawbackRow;
811
- referralId = typedReferral.id;
812
-
813
- // Round-4 review finding: reusing the shared 30-day
814
- // clawback_eligible_until for BOTH reasons broke the dispute path
815
- // entirely -- card-network dispute rules allow filing up to 120 days
816
- // after the charge, and Stripe's own dispute lifecycle typically runs
817
- // 60-90+ days end to end, so a `charge.dispute.closed` (lost) event
818
- // arrives well past day 30 in the overwhelming majority of real
819
- // cases. A lost dispute is, by definition, a reversal of a real
820
- // payment -- N2's "an unrelated LATER event must not reverse this"
821
- // rationale for the 30-day window doesn't apply the same way to it.
822
- // Give the dispute path its own, much longer window instead of
823
- // widening the shared one (which would reopen N2 for refunds).
824
- const windowMs = reasonTag === 'charge_dispute_closed_lost'
825
- ? 180 * 24 * 60 * 60 * 1000
826
- : 30 * 24 * 60 * 60 * 1000;
827
- const createdAtMs = typedReferral.clawback_eligible_until
828
- ? new Date(typedReferral.clawback_eligible_until).getTime() - 30 * 24 * 60 * 60 * 1000
829
- : null;
830
- if (createdAtMs == null || createdAtMs + windowMs <= Date.now()) {
831
- return; // outside this reason's clawback window -- an unrelated later refund/dispute must not reverse this
832
- }
833
-
834
- const { data: parties, error: partiesErr } = await supabase
835
- .from('memberships')
836
- .select('id,stripe_customer_id')
837
- .in('id', [typedReferral.referring_membership_id, typedReferral.referred_membership_id]);
838
- if (partiesErr || !parties) {
839
- console.error('[stripe-webhook] referral refund/dispute clawback membership lookup failed', {
840
- referral_id: typedReferral.id, message: partiesErr?.message ?? 'no rows',
841
- });
842
- await recordReferralFailure(supabase, typedReferral.id, 'credited', 'clawback_failed', partiesErr ?? new Error('membership lookup returned no rows'));
843
- return;
844
- }
845
- const referringCustomerId =
846
- parties.find((m) => m.id === typedReferral.referring_membership_id)?.stripe_customer_id ?? null;
847
- const referredCustomerId =
848
- parties.find((m) => m.id === typedReferral.referred_membership_id)?.stripe_customer_id ?? null;
849
- if (!referringCustomerId || !referredCustomerId) {
850
- console.error('[stripe-webhook] referral refund/dispute clawback missing stripe_customer_id', { referral_id: typedReferral.id });
851
- await recordReferralFailure(supabase, typedReferral.id, 'credited', 'clawback_failed', new Error('missing stripe_customer_id on one or both parties'));
852
- return;
853
- }
854
-
855
- if (typedReferral.referrer_credit_cents) {
856
- try {
857
- await stripe.customers.createBalanceTransaction(
858
- referringCustomerId,
859
- {
860
- amount: typedReferral.referrer_credit_cents,
861
- currency: 'usd',
862
- description:
863
- `Referral clawback (${reasonTag}): reversing ${typedReferral.stripe_balance_txn_id_referrer ?? 'unknown txn'} ` +
864
- `(referral ${typedReferral.id})`,
865
- },
866
- { idempotencyKey: `ref-${typedReferral.id}-referrer-clawback-${reasonTag}` },
867
- );
868
- } catch (e) {
869
- console.error('[stripe-webhook] referral refund/dispute clawback (referrer) failed', {
870
- referral_id: typedReferral.id, message: e instanceof Error ? e.message : String(e),
871
- });
872
- await recordReferralFailure(supabase, typedReferral.id, 'credited', 'clawback_failed', e);
873
- return;
874
- }
875
- }
876
-
877
- if (typedReferral.referred_credit_cents) {
878
- try {
879
- await stripe.customers.createBalanceTransaction(
880
- referredCustomerId,
881
- {
882
- amount: typedReferral.referred_credit_cents,
883
- currency: 'usd',
884
- description:
885
- `Referral clawback (${reasonTag}): reversing ${typedReferral.stripe_balance_txn_id_referred ?? 'unknown txn'} ` +
886
- `(referral ${typedReferral.id})`,
887
- },
888
- { idempotencyKey: `ref-${typedReferral.id}-referred-clawback-${reasonTag}` },
889
- );
890
- } catch (e) {
891
- console.error('[stripe-webhook] referral refund/dispute clawback (referred) failed -- referrer side already reversed above', {
892
- referral_id: typedReferral.id, message: e instanceof Error ? e.message : String(e),
893
- });
894
- await recordReferralFailure(supabase, typedReferral.id, 'credited', 'clawback_failed', e);
895
- return;
896
- }
897
- }
898
-
899
- const { error: clawUpdErr } = await supabase
900
- .from('referrals')
901
- .update({ status: 'clawed_back', clawed_back_at: new Date().toISOString() })
902
- .eq('id', typedReferral.id)
903
- .eq('status', 'credited');
904
- if (clawUpdErr) {
905
- console.error('[stripe-webhook] referral refund/dispute clawback row update failed', {
906
- referral_id: typedReferral.id, message: clawUpdErr.message,
907
- });
908
- }
909
- } catch (e) {
910
- console.error('[stripe-webhook] maybeClawbackReferralCreditForRefundOrDispute failed', {
911
- membership_id: referredMembershipId, message: e instanceof Error ? e.message : String(e),
912
- });
913
- // Round-3 review finding 4a: the grant path's outer catch records a
914
- // failure; this path's outer catch previously did not. Symmetric now.
915
- if (referralId) await recordReferralFailure(supabase, referralId, 'credited', 'clawback_failed', e);
916
- }
917
- }
918
-
919
- /**
920
- * Resolves a Stripe charge back to the gc-connect membership it belongs to,
921
- * via charge -> invoice -> subscription -> memberships.stripe_subscription_id.
922
- * Used by the refund/dispute clawback path above. Returns null (never
923
- * throws) for anything that isn't a subscription-invoice charge -- e.g. a
924
- * Day Pass charge, which has no subscription and is handled by the
925
- * existing day_pass_purchases refund logic instead.
926
- *
927
- * Round-3 review finding N1: ALWAYS re-retrieves the charge through this
928
- * file's own pinned Stripe client, even when the caller already has a
929
- * charge object straight from the webhook event payload. Webhook event
930
- * payloads render at whatever API version is configured on the Stripe
931
- * webhook ENDPOINT in the Dashboard, NOT at this file's pinned
932
- * apiVersion -- and this file already has resolveInvoiceSubId's old/new-
933
- * shape fallback logic elsewhere as direct evidence that the endpoint's
934
- * version has needed that shimming before. Trusting the event payload's
935
- * `charge.invoice` shape here would silently no-op (no clawback, no log)
936
- * exactly the way round-2's original bug did on a different code path.
937
- * Also uses resolveInvoiceSubId (already handles both the old
938
- * `invoice.subscription` and the new `invoice.parent.subscription_details`
939
- * shapes) instead of reimplementing that resolution inline.
940
- */
941
- async function findMembershipIdByChargeInvoice(chargeOrId: string | Stripe.Charge): Promise<string | null> {
942
- const chargeId = typeof chargeOrId === 'string' ? chargeOrId : chargeOrId.id;
943
- try {
944
- const charge = await stripe.charges.retrieve(chargeId);
945
- const invoiceId = typeof charge.invoice === 'string' ? charge.invoice : charge.invoice?.id ?? null;
946
- if (!invoiceId) return null; // no invoice at all -- e.g. a Day Pass charge, expected no-op
947
-
948
- const invoice = await stripe.invoices.retrieve(invoiceId);
949
- const subId = resolveInvoiceSubId(invoice as any);
950
- if (!subId) {
951
- // Has an invoice but we couldn't resolve a subscription from it --
952
- // unlike "no invoice at all" above, this is unexpected for a charge
953
- // that IS invoice-backed. Alert rather than silently no-op.
954
- await logOps(supabase, 'referral_clawback_invoice_sub_unresolved',
955
- { charge_id: chargeId, invoice_id: invoiceId },
956
- { severity: 'warning' }).catch(() => {});
957
- return null;
958
- }
959
- const { data: membership, error: memErr } = await supabase
960
- .from('memberships')
961
- .select('id')
962
- .eq('stripe_subscription_id', subId)
963
- .maybeSingle();
964
- if (memErr) {
965
- console.error('[stripe-webhook] findMembershipIdByChargeInvoice: membership lookup failed', {
966
- charge_id: chargeId, sub_id: subId, message: memErr.message,
967
- });
968
- return null;
969
- }
970
- return (membership?.id as string | undefined) ?? null;
971
- } catch (e) {
972
- console.error('[stripe-webhook] findMembershipIdByChargeInvoice failed', { charge_id: chargeId, message: e instanceof Error ? e.message : String(e) });
973
- await logOps(supabase, 'referral_clawback_charge_resolution_failed',
974
- { charge_id: chargeId, message: e instanceof Error ? e.message : String(e) },
975
- { severity: 'warning' }).catch(() => {});
976
- return null;
977
- }
978
- }
979
-
980
- async function upsertMembershipFromSubscription(
981
- sub: Stripe.Subscription,
982
- opts: { email?: string | null; forceStatus?: string } = {},
983
- ) {
984
- const subId = sub.id;
985
- const customerId = typeof sub.customer === 'string' ? sub.customer : sub.customer?.id ?? null;
986
- let planId = sub.metadata?.plan_id ?? null;
987
- let planSlug = sub.metadata?.plan_slug ?? null;
988
- if (!planId && sub.metadata?.checkout_type === 'private_office_agreement' && sub.metadata?.signature_document_id) {
989
- try {
990
- const { data: sigDoc } = await supabase
991
- .from('signature_documents')
992
- .select('field_values')
993
- .eq('id', sub.metadata.signature_document_id)
994
- .maybeSingle();
995
- const fv = (sigDoc?.field_values ?? {}) as Record<string, unknown>;
996
- if (typeof fv.plan_id === 'string' && fv.plan_id) planId = fv.plan_id;
997
- if (typeof fv.plan_slug === 'string' && fv.plan_slug) planSlug = fv.plan_slug;
998
- } catch (e) {
999
- console.warn('[stripe-webhook] plan_id fallback lookup failed', e);
1000
- }
1001
- }
1002
- // Door-access gating input (independent of the plan_id fallback above --
1003
- // that one is gated on !planId, which is false for our own subscriptions
1004
- // since maybeActivateAgreement always sets plan_id metadata; this must
1005
- // run regardless).
1006
- const isPrivateOfficeAgreementSub =
1007
- sub.metadata?.checkout_type === 'private_office_agreement' && !!sub.metadata?.signature_document_id;
1008
- let doorAccessNotBeforeIso: string | null = null;
1009
- if (isPrivateOfficeAgreementSub) {
1010
- try {
1011
- const { data: sigDoc } = await supabase
1012
- .from('signature_documents')
1013
- .select('start_date')
1014
- .eq('id', sub.metadata!.signature_document_id as string)
1015
- .maybeSingle();
1016
- const startInstant = pacificMidnightUtc(sigDoc?.start_date as string | null | undefined);
1017
- if (startInstant && startInstant.getTime() > Date.now()) {
1018
- doorAccessNotBeforeIso = startInstant.toISOString();
1019
- }
1020
- } catch (e) {
1021
- console.warn('[stripe-webhook] start_date lookup for door gating failed', e);
1022
- }
1023
- }
1024
- // Self-serve membership checkout with a chosen future start date. No DB read
1025
- // needed -- create-subscription-checkout puts the raw YYYY-MM-DD straight on
1026
- // the subscription metadata, unlike the office path's signature_documents
1027
- // lookup. Same pacificMidnightUtc helper, so the door gate and the Stripe
1028
- // billing_cycle_anchor can never disagree.
1029
- const isFutureDatedMembershipSub =
1030
- sub.metadata?.checkout_type === 'membership' && !!sub.metadata?.start_date;
1031
- if (isFutureDatedMembershipSub) {
1032
- const startInstant = pacificMidnightUtc(sub.metadata!.start_date as string);
1033
- if (startInstant && startInstant.getTime() > Date.now()) {
1034
- doorAccessNotBeforeIso = startInstant.toISOString();
1035
- }
1036
- }
1037
- const status = opts.forceStatus ?? sub.status;
1038
- const currentPeriodEnd = subCurrentPeriodEndISO(sub);
1039
-
1040
- // Best-effort email: explicit override, else fetch from customer.
1041
- let email = opts.email ?? null;
1042
- // Best-effort customer name enrichment (for admin visibility only).
1043
- // Never fail or delay the webhook if Stripe retrieve errors or name is missing.
1044
- let customerName: string | null = null;
1045
- if (customerId) {
1046
- try {
1047
- const cust = await stripe.customers.retrieve(customerId);
1048
- if (cust && !('deleted' in cust && cust.deleted)) {
1049
- const c = cust as Stripe.Customer;
1050
- if (!email) email = c.email ?? null;
1051
- customerName = c.name ?? null;
1052
- }
1053
- } catch (e) {
1054
- console.warn('[stripe-webhook] customer retrieve failed', e);
1055
- }
1056
- }
1057
- if (email) email = email.toLowerCase();
1058
-
1059
- // Phase 3 revoke loop v1: pre-read old status so we can detect a
1060
- // transition INTO / OUT OF a dunning/terminal state (past_due, canceled,
1061
- // unpaid) and set/clear the 5-day grace window. A missing pre-read (e.g.
1062
- // transient DB error) is not fatal — we treat it as "no known prior state"
1063
- // and only set grace on new-into. past_due is included so the grace clock
1064
- // starts at the FIRST failed-payment state, not only at final cancellation.
1065
- const REVOKED = new Set(['past_due', 'canceled', 'unpaid']);
1066
- const isRevoked = REVOKED.has(status);
1067
- const GRACE_MS = 5 * 24 * 60 * 60 * 1000;
1068
-
1069
- const { data: existing, error: existingErr } = await supabase
1070
- .from('memberships')
1071
- .select('id,email,status,pricing_grace_ends_at,membership_ended_at,plan_id')
1072
- .eq('stripe_subscription_id', subId)
1073
- .maybeSingle();
1074
- if (existingErr) {
1075
- console.warn('[stripe-webhook] membership pre-read failed', existingErr);
1076
- }
1077
- // Welcome decision only — never written to update/insert payloads.
1078
- const welcomePlanId = planId ?? (existing?.plan_id as string | null) ?? null;
1079
- const wasRevoked = existing ? REVOKED.has(existing.status) : false;
1080
-
1081
- // Retention anchor (Virtual Office onboarding purge). Stamped ONCE, the
1082
- // first time a membership resolves to a terminal state, and never
1083
- // overwritten — a later replay or a re-canceled sub must not slide the
1084
- // 2-year purge clock forward. Deliberately not cleared on reactivation;
1085
- // a resurrected member gets a fresh row-level clock only if the column
1086
- // was still null.
1087
- const ENDED = new Set(['canceled', 'unpaid']);
1088
- const isEnded = ENDED.has(status);
1089
-
1090
- // Try update-by-subscription first.
1091
- const updatePayload: Record<string, unknown> = {
1092
- status,
1093
- current_period_end: currentPeriodEnd,
1094
- stripe_customer_id: customerId,
1095
- };
1096
- if (email) {
1097
- const prior = existing?.email?.toLowerCase() ?? null;
1098
- if (prior === null || prior === email) {
1099
- updatePayload.email = email; // nothing to guard
1100
- } else {
1101
- updatePayload.email = email; // plurality: ALWAYS write
1102
- // Explicit .select() list, NOT .maybeSingle(): PostgREST answers an
1103
- // object-request matching >1 row with PGRST116 and returns null, so a
1104
- // .maybeSingle() safeguard goes blind exactly as duplicates accumulate,
1105
- // which under ratified plurality is the normal state. Error is bound and
1106
- // checked -- fail loud.
1107
- const { data: others, error: othersErr } = await supabase
1108
- .from('memberships').select('id,email,stripe_customer_id')
1109
- .ilike('email', email).neq('id', existing!.id);
1110
- // .ilike() is a broad PREFILTER only (`_` is a wildcard AND a legal email
1111
- // character) -- re-check with strict lowercase equality, per
1112
- // _shared/membership.ts's own documented idiom. See 2.4.6.7.
1113
- const real = (others ?? []).filter((r) => (r.email ?? '').toLowerCase() === email);
1114
- if (othersErr || real.length > 0) {
1115
- // Same-Stripe-customer collisions are the actual signature of a
1116
- // LEGITIMATE second-office-rental (one person, one Stripe Customer,
1117
- // two membership rows under one email) -- downgrade those to
1118
- // 'warning' so they stop paging Slack. Staff still see them: the
1119
- // admin dashboard's "Needs attention" list (useAttention.ts) filters
1120
- // this kind by KIND, not severity, so it renders either way -- only
1121
- // the immediate page is suppressed. A lookup error, a null/unknown
1122
- // customerId (the LEAST evidence of legitimacy, not the most), or a
1123
- // colliding row under a DIFFERENT customer (the shape a real bug
1124
- // would produce) all stay 'error'.
1125
- const allSameCustomer = !othersErr && real.length > 0 &&
1126
- typeof customerId === 'string' && customerId.length > 0 &&
1127
- real.every((r) => r.stripe_customer_id === customerId);
1128
- const flagged = await logOps(supabase, 'membership_email_collision_flagged',
1129
- { subscription_id: subId, membership_id: existing!.id, prior_email: prior,
1130
- attempted_email: email, colliding_ids: real.map((r) => r.id),
1131
- lookup_error: othersErr?.message ?? null },
1132
- { severity: allSameCustomer ? 'warning' : 'error',
1133
- // Shape is part of the key: without this, the FIRST observation
1134
- // pins severity forever under ON CONFLICT DO NOTHING, and a
1135
- // later genuine cross-customer collision on the same key would
1136
- // be silently dropped instead of alerting.
1137
- dedupeKey: 'flag:' + email + ':' + existing!.id + (allSameCustomer ? ':same' : ':cross') });
1138
- if (!flagged.ok) {
1139
- console.error('[stripe-webhook] collision flag failed to persist',
1140
- { subscription_id: subId, membership_id: existing!.id, error: flagged.error });
1141
- }
1142
- }
1143
- }
1144
- }
1145
- if (planId) updatePayload.plan_id = planId;
1146
- if (customerName) updatePayload.customer_name = customerName;
1147
-
1148
- // Grace bookkeeping: only write the column when the answer changes.
1149
- // - Transition INTO revoked (or unknown → revoked): start a 5-day grace.
1150
- // - Transition OUT of revoked to any non-revoked status: clear grace.
1151
- // - Still revoked (repeat event): leave column untouched so grace can't
1152
- // be extended by later webhooks for the same terminal state.
1153
- // D24: grace_start dunning email fires the instant this branch opens the
1154
- // window (best-effort, non-blocking -- see the maybeSendWelcomes-style
1155
- // send below, after the write succeeds). Captured here, not recomputed
1156
- // later, so the fired email always matches the exact instant actually
1157
- // written to the row.
1158
- let graceStartedNow = false;
1159
- let graceStartEndsAtIso: string | null = null;
1160
- if (isRevoked && !wasRevoked) {
1161
- graceStartEndsAtIso = new Date(Date.now() + GRACE_MS).toISOString();
1162
- updatePayload.pricing_grace_ends_at = graceStartEndsAtIso;
1163
- graceStartedNow = true;
1164
- } else if (!isRevoked && (existing?.pricing_grace_ends_at || wasRevoked)) {
1165
- updatePayload.pricing_grace_ends_at = null;
1166
- // A member who re-enters dunning later must get the full sequence
1167
- // again -- never leave a stage stamped true from a prior episode.
1168
- updatePayload.dunning_emails_sent = {};
1169
- }
1170
- if (isEnded && !existing?.membership_ended_at) {
1171
- updatePayload.membership_ended_at = new Date().toISOString();
1172
- }
1173
-
1174
- const { data: updated, error: updErr } = await supabase
1175
- .from('memberships')
1176
- .update(updatePayload)
1177
- .eq('stripe_subscription_id', subId)
1178
- .select('id,created_at,welcome_email_sent_at');
1179
- if (updErr) {
1180
- await logOps(supabase, 'membership_update_failed', {
1181
- subscription_id: subId, email, message: updErr.message,
1182
- }, { severity: 'error' });
1183
- if (isPermanentDbError(updErr)) return;
1184
- // D1 fix: a retrieve-OK-but-DB-write-fail webhook must NOT 200 and burn
1185
- // the Stripe event when the failure looks transient. Throw so the outer
1186
- // handler's catch (index.ts, near the bottom of Deno.serve) turns this
1187
- // into a 500, which both alerts via logOps above and lets Stripe retry
1188
- // the event on its own schedule. (A deterministic failure, checked
1189
- // above, returns instead -- see isPermanentDbError's own comment.)
1190
- throw new Error(`membership update failed for subscription ${subId}: ${updErr.message}`);
1191
- }
1192
- if (updated && updated.length > 0) {
1193
- // The bug this fixes: a row first inserted at 'incomplete' flips to
1194
- // 'active' via this path, and now finally gets its welcome email.
1195
- const row = updated[0];
1196
- await maybeSendWelcomes(
1197
- row.id, email ?? existing?.email ?? null, welcomePlanId, customerName, status,
1198
- (row.created_at as string | null) ?? null,
1199
- (row.welcome_email_sent_at as string | null) ?? null,
1200
- );
1201
- await maybeConvertTrialGrant(supabase, row.id as string, email ?? existing?.email ?? null);
1202
- await linkOfficeAssignment(sub, row.id as string);
1203
- await flagStaleOfficeAssignmentIfEnded(row.id as string, welcomePlanId, isEnded);
1204
- // D24: grace_start dunning email -- best-effort, non-blocking, same
1205
- // call style as the maybeSendWelcomes sends above. Fires only on the
1206
- // transition INTO the grace window (never on repeat events for the
1207
- // same terminal state -- graceStartedNow is only true the instant the
1208
- // window is first opened, above).
1209
- // Only billing-failure statuses get the payment-failure sequence. A
1210
- // voluntary 'canceled' also opens the grace window above, but that
1211
- // member chose to leave -- "we couldn't process your payment" is the
1212
- // wrong (and alarming) message for them.
1213
- if (graceStartedNow && graceStartEndsAtIso && status !== 'canceled') {
1214
- const dunningEmail = email ?? existing?.email ?? null;
1215
- if (dunningEmail) {
1216
- await sendDunningEmail(supabase, dunningEmail, row.id as string, 'grace_start', graceStartEndsAtIso, {
1217
- name: siteConfig.operatorName,
1218
- shortName: siteConfig.operatorShortName,
1219
- domain: siteConfig.domain,
1220
- supportEmail: siteConfig.supportEmail,
1221
- }).catch((e) => console.warn('[stripe-webhook] grace_start dunning email failed (ignored)', e));
1222
- }
1223
- }
1224
- return;
1225
- }
1226
-
1227
- // No row yet — insert. Need email + planId to satisfy schema (email NOT NULL).
1228
- if (!email) {
1229
- console.warn('[stripe-webhook] cannot insert membership without email', { subId, planSlug });
1230
- return;
1231
- }
1232
-
1233
- // ---- Deterministic pre-insert email resolution ----
1234
- // Replaces the old repair path that branched on
1235
- // `code === '23505' && msg.includes('memberships_email_unique_idx')`.
1236
- // That index is dropped (ratified plurality: two memberships MAY share one
1237
- // email), so an error code can no longer tell us a different row owns this
1238
- // email. Resolve it BEFORE the insert instead, and never guess: exactly one
1239
- // adoptable row adopts, anything else inserts a new row and flags for staff.
1240
- const { data: sameEmailRaw, error: sameEmailErr } = await supabase
1241
- .from('memberships')
1242
- // Exact column list is LOAD-BEARING, not style: step 5's compare-and-swap
1243
- // reads stripe_subscription_id off the candidate. Selecting fewer columns
1244
- // gets `undefined` there and the CAS silently degenerates into an
1245
- // unconditional update by id.
1246
- .select('id,email,status,stripe_customer_id,stripe_subscription_id')
1247
- // .ilike() is a broad PREFILTER only (`_` is a wildcard AND a legal email
1248
- // character) -- re-checked with strict lowercase equality below, per
1249
- // _shared/membership.ts's documented idiom. NEVER a bare .ilike() on a
1250
- // decision that attaches a paying subscription to a row: a false positive
1251
- // would attach it to a DIFFERENT PERSON's membership.
1252
- .ilike('email', email);
1253
- const sameEmail = (sameEmailRaw ?? [])
1254
- .filter((r) => ((r.email ?? '') as string).toLowerCase() === email);
1255
-
1256
- // The adopt path is restricted to self-serve membership checkout.
1257
- // Office-path subscriptions are NEVER adoptable by email. One agreement
1258
- // cannot legitimately mint a second subscription id (maybeActivateAgreement
1259
- // early-returns on an existing stripe_subscription_id and uses a
1260
- // per-agreement idempotency key), so there is no office "resubscribe" for
1261
- // this path to repair. plan_id cannot discriminate either -- one plan spans
1262
- // several offices at different negotiated prices -- and the office path's
1263
- // Stripe Customer IS shared across one person's agreements. A new office
1264
- // subscription is therefore always a new membership row.
1265
- const adoptEligible = sub.metadata?.checkout_type === 'membership';
1266
-
1267
- let adoptable: typeof sameEmail = [];
1268
- if (adoptEligible && customerId && sameEmail.length > 0) {
1269
- const candidates = sameEmail.filter((r) =>
1270
- r.stripe_customer_id === customerId &&
1271
- (r.status === 'canceled' || r.status === 'unpaid'));
1272
- if (candidates.length > 0) {
1273
- // An ACTIVE office assignment pointing at a row means that row is a live
1274
- // office rental, not a lapsed self-serve membership free to reuse.
1275
- const { data: activeOffices, error: officeErr } = await supabase
1276
- .from('office_assignments')
1277
- .select('membership_id')
1278
- .eq('status', 'active')
1279
- .in('membership_id', candidates.map((r) => r.id as string));
1280
- if (officeErr) {
1281
- // Fail CLOSED: we cannot prove any candidate is free, so adopt
1282
- // nothing and let the insert-and-flag path handle it.
1283
- await logOps(supabase, 'membership_adopt_office_check_failed', {
1284
- subscription_id: subId, email, message: officeErr.message,
1285
- }, { severity: 'error' });
1286
- } else {
1287
- const encumbered = new Set(
1288
- (activeOffices ?? [])
1289
- .map((o) => o.membership_id as string | null)
1290
- .filter((v): v is string => !!v));
1291
- adoptable = candidates.filter((r) => !encumbered.has(r.id as string));
1292
- }
1293
- }
1294
- }
1295
-
1296
- if (adoptable.length === 1) {
1297
- const candidate = adoptable[0];
1298
- const adoptPayload: Record<string, unknown> = {
1299
- ...updatePayload, stripe_subscription_id: subId,
1300
- };
1301
- // Stale-scheduling clears: `updatePayload`'s own isRevoked/wasRevoked
1302
- // logic above is keyed on `existing` (the row matched by subId), which
1303
- // is null throughout this whole branch -- adoption attaches to
1304
- // `candidate`, a DIFFERENT row found by email, so that logic never
1305
- // looks at what candidate actually has stale. candidate is, by
1306
- // construction, always a previously-REVOKED row (adoptable filters on
1307
- // status IN ('canceled','unpaid')), so treat this as a fresh
1308
- // transition rather than trusting the spread above.
1309
- adoptPayload.pricing_grace_ends_at = isRevoked
1310
- ? new Date(Date.now() + GRACE_MS).toISOString()
1311
- : null;
1312
- // cancel_at is a staff-scheduled cancel-at-period-end (set by
1313
- // admin-cancel-membership, cleared by admin-undo-membership-cancel)
1314
- // and is never touched elsewhere in this file. The new subscription
1315
- // has no cancellation scheduled against it, so a candidate reactivated
1316
- // out of a staff-initiated cancel must not keep reading as
1317
- // pending-cancellation.
1318
- adoptPayload.cancel_at = null;
1319
- // membership_ended_at must NEVER be written on this path. `existing` is
1320
- // always null in this branch (adoption attaches to `candidate`, found by
1321
- // email, not by subId), so the `if (isEnded && !existing?.membership_ended_at)`
1322
- // guard above degenerates to `if (isEnded)` -- meaning updatePayload can
1323
- // carry a freshly-stamped membership_ended_at whenever the new
1324
- // subscription's status is 'canceled' or 'unpaid', and the `...updatePayload`
1325
- // spread above would silently overwrite candidate's stamped-once 2-year
1326
- // retention anchor (the Virtual Office onboarding purge's cutoff). Deleting
1327
- // it here means it can only be set again by the normal update-by-subscription-id
1328
- // path, the next time this row genuinely reaches a terminal state.
1329
- delete adoptPayload.membership_ended_at;
1330
- // Only the future-dated SELF-SERVE branch of the old adopt-path door gate
1331
- // survives, and it must: a brand-new future-dated checkout has to defer
1332
- // access even if the prior row still reads as entitled inside its own
1333
- // post-cancellation grace, or a cancel/resubscribe cycle inside grace
1334
- // becomes a standing free-access loop. The old sibling branch (the
1335
- // computeEntitlement(byEmail...) one, for private-office agreements) is
1336
- // now unreachable -- adoptEligible excludes that checkout_type -- and is
1337
- // DELETED rather than carried forward as dead code.
1338
- // Unconditional (not just the future-dated branch): a stale future gate
1339
- // left on the candidate row must not survive adoption when the new
1340
- // subscription isn't future-dated.
1341
- adoptPayload.door_access_not_before =
1342
- (isFutureDatedMembershipSub && doorAccessNotBeforeIso) ? doorAccessNotBeforeIso : null;
1343
- // COMPARE-AND-SWAP on the value actually read. If another event attached a
1344
- // subscription to this row between our read and this write, we must not
1345
- // clobber it -- zero rows back means we lost the race and we fall through
1346
- // to INSERT + flag rather than reporting success. PostgREST's .eq() does
1347
- // not match NULL, so a null read needs .is().
1348
- const casBase = supabase.from('memberships').update(adoptPayload).eq('id', candidate.id);
1349
- const cas = candidate.stripe_subscription_id === null
1350
- ? casBase.is('stripe_subscription_id', null)
1351
- : casBase.eq('stripe_subscription_id', candidate.stripe_subscription_id as string);
1352
- const { data: adopted, error: adoptErr } = await cas.select('id');
1353
- if (adoptErr) {
1354
- await logOps(supabase, 'membership_resubscribe_repair_failed', {
1355
- subscription_id: subId, email, membership_id: candidate.id,
1356
- message: adoptErr.message,
1357
- }, { severity: 'error' });
1358
- if (isPermanentDbError(adoptErr)) return;
1359
- // D1 fix: same shape and same rationale as the update/insert paths
1360
- // above -- a genuine DB-write failure here must not 200 the webhook
1361
- // when it looks transient.
1362
- throw new Error(`membership resubscribe-repair update failed for subscription ${subId}: ${adoptErr.message}`);
1363
- }
1364
- if (adopted && adopted.length > 0) {
1365
- await logOps(supabase, 'membership_resubscribe_repaired', {
1366
- subscription_id: subId, email, membership_id: candidate.id,
1367
- }, { severity: 'warning' });
1368
- await maybeSendWelcomes(
1369
- candidate.id as string, email, welcomePlanId, customerName, status,
1370
- null, undefined,
1371
- // 8th arg, same as the insert path: a future-dated resubscribe must
1372
- // not send a "you have access now" welcome while door access is
1373
- // actually deferred to doorAccessNotBeforeIso.
1374
- isFutureDatedMembershipSub ? doorAccessNotBeforeIso : null,
1375
- );
1376
- await maybeConvertTrialGrant(supabase, candidate.id as string, email);
1377
- // linkOfficeAssignment() is a PROVABLE no-op here: it early-returns
1378
- // unless checkout_type === 'private_office_agreement', which
1379
- // adoptEligible excludes from ever reaching this path. Deliberately not
1380
- // carried forward as a call.
1381
- return;
1382
- }
1383
- // Zero rows: another event won the race. Fall through to INSERT + flag.
1384
- }
1385
-
1386
- const insertPayload: Record<string, unknown> = {
1387
- email,
1388
- plan_id: planId,
1389
- stripe_customer_id: customerId,
1390
- stripe_subscription_id: subId,
1391
- status,
1392
- current_period_end: currentPeriodEnd,
1393
- customer_name: customerName,
1394
- };
1395
- // Rare: first-seen row already in a revoked status (late replay of a
1396
- // cancellation for a sub we never saw active). Give it a fresh grace so
1397
- // customer isn't punished for our late arrival.
1398
- if (isRevoked) {
1399
- insertPayload.pricing_grace_ends_at = new Date(Date.now() + GRACE_MS).toISOString();
1400
- }
1401
- if (isEnded) {
1402
- insertPayload.membership_ended_at = new Date().toISOString();
1403
- }
1404
- // B15: door gate written in the SAME insert statement as row creation --
1405
- // never a separate follow-up call. wasEntitled is trivially false here;
1406
- // the row is being created for the first time in this very statement.
1407
- if ((isPrivateOfficeAgreementSub || isFutureDatedMembershipSub) && doorAccessNotBeforeIso) {
1408
- insertPayload.door_access_not_before = doorAccessNotBeforeIso;
1409
- }
1410
- const { data: inserted, error: insErr } = await supabase
1411
- .from('memberships')
1412
- .insert(insertPayload)
1413
- .select('id,created_at')
1414
- .maybeSingle();
1415
- if (insErr) {
1416
- // deno-lint-ignore no-explicit-any
1417
- const code = (insErr as any).code;
1418
- // deno-lint-ignore no-explicit-any
1419
- const msg = String((insErr as any).message ?? '');
1420
- // The `msg.includes('memberships_email_unique_idx')` adopt branch that
1421
- // used to sit here is REMOVED ENTIRELY -- that index is dropped, so it
1422
- // could never fire again. Adopt resolution now happens deterministically
1423
- // BEFORE the insert (see above). The 23505 handler below is retained ONLY
1424
- // for memberships_stripe_subscription_id_key, which survives as a real
1425
- // pg_constraint UNIQUE and still serializes the documented two-event race.
1426
- if (code === '23505') {
1427
- // Genuine concurrent-insert race on stripe_subscription_id itself.
1428
- const { data: retried, error: retryErr } = await supabase
1429
- .from('memberships')
1430
- .update(updatePayload)
1431
- .eq('stripe_subscription_id', subId)
1432
- .select('id,created_at,welcome_email_sent_at');
1433
- if (retryErr) {
1434
- await logOps(supabase, 'membership_23505_retry_failed', {
1435
- subscription_id: subId, email, message: retryErr.message,
1436
- }, { severity: 'error' });
1437
- if (isPermanentDbError(retryErr)) return;
1438
- // D1 fix: don't 200 a webhook whose DB write actually failed when the
1439
- // failure looks transient -- see the matching throw on the update-path
1440
- // updErr above for why (including the isPermanentDbError carve-out).
1441
- throw new Error(`membership 23505-retry update failed for subscription ${subId}: ${retryErr.message}`);
1442
- } else if (retried && retried.length > 0) {
1443
- const row = retried[0];
1444
- await maybeSendWelcomes(
1445
- row.id, email, welcomePlanId, customerName, status,
1446
- (row.created_at as string | null) ?? null,
1447
- (row.welcome_email_sent_at as string | null) ?? null,
1448
- );
1449
- await maybeConvertTrialGrant(supabase, row.id as string, email);
1450
- await linkOfficeAssignment(sub, row.id as string);
1451
- await flagStaleOfficeAssignmentIfEnded(row.id as string, welcomePlanId, isEnded);
1452
- }
1453
- return;
1454
- }
1455
- await logOps(supabase, 'membership_insert_failed', {
1456
- subscription_id: subId, email, message: msg,
1457
- }, { severity: 'error' });
1458
- if (isPermanentDbError(insErr)) return;
1459
- // D1 fix: don't 200 a webhook whose DB write actually failed when the
1460
- // failure looks transient -- see the matching throw on the update-path
1461
- // updErr above for why (including the isPermanentDbError carve-out).
1462
- throw new Error(`membership insert failed for subscription ${subId}: ${msg}`);
1463
- }
1464
- // True first-time creation of this membership row.
1465
- // A new row landed while other rows already share this email. That is the
1466
- // newly-LEGAL plural case (one person, two office rentals) -- so this is a
1467
- // detect-and-flag-for-staff-review event, never a block-on-write. Also
1468
- // covers "more than one adoptable row" (we refuse to guess which to adopt)
1469
- // and "we lost the adopt CAS race". dedupeKey keys on subId, NOT on
1470
- // `existing!.id` as in the update path -- `existing` is null here, so
1471
- // that shape would produce 'flag:<email>:undefined' and, under ON CONFLICT
1472
- // DO NOTHING, only the first-ever collision on the email would surface.
1473
- //
1474
- // Severity mirrors the update-path collision block above, but the
1475
- // downgrade condition is narrower here: adoptable.length === 0 requires
1476
- // there to have been NO adoptable candidate at all (excludes both the
1477
- // ">1 adoptable" case and "lost the CAS race", which both leave
1478
- // adoptable.length >= 1) -- only the clean one-person/two-memberships
1479
- // shape, where the colliding rows are active/trialing and never reach
1480
- // `adoptable` (which only ever holds canceled/unpaid candidates), gets
1481
- // downgraded. logOps only alerts Slack/webhook at 'error' -- but staff
1482
- // still see this either way on the dashboard's "Needs attention" list
1483
- // (useAttention.ts), which filters this kind by KIND, not severity.
1484
- if (sameEmailErr || sameEmail.length > 0) {
1485
- const allSameCustomer = !sameEmailErr && sameEmail.length > 0 &&
1486
- typeof customerId === 'string' && customerId.length > 0 &&
1487
- adoptable.length === 0 && !!inserted?.id &&
1488
- sameEmail.every((r) => r.stripe_customer_id === customerId);
1489
- const flagged = await logOps(supabase, 'membership_email_collision_flagged', {
1490
- subscription_id: subId, membership_id: inserted?.id ?? null,
1491
- prior_email: null, attempted_email: email,
1492
- colliding_ids: sameEmail.map((r) => r.id),
1493
- adoptable_count: adoptable.length,
1494
- lookup_error: sameEmailErr?.message ?? null,
1495
- }, { severity: allSameCustomer ? 'warning' : 'error',
1496
- dedupeKey: 'flag:' + email + ':' + subId + (allSameCustomer ? ':same' : ':cross') });
1497
- if (!flagged.ok) {
1498
- console.error('[stripe-webhook] collision flag failed to persist',
1499
- { subscription_id: subId, membership_id: inserted?.id ?? null, error: flagged.error });
1500
- }
1501
- }
1502
- await maybeSendWelcomes(
1503
- inserted?.id ?? null, email, welcomePlanId, customerName, status,
1504
- (inserted?.created_at as string | null) ?? null,
1505
- null,
1506
- isFutureDatedMembershipSub ? doorAccessNotBeforeIso : null,
1507
- );
1508
- await maybeConvertTrialGrant(supabase, inserted?.id ?? null, email);
1509
- await linkOfficeAssignment(sub, inserted?.id as string | null | undefined);
1510
- await flagStaleOfficeAssignmentIfEnded(inserted?.id as string | null | undefined, welcomePlanId, isEnded);
1511
- await maybeRecordReferral(sub, inserted?.id as string | null | undefined, planId);
1512
- }
1513
-
1514
- function isMembershipCheckoutSession(session: Stripe.Checkout.Session): boolean {
1515
- const t = session.metadata?.checkout_type;
1516
- return t === 'membership' || t === 'private_office_agreement';
1517
- }
1518
-
1519
- function isMembershipSubscription(sub: Stripe.Subscription): boolean {
1520
- const t = sub.metadata?.checkout_type;
1521
- return t === 'membership' || t === 'private_office_agreement';
1522
- }
1523
-
1524
- function resolveInvoiceSubId(inv: any): string | null {
1525
- if (typeof inv.subscription === 'string') return inv.subscription;
1526
- if (inv.subscription?.id) return inv.subscription.id;
1527
- const pd = inv.parent?.subscription_details?.subscription;
1528
- if (typeof pd === 'string') return pd;
1529
- if (pd?.id) return pd.id;
1530
- const lines = inv.lines?.data ?? [];
1531
- for (const ln of lines) {
1532
- const lsub = ln.subscription ?? ln.parent?.subscription_item_details?.subscription;
1533
- if (typeof lsub === 'string') return lsub;
1534
- if (lsub?.id) return lsub.id;
1535
- }
1536
- return null;
1537
- }
1538
-
1539
- function isRetryableStripeError(e: any): boolean {
1540
- const t = e?.type ?? '';
1541
- if (t === 'StripeConnectionError' || t === 'StripeAPIError') return true; // network / Stripe 5xx
1542
- const code = typeof e?.statusCode === 'number' ? e.statusCode : 0;
1543
- if (code === 429 || code >= 500) return true; // rate-limited / server error
1544
- return false; // resource_missing, auth, other 4xx = permanent; retry won't help
1545
- }
1546
-
1547
- // D1: classify a Postgres/PostgREST error as deterministic-and-permanent vs.
1548
- // presumed-transient, so the throw-on-DB-write-failure fix below doesn't create
1549
- // a poison-pill event. A not-null violation, FK violation, check violation, or a
1550
- // 42xxx-class error (undefined column/table, syntax, insufficient privilege) will
1551
- // fail identically on every Stripe retry -- throwing on those would burn Stripe's
1552
- // finite retry budget for nothing and, since Stripe tracks endpoint health per
1553
- // endpoint rather than per event type, risks Stripe disabling this webhook
1554
- // entirely after sustained failures (which would also break bookings, day
1555
- // passes, and office agreements -- everything else this same endpoint handles).
1556
- // Log-and-200 instead; the stripe-db-reconcile job is the backstop for these.
1557
- // Everything else (connection blips, serialization failures, etc.) is presumed
1558
- // transient and worth letting Stripe retry.
1559
- function isPermanentDbError(err: any): boolean {
1560
- const code = String(err?.code ?? '');
1561
- if (code === '23502' || code === '23503' || code === '23514') return true;
1562
- if (code.startsWith('42')) return true;
1563
- return false;
1564
- }
1565
-
1566
- try {
1567
- switch (event.type) {
1568
- case 'checkout.session.completed': {
1569
- const session = event.data.object as Stripe.Checkout.Session;
1570
- // Day Pass one-time checkout — record the purchase, no booking / no membership.
1571
- if (session.metadata?.checkout_type === 'day_pass') {
1572
- const email = session.customer_details?.email ?? session.customer_email ?? null;
1573
- const customerId = typeof session.customer === 'string'
1574
- ? session.customer
1575
- : session.customer?.id ?? null;
1576
- const paymentIntentId = typeof session.payment_intent === 'string'
1577
- ? session.payment_intent
1578
- : session.payment_intent?.id ?? null;
1579
- if (!email) {
1580
- await logOps(supabase, 'day_pass_purchase_failed',
1581
- { session_id: session.id, reason: 'missing_email' }, { severity: 'error' });
1582
- break;
1583
- }
1584
- const visitDate = session.metadata?.visit_date ?? null;
1585
- const arrivalTime = session.metadata?.arrival_time ?? null;
1586
- const customerName = session.customer_details?.name ?? null;
1587
- const amountCents = session.amount_total ?? null;
1588
- const { data: dpRow, error: dpErr } = await supabase
1589
- .from('day_pass_purchases')
1590
- .insert({
1591
- email,
1592
- customer_name: customerName,
1593
- stripe_customer_id: customerId,
1594
- stripe_checkout_session_id: session.id,
1595
- stripe_payment_intent: paymentIntentId,
1596
- plan_id: session.metadata?.plan_id ?? null,
1597
- amount_cents: amountCents,
1598
- visit_date: visitDate,
1599
- arrival_time: arrivalTime,
1600
- })
1601
- .select('id')
1602
- .maybeSingle();
1603
- if (dpErr && (dpErr as any).code !== '23505') {
1604
- // 23505 = duplicate webhook redelivery for the same session; no-op.
1605
- console.error('[stripe-webhook] day pass insert failed', dpErr);
1606
- await logOps(supabase, 'day_pass_purchase_failed',
1607
- { session_id: session.id, error: dpErr.message }, { severity: 'error' });
1608
- } else if (!dpErr) {
1609
- // The purchase row landed, so the payment is real -- settle any
1610
- // internal coupon reserved by create-day-pass-checkout.
1611
- await markCouponAppliedFromMetadata(session.metadata,
1612
- { session_id: session.id, checkout_type: 'day_pass' });
1613
-
1614
- // Best-effort Slack ping. Never let this break the webhook.
1615
- try {
1616
- const slackToken = Deno.env.get('SLACK_DAYPASS_BOT_TOKEN');
1617
- const slackChannel = Deno.env.get('SLACK_DAYPASS_CHANNEL_ID');
1618
- if (slackToken && slackChannel) {
1619
- const who = customerName || email;
1620
- const amount = typeof amountCents === 'number'
1621
- ? `$${(amountCents / 100).toFixed(2)}`
1622
- : 'unknown amount';
1623
- const when = arrivalTime ? `${visitDate ?? 'unknown date'} at ${arrivalTime}` : (visitDate ?? 'unknown date');
1624
- const slackRes = await fetch('https://slack.com/api/chat.postMessage', {
1625
- method: 'POST',
1626
- headers: {
1627
- 'Content-Type': 'application/json; charset=utf-8',
1628
- Authorization: `Bearer ${slackToken}`,
1629
- },
1630
- body: JSON.stringify({
1631
- channel: slackChannel,
1632
- text: `Day Pass purchased — ${who} · visit ${when} · ${amount}`,
1633
- }),
1634
- });
1635
- const slackBody = await slackRes.json().catch(() => null);
1636
- if (!slackBody?.ok) {
1637
- console.warn('[stripe-webhook] slack chat.postMessage failed:', slackBody?.error ?? `http_${slackRes.status}`);
1638
- }
1639
- }
1640
- } catch { /* ignore */ }
1641
-
1642
- // Door/WiFi provisioning notify to ftw-middleware. Best-effort, like
1643
- // everything else in this branch -- provisionDayPass() never throws
1644
- // (see dayPassProvisionClient.ts), so this can't break the webhook.
1645
- // Runs BEFORE the confirmation email so a minted wifi_code can be
1646
- // threaded into it; persisted to the row regardless of outcome so
1647
- // day-pass-status (and any admin view) can see what happened.
1648
- let wifiCodeForEmail: string | null = null;
1649
- if (dpRow?.id) {
1650
- // provisionDayPass() itself never throws (dayPassProvisionClient.ts),
1651
- // but this call site wraps it anyway -- a throw here, unguarded,
1652
- // would propagate to the outer handler's catch, which deletes the
1653
- // stripe_events idempotency-ledger row and 500s. Stripe would then
1654
- // retry a webhook whose payment already fully succeeded, the retry's
1655
- // day_pass_purchases insert would 23505, and the WHOLE `!dpErr`
1656
- // branch (coupon settlement, Slack ping, confirmation email, portal
1657
- // account) would be skipped forever for that guest -- not just
1658
- // provisioning. Belt-and-suspenders, matching busProvision's own
1659
- // try/catch a few hundred lines up in the room-booking path.
1660
- try {
1661
- const outcome = await provisionDayPass(
1662
- supabase, dpRow.id, visitDate ?? '', email, customerName ?? '',
1663
- );
1664
- wifiCodeForEmail = outcome.wifiCode;
1665
- const { error: provWriteErr } = await supabase
1666
- .from('day_pass_purchases')
1667
- .update({
1668
- provisioning_status: outcome.status,
1669
- credential_status: outcome.credentialStatus,
1670
- wifi_code: outcome.wifiCode,
1671
- wifi_valid_from: outcome.wifiValidFromIso,
1672
- wifi_valid_to: outcome.wifiValidToIso,
1673
- provisioned_at: (outcome.status === 'provisioned' || outcome.status === 'dry_run')
1674
- ? new Date().toISOString()
1675
- : null,
1676
- provision_error: outcome.error,
1677
- })
1678
- .eq('id', dpRow.id);
1679
- // supabase-js RESOLVES with {error} on a PostgREST failure --
1680
- // it does not throw -- so this is the only place that failure
1681
- // is ever visible. Without it, a stale PostgREST schema cache
1682
- // right after the migration (PGRST204) would silently leave
1683
- // provisioning_status/wifi_code NULL forever with zero record
1684
- // that provisioning actually succeeded on ftw-middleware.
1685
- if (provWriteErr) {
1686
- console.error('[stripe-webhook] day pass provisioning-status write failed', provWriteErr);
1687
- await logOps(supabase, 'day_pass_provision_status_write_failed',
1688
- { day_pass_id: dpRow.id, message: provWriteErr.message, pg_code: (provWriteErr as { code?: string }).code },
1689
- { severity: 'error' }).catch(() => {});
1690
- }
1691
- } catch (e) {
1692
- console.error('[stripe-webhook] day pass provisioning threw', e);
1693
- await logOps(supabase, 'day_pass_provision_threw',
1694
- { day_pass_id: dpRow.id, message: e instanceof Error ? e.message : String(e) },
1695
- { severity: 'error' }).catch(() => {});
1696
- }
1697
- }
1698
-
1699
- // Best-effort customer confirmation email. Never let this break the webhook --
1700
- // same invariant as the Slack ping above and as notifyGhl/createCalendarEvent
1701
- // in the room-booking branch below.
1702
- try {
1703
- await sendDayPassConfirmation(supabase, {
1704
- email,
1705
- customerName,
1706
- visitDate,
1707
- arrivalTime,
1708
- amountCents,
1709
- wifiCode: wifiCodeForEmail,
1710
- }, {
1711
- name: siteConfig.operatorName,
1712
- shortName: siteConfig.operatorShortName,
1713
- domain: siteConfig.domain,
1714
- supportEmail: siteConfig.supportEmail,
1715
- });
1716
- } catch (e) {
1717
- console.error('[stripe-webhook] day pass confirmation email threw', e);
1718
- await logOps(supabase, 'day_pass_confirmation_threw',
1719
- { session_id: session.id, message: String(e) }, { severity: 'warning' });
1720
- }
1721
-
1722
- // Portal account for the day-pass guest. Deliberately a SIBLING of
1723
- // the confirmation email above: decoupled by design, so one failing
1724
- // never affects the other. Claim-FIRST on its own column so a
1725
- // redelivered event can't create a second account or send a second
1726
- // login email. Never throws into the handler.
1727
- try {
1728
- if (dpRow?.id) {
1729
- const { data: claimed, error: claimErr } = await supabase
1730
- .from('day_pass_purchases')
1731
- .update({ portal_account_created_at: new Date().toISOString() })
1732
- .eq('id', dpRow.id)
1733
- .is('portal_account_created_at', null)
1734
- .select('id')
1735
- .maybeSingle();
1736
- if (claimErr) throw claimErr;
1737
- if (claimed) {
1738
- // Idempotent: a repeat guest simply reuses their account.
1739
- const { error: createErr } = await supabase.auth.admin.createUser({
1740
- email,
1741
- email_confirm: true,
1742
- app_metadata: { origin: 'day_pass' },
1743
- });
1744
- if (createErr) {
1745
- const msg = (createErr.message || '').toLowerCase();
1746
- const alreadyExists =
1747
- msg.includes('already been registered') ||
1748
- msg.includes('already registered') ||
1749
- msg.includes('already exists') ||
1750
- (createErr as any).code === 'email_exists' ||
1751
- createErr.status === 422;
1752
- if (!alreadyExists) throw createErr;
1753
- }
1754
- // Sign-in uses the existing branded, rate-limited
1755
- // portal-request-login flow -- no generateLink / signInWithOtp here.
1756
- const loginRes = await fetch(
1757
- `${Deno.env.get('SUPABASE_URL')}/functions/v1/portal-request-login`,
1758
- {
1759
- method: 'POST',
1760
- headers: {
1761
- 'Content-Type': 'application/json',
1762
- Authorization: `Bearer ${Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')}`,
1763
- },
1764
- body: JSON.stringify({
1765
- email,
1766
- redirect_to: dayPassPortalRedirectUrl,
1767
- }),
1768
- },
1769
- );
1770
- if (!loginRes.ok) {
1771
- throw new Error(`portal-request-login http_${loginRes.status}`);
1772
- }
1773
- }
1774
- }
1775
- } catch (e) {
1776
- console.error('[stripe-webhook] day pass portal account failed', e);
1777
- await logOps(supabase, 'day_pass_portal_account_failed',
1778
- { session_id: session.id, customer_email: email, message: String(e) },
1779
- { severity: 'error' });
1780
- }
1781
- }
1782
-
1783
- break;
1784
- }
1785
- // Membership subscription checkout — separate path from booking.
1786
- if (isMembershipCheckoutSession(session)) {
1787
- const subId = typeof session.subscription === 'string'
1788
- ? session.subscription
1789
- : session.subscription?.id ?? null;
1790
- if (subId) {
1791
- let sub: Stripe.Subscription | null = null;
1792
- try {
1793
- sub = await stripe.subscriptions.retrieve(subId);
1794
- } catch (e) {
1795
- console.warn('[stripe-webhook] checkout.session.completed: subscription retrieve failed', e);
1796
- await logOps(supabase, 'membership_sub_retrieve_failed',
1797
- { event_type: event.type, subscription_id: subId, message: String(e) },
1798
- { severity: 'error' });
1799
- // Transient (network/429/5xx) → throw so the outer catch deletes the ledger
1800
- // row and returns 500 → Stripe auto-retries. Permanent (4xx) → fall through
1801
- // to 200; retry can't help and the reconciler is the backstop.
1802
- if (isRetryableStripeError(e)) throw e;
1803
- }
1804
- // D1 fix: upsertMembershipFromSubscription throws its own Error on a
1805
- // genuine (and non-permanent) DB-write failure. That throw must reach
1806
- // the OUTER handler's catch, not this Stripe-retrieve-only catch above
1807
- // -- isRetryableStripeError only recognizes Stripe-shaped errors
1808
- // (e.type / e.statusCode) and would silently swallow a plain Error,
1809
- // defeating the fix entirely. So this call sits OUTSIDE that try block.
1810
- if (sub) {
1811
- const email = session.customer_details?.email ?? session.customer_email ?? null;
1812
- await upsertMembershipFromSubscription(sub, { email });
1813
- // Same signal that activates the membership above -- settle any
1814
- // internal coupon reserved by create-subscription-checkout.
1815
- await markCouponAppliedFromMetadata(session.metadata,
1816
- { session_id: session.id, subscription_id: subId, checkout_type: session.metadata?.checkout_type ?? null });
1817
- }
1818
- } else {
1819
- console.warn('[stripe-webhook] membership checkout.session.completed without subscription id', session.id);
1820
- }
1821
- break;
1822
- }
1823
- // Tier 3 (Commons) event deposit — a PARTIAL capture. It must never
1824
- // reach the generic booking-payment logic below, which would mark the
1825
- // booking fully 'paid' and fire access/calendar/confirmation effects.
1826
- if (session.metadata?.payment_type === 'commons_deposit') {
1827
- await handleCommonsDepositSession(supabase, session);
1828
- break;
1829
- }
1830
- const booking = await findBooking(session);
1831
- if (booking && booking.status !== 'paid' && booking.status !== 'deposit_paid') {
1832
- const paymentIntent = typeof session.payment_intent === 'string'
1833
- ? session.payment_intent
1834
- : session.payment_intent?.id ?? null;
1835
- const { data: flipped, error: flipErr } = await supabase
1836
- .from('bookings')
1837
- .update({
1838
- status: 'paid',
1839
- charged_amount_cents: session.amount_total ?? null,
1840
- stripe_payment_intent: paymentIntent,
1841
- })
1842
- .eq('id', booking.id)
1843
- .neq('status', 'paid')
1844
- // A Commons deposit capture is a PARTIAL payment: flipping it to
1845
- // 'paid' here would both overstate the money collected and violate
1846
- // bookings_amount_math_check. Excluded rather than tightening to
1847
- // status='pending', because this generic path legitimately serves
1848
- // other non-pending recoveries (e.g. a re-paid expired hold).
1849
- .neq('status', 'deposit_paid')
1850
- .select('id');
1851
-
1852
-
1853
- if (!flipErr && flipped && flipped.length > 0) {
1854
- // Post-payment side effects — MUST NOT break the webhook.
1855
- // FIRST: consume the period credit hold placed by create-booking
1856
- // (idempotent via the deterministic idempotency key), then mark any
1857
- // coupon redemption for this booking as applied.
1858
- try {
1859
- const { data: bkForCredit } = await supabase
1860
- .from('bookings')
1861
- .select('credit_applied_cents')
1862
- .eq('id', booking.id)
1863
- .maybeSingle();
1864
- if ((bkForCredit?.credit_applied_cents ?? 0) > 0) {
1865
- const { error: consErr } = await supabase.rpc('credit_consume', {
1866
- p_booking_id: booking.id,
1867
- p_idempotency_key: `consume:${booking.id}`,
1868
- });
1869
- if (consErr) throw consErr;
1870
- }
1871
- } catch (e) {
1872
- console.error('[stripe-webhook] credit_consume failed', e);
1873
- await logOps(supabase, 'booking_side_effect_failed',
1874
- { step: 'credit_consume', message: String(e) },
1875
- { severity: 'error', bookingId: booking.id });
1876
- }
1877
- // F4b: reschedules reserve System-B `grant` credits (redeemed_booking_id
1878
- // set, redeemed_at NULL) rather than placing a System-A hold. Finalize
1879
- // them here and re-issue any residual with the SOONEST original expiry.
1880
- // No-ops (returns 0) when the booking has no reservation.
1881
- try {
1882
- const { data: bkForRes } = await supabase
1883
- .from('bookings')
1884
- .select('credit_applied_cents')
1885
- .eq('id', booking.id)
1886
- .maybeSingle();
1887
- const { error: finErr } = await supabase.rpc('credit_reservation_finalize', {
1888
- p_booking_id: booking.id,
1889
- p_applied_cents: bkForRes?.credit_applied_cents ?? 0,
1890
- });
1891
- if (finErr) throw finErr;
1892
- } catch (e) {
1893
- console.error('[stripe-webhook] credit_reservation_finalize failed', e);
1894
- await logOps(supabase, 'booking_side_effect_failed',
1895
- { step: 'credit_reservation_finalize', message: String(e) },
1896
- { severity: 'error', bookingId: booking.id });
1897
- }
1898
- try {
1899
- const { data: redRow } = await supabase
1900
- .from('coupon_redemptions')
1901
- .select('id,status')
1902
- .eq('applied_to_type', 'booking')
1903
- .eq('applied_to_id', booking.id)
1904
- .maybeSingle();
1905
- if (redRow && redRow.status !== 'applied' && redRow.status !== 'reversed') {
1906
- const { error: cmErr } = await supabase.rpc('coupon_mark_applied', {
1907
- p_redemption_id: redRow.id,
1908
- });
1909
- if (cmErr) throw cmErr;
1910
- }
1911
- } catch (e) {
1912
- console.error('[stripe-webhook] coupon_mark_applied failed', e);
1913
- await logOps(supabase, 'coupon_mark_applied_failed',
1914
- { message: String(e) },
1915
- { severity: 'warning', bookingId: booking.id });
1916
- }
1917
- try {
1918
- const { data: full } = await supabase
1919
- .from('bookings')
1920
- .select('id,status,contact_name,contact_email,contact_phone,during,charged_amount_cents,list_amount_cents,google_event_id,rooms(id,name,address,google_calendar_id,slug,usage_instructions)')
1921
- .eq('id', booking.id)
1922
- .maybeSingle();
1923
- if (full) {
1924
- const f = full as unknown as BookingRow;
1925
- let busResp: Record<string, unknown> | null = null;
1926
- try {
1927
- const range = parseTstzRange(f.during);
1928
- const slug = f.rooms?.slug ?? null;
1929
- // Deposit-only (Commons) bookings are never access-provisioned.
1930
- if (range && slug && !isDepositOnly(f)) {
1931
- busResp = await busProvision({
1932
- bookingId: f.id,
1933
- roomKey: slug,
1934
- startUtc: range.startISO,
1935
- endUtc: range.endISO,
1936
- customer: {
1937
- name: f.contact_name ?? undefined,
1938
- email: f.contact_email,
1939
- phone: f.contact_phone ?? undefined,
1940
- },
1941
- }, supabase);
1942
- } else {
1943
- console.log('[stripe-webhook] busProvision skipped (missing slug/range)', booking.id);
1944
- }
1945
- } catch { /* never break the caller */ }
1946
- try { await notifyGhl(supabase, f, extractDoorAccess(busResp)); }
1947
- catch (e) {
1948
- console.error('[stripe-webhook] notifyGhl threw', e);
1949
- await logOps(supabase, 'booking_side_effect_failed',
1950
- { step: 'notifyGhl', message: String(e) },
1951
- { severity: 'warning', bookingId: booking.id });
1952
- }
1953
- try { await createCalendarEvent(supabase, f); }
1954
- catch (e) {
1955
- console.error('[stripe-webhook] createCalendarEvent threw', e);
1956
- await logOps(supabase, 'booking_side_effect_failed',
1957
- { step: 'createCalendarEvent', message: String(e) },
1958
- { severity: 'warning', bookingId: booking.id });
1959
- }
1960
- }
1961
- } catch (e) {
1962
- console.error('[stripe-webhook] post-paid side effects error', e);
1963
- }
1964
- }
1965
- }
1966
- break;
1967
- }
1968
- case 'charge.refunded': {
1969
- const charge = event.data.object as Stripe.Charge;
1970
- const piId = typeof charge.payment_intent === 'string'
1971
- ? charge.payment_intent
1972
- : charge.payment_intent?.id ?? null;
1973
- if (piId) {
1974
- const { data: refRow, error: refErr } = await supabase
1975
- .from('day_pass_purchases')
1976
- .update({ refunded_at: new Date().toISOString() })
1977
- .eq('stripe_payment_intent', piId)
1978
- .is('refunded_at', null)
1979
- .select('id')
1980
- .maybeSingle();
1981
- if (refErr) {
1982
- console.error('[stripe-webhook] day pass refund update failed', refErr);
1983
- } else if (refRow?.id && charge.refunded) {
1984
- // charge.refunded fires on PARTIAL refunds too -- Stripe's own
1985
- // charge.refunded boolean only flips true once the charge is
1986
- // refunded IN FULL (same rule the referral-clawback block below
1987
- // already applies, with the same reasoning). cancelDayPass is a
1988
- // real, sticky, PERMANENT revocation on ftw-middleware's side
1989
- // (see handle_cancel's own docstring) -- a partial refund must
1990
- // never trigger it, or a guest who still holds a paid pass loses
1991
- // their door/WiFi credential with no way to re-provision.
1992
- //
1993
- // Best-effort: cancelDayPass() never throws
1994
- // (dayPassProvisionClient.ts), so this can't block the refund
1995
- // itself; the try/catch here is belt-and-suspenders.
1996
- try {
1997
- await cancelDayPass(supabase, refRow.id);
1998
- } catch (e) {
1999
- console.error('[stripe-webhook] day pass cancel-on-refund threw', e);
2000
- }
2001
- }
2002
- }
2003
- // Referral clawback on refund (should-fix #7) -- FULL refunds only
2004
- // (round-3 finding N2): charge.refunded fires on partial refunds too,
2005
- // but Stripe's own `charge.refunded` boolean only flips true once the
2006
- // charge is refunded in full, so this naturally excludes partials.
2007
- // No-op for a Day Pass charge (findMembershipIdByChargeInvoice
2008
- // returns null since there's no subscription invoice behind it).
2009
- if (charge.refunded) {
2010
- try {
2011
- const membershipId = await findMembershipIdByChargeInvoice(charge);
2012
- if (membershipId) {
2013
- await maybeClawbackReferralCreditForRefundOrDispute(membershipId, 'charge_refunded');
2014
- }
2015
- } catch (e) {
2016
- console.error('[stripe-webhook] charge.refunded referral clawback step failed', e instanceof Error ? e.message : String(e));
2017
- }
2018
- }
2019
- break;
2020
- }
2021
- case 'charge.dispute.created': {
2022
- // Deliberately NOT clawing back here (round-3 finding N3) -- a
2023
- // dispute can still be WON, and there was no restore path for that.
2024
- // Log for visibility only; the actual clawback happens on
2025
- // charge.dispute.closed below, gated on status === 'lost'.
2026
- const dispute = event.data.object as Stripe.Dispute;
2027
- await logOps(supabase, 'referral_dispute_opened_no_action',
2028
- { dispute_id: dispute.id, charge: typeof dispute.charge === 'string' ? dispute.charge : dispute.charge?.id ?? null },
2029
- { severity: 'warning' }).catch(() => {});
2030
- break;
2031
- }
2032
- case 'charge.dispute.closed': {
2033
- // Referral clawback on a LOST dispute only (should-fix #7 / round-3
2034
- // finding N3). NOTE: both charge.dispute.created and
2035
- // charge.dispute.closed must actually be enabled on the Stripe
2036
- // webhook endpoint's subscribed-events list in the Dashboard for
2037
- // this to ever fire -- that's a Stripe dashboard config change, not
2038
- // code, and hasn't been confirmed done as part of this fix pass.
2039
- const dispute = event.data.object as Stripe.Dispute;
2040
- if (dispute.status !== 'lost') break; // won / warning_closed -- nothing to reverse
2041
- const chargeId = typeof dispute.charge === 'string' ? dispute.charge : dispute.charge?.id ?? null;
2042
- try {
2043
- const membershipId = chargeId ? await findMembershipIdByChargeInvoice(chargeId) : null;
2044
- if (membershipId) {
2045
- await maybeClawbackReferralCreditForRefundOrDispute(membershipId, 'charge_dispute_closed_lost');
2046
- }
2047
- } catch (e) {
2048
- console.error('[stripe-webhook] charge.dispute.closed referral clawback step failed', e instanceof Error ? e.message : String(e));
2049
- }
2050
- break;
2051
- }
2052
- case 'checkout.session.expired':
2053
- case 'checkout.session.async_payment_failed':
2054
- case 'payment_intent.payment_failed': {
2055
- // Internal coupon unwind runs FIRST, for every session-shaped event --
2056
- // membership and day-pass sessions both carry coupon_redemption_id and
2057
- // both would otherwise fall out of this case before anything releases
2058
- // the reservation (membership at the early-break just below, day pass
2059
- // at findBooking returning null). Skipped for
2060
- // payment_intent.payment_failed: that event's object is a
2061
- // PaymentIntent, and neither checkout function puts coupon metadata on
2062
- // one, so there is nothing to read.
2063
- if (event.type !== 'payment_intent.payment_failed') {
2064
- const s = event.data.object as Stripe.Checkout.Session;
2065
- await reverseCouponFromMetadata(s.metadata, event.type,
2066
- { session_id: s.id, checkout_type: s.metadata?.checkout_type ?? null });
2067
- // Ignore membership-scoped sessions from here on; booking-only path below.
2068
- if (isMembershipCheckoutSession(s)) break;
2069
- }
2070
- let session: Stripe.Checkout.Session | null = null;
2071
- let paymentIntentId: string | null = null;
2072
- if (event.type === 'payment_intent.payment_failed') {
2073
- const pi = event.data.object as Stripe.PaymentIntent;
2074
- paymentIntentId = pi.id;
2075
- } else {
2076
- session = event.data.object as Stripe.Checkout.Session;
2077
- }
2078
- let booking: { id: string; status: string } | null = null;
2079
- if (session) booking = await findBooking(session);
2080
- if (!booking && paymentIntentId) {
2081
- const { data } = await supabase
2082
- .from('bookings').select('id,status')
2083
- .eq('stripe_payment_intent', paymentIntentId).maybeSingle();
2084
- booking = data;
2085
- }
2086
- // Also act on 'expired': the expire-stale-booking-holds cron flips a
2087
- // reschedule's new booking to 'expired' (~15-20 min) BEFORE Stripe's own
2088
- // session expiry fires, so gating on 'pending' alone skipped the unwind.
2089
- if (booking && (booking.status === 'pending' || booking.status === 'expired')) {
2090
- if (booking.status === 'pending') {
2091
- await supabase.from('bookings').update({ status: 'expired' }).eq('id', booking.id);
2092
- }
2093
- // Release any credits reserved for this booking so the customer keeps
2094
- // their full credit balance and can try again. (Original booking on a
2095
- // reschedule stays cancelled_credited — the credit issued at that step
2096
- // is what we're releasing back to available here.)
2097
- // Unwinds BOTH credit systems: the System-A period hold placed by
2098
- // create-booking AND the System-B `grant` reservation placed by
2099
- // reschedule-booking (F4). Safe to call when there is nothing to undo.
2100
- try {
2101
- const { error: unwErr } = await supabase.rpc('booking_credit_unwind', {
2102
- p_booking_id: booking.id,
2103
- p_reason: 'checkout_expired_or_failed',
2104
- });
2105
- if (unwErr) throw unwErr;
2106
- } catch (e) {
2107
- console.error('[stripe-webhook] booking_credit_unwind failed', e);
2108
- await logOps(supabase, 'booking_side_effect_failed',
2109
- { step: 'booking_credit_unwind', message: String(e) },
2110
- { severity: 'warning', bookingId: booking.id });
2111
- }
2112
- try {
2113
- const { data: redRow } = await supabase
2114
- .from('coupon_redemptions')
2115
- .select('id,status')
2116
- .eq('applied_to_type', 'booking')
2117
- .eq('applied_to_id', booking.id)
2118
- .maybeSingle();
2119
- if (redRow && redRow.status !== 'reversed') {
2120
- const { error: cvErr } = await supabase.rpc('coupon_reverse', {
2121
- p_redemption_id: redRow.id,
2122
- p_reason: 'checkout_expired_or_failed',
2123
- p_actor_email: systemActorEmail,
2124
- });
2125
- if (cvErr) throw cvErr;
2126
- }
2127
- } catch (e) {
2128
- console.error('[stripe-webhook] coupon_reverse failed', e);
2129
- await logOps(supabase, 'coupon_reverse_failed',
2130
- { message: String(e) },
2131
- { severity: 'warning', bookingId: booking.id });
2132
- }
2133
- await logOps(supabase, 'payment_failed',
2134
- { event_type: event.type },
2135
- { severity: 'warning', bookingId: booking.id });
2136
- try {
2137
- const { data: cancelInfo } = await supabase
2138
- .from('bookings')
2139
- .select('id,during,rooms(slug)')
2140
- .eq('id', booking.id)
2141
- .maybeSingle();
2142
- // deno-lint-ignore no-explicit-any
2143
- const ci = cancelInfo as any;
2144
- const range = ci?.during ? parseTstzRange(ci.during) : null;
2145
- const slug = ci?.rooms?.slug ?? null;
2146
- if (range && slug) {
2147
- await busCancel({
2148
- bookingId: booking.id,
2149
- roomKey: slug,
2150
- startUtc: range.startISO,
2151
- endUtc: range.endISO,
2152
- }, supabase);
2153
- } else {
2154
- console.log('[stripe-webhook] busCancel skipped (missing slug/range)', booking.id);
2155
- }
2156
- } catch { /* never break the caller */ }
2157
- }
2158
- break;
2159
- }
2160
- case 'customer.subscription.created':
2161
- case 'customer.subscription.updated': {
2162
- const sub = event.data.object as Stripe.Subscription;
2163
- if (!isMembershipSubscription(sub)) break;
2164
- await upsertMembershipFromSubscription(sub);
2165
- break;
2166
- }
2167
- case 'customer.subscription.deleted': {
2168
- const sub = event.data.object as Stripe.Subscription;
2169
- if (!isMembershipSubscription(sub)) break;
2170
- await upsertMembershipFromSubscription(sub, { forceStatus: 'canceled' });
2171
- // sub.canceled_at reflects when cancellation was REQUESTED, not when
2172
- // this delete event fires -- see maybeClawbackReferralCredit's
2173
- // docstring (fix #2).
2174
- await maybeClawbackReferralCredit(sub.id, sub.canceled_at ?? null);
2175
- break;
2176
- }
2177
- case 'invoice.paid': {
2178
- const inv = event.data.object as Stripe.Invoice;
2179
-
2180
- // Touch Pass: a standalone one-off invoice, never tied to the member's
2181
- // subscription (see touch-pass-signup/index.ts's chargeActivationFee) --
2182
- // resolveInvoiceSubId would find nothing, and this case's existing
2183
- // "unresolved" error path below is for a genuinely different problem
2184
- // (a real subscription invoice with no resolvable subscription).
2185
- // Detect and handle by exact invoice-id match FIRST, then return
2186
- // before falling into that logic. System of record for activation
2187
- // per plan v7 §2 step 6: exact inv.id === touch_pass_activation_invoice_id
2188
- // match, never line-item inspection.
2189
- //
2190
- // Round 6 fix (BL-2): the UPDATE now WRITES
2191
- // touch_pass_activation_invoice_id instead of requiring it to already
2192
- // equal inv.id in the WHERE clause. That column is written by
2193
- // signup's OWN step 5 (see touch-pass-signup/index.ts), which can
2194
- // lose the race against this webhook -- the invoice.paid event can
2195
- // arrive before step 5's write lands. Requiring an exact match in the
2196
- // WHERE clause in that case would make this branch silently 0-row
2197
- // no-op on a genuine activation. The `.or(...)` clause below still
2198
- // allows the write when the column is NULL (the race case) OR
2199
- // already equals this invoice's id (an idempotent redelivery of the
2200
- // same event), while excluding a DIFFERENT invoice id already on
2201
- // file (a genuine conflict, not this case). A true 0-row result is
2202
- // now treated as a genuine miss and `throw`n (not warn-logged) so
2203
- // Stripe retries the delivery, UNLESS the row is independently
2204
- // confirmed already-active-on-this-invoice (an idempotent replay of
2205
- // an already-applied event, checked explicitly below).
2206
- if (inv.metadata?.feature === 'touch_pass' && inv.metadata?.membership_id) {
2207
- // Round 7 N-3: also write touch_pass_stripe_item_id here, sourced
2208
- // from the Invoice's own metadata (chargeActivationFee stamps
2209
- // {membership_id, feature:'touch_pass', touch_pass_stripe_item_id:
2210
- // item.id} on invoice creation -- see touch-pass-signup/index.ts).
2211
- // touch_pass_stripe_item_id currently has exactly one writer
2212
- // (signup's step 5). If that write never lands -- the webhook wins
2213
- // the activation race (the exact scenario BL-2's fix handles) or
2214
- // step 5 fails transiently -- the row goes 'active' with
2215
- // touch_pass_stripe_item_id still NULL: a live, billing $5/mo item
2216
- // that no membership row records, invisible to every orphan-
2217
- // detection path, until Job B's grace-window sweep cancels a
2218
- // paying, active member's add-on. This branch is the only other
2219
- // writer, so it must also cover that gap.
2220
- //
2221
- // Safe-fallback choice (see final report for the full reasoning):
2222
- // write the item id from metadata whenever present, with NO
2223
- // item-id-based guard of its own -- only the existing invoice-id
2224
- // .or() guard below (round 6, unchanged) narrows which rows this
2225
- // write can ever reach. This codebase's convention for combining
2226
- // two independent multi-condition .or() filters as an AND (the
2227
- // stricter alternative the round-7 brief also offered) could not
2228
- // be confirmed against a reference file in this repo, and
2229
- // supabase-js/PostgREST's exact behavior chaining two separate
2230
- // .or() calls isn't verified against this codebase's pinned
2231
- // version -- rather than guess new filter syntax against a live
2232
- // billing write, this takes the documented-safe direction: the
2233
- // item id is sourced from Stripe's own Invoice object, never
2234
- // client input, so an overwrite here is low-risk, and it can only
2235
- // ever fire on a row the invoice-id guard has already let through
2236
- // (which -- because a membership can have only one Touch Pass
2237
- // episode in flight at a time, per BL-9's claim guard -- means the
2238
- // item id being written is always the SAME episode's own item,
2239
- // not some unrelated item clobbering a different one).
2240
- const itemIdFromMetadata = inv.metadata.touch_pass_stripe_item_id ?? null;
2241
- const { data: activated, error: actErr } = await supabase
2242
- .from('memberships')
2243
- .update({
2244
- touch_pass_addon_status: 'active',
2245
- touch_pass_activation_invoice_id: inv.id,
2246
- ...(itemIdFromMetadata ? { touch_pass_stripe_item_id: itemIdFromMetadata } : {}),
2247
- })
2248
- .eq('id', inv.metadata.membership_id)
2249
- .eq('touch_pass_addon_status', 'pending')
2250
- .or(`touch_pass_activation_invoice_id.is.null,touch_pass_activation_invoice_id.eq.${inv.id}`)
2251
- .select('id');
2252
- if (actErr) {
2253
- console.error('[stripe-webhook] touch_pass activation write failed', actErr);
2254
- await logOps(supabase, 'touch_pass_activation_write_failed',
2255
- { membership_id: inv.metadata.membership_id, invoice_id: inv.id, message: actErr.message },
2256
- { severity: 'error' });
2257
- throw actErr; // let Stripe retry -- do not silently drop an activation
2258
- }
2259
- if (!activated || activated.length === 0) {
2260
- // Only a genuine miss reaches here now (a row already active on
2261
- // THIS invoice is a 0-row no-op we WANT, but that case can't
2262
- // reach here since eq('touch_pass_addon_status','pending')
2263
- // already excludes it) -- check explicitly to avoid a false
2264
- // retry loop on a harmless idempotent redelivery:
2265
- //
2266
- // Round 7 N-4 (same "check the error, continue on failure" fix
2267
- // applied to the reconciler's BL-7 re-check): this read's own
2268
- // error must not be swallowed. On a transient failure here we
2269
- // cannot confirm this is a harmless replay -- fail closed by
2270
- // falling through to the no_match throw below (safe: Stripe
2271
- // retrying an event that turns out to already be applied is
2272
- // exactly the harmless case this check exists to short-circuit,
2273
- // so retrying on an inconclusive read is the safe direction,
2274
- // never a silently dropped activation).
2275
- const { data: already, error: alreadyErr } = await supabase.from('memberships')
2276
- .select('id').eq('id', inv.metadata.membership_id)
2277
- .eq('touch_pass_addon_status', 'active').eq('touch_pass_activation_invoice_id', inv.id)
2278
- .maybeSingle();
2279
- if (alreadyErr) {
2280
- console.error('[stripe-webhook] touch_pass idempotent-replay check failed', alreadyErr);
2281
- await logOps(supabase, 'touch_pass_activation_replay_check_failed',
2282
- { membership_id: inv.metadata.membership_id, invoice_id: inv.id, message: alreadyErr.message },
2283
- { severity: 'warning' });
2284
- // unhealthy read -- do NOT assume this is a harmless replay; fall through.
2285
- } else if (already) {
2286
- break; // idempotent replay of an already-applied event -- fine
2287
- }
2288
- await logOps(supabase, 'touch_pass_activation_no_match',
2289
- { membership_id: inv.metadata.membership_id, invoice_id: inv.id }, { severity: 'error' });
2290
- throw new Error(`touch_pass activation no_match membership=${inv.metadata.membership_id} invoice=${inv.id}`);
2291
- }
2292
- break;
2293
- }
2294
-
2295
- const subId = resolveInvoiceSubId(inv as any);
2296
- if (!subId) {
2297
- await logOps(supabase, 'membership_sub_unresolved',
2298
- { event_type: event.type, invoice_id: inv.id },
2299
- { severity: 'error' });
2300
- break;
2301
- }
2302
- let sub: Stripe.Subscription | null = null;
2303
- try {
2304
- sub = await stripe.subscriptions.retrieve(subId);
2305
- } catch (e) {
2306
- console.warn('[stripe-webhook] invoice.paid: subscription retrieve failed', e);
2307
- await logOps(supabase, 'membership_sub_retrieve_failed',
2308
- { event_type: event.type, subscription_id: subId, message: String(e) },
2309
- { severity: 'error' });
2310
- // Transient (network/429/5xx) → throw so the outer catch deletes the ledger
2311
- // row and returns 500 → Stripe auto-retries. Permanent (4xx) → fall through
2312
- // to 200; retry can't help and the reconciler is the backstop.
2313
- if (isRetryableStripeError(e)) throw e;
2314
- }
2315
- if (sub) {
2316
- if (!isMembershipSubscription(sub)) break;
2317
- // D1 fix: upsertMembershipFromSubscription throws its own Error on a
2318
- // genuine (non-permanent) DB-write failure -- that throw must reach the
2319
- // OUTER handler's catch, not the Stripe-retrieve-only catch below, so
2320
- // this call (and everything depending on it) now sits outside that try.
2321
- await upsertMembershipFromSubscription(sub);
2322
-
2323
- // R8: a $0 first invoice from billing_cycle_anchor's
2324
- // subscription_create is not a real payment -- never let it count
2325
- // as "first invoice paid." first_invoice_paid_at is otherwise
2326
- // never written anywhere in this file (only backfilled once, in
2327
- // an earlier migration) -- this is the actual ongoing writer.
2328
- const isGenuineInvoicePayment =
2329
- inv.billing_reason !== 'subscription_create' || (inv.amount_paid ?? 0) > 0;
2330
- if (isGenuineInvoicePayment) {
2331
- // .select('id') added so the referral-credit step below can tell
2332
- // whether this call actually WON the compare-and-swap (this was
2333
- // genuinely the first real paid invoice) vs. a repeat event that
2334
- // found the column already set -- the update's own predicate and
2335
- // payload are unchanged.
2336
- const { data: fipRows, error: fipErr } = await supabase
2337
- .from('memberships')
2338
- .update({ first_invoice_paid_at: new Date().toISOString() })
2339
- .eq('stripe_subscription_id', subId)
2340
- .is('first_invoice_paid_at', null)
2341
- .select('id');
2342
- if (fipErr) console.warn('[stripe-webhook] first_invoice_paid_at write failed', fipErr);
2343
- // Round-3 review finding: isGenuineInvoicePayment is an OR that
2344
- // only blocks a $0 invoice when billing_reason ===
2345
- // 'subscription_create' -- every other billing_reason
2346
- // (subscription_cycle after a 100%-off code, a $0 invoice
2347
- // covered entirely by account balance, etc.) bypasses the
2348
- // amount check entirely. Gate the referral grant itself on a
2349
- // genuinely nonzero amount_paid, separately from
2350
- // first_invoice_paid_at (which has other consumers and should
2351
- // keep its existing, broader semantics).
2352
- if (!fipErr && fipRows && fipRows.length > 0 && (inv.amount_paid ?? 0) > 0) {
2353
- await maybeGrantReferralCredit(supabase, stripe, fipRows[0].id as string);
2354
- }
2355
- }
2356
- }
2357
- break;
2358
- }
2359
- case 'invoice.payment_failed': {
2360
- const inv = event.data.object as Stripe.Invoice;
2361
-
2362
- // Touch Pass: same standalone-invoice reasoning as invoice.paid above.
2363
- //
2364
- // Round 7 (N-5): CAS the DB status BEFORE canceling the Stripe item,
2365
- // not after -- this branch previously deleted the SubscriptionItem
2366
- // unconditionally, then updated the row with a plain (non-CAS) write
2367
- // and no row-count check. Round 7 named this "BL-8's rule, violated
2368
- // in the one place round 6 didn't look": Stripe does not guarantee
2369
- // event ordering, and this file's own ledger deletes-and-reprocesses
2370
- // on a throw, so a payment_failed event delivered or redelivered
2371
- // AFTER the row has already gone 'active' (e.g. a late/duplicate
2372
- // delivery racing a successful invoice.paid) is a real, not
2373
- // theoretical, scenario. Deleting the item unconditionally in that
2374
- // case destroys a paying, active member's live credential-billing
2375
- // item, and the old status update would then silently 0-row no-op
2376
- // with no alert. Fixed the same way Job A's reconciler sweep was
2377
- // fixed for the identical bug shape (round 6 BL-8): CAS the status
2378
- // FIRST, and only touch Stripe if a row was actually claimed.
2379
- if (inv.metadata?.feature === 'touch_pass' && inv.metadata?.membership_id) {
2380
- // Round 8 (NEW-2): give this CAS the same episode-scoping guard
2381
- // Anchor 1 already has (there, via the invoice-id .or()). Without
2382
- // this, a stale/redelivered payment_failed event from an OLD
2383
- // episode could CAS a NEWER 'pending' episode's row to 'canceled'
2384
- // even though that row has since moved on to a different episode's
2385
- // item -- payment_failed carries the failed invoice's own item id
2386
- // in metadata, so scope on that: only cancel if the row has no
2387
- // recorded item id yet (the race case, mirroring Anchor 1's
2388
- // is-null branch) OR its recorded item id matches THIS invoice's
2389
- // item id. Safe-fallback (same judgment call as N-3 in Anchor 1):
2390
- // if this invoice's own metadata has no touch_pass_stripe_item_id
2391
- // recorded, skip adding the .or() rather than guess.
2392
- const itemIdFromMetadata = inv.metadata.touch_pass_stripe_item_id ?? null;
2393
- let cancelQuery = supabase
2394
- .from('memberships')
2395
- .update({ touch_pass_addon_status: 'canceled', touch_pass_canceled_at: new Date().toISOString() })
2396
- .eq('id', inv.metadata.membership_id)
2397
- .eq('touch_pass_addon_status', 'pending');
2398
- if (itemIdFromMetadata) {
2399
- cancelQuery = cancelQuery.or(
2400
- `touch_pass_stripe_item_id.is.null,touch_pass_stripe_item_id.eq.${itemIdFromMetadata}`,
2401
- );
2402
- }
2403
- const { data: claimed, error: cancelErr } = await cancelQuery.select('id');
2404
- if (cancelErr) {
2405
- console.error('[stripe-webhook] touch_pass payment_failed cancel write failed', cancelErr);
2406
- await logOps(supabase, 'touch_pass_payment_failed_write_failed',
2407
- { membership_id: inv.metadata.membership_id, invoice_id: inv.id, message: cancelErr.message },
2408
- { severity: 'error' });
2409
- throw cancelErr;
2410
- }
2411
- if (!claimed || claimed.length === 0) {
2412
- // Row was not 'pending' -- already active (this event lost the
2413
- // race, or is a late/duplicate delivery after invoice.paid
2414
- // already activated it), already canceled by something else, or
2415
- // never existed. In every case: NEVER touch Stripe. A row that's
2416
- // already 'active' still has a live, correctly-billing item that
2417
- // this event must not destroy.
2418
- await logOps(supabase, 'touch_pass_payment_failed_no_match',
2419
- { membership_id: inv.metadata.membership_id, invoice_id: inv.id }, { severity: 'warning' });
2420
- break;
2421
- }
2422
- // metadata carries touch_pass_stripe_item_id specifically so this
2423
- // branch never needs a DB read to find it (see
2424
- // touch-pass-signup/index.ts's chargeActivationFee comment on why
2425
- // it's stamped on the Invoice's own metadata, not just the
2426
- // InvoiceItem's). If this del() call itself fails (anything other
2427
- // than a 404), the reconciler's Job C (forward-reconciliation pass,
2428
- // see touch-pass-reconciler/index.ts) retries it on its next
2429
- // hourly tick -- the row is already 'canceled' by the CAS above,
2430
- // which is what makes it visible to Job C's query.
2431
- const stripeItemId = inv.metadata.touch_pass_stripe_item_id;
2432
- if (stripeItemId) {
2433
- try {
2434
- await stripe.subscriptionItems.del(stripeItemId, { proration_behavior: 'none' });
2435
- } catch (e) {
2436
- const statusCode = (e as { statusCode?: number }).statusCode;
2437
- if (statusCode !== 404) {
2438
- console.warn('[stripe-webhook] touch_pass item cancel on payment_failed failed', e);
2439
- await logOps(supabase, 'touch_pass_payment_failed_cancel_failed',
2440
- { membership_id: inv.metadata.membership_id, stripe_item_id: stripeItemId, message: String(e) },
2441
- { severity: 'warning' });
2442
- }
2443
- }
2444
- }
2445
- await logOps(supabase, 'touch_pass_payment_failed',
2446
- { membership_id: inv.metadata.membership_id, invoice_id: inv.id, amount_due: inv.amount_due },
2447
- { severity: 'warning' });
2448
- break;
2449
- }
2450
-
2451
- const subId = resolveInvoiceSubId(inv as any);
2452
- if (!subId) {
2453
- await logOps(supabase, 'membership_sub_unresolved',
2454
- { event_type: event.type, invoice_id: inv.id },
2455
- { severity: 'error' });
2456
- break;
2457
- }
2458
- let sub: Stripe.Subscription | null = null;
2459
- try {
2460
- sub = await stripe.subscriptions.retrieve(subId);
2461
- } catch (e) {
2462
- console.warn('[stripe-webhook] invoice.payment_failed: subscription retrieve failed', e);
2463
- await logOps(supabase, 'membership_sub_retrieve_failed',
2464
- { event_type: event.type, subscription_id: subId, message: String(e) },
2465
- { severity: 'error' });
2466
- // Transient (network/429/5xx) → throw so the outer catch deletes the ledger
2467
- // row and returns 500 → Stripe auto-retries. Permanent (4xx) → fall through
2468
- // to 200; retry can't help and the reconciler is the backstop.
2469
- if (isRetryableStripeError(e)) throw e;
2470
- }
2471
- // D1 fix: upsertMembershipFromSubscription throws its own Error on a
2472
- // genuine (non-permanent) DB-write failure -- must reach the OUTER
2473
- // handler's catch, not the Stripe-retrieve-only catch above, so this
2474
- // call now sits outside that try block.
2475
- if (sub && isMembershipSubscription(sub)) {
2476
- await upsertMembershipFromSubscription(sub);
2477
- }
2478
- await logOps(supabase, 'subscription_payment_failed',
2479
- {
2480
- event_type: event.type,
2481
- subscription_id: subId,
2482
- invoice_id: inv.id,
2483
- customer_email: inv.customer_email ?? null,
2484
- amount_due: inv.amount_due,
2485
- },
2486
- { severity: 'error' });
2487
- break;
2488
- }
2489
- case 'payment_intent.succeeded': {
2490
- const pi = event.data.object as Stripe.PaymentIntent;
2491
- // Only the unified sign+pay flow's retainer PaymentIntent carries
2492
- // this metadata pair -- booking/day-pass PaymentIntents (created via
2493
- // Checkout Session) never do, so this can't double-fire on them.
2494
- const sigDocId = pi.metadata?.signature_document_id;
2495
- if (pi.metadata?.checkout_type !== 'private_office_agreement' || !sigDocId) break;
2496
-
2497
- const { data: claimed, error: claimErr } = await supabase
2498
- .from('signature_documents')
2499
- .update({
2500
- retainer_paid_at: new Date().toISOString(),
2501
- retainer_payment_intent_id: pi.id,
2502
- retainer_setup_intent_id: null,
2503
- retainer_intent_kind: 'payment_intent',
2504
- })
2505
- .eq('id', sigDocId)
2506
- .is('retainer_paid_at', null)
2507
- .select('id')
2508
- .maybeSingle();
2509
- if (claimErr) {
2510
- await logOps(supabase, 'retainer_paid_write_failed',
2511
- { signature_document_id: sigDocId, payment_intent_id: pi.id, message: claimErr.message },
2512
- { severity: 'error' });
2513
- }
2514
- void claimed; // outcome doesn't change what happens next -- activation is idempotent regardless of who won the claim
2515
-
2516
- try {
2517
- await maybeActivateAgreement(supabase, stripe, sigDocId);
2518
- } catch (e) {
2519
- console.error('[stripe-webhook] maybeActivateAgreement from payment_intent.succeeded failed', e);
2520
- await logOps(supabase, 'agreement_activation_trigger_failed',
2521
- { signature_document_id: sigDocId, message: String(e) },
2522
- { severity: 'error' });
2523
- }
2524
- break;
2525
- }
2526
- case 'setup_intent.succeeded': {
2527
- const si = event.data.object as Stripe.SetupIntent;
2528
- const sigDocId = si.metadata?.signature_document_id;
2529
- if (si.metadata?.checkout_type !== 'private_office_agreement' || !sigDocId) break;
2530
-
2531
- const { data: claimed, error: claimErr } = await supabase
2532
- .from('signature_documents')
2533
- .update({
2534
- retainer_paid_at: new Date().toISOString(),
2535
- retainer_setup_intent_id: si.id,
2536
- retainer_payment_intent_id: null,
2537
- retainer_intent_kind: 'setup_intent',
2538
- })
2539
- .eq('id', sigDocId)
2540
- .is('retainer_paid_at', null)
2541
- .select('id')
2542
- .maybeSingle();
2543
- if (claimErr) {
2544
- await logOps(supabase, 'retainer_paid_write_failed',
2545
- { signature_document_id: sigDocId, setup_intent_id: si.id, message: claimErr.message, pg_code: (claimErr as { code?: string }).code },
2546
- { severity: 'error' });
2547
- }
2548
- void claimed;
2549
-
2550
- try {
2551
- await maybeActivateAgreement(supabase, stripe, sigDocId);
2552
- } catch (e) {
2553
- console.error('[stripe-webhook] maybeActivateAgreement from setup_intent.succeeded failed', e);
2554
- await logOps(supabase, 'agreement_activation_trigger_failed',
2555
- { signature_document_id: sigDocId, message: String(e) }, { severity: 'error' });
2556
- }
2557
- break;
2558
- }
2559
- case 'setup_intent.setup_failed': {
2560
- const si = event.data.object as Stripe.SetupIntent;
2561
- const sigDocId = si.metadata?.signature_document_id;
2562
- if (si.metadata?.checkout_type !== 'private_office_agreement' || !sigDocId) break;
2563
- await logOps(supabase, 'agreement_zero_retainer_setup_failed',
2564
- { signature_document_id: sigDocId, setup_intent_id: si.id, last_error: si.last_setup_error?.message ?? null },
2565
- { severity: 'warning' });
2566
- break;
2567
- }
2568
- default:
2569
- // ignore
2570
- break;
2571
- }
2572
- } catch (e) {
2573
- console.error('webhook handler error', e);
2574
- // D1 fix: dedupeKey caps this at one ops_events ROW per Stripe event id
2575
- // (ops_events_dedupe_key_uidx), instead of one row per retry attempt --
2576
- // useful for anyone reviewing the ops log after the fact. It does NOT cap
2577
- // Slack/webhook alert volume: _shared/ops.ts's `if (severity === 'error')`
2578
- // block fires unconditionally, before/independent of the dedupe outcome,
2579
- // so a genuinely permanent failure retried by Stripe still pages once per
2580
- // attempt (~16x over the retry window). Capping alert volume itself would
2581
- // mean changing that block's behavior for every dedupeKey caller repo-wide
2582
- // -- a deliberate, separate change, not folded into this fix.
2583
- await logOps(supabase, 'webhook_error',
2584
- { message: String(e), event_type: event?.type },
2585
- { severity: 'error', dedupeKey: 'webhook_error:' + (event?.id ?? 'unknown') });
2586
- try { await supabase.from('stripe_events').delete().eq('event_id', event.id); }
2587
- catch (delErr) { console.error('[stripe-webhook] ledger cleanup failed', delErr); }
2588
- return new Response('handler error', { status: 500 });
2589
- }
2590
-
2591
- return new Response(JSON.stringify({ received: true }), {
2592
- headers: { 'Content-Type': 'application/json' }, status: 200,
2593
- });
2594
- };
2595
- }