diff --git a/e2e/tests/project-notices.spec.ts b/e2e/tests/project-notices.spec.ts index 022be26a3..8ed63a6c8 100644 --- a/e2e/tests/project-notices.spec.ts +++ b/e2e/tests/project-notices.spec.ts @@ -19,7 +19,7 @@ test("customer notices keep fullscreen panels and sidebar flyouts aligned", asyn await page.goto(`/p/${pid}/log_explorer?fullscreen=trace&showTrace=test-trace`); const admin = page.locator("#super-admin-banner"), billing = page.locator("#billing-downgrade-banner"); await expect(admin).toContainText("You are a super admin in a customer's project"); - await expect(billing.getByRole("link", { name: "Update payment method" })).toBeVisible(); + await expect(billing.getByRole("link", { name: "Reactivate subscription" })).toBeVisible(); await expect(page.locator("#apiLogsPage")).toHaveAttribute("data-fullscreen", "trace"); const noticeBottom = (await billing.boundingBox())!; const panel = await page.locator("#trace_expanded_view").boundingBox(); diff --git a/src/BackgroundJobs.hs b/src/BackgroundJobs.hs index 52d2734da..2758f3cb0 100644 --- a/src/BackgroundJobs.hs +++ b/src/BackgroundJobs.hs @@ -2949,11 +2949,14 @@ data StripeSubDetails = StripeSubDetails -- | One Stripe invoice. `periodStart`/`periodEnd` (POSIX seconds) are the usage -- window the invoice bills for โ€” contiguous with the subscription item's period, -- which is why they, and not our own month arithmetic, define a past cycle. --- `total` is in cents; `hostedUrl` is absent on drafts. +-- `total` and `amountRemaining` (still owed) are in cents; `hostedUrl` is absent on drafts. data StripeInvoice = StripeInvoice - { periodStart :: Int + { invoiceId :: Text + , periodStart :: Int , periodEnd :: Int , total :: Int + , amountRemaining :: Int + , currency :: Text , status :: Text , hostedUrl :: Maybe Text , number :: Maybe Text @@ -2991,12 +2994,15 @@ getStripeInvoices apiKey subId = do resp <- rightToMaybe respE v <- AE.decode @AE.Value (resp ^. W.responseBody) pure - [ StripeInvoice{periodStart, periodEnd, total, status, hostedUrl, number} + [ StripeInvoice{invoiceId, periodStart, periodEnd, total, amountRemaining, currency, status, hostedUrl, number} | inv <- v ^.. AL.key "data" . AL.values , let total = maybe 0 fromInteger $ inv ^? AL.key "total" . AL._Integer + amountRemaining = maybe 0 fromInteger $ inv ^? AL.key "amount_remaining" . AL._Integer status = fromMaybe "" $ inv ^? AL.key "status" . AL._String hostedUrl = inv ^? AL.key "hosted_invoice_url" . AL._String number = inv ^? AL.key "number" . AL._String + , Just invoiceId <- [inv ^? AL.key "id" . AL._String] + , Just currency <- [inv ^? AL.key "currency" . AL._String] , Just periodStart <- [fromInteger <$> inv ^? AL.key "period_start" . AL._Integer] , Just periodEnd <- [fromInteger <$> inv ^? AL.key "period_end" . AL._Integer] ] diff --git a/src/Pages/BodyWrapper.hs b/src/Pages/BodyWrapper.hs index 818cfcba7..95638a5dc 100644 --- a/src/Pages/BodyWrapper.hs +++ b/src/Pages/BodyWrapper.hs @@ -481,7 +481,10 @@ bodyWrapper bcfg child = do $ div_ [id_ "billing-downgrade-banner", role_ "alert", class_ "flex shrink-0 flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-strokeWarning-strong bg-fillWarning-weak px-4 py-2 text-xs text-textStrong"] do span_ "Your paid subscription is no longer active. This project has been downgraded to Free." a_ [href_ $ "/p/" <> project.id.toText <> "/manage_billing", class_ "font-medium text-textBrand underline underline-offset-2"] "Review billing or change plan" - a_ [href_ $ "/p/" <> project.id.toText <> "/manage_billing", hxGet_ $ "/p/" <> project.id.toText <> "/manage_subscription", term "hx-preload" "false", class_ "font-medium text-textBrand underline underline-offset-2"] "Update payment method" + -- A cancelled Stripe sub can't be revived from the portal; checkout starts a new one and collects what's owed. + let stripe = Projects.projectProvider project == Projects.StripeProvider + a_ ([href_ $ "/p/" <> project.id.toText <> "/manage_billing", class_ "font-medium text-textBrand underline underline-offset-2"] <> bool [hxGet_ $ "/p/" <> project.id.toText <> "/manage_subscription", term "hx-preload" "false"] [] stripe) + $ bool "Update payment method" "Reactivate subscription" stripe -- Keep fixed fullscreen panels and drawers below the project notices. section_ [class_ "relative flex flex-row flex-1 min-h-0 overflow-hidden", style_ "contain: layout"] do when (isJust bcfg.currProject) diff --git a/src/Pages/Components.hs b/src/Pages/Components.hs index 36225b6a8..a488f8782 100644 --- a/src/Pages/Components.hs +++ b/src/Pages/Components.hs @@ -1,4 +1,4 @@ -module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, facetRail_, facetSection_, facetOption_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, paymentPlanPicker) where +module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, facetRail_, facetSection_, facetOption_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, grantsTrial, paymentPlanPicker) where import Data.Default (Default (..)) import Data.List (elemIndex, findIndex, lookup) @@ -291,8 +291,8 @@ localTimeFmt_ dfFmt ts = (toHtml $ formatTime defaultTimeLocale "%b %d, %H:%M:%S UTC" ts) -paymentPlanPicker :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Bool -> Projects.BillingProvider -> Html () -paymentPlanPicker pid lemonUrl criticalUrl currentPlan freePricingEnabled basicAuthEnabled isOnboarding provider = do +paymentPlanPicker :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Bool -> Bool -> Projects.BillingProvider -> Html () +paymentPlanPicker pid lemonUrl criticalUrl currentPlan freePricingEnabled basicAuthEnabled trialEligible isOnboarding provider = do let useStripe = provider /= Projects.LemonSqueezyProvider div_ ([class_ "flex flex-col gap-8 w-full"] <> [hxVals_ "{\"isOnboarding\": true}" | isOnboarding]) do unless basicAuthEnabled $ div_ [class_ "flex flex-col gap-2 w-full"] do @@ -307,8 +307,8 @@ paymentPlanPicker pid lemonUrl criticalUrl currentPlan freePricingEnabled basicA then openSourcePricing pid (isCurrent "Open Source") >> enterprisePricing else do when freePricingEnabled $ freePricing pid (isCurrent "Free") - popularPricing pid lemonUrl (isCurrent "Bring nothing") freePricingEnabled useStripe - systemsPricing pid criticalUrl (isCurrent "Bring your own storage") useStripe + popularPricing pid lemonUrl (isCurrent "Bring nothing") freePricingEnabled trialEligible useStripe + systemsPricing pid criticalUrl (isCurrent "Bring your own storage") trialEligible useStripe unless useStripe do script_ [src_ "https://assets.lemonsqueezy.com/lemon.js"] ("" :: Text) script_ @@ -381,11 +381,18 @@ pricingButton_ isCurrent normalCls attrs label = $ bool label "Current plan" isCurrent +-- | Whether a Stripe checkout for @plan@ comes with the 30-day trial: first-time buyers only, +-- and never on Bring-your-own-storage. +grantsTrial :: Bool -> Text -> Bool +grantsTrial trialEligible plan = trialEligible && plan /= "SystemsPricing" + + -- | Plan CTA: inert when already the current plan, else a Stripe checkout POST or a LemonSqueezy popup. -pricingCta_ :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Html () -pricingCta_ pid plan normalCls lemonUrl isCurrent useStripe = +pricingCta_ :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Bool -> Html () +pricingCta_ pid plan normalCls lemonUrl isCurrent trialEligible useStripe = div_ [[__|on click halt|]] - $ pricingButton_ isCurrent normalCls (type_ "button" : attrs) "Start 30 day free trial" + $ pricingButton_ isCurrent normalCls (type_ "button" : attrs) + $ bool "Subscribe" "Start 30 day free trial" (not useStripe || grantsTrial trialEligible plan) where attrs :: [Attribute] attrs @@ -415,8 +422,8 @@ freePricing pid isCurrent = "What's included:" -popularPricing :: Projects.ProjectId -> Text -> Bool -> Bool -> Bool -> Html () -popularPricing pid lemonUrl isCurrent freeTierEnabled useStripe = +popularPricing :: Projects.ProjectId -> Text -> Bool -> Bool -> Bool -> Bool -> Html () +popularPricing pid lemonUrl isCurrent freeTierEnabled trialEligible useStripe = div_ [class_ "relative"] $ div_ (pricingPostAttrs pid "GraduatedPricing" "outline-strokeWeak shadow-[0px_3px_3px_-1.5px_rgba(10,13,18,0.04)] shadow-[0px_8px_8px_-4px_rgba(10,13,18,0.03)] shadow-[0px_20px_24px_-4px_rgba(10,13,18,0.08)]" [hxVals_ "js:{orderIdM: document.querySelector('#popularPricing').value}"]) do div_ [class_ "pricing-gradient-slate-wide"] pass @@ -426,13 +433,13 @@ popularPricing pid lemonUrl isCurrent freeTierEnabled useStripe = "Bring nothing" "This plan can be adjusted" (priceDisplay_ [term "hx-live:text" "(v => v <= 2e7 ? 29 : 29 + (v - 2e7) / 1e6)(+q('#price_range').value)"] "29" "/per month") - (pricingCta_ pid "GraduatedPricing" "btn-primary" lemonUrl isCurrent useStripe) + (pricingCta_ pid "GraduatedPricing" "btn-primary" lemonUrl isCurrent trialEligible useStripe) ["Fully managed cloud service", "Predictable usage-based pricing", "Intelligent incident alerts", "Query your data in english", "30 days data retention included"] (span_ [] $ when freeTierEnabled $ "Everything in " >> span_ [class_ "text-textBrand"] "free" >> " plus...") -systemsPricing :: Projects.ProjectId -> Text -> Bool -> Bool -> Html () -systemsPricing pid critical isCurrent useStripe = +systemsPricing :: Projects.ProjectId -> Text -> Bool -> Bool -> Bool -> Html () +systemsPricing pid critical isCurrent trialEligible useStripe = pricingBadge_ (span_ [class_ "text-sm font-medium leading-tight"] "๐ŸŒŸ" >> span_ [class_ "leading-tight text-sm"] "MOST POPULAR") $ div_ (pricingPostAttrs pid "SystemsPricing" "outline-strokeBrand-strong" [hxVals_ "js:{orderIdM: document.querySelector('#systemsPricing').value}"]) $ div_ [class_ "flex flex-col gap-2"] do @@ -442,7 +449,7 @@ systemsPricing pid critical isCurrent useStripe = "Bring your own storage" "Business plan" (priceDisplay_ [term "hx-live:text" "(v => v <= 1e8 ? 199 : 199 + (v - 1e8) / 1e6)(+q('#price_range').value)"] "199" "/per month") - (pricingCta_ pid "SystemsPricing" "bg-fillStrong text-textInverse-strong" critical isCurrent useStripe) + (pricingCta_ pid "SystemsPricing" "bg-fillStrong text-textInverse-strong" critical isCurrent trialEligible useStripe) ["Own and control all your data", "Save all your data to any S3-compatible bucket", "Unlimited data retention period", "Query years of data via monoscope", "No extra cost for data retention"] (span_ [] $ "Everything in " >> span_ [class_ "text-textBrand"] "bring nothing" >> " plus...") diff --git a/src/Pages/Onboarding.hs b/src/Pages/Onboarding.hs index 5340417e6..de2c6b512 100644 --- a/src/Pages/Onboarding.hs +++ b/src/Pages/Onboarding.hs @@ -74,9 +74,10 @@ onboardingGetH pid stepM = do discordUrl = "https://discord.com/oauth2/authorize?response_type=code&client_id=" <> appCtx.config.discordClientId <> "&permissions=277025392640&integration_type=0&scope=bot+applications.commands&state=" <> pid.toText <> "__onboarding&redirect_uri=" <> appCtx.env.discordRedirectUri pure $ NotifChannelStep pid slackUrl discordUrl phone (maybe mempty (.notify_emails) everyoneTeamM) hasSlack hasDiscord Integration -> IntegrationStep pid . maybe "" (.keyPrefix) . listToMaybe <$> ProjectApiKeys.projectApiKeysByProjectId pid - Pricing -> + Pricing -> do + billing <- Projects.userBilling sess.user.id let checkout u = u <> "&checkout[custom][project_id]=" <> pid.toText - in pure $ PricingStep pid (checkout appCtx.config.lemonSqueezyUrl) (checkout appCtx.config.lemonSqueezyCriticalUrl) project.paymentPlan appCtx.config.enableFreetier appCtx.config.basicAuthEnabled + pure $ PricingStep pid (checkout appCtx.config.lemonSqueezyUrl) (checkout appCtx.config.lemonSqueezyCriticalUrl) project.paymentPlan appCtx.config.enableFreetier appCtx.config.basicAuthEnabled (not billing.hasSubscribedBefore) Info -> pure $ InfoStep pid sess.user.firstName sess.user.lastName (q "companyName") (q "companySize") (q "foundUsFrom") addRespHeaders $ OnboardingGet $ PageCtx bw{currProject = Nothing, hideNavbar = True} stepData @@ -142,6 +143,7 @@ data OnboardingStepData , paymentPlan :: Text , enableFreetier :: Bool , basicAuthEnabled :: Bool + , trialEligible :: Bool } | CompleteStep { stepPid :: Projects.ProjectId @@ -162,7 +164,7 @@ instance ToHtml OnboardingGet where SurveyStep{..} -> onboardingConfigBody stepPid location functionality NotifChannelStep{..} -> notifChannelsWithUrls slackUrl discordUrl stepPid phoneNumber emails hasDiscord hasSlack IntegrationStep{..} -> integrationsPage stepPid apiKey - PricingStep{..} -> pricingPage stepPid lemonUrl criticalUrl paymentPlan enableFreetier basicAuthEnabled + PricingStep{..} -> pricingPage stepPid lemonUrl criticalUrl paymentPlan enableFreetier basicAuthEnabled trialEligible InfoStep{..} -> onboardingInfoBody stepPid firstName lastName companyName companySize foundUsFrom toHtmlRaw = toHtml @@ -272,12 +274,12 @@ onboardingCompleteBody pid = do script_ [src_ "/public/assets/js/confetti.js"] ("" :: Text) -pricingPage :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Html () -pricingPage pid lemon critical paymentPlan freeTierEnabled basicAuthEnabled = +pricingPage :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Bool -> Html () +pricingPage pid lemon critical paymentPlan freeTierEnabled basicAuthEnabled trialEligible = div_ [class_ "w-full max-w-[1100px] mx-auto mt-[70px] mb-10 px-4 md:px-0"] $ do div_ [class_ "flex-col gap-4 flex w-full"] $ do div_ [class_ "w-full md:w-1/2"] $ stepIndicator 5 "Please pick a plan" $ stepUrl pid Integration - paymentPlanPicker pid lemon critical paymentPlan freeTierEnabled basicAuthEnabled True Projects.NoBillingProvider + paymentPlanPicker pid lemon critical paymentPlan freeTierEnabled basicAuthEnabled trialEligible True Projects.NoBillingProvider div_ [class_ "flex flex-col gap-2 w-full pb-20"] do span_ [class_ "text-textStrong text-2xl mt-20"] "FAQ" div_ [class_ "join join-vertical w-full mt-4"] do diff --git a/src/Pages/Projects.hs b/src/Pages/Projects.hs index fccdbfbe8..e5a88a7b1 100644 --- a/src/Pages/Projects.hs +++ b/src/Pages/Projects.hs @@ -1159,9 +1159,11 @@ newtype StripeCheckoutForm = StripeCheckoutForm {plan :: Text} stripeCheckoutInitH :: Projects.ProjectId -> StripeCheckoutForm -> ATAuthCtx (RespHeaders (Html ())) stripeCheckoutInitH pid form = do - (sess, _) <- Projects.sessionAndProject pid + (sess, project) <- Projects.sessionAndProject pid appCtx <- ask @AuthContext let envCfg = appCtx.config + lapsedSubId = guard (Projects.isFreeTier project.paymentPlan && Projects.projectProvider project == Projects.StripeProvider) *> mfilter (not . T.null) project.subId + debts <- maybe (pure []) (fmap (filter \i -> i.status == "open" && i.amountRemaining > 0) . BackgroundJobs.getStripeInvoices envCfg.stripeSecretKey) lapsedSubId -- Keyed to the buyer, not the project: people run several projects, and each one -- used to mint its own Stripe customer and hand out its own 30-day trial. billing <- Projects.userBilling sess.user.id @@ -1169,6 +1171,7 @@ stripeCheckoutInitH pid form = do =<< Settings.createStripeCheckoutSession (not billing.hasSubscribedBefore) billing.stripeCustomerId + debts envCfg.stripeSecretKey envCfg.hostUrl pid diff --git a/src/Pages/Settings.hs b/src/Pages/Settings.hs index b8dc063a7..01ae7d6e5 100644 --- a/src/Pages/Settings.hs +++ b/src/Pages/Settings.hs @@ -60,7 +60,7 @@ module Pages.Settings ( billingUrl, ) where -import Control.Lens ((.~), (^.)) +import Control.Lens ((.~), (?~), (^.)) import Data.Aeson qualified as AE import Data.Aeson.Types (parseMaybe) import Data.ByteArray qualified as BA @@ -110,7 +110,7 @@ import Network.HTTP.Types (urlEncode) import Network.Minio qualified as Minio import Network.Wreq qualified as Wreq import Pages.BodyWrapper (BWConfig (..), PageCtx (..), mkPageCtx, settingsContentTarget) -import Pages.Components (BadgeColor (..), EmptyStateCfg (..), EmptyStateSize (..), FieldCfg (..), FieldSize (..), IconBadgeSize (..), ModalCfg (..), callout_, connectionBadge_, copyField_, copySourceAttr_, dangerAction_, disclosure_, emptyState_, filterInputAttr_, formActionsModal_, formCheckbox_, formField_, headerRow_, iconBadge_, keyboardActivateAttr_, localTimeFmt_, modalWith_, options_, paymentPlanPicker, searchInput_, sectionLabel_, settingsH2_, settingsSection_, tonePill_) +import Pages.Components (BadgeColor (..), EmptyStateCfg (..), EmptyStateSize (..), FieldCfg (..), FieldSize (..), IconBadgeSize (..), ModalCfg (..), callout_, connectionBadge_, copyField_, copySourceAttr_, dangerAction_, disclosure_, emptyState_, filterInputAttr_, formActionsModal_, formCheckbox_, formField_, grantsTrial, headerRow_, iconBadge_, keyboardActivateAttr_, localTimeFmt_, modalWith_, options_, paymentPlanPicker, searchInput_, sectionLabel_, settingsH2_, settingsSection_, tonePill_) import Pkg.Components.Table qualified as Table import Pkg.DeriveUtils (DB, UUIDId (..), WrappedEnumSC (..)) import Pkg.EmailTemplates qualified as ET @@ -1185,6 +1185,7 @@ data BillingData = BillingData , paymentPlan :: Text , enableFreetier :: Bool , basicAuthEnabled :: Bool + , trialEligible :: Bool , provider :: Projects.BillingProvider , dailyUsage :: [Projects.DailyUsage] -- ^ (day, total_requests, metrics, eventBytes, metricBytes); events = total_requests - metrics @@ -1223,7 +1224,8 @@ instance ToHtml BillingGet where manageBillingGetH :: Projects.ProjectId -> ATAuthCtx (RespHeaders BillingGet) manageBillingGetH pid = do - (_, project, bw) <- mkPageCtx pid + (sess, project, bw) <- mkPageCtx pid + billing <- Projects.userBilling sess.user.id let dat = fromMaybe project.createdAt project.billingDay envCfg = bw.config currentTime <- Time.currentTime @@ -1273,7 +1275,7 @@ manageBillingGetH pid = do lemonUrl = envCfg.lemonSqueezyUrl <> "&checkout[custom][project_id]=" <> pid.toText critical = envCfg.lemonSqueezyCriticalUrl <> "&checkout[custom][project_id]=" <> pid.toText provider = Projects.projectProvider project - addRespHeaders $ BillingGet $ PageCtx bwconf BillingData{pid, totalReqs = totalRequests, totalBytes, aiInputTokens, aiOutputTokens, aiCostMicrousd, aiInputRate = envCfg.aiInputMicrousdPerMillionTokens, aiOutputRate = envCfg.aiOutputMicrousdPerMillionTokens, lastReported, lemonUrl, critical, paymentPlan = project.paymentPlan, enableFreetier = envCfg.enableFreetier, basicAuthEnabled = envCfg.basicAuthEnabled, provider, dailyUsage, cycleStart = utctDay cycleStart, cycleEnd, currentInvoice, pastCycles} + addRespHeaders $ BillingGet $ PageCtx bwconf BillingData{pid, totalReqs = totalRequests, totalBytes, aiInputTokens, aiOutputTokens, aiCostMicrousd, aiInputRate = envCfg.aiInputMicrousdPerMillionTokens, aiOutputRate = envCfg.aiOutputMicrousdPerMillionTokens, lastReported, lemonUrl, critical, paymentPlan = project.paymentPlan, enableFreetier = envCfg.enableFreetier, basicAuthEnabled = envCfg.basicAuthEnabled, trialEligible = not billing.hasSubscribedBefore, provider, dailyUsage, cycleStart = utctDay cycleStart, cycleEnd, currentInvoice, pastCycles} where epochDay :: Int -> Day epochDay = utctDay . posixSecondsToUTCTime . fromIntegral @@ -1381,7 +1383,7 @@ billingPage d = div_ [] do span_ [class_ "text-textStrong text-2xl font-semibold"] "Compare Plans" p_ [class_ "mt-2 mb-4"] "Drag the slider to estimate costs at different usage levels." -- Free upgrades use Stripe; billing recovery keeps the existing provider. - paymentPlanPicker d.pid d.lemonUrl d.critical d.paymentPlan d.enableFreetier d.basicAuthEnabled False (bool d.provider Projects.NoBillingProvider isFree) + paymentPlanPicker d.pid d.lemonUrl d.critical d.paymentPlan d.enableFreetier d.basicAuthEnabled d.trialEligible False (bool d.provider Projects.NoBillingProvider isFree) usd :: Double -> Text @@ -1556,8 +1558,11 @@ stripeSessionUrl apiKey endpoint params = do -- `customerM` is the buyer's existing Stripe customer, when they have one. Omitting -- it makes Stripe mint a fresh Customer per session, so one person upgrading a second -- project became a second unrelated customer on the same card. -createStripeCheckoutSession :: W.HTTP :> es => Bool -> Maybe Text -> Text -> Text -> Projects.ProjectId -> Text -> Text -> Text -> Text -> Eff es (Maybe Text) -createStripeCheckoutSession trialEligible customerM apiKey hostUrl pid plan priceIdGraduated priceIdOverage priceIdBYOS = do +-- +-- `debts` are open invoices of the project's lapsed subscription: each becomes a +-- one-time line on the first payment, and 'handleStripeCheckout' marks them paid. +createStripeCheckoutSession :: W.HTTP :> es => Bool -> Maybe Text -> [BJ.StripeInvoice] -> Text -> Text -> Projects.ProjectId -> Text -> Text -> Text -> Text -> Eff es (Maybe Text) +createStripeCheckoutSession trialEligible customerM debts apiKey hostUrl pid plan priceIdGraduated priceIdOverage priceIdBYOS = do let basePrice = case plan of "SystemsPricing" -> priceIdBYOS _ -> priceIdGraduated @@ -1566,12 +1571,25 @@ createStripeCheckoutSession trialEligible customerM apiKey hostUrl pid plan pric , ("line_items[0][quantity]", "1") , ("line_items[1][price]", encodeUtf8 priceIdOverage) ] - trialParams = [("subscription_data[trial_period_days]", "30") | trialEligible && plan /= "SystemsPricing"] + trialParams = [("subscription_data[trial_period_days]", "30") | grantsTrial trialEligible plan] -- Stripe Managed Payments (MoR): Stripe becomes merchant of record and handles -- tax/address collection itself, so the automatic_tax + tax_id params are disallowed. managedPaymentsParams = [("managed_payments[enabled]", "true")] + debtParams = + concat + [ [ (item "[price_data][currency]", encodeUtf8 inv.currency) + , (item "[price_data][unit_amount]", show inv.amountRemaining) + , (item "[price_data][product_data][name]", encodeUtf8 $ "Outstanding balance" <> foldMap (", invoice " <>) inv.number) + , (item "[price_data][product_data][tax_code]", "txcd_10103001") + , (item "[quantity]", "1") + ] + | (i, inv) <- zip [2 :: Int ..] debts + , let item k = "line_items[" <> show i <> "]" <> k + ] + <> [("metadata[settles_invoices]", encodeUtf8 $ T.intercalate "," $ map (.invoiceId) debts) | not (null debts)] params = prices + <> debtParams <> trialParams <> managedPaymentsParams <> [("customer", encodeUtf8 c) | c <- maybeToList customerM] @@ -1604,9 +1622,12 @@ lemonSqueezyOpts apiKey = -- not block the deletion the user asked for, so failures are logged, not thrown. cancelProjectSubscription :: (Log.Log :> es, W.HTTP :> es) => EnvConfig -> Projects.Project -> Eff es () cancelProjectSubscription envConfig project = whenJust target \(opts, url) -> do - res <- trySync $ W.deleteWith opts url - whenLeft_ res \e -> - Log.logAttention "Subscription cancellation failed; subscription may still be billing" (project.id.toText, project.subId, show @Text e) + res <- trySync $ W.deleteWith (opts & Wreq.checkResponse ?~ \_ _ -> pass) url + case (^. Wreq.responseStatus . Wreq.statusCode) <$> res of + -- A sub that already ended (e.g. cancelled by dunning) 404s: nothing left to stop. + Right 404 -> Log.logInfo "Subscription already ended; nothing to cancel" (project.id.toText, project.subId) + Right code | code < 300 -> pass + failure -> Log.logAttention "Subscription cancellation failed; subscription may still be billing" (project.id.toText, project.subId, either (toText . displayException) (("HTTP " <>) . show @Text) failure) where target = do subId <- mfilter (not . T.null) project.subId @@ -1643,10 +1664,9 @@ stripeWebhookPostH sigHeaderM rawBody = do handlers = [ ("checkout.session.completed", handleStripeCheckout envConfig) , ("customer.subscription.deleted", handleStripeDowngrade envConfig "subscription.deleted" "was cancelled") - , ("customer.subscription.updated", handleStripeSubUpdated) - , ("customer.subscription.paused", handleStripeDowngrade envConfig "subscription.paused" "was paused") - , ("customer.subscription.resumed", handleStripeSubResumed envConfig) + , ("customer.subscription.updated", handleStripeSubUpdated envConfig) , ("invoice.payment_failed", handleStripePaymentFailed envConfig) + , ("invoice.paid", handleStripeInvoicePaid envConfig) ] case (,) <$> (eventType >>= flip lookup handlers) <*> sessionObj of Just (handle, obj) -> handle obj @@ -1670,33 +1690,42 @@ handleStripeCheckout envConfig obj = do let pidM = jsonField "client_reference_id" obj :: Maybe Text subIdM = jsonField "subscription" obj :: Maybe Text customerIdM = jsonField "customer" obj :: Maybe Text - planFromMetadata = (jsonField "metadata" obj :: Maybe AE.Value) >>= jsonField "plan" :: Maybe Text + metadata = jsonField "metadata" obj :: Maybe AE.Value + planFromMetadata = metadata >>= jsonField "plan" :: Maybe Text + settledInvoices = maybe [] (T.splitOn ",") (metadata >>= jsonField "settles_invoices") case (pidM >>= Projects.projectIdFromText, subIdM, customerIdM) of (Just pid, Just subId, Just customerId) -> do let plan = fromMaybe "GraduatedPricing" planFromMetadata projectM <- Projects.projectById pid - -- Idempotency: skip if this subscription is already set on the project - if maybe False (\p -> p.subId == Just subId) projectM - then pure "already processed" - else do - -- Cancel whatever subscription the project held before this checkout โ€” a - -- LemonSqueezy one (auto-migration) or an older Stripe one. The idempotency - -- guard above means project.subId is never the sub we just created, and the - -- row is about to be overwritten with the new sub, so anything left running - -- here bills the customer twice with nothing left pointing at it. - whenJust projectM $ cancelProjectSubscription envConfig - subDetails <- BJ.getStripeSubDetails envConfig.stripeSecretKey subId - when (isNothing subDetails) $ Log.logAttention "Stripe sub fetch failed after checkout" (pid.toText, subId) - let subItemId = maybe "" (.subItemId) subDetails - void $ Projects.updateStripeProjectBilling pid (Projects.PlanName plan) (Projects.SubId subId) (Projects.SubItemId subItemId) (Projects.CustomerId customerId) - void $ ProjectMembers.activateAllMembers pid - case subDetails of - Just BJ.StripeSubDetails{trialEnd = Just epoch} -> BJ.scheduleTrialReminders pid epoch - Just BJ.StripeSubDetails{status = "trialing"} -> Log.logAttention "Stripe sub trialing but trial_end missing; no reminders scheduled" (pid.toText, subId) - _ -> pass - whenJust projectM \project -> - Notify.runNotifyProduction $ notifyPlanChange envConfig project (ET.planUpgradedEmail plan) - pure "checkout processed" + -- Idempotency: skip if this subscription is already set on the project. Settling runs + -- on both paths, so a retry after a crash past the sub_id write still settles; it runs + -- after that write so the invoice.paid it triggers no longer matches the project. + res <- + if maybe False (\p -> p.subId == Just subId) projectM + then pure "already processed" + else do + -- Cancel whatever subscription the project held before this checkout โ€” a + -- LemonSqueezy one (auto-migration) or an older Stripe one. The idempotency + -- guard above means project.subId is never the sub we just created, and the + -- row is about to be overwritten with the new sub, so anything left running + -- here bills the customer twice with nothing left pointing at it. + whenJust projectM $ cancelProjectSubscription envConfig + subDetails <- BJ.getStripeSubDetails envConfig.stripeSecretKey subId + when (isNothing subDetails) $ Log.logAttention "Stripe sub fetch failed after checkout" (pid.toText, subId) + let subItemId = maybe "" (.subItemId) subDetails + void $ Projects.updateStripeProjectBilling pid (Projects.PlanName plan) (Projects.SubId subId) (Projects.SubItemId subItemId) (Projects.CustomerId customerId) + void $ ProjectMembers.activateAllMembers pid + case subDetails of + Just BJ.StripeSubDetails{trialEnd = Just epoch} -> BJ.scheduleTrialReminders pid epoch + Just BJ.StripeSubDetails{status = "trialing"} -> Log.logAttention "Stripe sub trialing but trial_end missing; no reminders scheduled" (pid.toText, subId) + _ -> pass + whenJust projectM \project -> + Notify.runNotifyProduction $ notifyPlanChange envConfig project (ET.planUpgradedEmail plan) + pure "checkout processed" + forM_ settledInvoices \invId -> + whenLeftM_ (trySync $ W.postWith (stripeOpts envConfig.stripeSecretKey) ("https://api.stripe.com/v1/invoices/" <> toString invId <> "/pay") ([("paid_out_of_band", "true")] :: [(ByteString, ByteString)])) \e -> + Log.logAttention "Stripe checkout collected an old invoice but marking it paid failed; it may be collected twice" (pid.toText, invId, show @Text e) + pure res _ -> do Log.logAttention "Stripe checkout missing project/sub/customer" (pidM, subIdM, customerIdM) pure "missing fields" @@ -1719,19 +1748,47 @@ handleStripeDowngrade envConfig event reason obj = pure "missing sub id" -handleStripeSubUpdated :: AE.Value -> ATBaseCtx (Html ()) -handleStripeSubUpdated obj = do - let subIdM = jsonField "id" obj :: Maybe Text - newItemIdM = (jsonField "items" obj >>= jsonField "data" :: Maybe [AE.Value]) >>= listToMaybe >>= jsonField "id" :: Maybe Text - case (subIdM, newItemIdM) of - (Just subId, Just newItemId) -> - void $ Projects.updateSubItemIdBySubId newItemId subId - _ -> Log.logAttention "Stripe subscription.updated missing sub_id or item_id" (subIdM, newItemIdM) +-- | Keeps the item id current and mirrors the sub's status onto the plan: dunning that ends at +-- @unpaid@ (or a pause) downgrades, and paying the invoice by any route returns the same sub to +-- @active@, which restores the plan its price maps to. Guarded on the current plan so repeat +-- updates don't re-notify. +handleStripeSubUpdated :: EnvConfig -> AE.Value -> ATBaseCtx (Html ()) +handleStripeSubUpdated envConfig obj = do + let item0 = (jsonField "items" obj >>= jsonField "data" :: Maybe [AE.Value]) >>= listToMaybe + itemIdM = item0 >>= jsonField "id" :: Maybe Text + case (jsonField "id" obj :: Maybe Text, itemIdM) of + (Just subId, Just itemId) -> do + void $ Projects.updateSubItemIdBySubId itemId subId + whenJustM (Projects.projectBySubId subId) \project -> case (jsonField "status" obj :: Maybe Text, Projects.isFreeTier project.paymentPlan) of + (Just "unpaid", False) -> void $ handleStripeDowngrade envConfig "subscription.unpaid" "is unpaid" obj + (Just "paused", False) -> void $ handleStripeDowngrade envConfig "subscription.paused" "was paused" obj + (Just status, True) | status `elem` ["active", "trialing"] -> do + let plan = bool "GraduatedPricing" "SystemsPricing" ((item0 >>= jsonField "price" >>= jsonField "id") == Just envConfig.stripePriceIdByos) + void $ Projects.setPlanBySubId (Projects.PlanName plan) (Projects.SubItemId itemId) (Projects.SubId subId) + Notify.runNotifyProduction $ notifyPlanChange envConfig project (ET.planUpgradedEmail plan) + _ -> pass + ids -> Log.logAttention "Stripe subscription.updated missing sub_id or item_id" ids pure "subscription updated" +-- | A cancelled sub can't be revived, so paying its leftover invoice outside our checkout +-- (hosted link, email, portal) leaves the project on Free: point the payer at checkout. +-- An @unpaid@ sub's revival arrives as customer.subscription.updated instead. +handleStripeInvoicePaid :: EnvConfig -> AE.Value -> ATBaseCtx (Html ()) +handleStripeInvoicePaid envConfig obj = do + let subIdM = (jsonField "parent" obj >>= jsonField "subscription_details" >>= jsonField "subscription") <|> jsonField "subscription" obj :: Maybe Text + whenJust subIdM \subId -> whenJustM (Projects.projectBySubId subId) \project -> + when (Projects.isFreeTier project.paymentPlan) $ BJ.getStripeSubDetails envConfig.stripeSecretKey subId >>= \case + Just BJ.StripeSubDetails{status = "canceled"} -> do + Log.logInfo "Stripe invoice paid on a cancelled subscription; asking the payer to reactivate" (project.id.toText, subId) + Notify.runNotifyProduction $ notifyPlanChange envConfig project ET.invoiceSettledEmail + Just _ -> pass + Nothing -> Log.logAttention "Stripe invoice.paid: sub fetch failed; a lapsed payer may not be told to reactivate" (project.id.toText, subId) + pure "invoice paid handled" + + -- Notification only โ€” Stripe retries payments automatically over its dunning period. --- Downgrade happens via customer.subscription.deleted when Stripe gives up. +-- Downgrade happens when Stripe gives up: subscription.deleted, or .updated to unpaid. handleStripePaymentFailed :: EnvConfig -> AE.Value -> ATBaseCtx (Html ()) handleStripePaymentFailed envConfig obj = do let attemptCount = jsonField "attempt_count" obj :: Maybe Int @@ -1741,31 +1798,3 @@ handleStripePaymentFailed envConfig obj = do Log.logAttention "Stripe invoice.payment_failed" (project.id, attemptCount, nextAttempt) Notify.runNotifyProduction $ notifyPlanChange envConfig project ET.paymentFailedEmail pure "payment failed handled" - - --- Look up the sub's price via the Stripe API, reverse-map to our plan name, and re-upgrade. --- (Pause preserved the IDs, so resume never needs a re-checkout.) -handleStripeSubResumed :: EnvConfig -> AE.Value -> ATBaseCtx (Html ()) -handleStripeSubResumed envConfig obj = - case jsonField "id" obj :: Maybe Text of - Just subId -> do - subDetailsM <- BJ.getStripeSubDetails envConfig.stripeSecretKey subId - case subDetailsM of - -- the price id reverse-maps to our internal plan name - Just BJ.StripeSubDetails{subItemId = itemId, priceId} -> do - let plan - | priceId == envConfig.stripePriceIdByos = "SystemsPricing" - | otherwise = "GraduatedPricing" - rows <- Projects.setPlanBySubId (Projects.PlanName plan) (Projects.SubItemId itemId) (Projects.SubId subId) - when (rows == 0) $ Log.logAttention "Stripe subscription.resumed: no project for sub_id" (subId, plan) - when (rows > 1) $ Log.logAttention "Stripe subscription.resumed touched multiple rows" (subId, rows) - when (rows > 0) - $ whenJustM (Projects.projectBySubId subId) \project -> - Notify.runNotifyProduction $ notifyPlanChange envConfig project (ET.planUpgradedEmail plan) - pure "subscription resumed" - Nothing -> do - Log.logAttention "Stripe subscription.resumed: could not fetch sub items" subId - pure "missing items" - Nothing -> do - Log.logAttention "Stripe subscription.resumed: missing sub id" () - pure "missing sub id" diff --git a/src/Pkg/EmailTemplates.hs b/src/Pkg/EmailTemplates.hs index 21fc63209..c2be85697 100644 --- a/src/Pkg/EmailTemplates.hs +++ b/src/Pkg/EmailTemplates.hs @@ -33,6 +33,7 @@ module Pkg.EmailTemplates ( freeTierUsageEmail, planUpgradedEmail, planDowngradedEmail, + invoiceSettledEmail, paymentFailedEmail, trialEndingEmail, @@ -1249,6 +1250,21 @@ planDowngradedEmail reason projectName = "Upgrade Plan" +-- | A cancelled subscription's leftover invoice was paid outside checkout: the money is in, but +-- nothing reactivated, since a cancelled subscription can't be revived. +invoiceSettledEmail :: Text -> Text -> (Text, Html ()) +invoiceSettledEmail projectName = + ctaEmail + ("[ยทยทยท] Payment received - " <> projectName) + True + ( do + h1_ "Payment Received" + richP_ ["Thanks, your outstanding invoice for ", projectName, " is paid. The subscription it belonged to had already ended, so the project is still on the Free plan."] + p_ "Reactivate from the billing page to restore full access." + ) + "Reactivate Subscription" + + -- | Provider dunning is still retrying, so nothing has changed yet; the downgrade only follows -- if every retry fails. paymentFailedEmail :: Text -> Text -> (Text, Html ()) diff --git a/test/integration/Pages/BusinessFlowsSpec.hs b/test/integration/Pages/BusinessFlowsSpec.hs index 37b698fe2..c52dc8740 100644 --- a/test/integration/Pages/BusinessFlowsSpec.hs +++ b/test/integration/Pages/BusinessFlowsSpec.hs @@ -7,8 +7,9 @@ import Data.ByteArray qualified as BA import Data.ByteString.Base16 qualified as B16 import Data.ByteString.Lazy qualified as BL import Data.Default (def) +import Data.List (lookup) import Data.Effectful.Hasql qualified as Hasql -import Data.Effectful.Wreq (HTTP) +import Data.Effectful.Wreq (HTTP, Options) import Data.Pool (Pool, withResource) import Data.Text qualified as T import Data.Text.Lazy qualified as TL @@ -27,8 +28,10 @@ import Hasql.Interpolate qualified as HI import Lucid (renderText, toHtml) import Models.Apis.Issues qualified as Issues import Models.Projects.Projects qualified as Projects +import Network.HTTP.Types.URI (parseSimpleQuery) import OpenTelemetry.Instrumentation.Hasql qualified as OHasql import Pages.BodyWrapper (PageCtx (..)) +import Pages.Bots.BotTestHelpers (withHTTPResponses) import Pages.Dashboards qualified as Dashboards import Pages.LogExplorer.Log qualified as Log import Pages.Monitors qualified as Monitors @@ -314,6 +317,8 @@ settingsTests = do html `shouldSatisfy` TL.isInfixOf "id=\"billing-downgrade-banner\"" html `shouldSatisfy` TL.isInfixOf "Your paid subscription is no longer active. This project has been downgraded to Free." html `shouldSatisfy` TL.isInfixOf ("href=\"/p/" <> toLazy testPid.toText <> "/manage_billing\"") + -- A cancelled Stripe sub can't be revived from the portal, only by a new checkout. + html `shouldSatisfy` TL.isInfixOf (bool "Update payment method" "Reactivate subscription" (provider == Projects.StripeProvider)) session <- refreshSession tr.trPool tr.trATCtx.hasqlPool tr.trSessAndHeader (_, billing) <- testServant tr{trSessAndHeader = session} $ Settings.manageBillingGetH testPid renderText (toHtml billing) `shouldSatisfy` TL.isInfixOf ("hx-get=\"/p/" <> toLazy testPid.toText <> "/manage_subscription\"") @@ -517,7 +522,9 @@ stripeBillingTests = do let checkout = runAsBaseRecordingHTTP tr . atAuthToBase tr.trSessAndHeader . flip CreateProject.stripeCheckoutInitH (CreateProject.StripeCheckoutForm "GraduatedPricing") sessionBody reqs = snd <$> find ((== "https://api.stripe.com/v1/checkout/sessions") . fst) reqs - -- First ever upgrade: no customer to reuse, trial granted. + -- First ever upgrade: no customer to reuse, trial granted, and the plan button says so. + (_, LemonSqueezy.BillingGet (PageCtx _ fresh)) <- testServant tr $ LemonSqueezy.manageBillingGetH testPid + renderText (LemonSqueezy.billingPage fresh) `shouldSatisfy` TL.isInfixOf "Start 30 day free trial" (firstReqs, _) <- checkout testPid case sessionBody firstReqs of Nothing -> fail "no checkout session request recorded" @@ -540,28 +547,74 @@ stripeBillingTests = do -- that the cancel reads the OLD sub_id, i.e. that it stays ahead of the write. it "stripe checkout webhook cancels the subscription the project held before" \TestContext{tcResources = tr, tcProjectId = testPid} -> do _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "sub_old") (Projects.SubItemId "si_old") (Projects.CustomerId "cus_test") - now <- getTestTime tr.trTestClock - let body = - BL.toStrict - $ AE.encode - $ AE.object - [ "type" AE..= ("checkout.session.completed" :: Text) - , "data" - AE..= AE.object - [ "object" - AE..= AE.object - [ "client_reference_id" AE..= testPid.toText - , "subscription" AE..= ("sub_new" :: Text) - , "customer" AE..= ("cus_test" :: Text) - ] - ] - ] - ts = show @Text @Integer $ round $ utcTimeToPOSIXSeconds now - mac = HMAC.hmac (encodeUtf8 @Text @ByteString tr.trATCtx.env.stripeWebhookSecret) (encodeUtf8 @Text @ByteString ts <> "." <> body) :: HMAC.HMAC SHA256 - sigHeader = "t=" <> ts <> ",v1=" <> decodeUtf8 (B16.encode $ BA.convert mac) - (reqs, _) <- runAsBaseRecordingHTTP tr $ LemonSqueezy.stripeWebhookPostH (Just sigHeader) body + reqs <- stripeCheckoutCompleted tr testPid [] map fst reqs `shouldContain` ["https://api.stripe.com/v1/subscriptions/sub_old"] + -- Stripe cancels a subscription whose payments keep failing, and a cancelled one can't + -- be revived. Paying the leftover invoice in the portal left the project on Free, so + -- reactivating is one Managed Payments checkout that also carries that invoice + -- (Shipbubble, 2026-10-23: $68.37 open on a sub cancelled 2026-09-29). + it "stripeReactivation_lapsedSubscription_settlesOpenInvoiceAndUpgrades" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "sub_lapsed") (Projects.SubItemId "si_lapsed") (Projects.CustomerId "cus_lapsed") + _ <- runQueryEffect tr $ Projects.downgradeToFreeBySubId "sub_lapsed" + session <- refreshSession tr.trPool tr.trATCtx.hasqlPool tr.trSessAndHeader + -- Checkout withholds a repeat trial, so the button must not promise one. + (_, LemonSqueezy.BillingGet (PageCtx _ lapsed)) <- testServant tr{trSessAndHeader = session} $ LemonSqueezy.manageBillingGetH testPid + renderText (LemonSqueezy.billingPage lapsed) `shouldNotSatisfy` TL.isInfixOf "free trial" + let invoices = AE.encode $ AE.object ["data" AE..= ([invoice "in_owed" "open" 6837, invoice "in_settled" "paid" 0] :: [AE.Value])] + invoice id' status remaining = AE.object ["id" AE..= (id' :: Text), "currency" AE..= ("usd" :: Text), "status" AE..= (status :: Text), "number" AE..= ("MONO-0003" :: Text), "total" AE..= (6837 :: Int), "amount_remaining" AE..= (remaining :: Int), "period_start" AE..= (1786787328 :: Int), "period_end" AE..= (1789465728 :: Int)] + lapsedInvoices _ url = pure $ invoices <$ guard (url == "https://api.stripe.com/v1/invoices?limit=12&subscription=sub_lapsed") + (reqs, _) <- runAsBaseRecordingHTTP tr $ withHTTPResponses lapsedInvoices $ atAuthToBase session $ CreateProject.stripeCheckoutInitH testPid (CreateProject.StripeCheckoutForm "GraduatedPricing") + form <- maybe (fail "no checkout session request recorded") (pure . parseSimpleQuery . toStrict) $ snd <$> find ((== "https://api.stripe.com/v1/checkout/sessions") . fst) reqs + map (`lookup` form) ["line_items[2][price_data][unit_amount]", "line_items[3][price_data][unit_amount]", "metadata[settles_invoices]", "managed_payments[enabled]"] + `shouldBe` ([Just "6837", Nothing, Just "in_owed", Just "true"] :: [Maybe ByteString]) + + paid <- stripeCheckoutCompleted tr testPid [("settles_invoices", "in_owed")] + lookup "https://api.stripe.com/v1/invoices/in_owed/pay" paid `shouldBe` Just "paid_out_of_band=true" + fmap (.paymentPlan) <$> runQueryEffect tr (Projects.projectById testPid) `shouldReturn` Just "GraduatedPricing" + + -- Dunning that ends at `unpaid` keeps the subscription: paying its invoice by any route + -- (hosted link, email, portal) makes Stripe flip it back to `active`, and only + -- customer.subscription.updated says so โ€” the project must follow both ways. + it "stripeDunning_unpaidThenPaidAnywhere_followsSubscriptionStatus" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "sub_dun") (Projects.SubItemId "si_dun") (Projects.CustomerId "cus_dun") + let plan = fmap (.paymentPlan) <$> runQueryEffect tr (Projects.projectById testPid) + sub status = AE.object ["id" AE..= ("sub_dun" :: Text), "status" AE..= (status :: Text), "items" AE..= AE.object ["data" AE..= ([AE.object ["id" AE..= ("si_dun" :: Text), "price" AE..= AE.object ["id" AE..= ("price_graduated" :: Text)]]] :: [AE.Value])]] + _ <- stripeWebhook tr (\_ _ -> pure Nothing) "customer.subscription.updated" (sub "unpaid") + plan `shouldReturn` Just "Free" + _ <- stripeWebhook tr (\_ _ -> pure Nothing) "customer.subscription.updated" (sub "active") + plan `shouldReturn` Just "GraduatedPricing" + + -- A sub Stripe already cancelled can't come back, so paying its leftover invoice outside + -- our checkout must not pretend to reactivate; the payer is pointed back at checkout. + it "stripeInvoicePaid_cancelledSubscription_staysFree" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "sub_gone") (Projects.SubItemId "si_gone") (Projects.CustomerId "cus_gone") + _ <- runQueryEffect tr $ Projects.downgradeToFreeBySubId "sub_gone" + let cancelled _ url = pure $ AE.encode (AE.object ["status" AE..= ("canceled" :: Text), "items" AE..= AE.object ["data" AE..= ([AE.object ["id" AE..= ("si_gone" :: Text), "price" AE..= AE.object ["id" AE..= ("price_graduated" :: Text)]]] :: [AE.Value])]]) <$ guard (url == "https://api.stripe.com/v1/subscriptions/sub_gone") + reqs <- stripeWebhook tr cancelled "invoice.paid" $ AE.object ["id" AE..= ("in_gone" :: Text), "customer" AE..= ("cus_gone" :: Text), "parent" AE..= AE.object ["subscription_details" AE..= AE.object ["subscription" AE..= ("sub_gone" :: Text)]]] + map fst reqs `shouldContain` ["https://api.stripe.com/v1/subscriptions/sub_gone"] + fmap (.paymentPlan) <$> runQueryEffect tr (Projects.projectById testPid) `shouldReturn` Just "Free" + + +-- | Deliver a signed checkout.session.completed for @pid@ (new sub @sub_new@) carrying +-- the given session metadata; returns the outgoing Stripe requests. +stripeCheckoutCompleted :: TestResources -> Projects.ProjectId -> [(AE.Key, Text)] -> IO [(Text, LByteString)] +stripeCheckoutCompleted tr pid metadata = + stripeWebhook tr (\_ _ -> pure Nothing) "checkout.session.completed" + $ AE.object ["client_reference_id" AE..= pid.toText, "subscription" AE..= ("sub_new" :: Text), "customer" AE..= ("cus_test" :: Text), "metadata" AE..= AE.object (map (fmap AE.toJSON) metadata)] + + +-- | Deliver a signed Stripe event of @eventType@ wrapping @obj@, answering Stripe calls from +-- @responses@; returns the outgoing Stripe requests. +stripeWebhook :: TestResources -> (Options -> String -> IO (Maybe LByteString)) -> Text -> AE.Value -> IO [(Text, LByteString)] +stripeWebhook tr responses eventType obj = do + now <- getTestTime tr.trTestClock + let body = BL.toStrict $ AE.encode $ AE.object ["type" AE..= eventType, "data" AE..= AE.object ["object" AE..= obj]] + ts = show @Text @Integer $ round $ utcTimeToPOSIXSeconds now + mac = HMAC.hmac (encodeUtf8 @Text @ByteString tr.trATCtx.env.stripeWebhookSecret) (encodeUtf8 @Text @ByteString ts <> "." <> body) :: HMAC.HMAC SHA256 + sigHeader = "t=" <> ts <> ",v1=" <> decodeUtf8 (B16.encode $ BA.convert mac) + fst <$> runAsBaseRecordingHTTP tr (withHTTPResponses responses $ LemonSqueezy.stripeWebhookPostH (Just sigHeader) body) + -- | LemonSqueezy Webhook Tests - Table-driven testing for all webhook events lemonSqueezyWebhookTests :: SpecWith TestContext diff --git a/tests/golden/https___api.stripe.com_v1_invoices_limit=12_subscription=sub_test123_get_with.json b/tests/golden/https___api.stripe.com_v1_invoices_limit=12_subscription=sub_test123_get_with.json index 87858fe59..b95d9c37b 100644 --- a/tests/golden/https___api.stripe.com_v1_invoices_limit=12_subscription=sub_test123_get_with.json +++ b/tests/golden/https___api.stripe.com_v1_invoices_limit=12_subscription=sub_test123_get_with.json @@ -1,7 +1,7 @@ { "statusCode": 200, "statusMessage": "OK", - "respBody": "{\"object\": \"list\", \"data\": [{\"object\": \"invoice\", \"number\": null, \"status\": \"draft\", \"total\": 4150, \"amount_paid\": 0, \"period_start\": 1710498600, \"period_end\": 1713177000, \"hosted_invoice_url\": null, \"lines\": {\"data\": [{\"description\": \"1 x Graduated\", \"period\": {\"start\": 1710498600, \"end\": 1713177000}}]}}, {\"object\": \"invoice\", \"number\": \"MONO-0002\", \"status\": \"paid\", \"total\": 3400, \"amount_paid\": 3400, \"period_start\": 1707993000, \"period_end\": 1710498600, \"hosted_invoice_url\": \"https://invoice.stripe.com/i/inv_two\", \"lines\": {\"data\": [{\"description\": \"1 x Graduated\", \"period\": {\"start\": 1707993000, \"end\": 1710498600}}]}}, {\"object\": \"invoice\", \"number\": \"MONO-0001\", \"status\": \"paid\", \"total\": 2900, \"amount_paid\": 2900, \"period_start\": 1705314600, \"period_end\": 1707993000, \"hosted_invoice_url\": \"https://invoice.stripe.com/i/inv_one\", \"lines\": {\"data\": [{\"description\": \"1 x Graduated\", \"period\": {\"start\": 1705314600, \"end\": 1707993000}}]}}, {\"object\": \"invoice\", \"number\": \"MONO-0000\", \"status\": \"paid\", \"total\": 0, \"amount_paid\": 0, \"period_start\": 1705314600, \"period_end\": 1705314600, \"hosted_invoice_url\": \"https://invoice.stripe.com/i/inv_zero\", \"lines\": {\"data\": [{\"description\": \"Trial start\", \"period\": {\"start\": 1705314600, \"end\": 1705314600}}]}}]}", + "respBody": "{\"object\": \"list\", \"data\": [{\"object\": \"invoice\", \"currency\": \"usd\", \"id\": \"in_draft\", \"number\": null, \"status\": \"draft\", \"total\": 4150, \"amount_paid\": 0, \"period_start\": 1710498600, \"period_end\": 1713177000, \"hosted_invoice_url\": null, \"lines\": {\"data\": [{\"description\": \"1 x Graduated\", \"period\": {\"start\": 1710498600, \"end\": 1713177000}}]}}, {\"object\": \"invoice\", \"currency\": \"usd\", \"number\": \"MONO-0002\", \"status\": \"paid\", \"total\": 3400, \"amount_paid\": 3400, \"period_start\": 1707993000, \"period_end\": 1710498600, \"id\": \"in_two\", \"hosted_invoice_url\": \"https://invoice.stripe.com/i/inv_two\", \"lines\": {\"data\": [{\"description\": \"1 x Graduated\", \"period\": {\"start\": 1707993000, \"end\": 1710498600}}]}}, {\"object\": \"invoice\", \"currency\": \"usd\", \"number\": \"MONO-0001\", \"status\": \"paid\", \"total\": 2900, \"amount_paid\": 2900, \"period_start\": 1705314600, \"period_end\": 1707993000, \"id\": \"in_one\", \"hosted_invoice_url\": \"https://invoice.stripe.com/i/inv_one\", \"lines\": {\"data\": [{\"description\": \"1 x Graduated\", \"period\": {\"start\": 1705314600, \"end\": 1707993000}}]}}, {\"object\": \"invoice\", \"currency\": \"usd\", \"number\": \"MONO-0000\", \"status\": \"paid\", \"total\": 0, \"amount_paid\": 0, \"period_start\": 1705314600, \"period_end\": 1705314600, \"id\": \"in_zero\", \"hosted_invoice_url\": \"https://invoice.stripe.com/i/inv_zero\", \"lines\": {\"data\": [{\"description\": \"Trial start\", \"period\": {\"start\": 1705314600, \"end\": 1705314600}}]}}]}", "responseHeaders": [ [ "Content-Type",