@simplelayer/graniteer-core 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (475) hide show
  1. package/dist/adminBookingCredit.d.ts +107 -0
  2. package/dist/adminBookingCredit.js +163 -0
  3. package/dist/agreementCheckout.d.ts +34 -0
  4. package/dist/agreementCheckout.js +211 -0
  5. package/dist/agreementPortalEmail.d.ts +15 -0
  6. package/dist/agreementPortalEmail.js +107 -0
  7. package/dist/availability.d.ts +51 -0
  8. package/dist/availability.js +152 -0
  9. package/dist/billingPortalLinkEmail.d.ts +14 -0
  10. package/dist/billingPortalLinkEmail.js +98 -0
  11. package/dist/bookingAgreementEmail.d.ts +23 -0
  12. package/dist/bookingAgreementEmail.js +116 -0
  13. package/dist/bookingEffects.d.ts +84 -0
  14. package/dist/bookingEffects.js +309 -0
  15. package/dist/bookingHoldReclaim.d.ts +16 -0
  16. package/dist/bookingHoldReclaim.js +74 -0
  17. package/dist/busClient.d.ts +44 -0
  18. package/dist/busClient.js +196 -0
  19. package/dist/busSignature.d.ts +19 -0
  20. package/{src/busSignature.ts → dist/busSignature.js} +26 -33
  21. package/dist/checkoutCoupon.d.ts +156 -0
  22. package/dist/checkoutCoupon.js +369 -0
  23. package/dist/checkoutSessionParams.d.ts +19 -0
  24. package/dist/checkoutSessionParams.js +36 -0
  25. package/dist/commonsContract.d.ts +70 -0
  26. package/dist/commonsContract.js +142 -0
  27. package/dist/commonsDeposit.d.ts +78 -0
  28. package/dist/commonsDeposit.js +199 -0
  29. package/dist/commonsDepositWebhook.d.ts +37 -0
  30. package/dist/commonsDepositWebhook.js +147 -0
  31. package/dist/conductorAdmin.d.ts +76 -0
  32. package/dist/conductorAdmin.js +88 -0
  33. package/dist/dayPassConfirmation.d.ts +17 -0
  34. package/dist/dayPassConfirmation.js +187 -0
  35. package/dist/dunningEmails.d.ts +40 -0
  36. package/dist/dunningEmails.js +174 -0
  37. package/dist/email-templates/brand.d.ts +82 -0
  38. package/dist/email-templates/brand.js +72 -0
  39. package/dist/email-templates/email-change.d.ts +10 -0
  40. package/dist/email-templates/email-change.js +50 -0
  41. package/dist/email-templates/invite.d.ts +8 -0
  42. package/dist/email-templates/invite.js +44 -0
  43. package/dist/email-templates/magic-link.d.ts +10 -0
  44. package/dist/email-templates/magic-link.js +26 -0
  45. package/dist/email-templates/reauthentication.d.ts +6 -0
  46. package/dist/email-templates/reauthentication.js +35 -0
  47. package/dist/email-templates/recovery.d.ts +10 -0
  48. package/dist/email-templates/recovery.js +26 -0
  49. package/dist/email-templates/signup.d.ts +12 -0
  50. package/dist/email-templates/signup.js +30 -0
  51. package/dist/functions/admin-cancel-membership.d.ts +1 -0
  52. package/dist/functions/admin-cancel-membership.js +286 -0
  53. package/dist/functions/admin-change-membership-plan.d.ts +1 -0
  54. package/dist/functions/admin-change-membership-plan.js +281 -0
  55. package/dist/functions/admin-charge-guest-print.d.ts +1 -0
  56. package/dist/functions/admin-charge-guest-print.js +227 -0
  57. package/dist/functions/admin-correct-booking.d.ts +1 -0
  58. package/dist/functions/admin-correct-booking.js +326 -0
  59. package/dist/functions/admin-create-booking.d.ts +43 -0
  60. package/dist/functions/admin-create-booking.js +410 -0
  61. package/dist/functions/admin-create-commons-event.d.ts +1 -0
  62. package/dist/functions/admin-create-commons-event.js +237 -0
  63. package/dist/functions/admin-debug-boldsign-doc.d.ts +1 -0
  64. package/dist/functions/admin-debug-boldsign-doc.js +110 -0
  65. package/dist/functions/admin-door-write.d.ts +1 -0
  66. package/dist/functions/admin-door-write.js +267 -0
  67. package/dist/functions/admin-issue-day-pass.d.ts +14 -0
  68. package/dist/functions/admin-issue-day-pass.js +213 -0
  69. package/dist/functions/admin-mark-booking-paid.d.ts +1 -0
  70. package/dist/functions/admin-mark-booking-paid.js +202 -0
  71. package/dist/functions/admin-mint-billing-portal-link.d.ts +6 -0
  72. package/dist/functions/admin-mint-billing-portal-link.js +159 -0
  73. package/dist/functions/admin-mint-portal-link.d.ts +3 -0
  74. package/dist/functions/admin-mint-portal-link.js +54 -0
  75. package/dist/functions/admin-photo-upload.d.ts +1 -0
  76. package/dist/functions/admin-photo-upload.js +104 -0
  77. package/dist/functions/admin-remove-team-member.d.ts +1 -0
  78. package/dist/functions/admin-remove-team-member.js +140 -0
  79. package/dist/functions/admin-request-trial.d.ts +5 -0
  80. package/dist/functions/admin-request-trial.js +349 -0
  81. package/dist/functions/admin-resend-commons-deposit-link.d.ts +7 -0
  82. package/dist/functions/admin-resend-commons-deposit-link.js +298 -0
  83. package/dist/functions/admin-reset-mfa.d.ts +1 -0
  84. package/dist/functions/admin-reset-mfa.js +129 -0
  85. package/dist/functions/admin-retry-invoice-payment.d.ts +76 -0
  86. package/dist/functions/admin-retry-invoice-payment.js +269 -0
  87. package/dist/functions/admin-reverse-coupon-redemption.d.ts +1 -0
  88. package/dist/functions/admin-reverse-coupon-redemption.js +91 -0
  89. package/dist/functions/admin-revoke-agreement.d.ts +4 -0
  90. package/dist/functions/admin-revoke-agreement.js +410 -0
  91. package/dist/functions/admin-send-commons-agreement.d.ts +1 -0
  92. package/dist/functions/admin-send-commons-agreement.js +212 -0
  93. package/dist/functions/admin-set-credit-amount.d.ts +1 -0
  94. package/dist/functions/admin-set-credit-amount.js +112 -0
  95. package/dist/functions/admin-skip-commons-contract.d.ts +1 -0
  96. package/dist/functions/admin-skip-commons-contract.js +170 -0
  97. package/dist/functions/admin-undo-membership-cancel.d.ts +1 -0
  98. package/dist/functions/admin-undo-membership-cancel.js +135 -0
  99. package/dist/functions/admin-wall-photo-write.d.ts +1 -0
  100. package/dist/functions/admin-wall-photo-write.js +137 -0
  101. package/dist/functions/auth-email-hook.d.ts +20 -0
  102. package/dist/functions/auth-email-hook.js +209 -0
  103. package/dist/functions/boldsign-sender-identity.d.ts +1 -0
  104. package/dist/functions/boldsign-sender-identity.js +109 -0
  105. package/dist/functions/booking-availability.d.ts +1 -0
  106. package/dist/functions/booking-availability.js +355 -0
  107. package/dist/functions/booking-member-preview.d.ts +1 -0
  108. package/dist/functions/booking-member-preview.js +123 -0
  109. package/dist/functions/booking-status.d.ts +3 -0
  110. package/dist/functions/booking-status.js +139 -0
  111. package/dist/functions/conductor.d.ts +3 -0
  112. package/dist/functions/conductor.js +451 -0
  113. package/dist/functions/create-agreement.d.ts +8 -0
  114. package/dist/functions/create-agreement.js +498 -0
  115. package/dist/functions/create-booking.d.ts +44 -0
  116. package/dist/functions/create-booking.js +538 -0
  117. package/dist/functions/create-day-pass-checkout.d.ts +4 -0
  118. package/dist/functions/create-day-pass-checkout.js +196 -0
  119. package/dist/functions/create-portal-session.d.ts +4 -0
  120. package/dist/functions/create-portal-session.js +127 -0
  121. package/dist/functions/create-subscription-checkout.d.ts +4 -0
  122. package/dist/functions/create-subscription-checkout.js +394 -0
  123. package/dist/functions/day-pass-status.d.ts +1 -0
  124. package/dist/functions/day-pass-status.js +70 -0
  125. package/dist/functions/dayStatus.d.ts +15 -0
  126. package/dist/functions/dayStatus.js +59 -0
  127. package/dist/functions/diag-webpush-test.d.ts +1 -0
  128. package/dist/functions/diag-webpush-test.js +42 -0
  129. package/dist/functions/event-access-admin.d.ts +17 -0
  130. package/dist/functions/event-access-admin.js +262 -0
  131. package/dist/functions/event-access-store.d.ts +1 -0
  132. package/dist/functions/event-access-store.js +343 -0
  133. package/dist/functions/ezeep-print-webhook.d.ts +1 -0
  134. package/dist/functions/ezeep-print-webhook.js +160 -0
  135. package/dist/functions/ezeep-usage-reconcile.d.ts +1 -0
  136. package/dist/functions/ezeep-usage-reconcile.js +305 -0
  137. package/dist/functions/fetch-avatar-original.d.ts +3 -0
  138. package/dist/functions/fetch-avatar-original.js +423 -0
  139. package/dist/functions/get-provider-sign-link.d.ts +3 -0
  140. package/dist/functions/get-provider-sign-link.js +146 -0
  141. package/dist/functions/get-signing-link.d.ts +1 -0
  142. package/dist/functions/get-signing-link.js +192 -0
  143. package/dist/functions/guest-print-setup-confirm.d.ts +1 -0
  144. package/dist/functions/guest-print-setup-confirm.js +126 -0
  145. package/dist/functions/guest-print-submit.d.ts +1 -0
  146. package/dist/functions/guest-print-submit.js +145 -0
  147. package/dist/functions/luma-webhook.d.ts +1 -0
  148. package/dist/functions/luma-webhook.js +123 -0
  149. package/dist/functions/manage-booking.d.ts +75 -0
  150. package/dist/functions/manage-booking.js +409 -0
  151. package/dist/functions/mcp.d.ts +16 -0
  152. package/dist/functions/mcp.js +51 -0
  153. package/dist/functions/member-door-action.d.ts +60 -0
  154. package/dist/functions/member-door-action.js +774 -0
  155. package/dist/functions/member-unifi-mapping.d.ts +15 -0
  156. package/dist/functions/member-unifi-mapping.js +198 -0
  157. package/dist/functions/membership-door-sync.d.ts +14 -0
  158. package/dist/functions/membership-door-sync.js +863 -0
  159. package/dist/functions/migration-collision-alert.copy.d.ts +7 -0
  160. package/dist/functions/migration-collision-alert.copy.js +207 -0
  161. package/dist/functions/migration-collision-alert.d.ts +7 -0
  162. package/dist/functions/migration-collision-alert.js +207 -0
  163. package/dist/functions/office-assignment-end.d.ts +12 -0
  164. package/dist/functions/office-assignment-end.js +140 -0
  165. package/dist/functions/portal-booking-access.d.ts +22 -0
  166. package/dist/functions/portal-booking-access.js +163 -0
  167. package/dist/functions/portal-list-invoices.d.ts +1 -0
  168. package/dist/functions/portal-list-invoices.js +90 -0
  169. package/dist/functions/portal-request-login.d.ts +7 -0
  170. package/dist/functions/portal-request-login.js +199 -0
  171. package/dist/functions/portal-resend-invite.d.ts +6 -0
  172. package/dist/functions/portal-resend-invite.js +225 -0
  173. package/dist/functions/portal-submit-event.d.ts +4 -0
  174. package/dist/functions/portal-submit-event.js +152 -0
  175. package/dist/functions/print-billing-recover.d.ts +1 -0
  176. package/dist/functions/print-billing-recover.js +83 -0
  177. package/dist/functions/print-billing-run.d.ts +1 -0
  178. package/dist/functions/print-billing-run.js +153 -0
  179. package/dist/functions/public-facts.d.ts +1 -0
  180. package/dist/functions/public-facts.js +141 -0
  181. package/dist/functions/push-send.d.ts +3 -0
  182. package/dist/functions/push-send.js +297 -0
  183. package/dist/functions/push-test.d.ts +3 -0
  184. package/dist/functions/push-test.js +215 -0
  185. package/dist/functions/request-portal-link.d.ts +7 -0
  186. package/dist/functions/request-portal-link.js +178 -0
  187. package/dist/functions/reschedule-booking.d.ts +50 -0
  188. package/dist/functions/reschedule-booking.js +571 -0
  189. package/dist/functions/review-ratings.d.ts +1 -0
  190. package/dist/functions/review-ratings.js +95 -0
  191. package/dist/functions/space-availability-range.d.ts +1 -0
  192. package/dist/functions/space-availability-range.js +109 -0
  193. package/dist/functions/stripe-db-reconcile.d.ts +3 -0
  194. package/dist/functions/stripe-db-reconcile.js +314 -0
  195. package/dist/functions/stripe-webhook.d.ts +46 -0
  196. package/dist/functions/stripe-webhook.js +2367 -0
  197. package/dist/functions/sync-gcal-blackouts.d.ts +1 -0
  198. package/dist/functions/sync-gcal-blackouts.js +251 -0
  199. package/dist/functions/timetable-event-register.d.ts +1 -0
  200. package/dist/functions/timetable-event-register.js +155 -0
  201. package/dist/functions/timetable-event-status.d.ts +1 -0
  202. package/dist/functions/timetable-event-status.js +86 -0
  203. package/dist/functions/timetable-spaces.d.ts +1 -0
  204. package/dist/functions/timetable-spaces.js +161 -0
  205. package/dist/functions/touch-pass-reconciler.d.ts +1 -0
  206. package/dist/functions/touch-pass-reconciler.js +688 -0
  207. package/dist/functions/touch-pass-signup.d.ts +1 -0
  208. package/dist/functions/touch-pass-signup.js +447 -0
  209. package/dist/functions/upload-booking-display-image.d.ts +4 -0
  210. package/dist/functions/upload-booking-display-image.js +159 -0
  211. package/dist/functions/virtual-onboarding-purge.d.ts +1 -0
  212. package/dist/functions/virtual-onboarding-purge.js +123 -0
  213. package/dist/functions/virtual-onboarding-submit.d.ts +1 -0
  214. package/dist/functions/virtual-onboarding-submit.js +303 -0
  215. package/dist/functions/voice-booking.d.ts +10 -0
  216. package/dist/functions/voice-booking.js +360 -0
  217. package/dist/functions/voice-day-pass.d.ts +15 -0
  218. package/dist/functions/voice-day-pass.js +269 -0
  219. package/dist/functions/voice-inquiry.d.ts +1 -0
  220. package/dist/functions/voice-inquiry.js +156 -0
  221. package/dist/functions/voice-membership-signup.d.ts +15 -0
  222. package/dist/functions/voice-membership-signup.js +273 -0
  223. package/dist/functions/voice-tour-availability.d.ts +1 -0
  224. package/dist/functions/voice-tour-availability.js +179 -0
  225. package/dist/functions/voice-tour-booking.d.ts +21 -0
  226. package/dist/functions/voice-tour-booking.js +308 -0
  227. package/dist/gcalSync.d.ts +29 -0
  228. package/dist/gcalSync.js +119 -0
  229. package/dist/ghlEventInquiry.d.ts +16 -0
  230. package/dist/ghlEventInquiry.js +116 -0
  231. package/dist/ghlNote.d.ts +5 -0
  232. package/dist/ghlNote.js +29 -0
  233. package/dist/ghlTask.d.ts +7 -0
  234. package/dist/ghlTask.js +39 -0
  235. package/dist/ghlVoiceInquiry.d.ts +26 -0
  236. package/dist/ghlVoiceInquiry.js +68 -0
  237. package/dist/guestPrintCapture.d.ts +217 -0
  238. package/dist/guestPrintCapture.js +362 -0
  239. package/dist/index.d.ts +3 -0
  240. package/{index.js → dist/index.js} +2 -1
  241. package/dist/lumaGhl.d.ts +19 -0
  242. package/dist/lumaGhl.js +147 -0
  243. package/dist/mailArrivalEmail.d.ts +15 -0
  244. package/dist/mailArrivalEmail.js +99 -0
  245. package/dist/manageToken.d.ts +64 -0
  246. package/dist/manageToken.js +261 -0
  247. package/dist/membership.d.ts +20 -0
  248. package/dist/membership.js +87 -0
  249. package/dist/membershipBusClient.d.ts +139 -0
  250. package/dist/membershipBusClient.js +443 -0
  251. package/dist/membershipWelcome.d.ts +117 -0
  252. package/dist/membershipWelcome.js +497 -0
  253. package/dist/migrationCheckout.d.ts +169 -0
  254. package/dist/migrationCheckout.js +250 -0
  255. package/dist/money.d.ts +20 -0
  256. package/dist/money.js +35 -0
  257. package/dist/ops.d.ts +27 -0
  258. package/dist/ops.js +87 -0
  259. package/dist/pacificDate.d.ts +8 -0
  260. package/{src/pacificDate.ts → dist/pacificDate.js} +76 -88
  261. package/dist/paymentLinkEmail.d.ts +15 -0
  262. package/dist/paymentLinkEmail.js +102 -0
  263. package/dist/policyAcknowledgment.d.ts +46 -0
  264. package/dist/policyAcknowledgment.js +58 -0
  265. package/dist/portalSession.d.ts +15 -0
  266. package/dist/portalSession.js +31 -0
  267. package/dist/pricing.d.ts +306 -0
  268. package/dist/pricing.js +788 -0
  269. package/dist/printBilling.d.ts +340 -0
  270. package/dist/printBilling.js +619 -0
  271. package/dist/printBillingAdapters.d.ts +29 -0
  272. package/dist/printBillingAdapters.js +130 -0
  273. package/dist/printCorrections.d.ts +175 -0
  274. package/dist/printCorrections.js +328 -0
  275. package/dist/rateLimit.d.ts +20 -0
  276. package/dist/rateLimit.js +70 -0
  277. package/dist/referralCredits.d.ts +5 -0
  278. package/{src/referralCredits.ts → dist/referralCredits.js} +27 -34
  279. package/dist/referralGrant.d.ts +49 -0
  280. package/dist/referralGrant.js +268 -0
  281. package/dist/rescheduleCredit.d.ts +98 -0
  282. package/dist/rescheduleCredit.js +263 -0
  283. package/dist/reservationWifiCode.d.ts +19 -0
  284. package/{src/reservationWifiCode.ts → dist/reservationWifiCode.js} +67 -81
  285. package/dist/retellCallAnalyzed.d.ts +18 -0
  286. package/dist/retellCallAnalyzed.js +91 -0
  287. package/dist/retellSignature.d.ts +14 -0
  288. package/dist/retellSignature.js +60 -0
  289. package/dist/signedUnpaidReminderEmail.d.ts +15 -0
  290. package/dist/signedUnpaidReminderEmail.js +111 -0
  291. package/dist/slackAlert.d.ts +13 -0
  292. package/dist/slackAlert.js +37 -0
  293. package/dist/stripeCoworkingPortal.d.ts +21 -0
  294. package/dist/stripeCoworkingPortal.js +80 -0
  295. package/dist/supabaseTestFakes.d.ts +67 -0
  296. package/dist/supabaseTestFakes.js +79 -0
  297. package/dist/supportTicketEmail.d.ts +16 -0
  298. package/dist/supportTicketEmail.js +98 -0
  299. package/dist/tier1Agreement.d.ts +51 -0
  300. package/dist/tier1Agreement.js +86 -0
  301. package/dist/unifiAccessPolicies.d.ts +36 -0
  302. package/dist/unifiAccessPolicies.js +185 -0
  303. package/dist/unifiGroups.d.ts +26 -0
  304. package/dist/unifiGroups.js +106 -0
  305. package/package.json +645 -169
  306. package/src/adminBookingCredit.test.ts +0 -451
  307. package/src/adminBookingCredit.ts +0 -239
  308. package/src/agreementCheckout.ts +0 -250
  309. package/src/agreementPortalEmail.ts +0 -128
  310. package/src/availability.test.ts +0 -25
  311. package/src/availability.ts +0 -201
  312. package/src/billingPortalLinkEmail.ts +0 -117
  313. package/src/bookingAgreementEmail.ts +0 -149
  314. package/src/bookingEffects.ts +0 -388
  315. package/src/bookingHoldReclaim.ts +0 -94
  316. package/src/busClient.ts +0 -268
  317. package/src/checkoutCoupon.test.ts +0 -675
  318. package/src/checkoutCoupon.ts +0 -455
  319. package/src/checkoutSessionParams.ts +0 -56
  320. package/src/commonsContract.ts +0 -175
  321. package/src/commonsDeposit.ts +0 -298
  322. package/src/commonsDepositWebhook.ts +0 -237
  323. package/src/conductorAdmin.ts +0 -141
  324. package/src/dayPassConfirmation.ts +0 -230
  325. package/src/dunningEmails.test.ts +0 -263
  326. package/src/dunningEmails.ts +0 -203
  327. package/src/email-templates/brand.ts +0 -93
  328. package/src/email-templates/email-change.tsx +0 -92
  329. package/src/email-templates/invite.tsx +0 -79
  330. package/src/email-templates/magic-link.tsx +0 -59
  331. package/src/email-templates/reauthentication.tsx +0 -60
  332. package/src/email-templates/recovery.tsx +0 -59
  333. package/src/email-templates/signup.tsx +0 -67
  334. package/src/functions/admin-cancel-membership.ts +0 -311
  335. package/src/functions/admin-change-membership-plan.ts +0 -312
  336. package/src/functions/admin-charge-guest-print.ts +0 -229
  337. package/src/functions/admin-correct-booking.ts +0 -333
  338. package/src/functions/admin-create-booking.ts +0 -460
  339. package/src/functions/admin-create-commons-event.ts +0 -244
  340. package/src/functions/admin-debug-boldsign-doc.ts +0 -93
  341. package/src/functions/admin-door-write.ts +0 -272
  342. package/src/functions/admin-issue-day-pass.ts +0 -231
  343. package/src/functions/admin-mark-booking-paid.ts +0 -203
  344. package/src/functions/admin-mint-billing-portal-link.ts +0 -168
  345. package/src/functions/admin-mint-portal-link.ts +0 -62
  346. package/src/functions/admin-photo-upload.ts +0 -128
  347. package/src/functions/admin-remove-team-member.ts +0 -150
  348. package/src/functions/admin-request-trial.ts +0 -366
  349. package/src/functions/admin-resend-commons-deposit-link.ts +0 -323
  350. package/src/functions/admin-reset-mfa.ts +0 -138
  351. package/src/functions/admin-retry-invoice-payment.test.ts +0 -567
  352. package/src/functions/admin-retry-invoice-payment.ts +0 -333
  353. package/src/functions/admin-reverse-coupon-redemption.ts +0 -98
  354. package/src/functions/admin-revoke-agreement.ts +0 -467
  355. package/src/functions/admin-send-commons-agreement.ts +0 -214
  356. package/src/functions/admin-set-credit-amount.ts +0 -123
  357. package/src/functions/admin-skip-commons-contract.ts +0 -165
  358. package/src/functions/admin-undo-membership-cancel.ts +0 -144
  359. package/src/functions/admin-wall-photo-write.ts +0 -141
  360. package/src/functions/auth-email-hook.ts +0 -259
  361. package/src/functions/boldsign-sender-identity.ts +0 -114
  362. package/src/functions/booking-availability.ts +0 -419
  363. package/src/functions/booking-member-preview.ts +0 -136
  364. package/src/functions/booking-status.ts +0 -149
  365. package/src/functions/conductor.ts +0 -505
  366. package/src/functions/create-agreement.ts +0 -537
  367. package/src/functions/create-booking.ts +0 -648
  368. package/src/functions/create-day-pass-checkout.ts +0 -218
  369. package/src/functions/create-portal-session.ts +0 -142
  370. package/src/functions/create-subscription-checkout.test.ts +0 -222
  371. package/src/functions/create-subscription-checkout.ts +0 -440
  372. package/src/functions/day-pass-status.ts +0 -89
  373. package/src/functions/dayStatus.ts +0 -71
  374. package/src/functions/diag-webpush-test.ts +0 -45
  375. package/src/functions/event-access-admin.ts +0 -277
  376. package/src/functions/event-access-store.ts +0 -334
  377. package/src/functions/ezeep-print-webhook.ts +0 -213
  378. package/src/functions/ezeep-usage-reconcile.ts +0 -299
  379. package/src/functions/fetch-avatar-original.ts +0 -457
  380. package/src/functions/get-provider-sign-link.ts +0 -155
  381. package/src/functions/get-signing-link.ts +0 -211
  382. package/src/functions/guest-print-setup-confirm.ts +0 -128
  383. package/src/functions/guest-print-submit.ts +0 -149
  384. package/src/functions/luma-webhook.ts +0 -165
  385. package/src/functions/manage-booking.ts +0 -472
  386. package/src/functions/mcp.ts +0 -67
  387. package/src/functions/member-door-action.test.ts +0 -1248
  388. package/src/functions/member-door-action.ts +0 -863
  389. package/src/functions/member-unifi-mapping.test.ts +0 -516
  390. package/src/functions/member-unifi-mapping.ts +0 -206
  391. package/src/functions/membership-door-sync.ts +0 -956
  392. package/src/functions/migration-collision-alert.copy.ts +0 -232
  393. package/src/functions/migration-collision-alert.test.ts +0 -349
  394. package/src/functions/migration-collision-alert.ts +0 -232
  395. package/src/functions/office-assignment-end.ts +0 -146
  396. package/src/functions/portal-booking-access.ts +0 -217
  397. package/src/functions/portal-list-invoices.ts +0 -99
  398. package/src/functions/portal-request-login.ts +0 -192
  399. package/src/functions/portal-resend-invite.ts +0 -248
  400. package/src/functions/portal-submit-event.ts +0 -168
  401. package/src/functions/print-billing-recover.ts +0 -97
  402. package/src/functions/print-billing-run.ts +0 -183
  403. package/src/functions/public-facts.ts +0 -168
  404. package/src/functions/push-send.ts +0 -348
  405. package/src/functions/push-test.ts +0 -234
  406. package/src/functions/request-portal-link.ts +0 -211
  407. package/src/functions/reschedule-booking.ts +0 -649
  408. package/src/functions/review-ratings.ts +0 -113
  409. package/src/functions/space-availability-range.acceptance.test.ts +0 -161
  410. package/src/functions/space-availability-range.ts +0 -142
  411. package/src/functions/stripe-db-reconcile.ts +0 -319
  412. package/src/functions/stripe-webhook.moved-regression.test.ts +0 -78
  413. package/src/functions/stripe-webhook.ts +0 -2595
  414. package/src/functions/sync-gcal-blackouts.ts +0 -298
  415. package/src/functions/timetable-event-register.ts +0 -162
  416. package/src/functions/timetable-event-status.ts +0 -90
  417. package/src/functions/timetable-spaces.ts +0 -219
  418. package/src/functions/touch-pass-reconciler.ts +0 -689
  419. package/src/functions/touch-pass-signup.ts +0 -478
  420. package/src/functions/upload-booking-display-image.ts +0 -179
  421. package/src/functions/virtual-onboarding-purge.ts +0 -134
  422. package/src/functions/virtual-onboarding-submit.ts +0 -315
  423. package/src/functions/voice-booking.ts +0 -453
  424. package/src/functions/voice-day-pass.ts +0 -346
  425. package/src/functions/voice-inquiry.test.ts +0 -301
  426. package/src/functions/voice-inquiry.ts +0 -198
  427. package/src/functions/voice-membership-signup.ts +0 -355
  428. package/src/functions/voice-tour-availability.ts +0 -204
  429. package/src/functions/voice-tour-booking.ts +0 -429
  430. package/src/gcalSync.ts +0 -142
  431. package/src/ghlEventInquiry.ts +0 -143
  432. package/src/ghlNote.ts +0 -34
  433. package/src/ghlTask.ts +0 -48
  434. package/src/ghlVoiceInquiry.ts +0 -90
  435. package/src/guestPrintCapture.test.ts +0 -722
  436. package/src/guestPrintCapture.ts +0 -538
  437. package/src/lumaGhl.ts +0 -195
  438. package/src/mailArrivalEmail.ts +0 -121
  439. package/src/manageToken.ts +0 -363
  440. package/src/membership.ts +0 -109
  441. package/src/membershipBusClient.ts +0 -537
  442. package/src/membershipWelcome.ts +0 -683
  443. package/src/migrationCheckout.ts +0 -366
  444. package/src/money.ts +0 -36
  445. package/src/ops.ts +0 -97
  446. package/src/paymentLinkEmail.ts +0 -123
  447. package/src/policyAcknowledgment.test.ts +0 -50
  448. package/src/policyAcknowledgment.ts +0 -96
  449. package/src/portalSession.ts +0 -46
  450. package/src/pricing.test.ts +0 -660
  451. package/src/pricing.ts +0 -1025
  452. package/src/printBilling.test.ts +0 -750
  453. package/src/printBilling.ts +0 -891
  454. package/src/printBillingAdapters.ts +0 -169
  455. package/src/printCorrections.test.ts +0 -348
  456. package/src/printCorrections.ts +0 -496
  457. package/src/rateLimit.ts +0 -82
  458. package/src/referralCredits.test.ts +0 -31
  459. package/src/referralGrant.ts +0 -321
  460. package/src/rescheduleCredit.test.ts +0 -521
  461. package/src/rescheduleCredit.ts +0 -337
  462. package/src/reservationWifiCode.test.ts +0 -69
  463. package/src/retellCallAnalyzed.test.ts +0 -167
  464. package/src/retellCallAnalyzed.ts +0 -113
  465. package/src/retellSignature.test.ts +0 -137
  466. package/src/retellSignature.ts +0 -82
  467. package/src/signedUnpaidReminderEmail.test.ts +0 -246
  468. package/src/signedUnpaidReminderEmail.ts +0 -132
  469. package/src/slackAlert.ts +0 -38
  470. package/src/stripeCoworkingPortal.ts +0 -91
  471. package/src/supabaseTestFakes.ts +0 -131
  472. package/src/supportTicketEmail.ts +0 -119
  473. package/src/tier1Agreement.ts +0 -125
  474. package/src/unifiAccessPolicies.ts +0 -228
  475. package/src/unifiGroups.ts +0 -129
