@simplelayer/graniteer-core 0.2.2 → 0.3.0

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