@@ -0,0 +1,2367 @@
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
+ try {
1373
+ switch (event.type) {
1374
+ case 'checkout.session.completed': {
1375
+ const session = event.data.object;
1376
+ // Day Pass one-time checkout — record the purchase, no booking / no membership.
1377
+ if (session.metadata?.checkout_type === 'day_pass') {
1378
+ const email = session.customer_details?.email ?? session.customer_email ?? null;
1379
+ const customerId = typeof session.customer === 'string'
1380
+ ? session.customer
1381
+ : session.customer?.id ?? null;
1382
+ const paymentIntentId = typeof session.payment_intent === 'string'
1383
+ ? session.payment_intent
1384
+ : session.payment_intent?.id ?? null;
1385
+ if (!email) {
1386
+ await logOps(supabase, 'day_pass_purchase_failed', { session_id: session.id, reason: 'missing_email' }, { severity: 'error' });
1387
+ break;
1388
+ }
1389
+ const visitDate = session.metadata?.visit_date ?? null;
1390
+ const arrivalTime = session.metadata?.arrival_time ?? null;
1391
+ const customerName = session.customer_details?.name ?? null;
1392
+ const amountCents = session.amount_total ?? null;
1393
+ const { data: dpRow, error: dpErr } = await supabase
1394
+ .from('day_pass_purchases')
1395
+ .insert({
1396
+ email,
1397
+ customer_name: customerName,
1398
+ stripe_customer_id: customerId,
1399
+ stripe_checkout_session_id: session.id,
1400
+ stripe_payment_intent: paymentIntentId,
1401
+ plan_id: session.metadata?.plan_id ?? null,
1402
+ amount_cents: amountCents,
1403
+ visit_date: visitDate,
1404
+ arrival_time: arrivalTime,
1405
+ })
1406
+ .select('id')
1407
+ .maybeSingle();
1408
+ if (dpErr && dpErr.code !== '23505') {
1409
+ // 23505 = duplicate webhook redelivery for the same session; no-op.
1410
+ console.error('[stripe-webhook] day pass insert failed', dpErr);
1411
+ await logOps(supabase, 'day_pass_purchase_failed', { session_id: session.id, error: dpErr.message }, { severity: 'error' });
1412
+ }
1413
+ else if (!dpErr) {
1414
+ // The purchase row landed, so the payment is real -- settle any
1415
+ // internal coupon reserved by create-day-pass-checkout.
1416
+ await markCouponAppliedFromMetadata(session.metadata, { session_id: session.id, checkout_type: 'day_pass' });
1417
+ // Best-effort Slack ping. Never let this break the webhook.
1418
+ try {
1419
+ const slackToken = Deno.env.get('SLACK_DAYPASS_BOT_TOKEN');
1420
+ const slackChannel = Deno.env.get('SLACK_DAYPASS_CHANNEL_ID');
1421
+ if (slackToken && slackChannel) {
1422
+ const who = customerName || email;
1423
+ const amount = typeof amountCents === 'number'
1424
+ ? `$${(amountCents / 100).toFixed(2)}`
1425
+ : 'unknown amount';
1426
+ const when = arrivalTime ? `${visitDate ?? 'unknown date'} at ${arrivalTime}` : (visitDate ?? 'unknown date');
1427
+ const slackRes = await fetch('https://slack.com/api/chat.postMessage', {
1428
+ method: 'POST',
1429
+ headers: {
1430
+ 'Content-Type': 'application/json; charset=utf-8',
1431
+ Authorization: `Bearer ${slackToken}`,
1432
+ },
1433
+ body: JSON.stringify({
1434
+ channel: slackChannel,
1435
+ text: `Day Pass purchased — ${who} · visit ${when} · ${amount}`,
1436
+ }),
1437
+ });
1438
+ const slackBody = await slackRes.json().catch(() => null);
1439
+ if (!slackBody?.ok) {
1440
+ console.warn('[stripe-webhook] slack chat.postMessage failed:', slackBody?.error ?? `http_${slackRes.status}`);
1441
+ }
1442
+ }
1443
+ }
1444
+ catch { /* ignore */ }
1445
+ // Door/WiFi provisioning notify to ftw-middleware. Best-effort, like
1446
+ // everything else in this branch -- provisionDayPass() never throws
1447
+ // (see dayPassProvisionClient.ts), so this can't break the webhook.
1448
+ // Runs BEFORE the confirmation email so a minted wifi_code can be
1449
+ // threaded into it; persisted to the row regardless of outcome so
1450
+ // day-pass-status (and any admin view) can see what happened.
1451
+ let wifiCodeForEmail = null;
1452
+ if (dpRow?.id) {
1453
+ // provisionDayPass() itself never throws (dayPassProvisionClient.ts),
1454
+ // but this call site wraps it anyway -- a throw here, unguarded,
1455
+ // would propagate to the outer handler's catch, which deletes the
1456
+ // stripe_events idempotency-ledger row and 500s. Stripe would then
1457
+ // retry a webhook whose payment already fully succeeded, the retry's
1458
+ // day_pass_purchases insert would 23505, and the WHOLE `!dpErr`
1459
+ // branch (coupon settlement, Slack ping, confirmation email, portal
1460
+ // account) would be skipped forever for that guest -- not just
1461
+ // provisioning. Belt-and-suspenders, matching busProvision's own
1462
+ // try/catch a few hundred lines up in the room-booking path.
1463
+ try {
1464
+ const outcome = await provisionDayPass(supabase, dpRow.id, visitDate ?? '', email, customerName ?? '');
1465
+ wifiCodeForEmail = outcome.wifiCode;
1466
+ const { error: provWriteErr } = await supabase
1467
+ .from('day_pass_purchases')
1468
+ .update({
1469
+ provisioning_status: outcome.status,
1470
+ credential_status: outcome.credentialStatus,
1471
+ wifi_code: outcome.wifiCode,
1472
+ wifi_valid_from: outcome.wifiValidFromIso,
1473
+ wifi_valid_to: outcome.wifiValidToIso,
1474
+ provisioned_at: (outcome.status === 'provisioned' || outcome.status === 'dry_run')
1475
+ ? new Date().toISOString()
1476
+ : null,
1477
+ provision_error: outcome.error,
1478
+ })
1479
+ .eq('id', dpRow.id);
1480
+ // supabase-js RESOLVES with {error} on a PostgREST failure --
1481
+ // it does not throw -- so this is the only place that failure
1482
+ // is ever visible. Without it, a stale PostgREST schema cache
1483
+ // right after the migration (PGRST204) would silently leave
1484
+ // provisioning_status/wifi_code NULL forever with zero record
1485
+ // that provisioning actually succeeded on ftw-middleware.
1486
+ if (provWriteErr) {
1487
+ console.error('[stripe-webhook] day pass provisioning-status write failed', provWriteErr);
1488
+ await logOps(supabase, 'day_pass_provision_status_write_failed', { day_pass_id: dpRow.id, message: provWriteErr.message, pg_code: provWriteErr.code }, { severity: 'error' }).catch(() => { });
1489
+ }
1490
+ }
1491
+ catch (e) {
1492
+ console.error('[stripe-webhook] day pass provisioning threw', e);
1493
+ await logOps(supabase, 'day_pass_provision_threw', { day_pass_id: dpRow.id, message: e instanceof Error ? e.message : String(e) }, { severity: 'error' }).catch(() => { });
1494
+ }
1495
+ }
1496
+ // Best-effort customer confirmation email. Never let this break the webhook --
1497
+ // same invariant as the Slack ping above and as notifyGhl/createCalendarEvent
1498
+ // in the room-booking branch below.
1499
+ try {
1500
+ await sendDayPassConfirmation(supabase, {
1501
+ email,
1502
+ customerName,
1503
+ visitDate,
1504
+ arrivalTime,
1505
+ amountCents,
1506
+ wifiCode: wifiCodeForEmail,
1507
+ }, {
1508
+ name: siteConfig.operatorName,
1509
+ shortName: siteConfig.operatorShortName,
1510
+ domain: siteConfig.domain,
1511
+ supportEmail: siteConfig.supportEmail,
1512
+ });
1513
+ }
1514
+ catch (e) {
1515
+ console.error('[stripe-webhook] day pass confirmation email threw', e);
1516
+ await logOps(supabase, 'day_pass_confirmation_threw', { session_id: session.id, message: String(e) }, { severity: 'warning' });
1517
+ }
1518
+ // Portal account for the day-pass guest. Deliberately a SIBLING of
1519
+ // the confirmation email above: decoupled by design, so one failing
1520
+ // never affects the other. Claim-FIRST on its own column so a
1521
+ // redelivered event can't create a second account or send a second
1522
+ // login email. Never throws into the handler.
1523
+ try {
1524
+ if (dpRow?.id) {
1525
+ const { data: claimed, error: claimErr } = await supabase
1526
+ .from('day_pass_purchases')
1527
+ .update({ portal_account_created_at: new Date().toISOString() })
1528
+ .eq('id', dpRow.id)
1529
+ .is('portal_account_created_at', null)
1530
+ .select('id')
1531
+ .maybeSingle();
1532
+ if (claimErr)
1533
+ throw claimErr;
1534
+ if (claimed) {
1535
+ // Idempotent: a repeat guest simply reuses their account.
1536
+ const { error: createErr } = await supabase.auth.admin.createUser({
1537
+ email,
1538
+ email_confirm: true,
1539
+ app_metadata: { origin: 'day_pass' },
1540
+ });
1541
+ if (createErr) {
1542
+ const msg = (createErr.message || '').toLowerCase();
1543
+ const alreadyExists = msg.includes('already been registered') ||
1544
+ msg.includes('already registered') ||
1545
+ msg.includes('already exists') ||
1546
+ createErr.code === 'email_exists' ||
1547
+ createErr.status === 422;
1548
+ if (!alreadyExists)
1549
+ throw createErr;
1550
+ }
1551
+ // Sign-in uses the existing branded, rate-limited
1552
+ // portal-request-login flow -- no generateLink / signInWithOtp here.
1553
+ const loginRes = await fetch(`${Deno.env.get('SUPABASE_URL')}/functions/v1/portal-request-login`, {
1554
+ method: 'POST',
1555
+ headers: {
1556
+ 'Content-Type': 'application/json',
1557
+ Authorization: `Bearer ${Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')}`,
1558
+ },
1559
+ body: JSON.stringify({
1560
+ email,
1561
+ redirect_to: dayPassPortalRedirectUrl,
1562
+ }),
1563
+ });
1564
+ if (!loginRes.ok) {
1565
+ throw new Error(`portal-request-login http_${loginRes.status}`);
1566
+ }
1567
+ }
1568
+ }
1569
+ }
1570
+ catch (e) {
1571
+ console.error('[stripe-webhook] day pass portal account failed', e);
1572
+ await logOps(supabase, 'day_pass_portal_account_failed', { session_id: session.id, customer_email: email, message: String(e) }, { severity: 'error' });
1573
+ }
1574
+ }
1575
+ break;
1576
+ }
1577
+ // Membership subscription checkout — separate path from booking.
1578
+ if (isMembershipCheckoutSession(session)) {
1579
+ const subId = typeof session.subscription === 'string'
1580
+ ? session.subscription
1581
+ : session.subscription?.id ?? null;
1582
+ if (subId) {
1583
+ let sub = null;
1584
+ try {
1585
+ sub = await stripe.subscriptions.retrieve(subId);
1586
+ }
1587
+ catch (e) {
1588
+ console.warn('[stripe-webhook] checkout.session.completed: subscription retrieve failed', e);
1589
+ await logOps(supabase, 'membership_sub_retrieve_failed', { event_type: event.type, subscription_id: subId, message: String(e) }, { severity: 'error' });
1590
+ // Transient (network/429/5xx) → throw so the outer catch deletes the ledger
1591
+ // row and returns 500 → Stripe auto-retries. Permanent (4xx) → fall through
1592
+ // to 200; retry can't help and the reconciler is the backstop.
1593
+ if (isRetryableStripeError(e))
1594
+ throw e;
1595
+ }
1596
+ // D1 fix: upsertMembershipFromSubscription throws its own Error on a
1597
+ // genuine (and non-permanent) DB-write failure. That throw must reach
1598
+ // the OUTER handler's catch, not this Stripe-retrieve-only catch above
1599
+ // -- isRetryableStripeError only recognizes Stripe-shaped errors
1600
+ // (e.type / e.statusCode) and would silently swallow a plain Error,
1601
+ // defeating the fix entirely. So this call sits OUTSIDE that try block.
1602
+ if (sub) {
1603
+ const email = session.customer_details?.email ?? session.customer_email ?? null;
1604
+ await upsertMembershipFromSubscription(sub, { email });
1605
+ // Same signal that activates the membership above -- settle any
1606
+ // internal coupon reserved by create-subscription-checkout.
1607
+ await markCouponAppliedFromMetadata(session.metadata, { session_id: session.id, subscription_id: subId, checkout_type: session.metadata?.checkout_type ?? null });
1608
+ }
1609
+ }
1610
+ else {
1611
+ console.warn('[stripe-webhook] membership checkout.session.completed without subscription id', session.id);
1612
+ }
1613
+ break;
1614
+ }
1615
+ // Tier 3 (Commons) event deposit — a PARTIAL capture. It must never
1616
+ // reach the generic booking-payment logic below, which would mark the
1617
+ // booking fully 'paid' and fire access/calendar/confirmation effects.
1618
+ if (session.metadata?.payment_type === 'commons_deposit') {
1619
+ await handleCommonsDepositSession(supabase, session);
1620
+ break;
1621
+ }
1622
+ const booking = await findBooking(session);
1623
+ if (booking && booking.status !== 'paid' && booking.status !== 'deposit_paid') {
1624
+ const paymentIntent = typeof session.payment_intent === 'string'
1625
+ ? session.payment_intent
1626
+ : session.payment_intent?.id ?? null;
1627
+ const { data: flipped, error: flipErr } = await supabase
1628
+ .from('bookings')
1629
+ .update({
1630
+ status: 'paid',
1631
+ charged_amount_cents: session.amount_total ?? null,
1632
+ stripe_payment_intent: paymentIntent,
1633
+ })
1634
+ .eq('id', booking.id)
1635
+ .neq('status', 'paid')
1636
+ // A Commons deposit capture is a PARTIAL payment: flipping it to
1637
+ // 'paid' here would both overstate the money collected and violate
1638
+ // bookings_amount_math_check. Excluded rather than tightening to
1639
+ // status='pending', because this generic path legitimately serves
1640
+ // other non-pending recoveries (e.g. a re-paid expired hold).
1641
+ .neq('status', 'deposit_paid')
1642
+ .select('id');
1643
+ if (!flipErr && flipped && flipped.length > 0) {
1644
+ // Post-payment side effects — MUST NOT break the webhook.
1645
+ // FIRST: consume the period credit hold placed by create-booking
1646
+ // (idempotent via the deterministic idempotency key), then mark any
1647
+ // coupon redemption for this booking as applied.
1648
+ try {
1649
+ const { data: bkForCredit } = await supabase
1650
+ .from('bookings')
1651
+ .select('credit_applied_cents')
1652
+ .eq('id', booking.id)
1653
+ .maybeSingle();
1654
+ if ((bkForCredit?.credit_applied_cents ?? 0) > 0) {
1655
+ const { error: consErr } = await supabase.rpc('credit_consume', {
1656
+ p_booking_id: booking.id,
1657
+ p_idempotency_key: `consume:${booking.id}`,
1658
+ });
1659
+ if (consErr)
1660
+ throw consErr;
1661
+ }
1662
+ }
1663
+ catch (e) {
1664
+ console.error('[stripe-webhook] credit_consume failed', e);
1665
+ await logOps(supabase, 'booking_side_effect_failed', { step: 'credit_consume', message: String(e) }, { severity: 'error', bookingId: booking.id });
1666
+ }
1667
+ // F4b: reschedules reserve System-B `grant` credits (redeemed_booking_id
1668
+ // set, redeemed_at NULL) rather than placing a System-A hold. Finalize
1669
+ // them here and re-issue any residual with the SOONEST original expiry.
1670
+ // No-ops (returns 0) when the booking has no reservation.
1671
+ try {
1672
+ const { data: bkForRes } = await supabase
1673
+ .from('bookings')
1674
+ .select('credit_applied_cents')
1675
+ .eq('id', booking.id)
1676
+ .maybeSingle();
1677
+ const { error: finErr } = await supabase.rpc('credit_reservation_finalize', {
1678
+ p_booking_id: booking.id,
1679
+ p_applied_cents: bkForRes?.credit_applied_cents ?? 0,
1680
+ });
1681
+ if (finErr)
1682
+ throw finErr;
1683
+ }
1684
+ catch (e) {
1685
+ console.error('[stripe-webhook] credit_reservation_finalize failed', e);
1686
+ await logOps(supabase, 'booking_side_effect_failed', { step: 'credit_reservation_finalize', message: String(e) }, { severity: 'error', bookingId: booking.id });
1687
+ }
1688
+ try {
1689
+ const { data: redRow } = await supabase
1690
+ .from('coupon_redemptions')
1691
+ .select('id,status')
1692
+ .eq('applied_to_type', 'booking')
1693
+ .eq('applied_to_id', booking.id)
1694
+ .maybeSingle();
1695
+ if (redRow && redRow.status !== 'applied' && redRow.status !== 'reversed') {
1696
+ const { error: cmErr } = await supabase.rpc('coupon_mark_applied', {
1697
+ p_redemption_id: redRow.id,
1698
+ });
1699
+ if (cmErr)
1700
+ throw cmErr;
1701
+ }
1702
+ }
1703
+ catch (e) {
1704
+ console.error('[stripe-webhook] coupon_mark_applied failed', e);
1705
+ await logOps(supabase, 'coupon_mark_applied_failed', { message: String(e) }, { severity: 'warning', bookingId: booking.id });
1706
+ }
1707
+ try {
1708
+ const { data: full } = await supabase
1709
+ .from('bookings')
1710
+ .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)')
1711
+ .eq('id', booking.id)
1712
+ .maybeSingle();
1713
+ if (full) {
1714
+ const f = full;
1715
+ let busResp = null;
1716
+ try {
1717
+ const range = parseTstzRange(f.during);
1718
+ const slug = f.rooms?.slug ?? null;
1719
+ // Deposit-only (Commons) bookings are never access-provisioned.
1720
+ if (range && slug && !isDepositOnly(f)) {
1721
+ busResp = await busProvision({
1722
+ bookingId: f.id,
1723
+ roomKey: slug,
1724
+ startUtc: range.startISO,
1725
+ endUtc: range.endISO,
1726
+ customer: {
1727
+ name: f.contact_name ?? undefined,
1728
+ email: f.contact_email,
1729
+ phone: f.contact_phone ?? undefined,
1730
+ },
1731
+ }, supabase);
1732
+ }
1733
+ else {
1734
+ console.log('[stripe-webhook] busProvision skipped (missing slug/range)', booking.id);
1735
+ }
1736
+ }
1737
+ catch { /* never break the caller */ }
1738
+ try {
1739
+ await notifyGhl(supabase, f, extractDoorAccess(busResp));
1740
+ }
1741
+ catch (e) {
1742
+ console.error('[stripe-webhook] notifyGhl threw', e);
1743
+ await logOps(supabase, 'booking_side_effect_failed', { step: 'notifyGhl', message: String(e) }, { severity: 'warning', bookingId: booking.id });
1744
+ }
1745
+ try {
1746
+ await createCalendarEvent(supabase, f);
1747
+ }
1748
+ catch (e) {
1749
+ console.error('[stripe-webhook] createCalendarEvent threw', e);
1750
+ await logOps(supabase, 'booking_side_effect_failed', { step: 'createCalendarEvent', message: String(e) }, { severity: 'warning', bookingId: booking.id });
1751
+ }
1752
+ }
1753
+ }
1754
+ catch (e) {
1755
+ console.error('[stripe-webhook] post-paid side effects error', e);
1756
+ }
1757
+ }
1758
+ }
1759
+ break;
1760
+ }
1761
+ case 'charge.refunded': {
1762
+ const charge = event.data.object;
1763
+ const piId = typeof charge.payment_intent === 'string'
1764
+ ? charge.payment_intent
1765
+ : charge.payment_intent?.id ?? null;
1766
+ if (piId) {
1767
+ const { data: refRow, error: refErr } = await supabase
1768
+ .from('day_pass_purchases')
1769
+ .update({ refunded_at: new Date().toISOString() })
1770
+ .eq('stripe_payment_intent', piId)
1771
+ .is('refunded_at', null)
1772
+ .select('id')
1773
+ .maybeSingle();
1774
+ if (refErr) {
1775
+ console.error('[stripe-webhook] day pass refund update failed', refErr);
1776
+ }
1777
+ else if (refRow?.id && charge.refunded) {
1778
+ // charge.refunded fires on PARTIAL refunds too -- Stripe's own
1779
+ // charge.refunded boolean only flips true once the charge is
1780
+ // refunded IN FULL (same rule the referral-clawback block below
1781
+ // already applies, with the same reasoning). cancelDayPass is a
1782
+ // real, sticky, PERMANENT revocation on ftw-middleware's side
1783
+ // (see handle_cancel's own docstring) -- a partial refund must
1784
+ // never trigger it, or a guest who still holds a paid pass loses
1785
+ // their door/WiFi credential with no way to re-provision.
1786
+ //
1787
+ // Best-effort: cancelDayPass() never throws
1788
+ // (dayPassProvisionClient.ts), so this can't block the refund
1789
+ // itself; the try/catch here is belt-and-suspenders.
1790
+ try {
1791
+ await cancelDayPass(supabase, refRow.id);
1792
+ }
1793
+ catch (e) {
1794
+ console.error('[stripe-webhook] day pass cancel-on-refund threw', e);
1795
+ }
1796
+ }
1797
+ }
1798
+ // Referral clawback on refund (should-fix #7) -- FULL refunds only
1799
+ // (round-3 finding N2): charge.refunded fires on partial refunds too,
1800
+ // but Stripe's own `charge.refunded` boolean only flips true once the
1801
+ // charge is refunded in full, so this naturally excludes partials.
1802
+ // No-op for a Day Pass charge (findMembershipIdByChargeInvoice
1803
+ // returns null since there's no subscription invoice behind it).
1804
+ if (charge.refunded) {
1805
+ try {
1806
+ const membershipId = await findMembershipIdByChargeInvoice(charge);
1807
+ if (membershipId) {
1808
+ await maybeClawbackReferralCreditForRefundOrDispute(membershipId, 'charge_refunded');
1809
+ }
1810
+ }
1811
+ catch (e) {
1812
+ console.error('[stripe-webhook] charge.refunded referral clawback step failed', e instanceof Error ? e.message : String(e));
1813
+ }
1814
+ }
1815
+ break;
1816
+ }
1817
+ case 'charge.dispute.created': {
1818
+ // Deliberately NOT clawing back here (round-3 finding N3) -- a
1819
+ // dispute can still be WON, and there was no restore path for that.
1820
+ // Log for visibility only; the actual clawback happens on
1821
+ // charge.dispute.closed below, gated on status === 'lost'.
1822
+ const dispute = event.data.object;
1823
+ 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(() => { });
1824
+ break;
1825
+ }
1826
+ case 'charge.dispute.closed': {
1827
+ // Referral clawback on a LOST dispute only (should-fix #7 / round-3
1828
+ // finding N3). NOTE: both charge.dispute.created and
1829
+ // charge.dispute.closed must actually be enabled on the Stripe
1830
+ // webhook endpoint's subscribed-events list in the Dashboard for
1831
+ // this to ever fire -- that's a Stripe dashboard config change, not
1832
+ // code, and hasn't been confirmed done as part of this fix pass.
1833
+ const dispute = event.data.object;
1834
+ if (dispute.status !== 'lost')
1835
+ break; // won / warning_closed -- nothing to reverse
1836
+ const chargeId = typeof dispute.charge === 'string' ? dispute.charge : dispute.charge?.id ?? null;
1837
+ try {
1838
+ const membershipId = chargeId ? await findMembershipIdByChargeInvoice(chargeId) : null;
1839
+ if (membershipId) {
1840
+ await maybeClawbackReferralCreditForRefundOrDispute(membershipId, 'charge_dispute_closed_lost');
1841
+ }
1842
+ }
1843
+ catch (e) {
1844
+ console.error('[stripe-webhook] charge.dispute.closed referral clawback step failed', e instanceof Error ? e.message : String(e));
1845
+ }
1846
+ break;
1847
+ }
1848
+ case 'checkout.session.expired':
1849
+ case 'checkout.session.async_payment_failed':
1850
+ case 'payment_intent.payment_failed': {
1851
+ // Internal coupon unwind runs FIRST, for every session-shaped event --
1852
+ // membership and day-pass sessions both carry coupon_redemption_id and
1853
+ // both would otherwise fall out of this case before anything releases
1854
+ // the reservation (membership at the early-break just below, day pass
1855
+ // at findBooking returning null). Skipped for
1856
+ // payment_intent.payment_failed: that event's object is a
1857
+ // PaymentIntent, and neither checkout function puts coupon metadata on
1858
+ // one, so there is nothing to read.
1859
+ if (event.type !== 'payment_intent.payment_failed') {
1860
+ const s = event.data.object;
1861
+ await reverseCouponFromMetadata(s.metadata, event.type, { session_id: s.id, checkout_type: s.metadata?.checkout_type ?? null });
1862
+ // Ignore membership-scoped sessions from here on; booking-only path below.
1863
+ if (isMembershipCheckoutSession(s))
1864
+ break;
1865
+ }
1866
+ let session = null;
1867
+ let paymentIntentId = null;
1868
+ if (event.type === 'payment_intent.payment_failed') {
1869
+ const pi = event.data.object;
1870
+ paymentIntentId = pi.id;
1871
+ }
1872
+ else {
1873
+ session = event.data.object;
1874
+ }
1875
+ let booking = null;
1876
+ if (session)
1877
+ booking = await findBooking(session);
1878
+ if (!booking && paymentIntentId) {
1879
+ const { data } = await supabase
1880
+ .from('bookings').select('id,status')
1881
+ .eq('stripe_payment_intent', paymentIntentId).maybeSingle();
1882
+ booking = data;
1883
+ }
1884
+ // Also act on 'expired': the expire-stale-booking-holds cron flips a
1885
+ // reschedule's new booking to 'expired' (~15-20 min) BEFORE Stripe's own
1886
+ // session expiry fires, so gating on 'pending' alone skipped the unwind.
1887
+ if (booking && (booking.status === 'pending' || booking.status === 'expired')) {
1888
+ if (booking.status === 'pending') {
1889
+ await supabase.from('bookings').update({ status: 'expired' }).eq('id', booking.id);
1890
+ }
1891
+ // Release any credits reserved for this booking so the customer keeps
1892
+ // their full credit balance and can try again. (Original booking on a
1893
+ // reschedule stays cancelled_credited — the credit issued at that step
1894
+ // is what we're releasing back to available here.)
1895
+ // Unwinds BOTH credit systems: the System-A period hold placed by
1896
+ // create-booking AND the System-B `grant` reservation placed by
1897
+ // reschedule-booking (F4). Safe to call when there is nothing to undo.
1898
+ try {
1899
+ const { error: unwErr } = await supabase.rpc('booking_credit_unwind', {
1900
+ p_booking_id: booking.id,
1901
+ p_reason: 'checkout_expired_or_failed',
1902
+ });
1903
+ if (unwErr)
1904
+ throw unwErr;
1905
+ }
1906
+ catch (e) {
1907
+ console.error('[stripe-webhook] booking_credit_unwind failed', e);
1908
+ await logOps(supabase, 'booking_side_effect_failed', { step: 'booking_credit_unwind', message: String(e) }, { severity: 'warning', bookingId: booking.id });
1909
+ }
1910
+ try {
1911
+ const { data: redRow } = await supabase
1912
+ .from('coupon_redemptions')
1913
+ .select('id,status')
1914
+ .eq('applied_to_type', 'booking')
1915
+ .eq('applied_to_id', booking.id)
1916
+ .maybeSingle();
1917
+ if (redRow && redRow.status !== 'reversed') {
1918
+ const { error: cvErr } = await supabase.rpc('coupon_reverse', {
1919
+ p_redemption_id: redRow.id,
1920
+ p_reason: 'checkout_expired_or_failed',
1921
+ p_actor_email: systemActorEmail,
1922
+ });
1923
+ if (cvErr)
1924
+ throw cvErr;
1925
+ }
1926
+ }
1927
+ catch (e) {
1928
+ console.error('[stripe-webhook] coupon_reverse failed', e);
1929
+ await logOps(supabase, 'coupon_reverse_failed', { message: String(e) }, { severity: 'warning', bookingId: booking.id });
1930
+ }
1931
+ await logOps(supabase, 'payment_failed', { event_type: event.type }, { severity: 'warning', bookingId: booking.id });
1932
+ try {
1933
+ const { data: cancelInfo } = await supabase
1934
+ .from('bookings')
1935
+ .select('id,during,rooms(slug)')
1936
+ .eq('id', booking.id)
1937
+ .maybeSingle();
1938
+ // deno-lint-ignore no-explicit-any
1939
+ const ci = cancelInfo;
1940
+ const range = ci?.during ? parseTstzRange(ci.during) : null;
1941
+ const slug = ci?.rooms?.slug ?? null;
1942
+ if (range && slug) {
1943
+ await busCancel({
1944
+ bookingId: booking.id,
1945
+ roomKey: slug,
1946
+ startUtc: range.startISO,
1947
+ endUtc: range.endISO,
1948
+ }, supabase);
1949
+ }
1950
+ else {
1951
+ console.log('[stripe-webhook] busCancel skipped (missing slug/range)', booking.id);
1952
+ }
1953
+ }
1954
+ catch { /* never break the caller */ }
1955
+ }
1956
+ break;
1957
+ }
1958
+ case 'customer.subscription.created':
1959
+ case 'customer.subscription.updated': {
1960
+ const sub = event.data.object;
1961
+ if (!isMembershipSubscription(sub))
1962
+ break;
1963
+ await upsertMembershipFromSubscription(sub);
1964
+ break;
1965
+ }
1966
+ case 'customer.subscription.deleted': {
1967
+ const sub = event.data.object;
1968
+ if (!isMembershipSubscription(sub))
1969
+ break;
1970
+ await upsertMembershipFromSubscription(sub, { forceStatus: 'canceled' });
1971
+ // sub.canceled_at reflects when cancellation was REQUESTED, not when
1972
+ // this delete event fires -- see maybeClawbackReferralCredit's
1973
+ // docstring (fix #2).
1974
+ await maybeClawbackReferralCredit(sub.id, sub.canceled_at ?? null);
1975
+ break;
1976
+ }
1977
+ case 'invoice.paid': {
1978
+ const inv = event.data.object;
1979
+ // Touch Pass: a standalone one-off invoice, never tied to the member's
1980
+ // subscription (see touch-pass-signup/index.ts's chargeActivationFee) --
1981
+ // resolveInvoiceSubId would find nothing, and this case's existing
1982
+ // "unresolved" error path below is for a genuinely different problem
1983
+ // (a real subscription invoice with no resolvable subscription).
1984
+ // Detect and handle by exact invoice-id match FIRST, then return
1985
+ // before falling into that logic. System of record for activation
1986
+ // per plan v7 §2 step 6: exact inv.id === touch_pass_activation_invoice_id
1987
+ // match, never line-item inspection.
1988
+ //
1989
+ // Round 6 fix (BL-2): the UPDATE now WRITES
1990
+ // touch_pass_activation_invoice_id instead of requiring it to already
1991
+ // equal inv.id in the WHERE clause. That column is written by
1992
+ // signup's OWN step 5 (see touch-pass-signup/index.ts), which can
1993
+ // lose the race against this webhook -- the invoice.paid event can
1994
+ // arrive before step 5's write lands. Requiring an exact match in the
1995
+ // WHERE clause in that case would make this branch silently 0-row
1996
+ // no-op on a genuine activation. The `.or(...)` clause below still
1997
+ // allows the write when the column is NULL (the race case) OR
1998
+ // already equals this invoice's id (an idempotent redelivery of the
1999
+ // same event), while excluding a DIFFERENT invoice id already on
2000
+ // file (a genuine conflict, not this case). A true 0-row result is
2001
+ // now treated as a genuine miss and `throw`n (not warn-logged) so
2002
+ // Stripe retries the delivery, UNLESS the row is independently
2003
+ // confirmed already-active-on-this-invoice (an idempotent replay of
2004
+ // an already-applied event, checked explicitly below).
2005
+ if (inv.metadata?.feature === 'touch_pass' && inv.metadata?.membership_id) {
2006
+ // Round 7 N-3: also write touch_pass_stripe_item_id here, sourced
2007
+ // from the Invoice's own metadata (chargeActivationFee stamps
2008
+ // {membership_id, feature:'touch_pass', touch_pass_stripe_item_id:
2009
+ // item.id} on invoice creation -- see touch-pass-signup/index.ts).
2010
+ // touch_pass_stripe_item_id currently has exactly one writer
2011
+ // (signup's step 5). If that write never lands -- the webhook wins
2012
+ // the activation race (the exact scenario BL-2's fix handles) or
2013
+ // step 5 fails transiently -- the row goes 'active' with
2014
+ // touch_pass_stripe_item_id still NULL: a live, billing $5/mo item
2015
+ // that no membership row records, invisible to every orphan-
2016
+ // detection path, until Job B's grace-window sweep cancels a
2017
+ // paying, active member's add-on. This branch is the only other
2018
+ // writer, so it must also cover that gap.
2019
+ //
2020
+ // Safe-fallback choice (see final report for the full reasoning):
2021
+ // write the item id from metadata whenever present, with NO
2022
+ // item-id-based guard of its own -- only the existing invoice-id
2023
+ // .or() guard below (round 6, unchanged) narrows which rows this
2024
+ // write can ever reach. This codebase's convention for combining
2025
+ // two independent multi-condition .or() filters as an AND (the
2026
+ // stricter alternative the round-7 brief also offered) could not
2027
+ // be confirmed against a reference file in this repo, and
2028
+ // supabase-js/PostgREST's exact behavior chaining two separate
2029
+ // .or() calls isn't verified against this codebase's pinned
2030
+ // version -- rather than guess new filter syntax against a live
2031
+ // billing write, this takes the documented-safe direction: the
2032
+ // item id is sourced from Stripe's own Invoice object, never
2033
+ // client input, so an overwrite here is low-risk, and it can only
2034
+ // ever fire on a row the invoice-id guard has already let through
2035
+ // (which -- because a membership can have only one Touch Pass
2036
+ // episode in flight at a time, per BL-9's claim guard -- means the
2037
+ // item id being written is always the SAME episode's own item,
2038
+ // not some unrelated item clobbering a different one).
2039
+ const itemIdFromMetadata = inv.metadata.touch_pass_stripe_item_id ?? null;
2040
+ const { data: activated, error: actErr } = await supabase
2041
+ .from('memberships')
2042
+ .update({
2043
+ touch_pass_addon_status: 'active',
2044
+ touch_pass_activation_invoice_id: inv.id,
2045
+ ...(itemIdFromMetadata ? { touch_pass_stripe_item_id: itemIdFromMetadata } : {}),
2046
+ })
2047
+ .eq('id', inv.metadata.membership_id)
2048
+ .eq('touch_pass_addon_status', 'pending')
2049
+ .or(`touch_pass_activation_invoice_id.is.null,touch_pass_activation_invoice_id.eq.${inv.id}`)
2050
+ .select('id');
2051
+ if (actErr) {
2052
+ console.error('[stripe-webhook] touch_pass activation write failed', actErr);
2053
+ await logOps(supabase, 'touch_pass_activation_write_failed', { membership_id: inv.metadata.membership_id, invoice_id: inv.id, message: actErr.message }, { severity: 'error' });
2054
+ throw actErr; // let Stripe retry -- do not silently drop an activation
2055
+ }
2056
+ if (!activated || activated.length === 0) {
2057
+ // Only a genuine miss reaches here now (a row already active on
2058
+ // THIS invoice is a 0-row no-op we WANT, but that case can't
2059
+ // reach here since eq('touch_pass_addon_status','pending')
2060
+ // already excludes it) -- check explicitly to avoid a false
2061
+ // retry loop on a harmless idempotent redelivery:
2062
+ //
2063
+ // Round 7 N-4 (same "check the error, continue on failure" fix
2064
+ // applied to the reconciler's BL-7 re-check): this read's own
2065
+ // error must not be swallowed. On a transient failure here we
2066
+ // cannot confirm this is a harmless replay -- fail closed by
2067
+ // falling through to the no_match throw below (safe: Stripe
2068
+ // retrying an event that turns out to already be applied is
2069
+ // exactly the harmless case this check exists to short-circuit,
2070
+ // so retrying on an inconclusive read is the safe direction,
2071
+ // never a silently dropped activation).
2072
+ const { data: already, error: alreadyErr } = await supabase.from('memberships')
2073
+ .select('id').eq('id', inv.metadata.membership_id)
2074
+ .eq('touch_pass_addon_status', 'active').eq('touch_pass_activation_invoice_id', inv.id)
2075
+ .maybeSingle();
2076
+ if (alreadyErr) {
2077
+ console.error('[stripe-webhook] touch_pass idempotent-replay check failed', alreadyErr);
2078
+ await logOps(supabase, 'touch_pass_activation_replay_check_failed', { membership_id: inv.metadata.membership_id, invoice_id: inv.id, message: alreadyErr.message }, { severity: 'warning' });
2079
+ // unhealthy read -- do NOT assume this is a harmless replay; fall through.
2080
+ }
2081
+ else if (already) {
2082
+ break; // idempotent replay of an already-applied event -- fine
2083
+ }
2084
+ await logOps(supabase, 'touch_pass_activation_no_match', { membership_id: inv.metadata.membership_id, invoice_id: inv.id }, { severity: 'error' });
2085
+ throw new Error(`touch_pass activation no_match membership=${inv.metadata.membership_id} invoice=${inv.id}`);
2086
+ }
2087
+ break;
2088
+ }
2089
+ const subId = resolveInvoiceSubId(inv);
2090
+ if (!subId) {
2091
+ await logOps(supabase, 'membership_sub_unresolved', { event_type: event.type, invoice_id: inv.id }, { severity: 'error' });
2092
+ break;
2093
+ }
2094
+ let sub = null;
2095
+ try {
2096
+ sub = await stripe.subscriptions.retrieve(subId);
2097
+ }
2098
+ catch (e) {
2099
+ console.warn('[stripe-webhook] invoice.paid: subscription retrieve failed', e);
2100
+ await logOps(supabase, 'membership_sub_retrieve_failed', { event_type: event.type, subscription_id: subId, message: String(e) }, { severity: 'error' });
2101
+ // Transient (network/429/5xx) → throw so the outer catch deletes the ledger
2102
+ // row and returns 500 → Stripe auto-retries. Permanent (4xx) → fall through
2103
+ // to 200; retry can't help and the reconciler is the backstop.
2104
+ if (isRetryableStripeError(e))
2105
+ throw e;
2106
+ }
2107
+ if (sub) {
2108
+ if (!isMembershipSubscription(sub))
2109
+ break;
2110
+ // D1 fix: upsertMembershipFromSubscription throws its own Error on a
2111
+ // genuine (non-permanent) DB-write failure -- that throw must reach the
2112
+ // OUTER handler's catch, not the Stripe-retrieve-only catch below, so
2113
+ // this call (and everything depending on it) now sits outside that try.
2114
+ await upsertMembershipFromSubscription(sub);
2115
+ // R8: a $0 first invoice from billing_cycle_anchor's
2116
+ // subscription_create is not a real payment -- never let it count
2117
+ // as "first invoice paid." first_invoice_paid_at is otherwise
2118
+ // never written anywhere in this file (only backfilled once, in
2119
+ // an earlier migration) -- this is the actual ongoing writer.
2120
+ const isGenuineInvoicePayment = inv.billing_reason !== 'subscription_create' || (inv.amount_paid ?? 0) > 0;
2121
+ if (isGenuineInvoicePayment) {
2122
+ // .select('id') added so the referral-credit step below can tell
2123
+ // whether this call actually WON the compare-and-swap (this was
2124
+ // genuinely the first real paid invoice) vs. a repeat event that
2125
+ // found the column already set -- the update's own predicate and
2126
+ // payload are unchanged.
2127
+ const { data: fipRows, error: fipErr } = await supabase
2128
+ .from('memberships')
2129
+ .update({ first_invoice_paid_at: new Date().toISOString() })
2130
+ .eq('stripe_subscription_id', subId)
2131
+ .is('first_invoice_paid_at', null)
2132
+ .select('id');
2133
+ if (fipErr)
2134
+ console.warn('[stripe-webhook] first_invoice_paid_at write failed', fipErr);
2135
+ // Round-3 review finding: isGenuineInvoicePayment is an OR that
2136
+ // only blocks a $0 invoice when billing_reason ===
2137
+ // 'subscription_create' -- every other billing_reason
2138
+ // (subscription_cycle after a 100%-off code, a $0 invoice
2139
+ // covered entirely by account balance, etc.) bypasses the
2140
+ // amount check entirely. Gate the referral grant itself on a
2141
+ // genuinely nonzero amount_paid, separately from
2142
+ // first_invoice_paid_at (which has other consumers and should
2143
+ // keep its existing, broader semantics).
2144
+ if (!fipErr && fipRows && fipRows.length > 0 && (inv.amount_paid ?? 0) > 0) {
2145
+ await maybeGrantReferralCredit(supabase, stripe, fipRows[0].id);
2146
+ }
2147
+ }
2148
+ }
2149
+ break;
2150
+ }
2151
+ case 'invoice.payment_failed': {
2152
+ const inv = event.data.object;
2153
+ // Touch Pass: same standalone-invoice reasoning as invoice.paid above.
2154
+ //
2155
+ // Round 7 (N-5): CAS the DB status BEFORE canceling the Stripe item,
2156
+ // not after -- this branch previously deleted the SubscriptionItem
2157
+ // unconditionally, then updated the row with a plain (non-CAS) write
2158
+ // and no row-count check. Round 7 named this "BL-8's rule, violated
2159
+ // in the one place round 6 didn't look": Stripe does not guarantee
2160
+ // event ordering, and this file's own ledger deletes-and-reprocesses
2161
+ // on a throw, so a payment_failed event delivered or redelivered
2162
+ // AFTER the row has already gone 'active' (e.g. a late/duplicate
2163
+ // delivery racing a successful invoice.paid) is a real, not
2164
+ // theoretical, scenario. Deleting the item unconditionally in that
2165
+ // case destroys a paying, active member's live credential-billing
2166
+ // item, and the old status update would then silently 0-row no-op
2167
+ // with no alert. Fixed the same way Job A's reconciler sweep was
2168
+ // fixed for the identical bug shape (round 6 BL-8): CAS the status
2169
+ // FIRST, and only touch Stripe if a row was actually claimed.
2170
+ if (inv.metadata?.feature === 'touch_pass' && inv.metadata?.membership_id) {
2171
+ // Round 8 (NEW-2): give this CAS the same episode-scoping guard
2172
+ // Anchor 1 already has (there, via the invoice-id .or()). Without
2173
+ // this, a stale/redelivered payment_failed event from an OLD
2174
+ // episode could CAS a NEWER 'pending' episode's row to 'canceled'
2175
+ // even though that row has since moved on to a different episode's
2176
+ // item -- payment_failed carries the failed invoice's own item id
2177
+ // in metadata, so scope on that: only cancel if the row has no
2178
+ // recorded item id yet (the race case, mirroring Anchor 1's
2179
+ // is-null branch) OR its recorded item id matches THIS invoice's
2180
+ // item id. Safe-fallback (same judgment call as N-3 in Anchor 1):
2181
+ // if this invoice's own metadata has no touch_pass_stripe_item_id
2182
+ // recorded, skip adding the .or() rather than guess.
2183
+ const itemIdFromMetadata = inv.metadata.touch_pass_stripe_item_id ?? null;
2184
+ let cancelQuery = supabase
2185
+ .from('memberships')
2186
+ .update({ touch_pass_addon_status: 'canceled', touch_pass_canceled_at: new Date().toISOString() })
2187
+ .eq('id', inv.metadata.membership_id)
2188
+ .eq('touch_pass_addon_status', 'pending');
2189
+ if (itemIdFromMetadata) {
2190
+ cancelQuery = cancelQuery.or(`touch_pass_stripe_item_id.is.null,touch_pass_stripe_item_id.eq.${itemIdFromMetadata}`);
2191
+ }
2192
+ const { data: claimed, error: cancelErr } = await cancelQuery.select('id');
2193
+ if (cancelErr) {
2194
+ console.error('[stripe-webhook] touch_pass payment_failed cancel write failed', cancelErr);
2195
+ await logOps(supabase, 'touch_pass_payment_failed_write_failed', { membership_id: inv.metadata.membership_id, invoice_id: inv.id, message: cancelErr.message }, { severity: 'error' });
2196
+ throw cancelErr;
2197
+ }
2198
+ if (!claimed || claimed.length === 0) {
2199
+ // Row was not 'pending' -- already active (this event lost the
2200
+ // race, or is a late/duplicate delivery after invoice.paid
2201
+ // already activated it), already canceled by something else, or
2202
+ // never existed. In every case: NEVER touch Stripe. A row that's
2203
+ // already 'active' still has a live, correctly-billing item that
2204
+ // this event must not destroy.
2205
+ await logOps(supabase, 'touch_pass_payment_failed_no_match', { membership_id: inv.metadata.membership_id, invoice_id: inv.id }, { severity: 'warning' });
2206
+ break;
2207
+ }
2208
+ // metadata carries touch_pass_stripe_item_id specifically so this
2209
+ // branch never needs a DB read to find it (see
2210
+ // touch-pass-signup/index.ts's chargeActivationFee comment on why
2211
+ // it's stamped on the Invoice's own metadata, not just the
2212
+ // InvoiceItem's). If this del() call itself fails (anything other
2213
+ // than a 404), the reconciler's Job C (forward-reconciliation pass,
2214
+ // see touch-pass-reconciler/index.ts) retries it on its next
2215
+ // hourly tick -- the row is already 'canceled' by the CAS above,
2216
+ // which is what makes it visible to Job C's query.
2217
+ const stripeItemId = inv.metadata.touch_pass_stripe_item_id;
2218
+ if (stripeItemId) {
2219
+ try {
2220
+ await stripe.subscriptionItems.del(stripeItemId, { proration_behavior: 'none' });
2221
+ }
2222
+ catch (e) {
2223
+ const statusCode = e.statusCode;
2224
+ if (statusCode !== 404) {
2225
+ console.warn('[stripe-webhook] touch_pass item cancel on payment_failed failed', e);
2226
+ await logOps(supabase, 'touch_pass_payment_failed_cancel_failed', { membership_id: inv.metadata.membership_id, stripe_item_id: stripeItemId, message: String(e) }, { severity: 'warning' });
2227
+ }
2228
+ }
2229
+ }
2230
+ await logOps(supabase, 'touch_pass_payment_failed', { membership_id: inv.metadata.membership_id, invoice_id: inv.id, amount_due: inv.amount_due }, { severity: 'warning' });
2231
+ break;
2232
+ }
2233
+ const subId = resolveInvoiceSubId(inv);
2234
+ if (!subId) {
2235
+ await logOps(supabase, 'membership_sub_unresolved', { event_type: event.type, invoice_id: inv.id }, { severity: 'error' });
2236
+ break;
2237
+ }
2238
+ let sub = null;
2239
+ try {
2240
+ sub = await stripe.subscriptions.retrieve(subId);
2241
+ }
2242
+ catch (e) {
2243
+ console.warn('[stripe-webhook] invoice.payment_failed: subscription retrieve failed', e);
2244
+ await logOps(supabase, 'membership_sub_retrieve_failed', { event_type: event.type, subscription_id: subId, message: String(e) }, { severity: 'error' });
2245
+ // Transient (network/429/5xx) → throw so the outer catch deletes the ledger
2246
+ // row and returns 500 → Stripe auto-retries. Permanent (4xx) → fall through
2247
+ // to 200; retry can't help and the reconciler is the backstop.
2248
+ if (isRetryableStripeError(e))
2249
+ throw e;
2250
+ }
2251
+ // D1 fix: upsertMembershipFromSubscription throws its own Error on a
2252
+ // genuine (non-permanent) DB-write failure -- must reach the OUTER
2253
+ // handler's catch, not the Stripe-retrieve-only catch above, so this
2254
+ // call now sits outside that try block.
2255
+ if (sub && isMembershipSubscription(sub)) {
2256
+ await upsertMembershipFromSubscription(sub);
2257
+ }
2258
+ await logOps(supabase, 'subscription_payment_failed', {
2259
+ event_type: event.type,
2260
+ subscription_id: subId,
2261
+ invoice_id: inv.id,
2262
+ customer_email: inv.customer_email ?? null,
2263
+ amount_due: inv.amount_due,
2264
+ }, { severity: 'error' });
2265
+ break;
2266
+ }
2267
+ case 'payment_intent.succeeded': {
2268
+ const pi = event.data.object;
2269
+ // Only the unified sign+pay flow's retainer PaymentIntent carries
2270
+ // this metadata pair -- booking/day-pass PaymentIntents (created via
2271
+ // Checkout Session) never do, so this can't double-fire on them.
2272
+ const sigDocId = pi.metadata?.signature_document_id;
2273
+ if (pi.metadata?.checkout_type !== 'private_office_agreement' || !sigDocId)
2274
+ break;
2275
+ const { data: claimed, error: claimErr } = await supabase
2276
+ .from('signature_documents')
2277
+ .update({
2278
+ retainer_paid_at: new Date().toISOString(),
2279
+ retainer_payment_intent_id: pi.id,
2280
+ retainer_setup_intent_id: null,
2281
+ retainer_intent_kind: 'payment_intent',
2282
+ })
2283
+ .eq('id', sigDocId)
2284
+ .is('retainer_paid_at', null)
2285
+ .select('id')
2286
+ .maybeSingle();
2287
+ if (claimErr) {
2288
+ await logOps(supabase, 'retainer_paid_write_failed', { signature_document_id: sigDocId, payment_intent_id: pi.id, message: claimErr.message }, { severity: 'error' });
2289
+ }
2290
+ void claimed; // outcome doesn't change what happens next -- activation is idempotent regardless of who won the claim
2291
+ try {
2292
+ await maybeActivateAgreement(supabase, stripe, sigDocId);
2293
+ }
2294
+ catch (e) {
2295
+ console.error('[stripe-webhook] maybeActivateAgreement from payment_intent.succeeded failed', e);
2296
+ await logOps(supabase, 'agreement_activation_trigger_failed', { signature_document_id: sigDocId, message: String(e) }, { severity: 'error' });
2297
+ }
2298
+ break;
2299
+ }
2300
+ case 'setup_intent.succeeded': {
2301
+ const si = event.data.object;
2302
+ const sigDocId = si.metadata?.signature_document_id;
2303
+ if (si.metadata?.checkout_type !== 'private_office_agreement' || !sigDocId)
2304
+ break;
2305
+ const { data: claimed, error: claimErr } = await supabase
2306
+ .from('signature_documents')
2307
+ .update({
2308
+ retainer_paid_at: new Date().toISOString(),
2309
+ retainer_setup_intent_id: si.id,
2310
+ retainer_payment_intent_id: null,
2311
+ retainer_intent_kind: 'setup_intent',
2312
+ })
2313
+ .eq('id', sigDocId)
2314
+ .is('retainer_paid_at', null)
2315
+ .select('id')
2316
+ .maybeSingle();
2317
+ if (claimErr) {
2318
+ 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' });
2319
+ }
2320
+ void claimed;
2321
+ try {
2322
+ await maybeActivateAgreement(supabase, stripe, sigDocId);
2323
+ }
2324
+ catch (e) {
2325
+ console.error('[stripe-webhook] maybeActivateAgreement from setup_intent.succeeded failed', e);
2326
+ await logOps(supabase, 'agreement_activation_trigger_failed', { signature_document_id: sigDocId, message: String(e) }, { severity: 'error' });
2327
+ }
2328
+ break;
2329
+ }
2330
+ case 'setup_intent.setup_failed': {
2331
+ const si = event.data.object;
2332
+ const sigDocId = si.metadata?.signature_document_id;
2333
+ if (si.metadata?.checkout_type !== 'private_office_agreement' || !sigDocId)
2334
+ break;
2335
+ 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' });
2336
+ break;
2337
+ }
2338
+ default:
2339
+ // ignore
2340
+ break;
2341
+ }
2342
+ }
2343
+ catch (e) {
2344
+ console.error('webhook handler error', e);
2345
+ // D1 fix: dedupeKey caps this at one ops_events ROW per Stripe event id
2346
+ // (ops_events_dedupe_key_uidx), instead of one row per retry attempt --
2347
+ // useful for anyone reviewing the ops log after the fact. It does NOT cap
2348
+ // Slack/webhook alert volume: _shared/ops.ts's `if (severity === 'error')`
2349
+ // block fires unconditionally, before/independent of the dedupe outcome,
2350
+ // so a genuinely permanent failure retried by Stripe still pages once per
2351
+ // attempt (~16x over the retry window). Capping alert volume itself would
2352
+ // mean changing that block's behavior for every dedupeKey caller repo-wide
2353
+ // -- a deliberate, separate change, not folded into this fix.
2354
+ await logOps(supabase, 'webhook_error', { message: String(e), event_type: event?.type }, { severity: 'error', dedupeKey: 'webhook_error:' + (event?.id ?? 'unknown') });
2355
+ try {
2356
+ await supabase.from('stripe_events').delete().eq('event_id', event.id);
2357
+ }
2358
+ catch (delErr) {
2359
+ console.error('[stripe-webhook] ledger cleanup failed', delErr);
2360
+ }
2361
+ return new Response('handler error', { status: 500 });
2362
+ }
2363
+ return new Response(JSON.stringify({ received: true }), {
2364
+ headers: { 'Content-Type': 'application/json' }, status: 200,
2365
+ });
2366
+ };
2367
+ }