{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "cancel-flow",
  "title": "Cancel flow",
  "author": "PumpGTM (https://pumpgtm.com)",
  "description": "An in-app Stripe cancel dialog: a reason with one follow-up question, then a full refund if they were charged in the last 24 hours, or one save offer picked from the reason (more trial days, a pause, a discount, a free month, or this month forgiven when a payment failed), then a real cancellation. Past-due cancels void what is owed. Records everything on Stripe, so there is no table to add.",
  "dependencies": [
    "stripe",
    "server-only"
  ],
  "registryDependencies": [
    "button",
    "dialog",
    "input",
    "label",
    "radio-group",
    "textarea",
    "@gtm/subscription-state"
  ],
  "files": [
    {
      "path": "registry/pumpgtm/cancel-flow/cancel-flow.tsx",
      "content": "\"use client\";\n\nimport { useState, useTransition, type ReactNode } from \"react\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n} from \"@/components/ui/dialog\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { RadioGroup, RadioGroupItem } from \"@/components/ui/radio-group\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport type { SubscriptionState } from \"@/lib/subscription-state\";\nimport {\n  FOLLOW_UP_QUESTIONS,\n  PAID_REASONS,\n  TRIAL_REASONS,\n  describeOffer,\n  pickOffer,\n  type CancelReason,\n  type OfferPolicy,\n  type SaveOffer,\n} from \"@/lib/cancel-offer\";\nimport type { CancelRequest, CancelResult, RefundableCharge } from \"@/lib/cancel-subscription\";\n\n// Reason, then one next step, then the cancellation. Within a day of a charge\n// the next step is the money back; otherwise it is at most one save offer,\n// with the same moves in the same order: talk to a person, take the offer, or\n// cancel. \"No thanks, cancel\" is always visible and never a trick.\n\nexport interface CancelFlowProps {\n  state: SubscriptionState;\n  // True once this customer has accepted a save offer: `await offerUsed(stripe, customerId)`.\n  offerUsed: boolean;\n  // A charge recent enough to give back: `await refundableCharge(stripe, subscriptionId)`.\n  refund?: RefundableCharge | null;\n  // Your server action: authenticate, look up the user's subscription id, then\n  // return `cancelSubscription(stripe, subscriptionId, request)`.\n  action: (request: CancelRequest) => Promise<CancelResult>;\n  policy?: OfferPolicy;\n  // A booking link for a call with a real person, offered first.\n  bookingUrl?: string;\n  // Shown above the offer, for example a short founder video.\n  media?: ReactNode;\n  triggerLabel?: string;\n  onDone?: (result: CancelResult) => void;\n}\n\nexport function CancelFlow({\n  state,\n  offerUsed,\n  refund = null,\n  action,\n  policy,\n  bookingUrl,\n  media,\n  triggerLabel,\n  onDone,\n}: CancelFlowProps) {\n  const isTrial = state === \"trialing\";\n  const noun = isTrial ? \"trial\" : \"subscription\";\n  const reasons: Record<string, string> = isTrial ? TRIAL_REASONS : PAID_REASONS;\n  const [open, setOpen] = useState(false);\n  const [step, setStep] = useState<\"reason\" | \"refund\" | \"offer\" | \"done\">(\"reason\");\n  const [reason, setReason] = useState<CancelReason | null>(null);\n  const [followUp, setFollowUp] = useState(\"\");\n  const [comment, setComment] = useState(\"\");\n  const [result, setResult] = useState<CancelResult | null>(null);\n  const [error, setError] = useState<string | null>(null);\n  const [pending, startTransition] = useTransition();\n  const offer = reason ? pickOffer({ state, reason, offerUsed, policy }) : null;\n  const followUpQuestion = reason ? FOLLOW_UP_QUESTIONS[reason] : undefined;\n  // Whether another step follows, known before a reason is picked so the\n  // button does not change its label under the customer's cursor.\n  const nextStep = refund\n    ? \"refund\"\n    : pickOffer({ state, reason: reason ?? \"other\", offerUsed, policy })\n      ? \"offer\"\n      : null;\n\n  function openChange(next: boolean) {\n    setOpen(next);\n    if (next) return;\n    if (result) onDone?.(result);\n    setStep(\"reason\");\n    setReason(null);\n    setFollowUp(\"\");\n    setComment(\"\");\n    setResult(null);\n    setError(null);\n  }\n\n  function submit(decision: CancelRequest[\"decision\"]) {\n    if (!reason) return;\n    setError(null);\n    startTransition(async () => {\n      try {\n        const next = await action({\n          reason,\n          followUp: followUpQuestion ? followUp : null,\n          comment,\n          decision,\n        });\n        if (next.outcome === \"invalid\") {\n          setError(\n            next.error === \"refund_unavailable\"\n              ? \"That charge can no longer be refunded here. You can still cancel.\"\n              : \"This subscription can't be changed right now. Refresh the page and try again.\",\n          );\n          return;\n        }\n        setResult(next);\n        setStep(\"done\");\n      } catch {\n        setError(\"Something went wrong and nothing was changed. Please try again.\");\n      }\n    });\n  }\n\n  const cancelLink = (label: string) => (\n    <Button variant=\"ghost\" disabled={pending} onClick={() => submit(\"cancel\")}>\n      {label}\n    </Button>\n  );\n  const back = (\n    <Button variant=\"ghost\" disabled={pending} onClick={() => setStep(\"reason\")}>\n      Back\n    </Button>\n  );\n\n  return (\n    // No asChild or render props anywhere, so the same file works with the\n    // Radix and the Base UI flavours of the shadcn primitives.\n    <Dialog open={open} onOpenChange={openChange}>\n      <Button variant=\"outline\" onClick={() => setOpen(true)}>\n        {triggerLabel ?? `Cancel ${noun}`}\n      </Button>\n      <DialogContent className=\"sm:max-w-lg\">\n        {step === \"reason\" && (\n          <>\n            <DialogHeader>\n              <DialogTitle>Before you go, what&apos;s the main reason?</DialogTitle>\n              <DialogDescription>One answer is enough.</DialogDescription>\n            </DialogHeader>\n            <RadioGroup\n              value={reason ?? \"\"}\n              onValueChange={(value: unknown) => setReason(value as CancelReason)}\n              className=\"grid gap-2 sm:grid-cols-2\"\n            >\n              {Object.entries(reasons).map(([value, label]) => (\n                <Label\n                  key={value}\n                  htmlFor={`cancel-reason-${value}`}\n                  className=\"flex cursor-pointer items-center gap-2.5 rounded-md border px-3 py-2.5 font-normal has-[[aria-checked=true]]:border-primary has-[[aria-checked=true]]:bg-accent\"\n                >\n                  <RadioGroupItem id={`cancel-reason-${value}`} value={value} />\n                  {label}\n                </Label>\n              ))}\n            </RadioGroup>\n            {followUpQuestion && (\n              <div className=\"grid gap-1.5\">\n                <Label htmlFor=\"cancel-follow-up\" className=\"text-muted-foreground font-normal\">\n                  {followUpQuestion} (optional)\n                </Label>\n                <Input\n                  id=\"cancel-follow-up\"\n                  maxLength={200}\n                  value={followUp}\n                  onChange={(event) => setFollowUp(event.target.value)}\n                />\n              </div>\n            )}\n            <div className=\"grid gap-1.5\">\n              <Label htmlFor=\"cancel-comment\" className=\"text-muted-foreground font-normal\">\n                What would have changed your mind? (optional)\n              </Label>\n              <Textarea\n                id=\"cancel-comment\"\n                maxLength={500}\n                rows={3}\n                value={comment}\n                onChange={(event) => setComment(event.target.value)}\n              />\n            </div>\n            {error && <p className=\"text-destructive text-sm\">{error}</p>}\n            <DialogFooter className=\"sm:justify-between\">\n              <Button variant=\"ghost\" onClick={() => openChange(false)}>\n                Keep my {noun}\n              </Button>\n              {nextStep ? (\n                <Button disabled={!reason} onClick={() => setStep(nextStep)}>\n                  Continue\n                </Button>\n              ) : (\n                <Button\n                  variant=\"destructive\"\n                  disabled={!reason || pending}\n                  onClick={() => submit(\"cancel\")}\n                >\n                  Cancel my {noun}\n                </Button>\n              )}\n            </DialogFooter>\n          </>\n        )}\n\n        {step === \"refund\" && refund && (\n          <>\n            <DialogHeader>\n              <DialogTitle>No problem, have it back</DialogTitle>\n              <DialogDescription>\n                You were charged {formatMoney(refund.amountCents, refund.currency)}{\" \"}\n                {hoursAgo(refund.paidAt)}. Take a full refund now and your {noun} ends\n                today.\n              </DialogDescription>\n            </DialogHeader>\n            <Button disabled={pending} onClick={() => submit(\"refund\")}>\n              Refund {formatMoney(refund.amountCents, refund.currency)} and cancel\n            </Button>\n            {error && <p className=\"text-destructive text-sm\">{error}</p>}\n            <DialogFooter className=\"sm:justify-between\">\n              {cancelLink(\"Keep access until the period ends instead\")}\n              {back}\n            </DialogFooter>\n          </>\n        )}\n\n        {step === \"offer\" && offer && (\n          <>\n            <DialogHeader>\n              <DialogTitle>{bookingUrl ? \"Can we talk first?\" : \"Before you cancel\"}</DialogTitle>\n              <DialogDescription>{offerPitch(offer, Boolean(bookingUrl))}</DialogDescription>\n            </DialogHeader>\n            {media}\n            <div className=\"flex flex-col gap-2 sm:flex-row\">\n              {bookingUrl && (\n                <a href={bookingUrl} target=\"_blank\" rel=\"noreferrer\" className={buttonVariants()}>\n                  Book a call\n                </a>\n              )}\n              <Button\n                variant={bookingUrl ? \"outline\" : \"default\"}\n                disabled={pending}\n                onClick={() => submit(\"accept_offer\")}\n              >\n                {describeOffer(offer)}\n              </Button>\n            </div>\n            {error && <p className=\"text-destructive text-sm\">{error}</p>}\n            <DialogFooter className=\"sm:justify-between\">\n              {cancelLink(`No thanks, cancel my ${noun}`)}\n              {back}\n            </DialogFooter>\n          </>\n        )}\n\n        {step === \"done\" && result && (\n          <>\n            <DialogHeader>\n              <DialogTitle>{doneTitle(result, noun)}</DialogTitle>\n              <DialogDescription>{doneMessage(result, noun)}</DialogDescription>\n            </DialogHeader>\n            <DialogFooter>\n              <Button onClick={() => openChange(false)}>Close</Button>\n            </DialogFooter>\n          </>\n        )}\n      </DialogContent>\n    </Dialog>\n  );\n}\n\nfunction formatMoney(cents: number, currency: string): string {\n  return new Intl.NumberFormat(undefined, { style: \"currency\", currency }).format(cents / 100);\n}\n\nfunction hoursAgo(paidAt: Date): string {\n  const hours = Math.floor((Date.now() - new Date(paidAt).getTime()) / 3_600_000);\n  return hours < 1 ? \"less than an hour ago\" : hours === 1 ? \"an hour ago\" : `${hours} hours ago`;\n}\n\nfunction offerPitch(offer: SaveOffer, canCall: boolean): string {\n  const call = canCall ? \"A short call is the fastest way to fix what went wrong. Or: \" : \"\";\n  switch (offer.kind) {\n    case \"extend_trial\":\n      return `${call}take ${offer.days} more days, free. A short trial is rarely long enough to judge it.`;\n    case \"pause\":\n      return `${call}pause billing for ${offer.months === 1 ? \"a month\" : `${offer.months} months`}. Your account stays exactly as it is and picks up again on its own.`;\n    case \"waive_invoice\":\n      return `${call}keep your account and skip this month's payment, on us.`;\n    case \"discount\":\n      return offer.percentOff === 100\n        ? `${call}take your next ${offer.months === 1 ? \"month\" : `${offer.months} months`} free, on us.`\n        : `${call}take ${offer.percentOff}% off your next ${offer.months} months.`;\n  }\n}\n\nfunction doneTitle(result: CancelResult, noun: string): string {\n  if (result.outcome === \"saved\") return \"Done, thank you for staying\";\n  if (result.outcome === \"refunded\") return \"Refunded and cancelled\";\n  return `Your ${noun} is cancelled`;\n}\n\nfunction doneMessage(result: CancelResult, noun: string): string {\n  if (result.outcome === \"saved\") {\n    if (result.offer.kind === \"pause\") return \"Billing is paused. Nothing else changes.\";\n    if (result.offer.kind === \"waive_invoice\") return \"This month's payment is cancelled. Nothing else changes.\";\n    return \"The offer is applied to your account.\";\n  }\n  if (result.outcome === \"refunded\") {\n    return `${formatMoney(result.amountCents, result.currency)} is on its way back. It usually reaches your card in 5 to 10 days.`;\n  }\n  if (result.outcome === \"cancelled\" && result.accessEndsAt) {\n    const endsAt = new Date(result.accessEndsAt);\n    const date = endsAt.toLocaleDateString(undefined, { month: \"long\", day: \"numeric\", year: \"numeric\" });\n    return endsAt.getTime() <= Date.now() + 60_000\n      ? `Your ${noun} has ended. You won't be charged again.`\n      : `You keep full access until ${date}. You won't be charged again.`;\n  }\n  return \"You won't be charged again.\";\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/pumpgtm/cancel-flow/cancel-offer.ts",
      "content": "import type { SubscriptionState } from \"@/lib/subscription-state\";\n\n// Which save offer a cancelling customer sees. Pure, so the page that renders\n// the dialog and the server action that applies the decision pick the same\n// offer from the same facts. The server always re-picks; the browser never\n// tells it which offer was shown.\n//\n// One offer per customer, ever: a restarted subscription does not earn another.\n// A trial is offered time, never money: a discount on a product someone has not\n// used yet saves nobody. A paying customer is offered what their reason asks\n// for. A customer whose renewal already failed gets that month forgiven: a\n// coupon only discounts next month and would leave this one owed.\n\nexport const TRIAL_REASONS = {\n  setup: \"Couldn't get it set up\",\n  no_time: \"Haven't had time to try it properly\",\n  no_results_yet: \"Didn't see results yet\",\n  too_expensive: \"Too expensive for me right now\",\n  not_expected: \"Not what I expected\",\n  switched: \"Switching to another tool\",\n  other: \"Something else\",\n} as const;\n\nexport const PAID_REASONS = {\n  no_results: \"Not getting enough value\",\n  too_expensive: \"Too expensive\",\n  pausing: \"Pausing for now\",\n  switched: \"Switching to another tool\",\n  missing_feature: \"Missing a feature I need\",\n  hard_to_use: \"Hard to set up or use\",\n  other: \"Something else\",\n} as const;\n\nexport type CancelReason = keyof typeof TRIAL_REASONS | keyof typeof PAID_REASONS;\n\n// The one follow-up question, asked only after these reasons. The answer is\n// stored with the cancellation so you learn the price, the competitor or the\n// missing feature, not just the category.\nexport const FOLLOW_UP_QUESTIONS: Partial<Record<CancelReason, string>> = {\n  too_expensive: \"What would you pay per month?\",\n  switched: \"Which tool are you switching to?\",\n  missing_feature: \"Which feature do you need?\",\n};\n\nexport type SaveOffer =\n  | { kind: \"extend_trial\"; days: number }\n  | { kind: \"discount\"; percentOff: number; months: number }\n  | { kind: \"pause\"; months: number }\n  | { kind: \"waive_invoice\" };\n\nexport interface OfferPolicy {\n  trialExtensionDays: number;\n  // A trial can never run longer than this many days in total, extensions included.\n  maxTrialDays: number;\n  discount: { percentOff: number; months: number };\n  pauseMonths: number;\n  // Cancelling within this many hours of a charge offers it back in full.\n  refundWindowHours: number;\n}\n\nexport const DEFAULT_OFFER_POLICY: OfferPolicy = {\n  trialExtensionDays: 7,\n  maxTrialDays: 14,\n  discount: { percentOff: 50, months: 2 },\n  pauseMonths: 1,\n  refundWindowHours: 24,\n};\n\nexport function isCancelReason(state: SubscriptionState, value: unknown): value is CancelReason {\n  const reasons = state === \"trialing\" ? TRIAL_REASONS : PAID_REASONS;\n  return typeof value === \"string\" && Object.hasOwn(reasons, value);\n}\n\nexport function pickOffer(input: {\n  state: SubscriptionState;\n  reason: CancelReason;\n  // True once this customer has accepted any save offer, on any subscription.\n  offerUsed: boolean;\n  policy?: OfferPolicy;\n}): SaveOffer | null {\n  const policy = input.policy ?? DEFAULT_OFFER_POLICY;\n  if (input.offerUsed) return null;\n  if (input.state === \"trialing\") {\n    return { kind: \"extend_trial\", days: policy.trialExtensionDays };\n  }\n  if (input.state === \"past_due\") return { kind: \"waive_invoice\" };\n  if (input.state !== \"active\") return null;\n  if (input.reason === \"pausing\") return { kind: \"pause\", months: policy.pauseMonths };\n  if (input.reason === \"too_expensive\") return { kind: \"discount\", ...policy.discount };\n  // Everything else gets a free month: the time to fix what went wrong.\n  return { kind: \"discount\", percentOff: 100, months: 1 };\n}\n\n// Adds the days to whatever is left of the trial, but never past the total cap\n// counted from the trial's start.\nexport function extendedTrialEnd(\n  subscription: { trial_start: number | null; trial_end: number | null },\n  days: number,\n  maxTrialDays: number,\n  now: Date = new Date(),\n): number {\n  const nowSeconds = Math.floor(now.getTime() / 1000);\n  const base = Math.max(subscription.trial_end ?? nowSeconds, nowSeconds);\n  const wanted = base + days * 86_400;\n  const cap = (subscription.trial_start ?? nowSeconds) + maxTrialDays * 86_400;\n  return Math.max(base, Math.min(wanted, cap));\n}\n\n// Whether a charge paid at `paidAt` may still be refunded in the cancel flow.\nexport function isWithinRefundWindow(paidAt: Date, now: Date, windowHours: number): boolean {\n  const age = now.getTime() - paidAt.getTime();\n  return age >= 0 && age <= windowHours * 3_600_000;\n}\n\nexport function describeOffer(offer: SaveOffer): string {\n  switch (offer.kind) {\n    case \"waive_invoice\":\n      return \"Take this month free\";\n    case \"extend_trial\":\n      return `Add ${offer.days} days to my trial`;\n    case \"pause\":\n      return offer.months === 1 ? \"Pause for a month instead\" : `Pause for ${offer.months} months instead`;\n    case \"discount\":\n      if (offer.percentOff === 100) {\n        return offer.months === 1 ? \"Take next month free\" : `Take ${offer.months} months free`;\n      }\n      return `Take ${offer.percentOff}% off for ${offer.months} months`;\n  }\n}\n",
      "type": "registry:lib"
    },
    {
      "path": "registry/pumpgtm/cancel-flow/cancel-subscription.ts",
      "content": "import \"server-only\";\nimport type Stripe from \"stripe\";\nimport { subscriptionState, canCancel } from \"@/lib/subscription-state\";\nimport {\n  DEFAULT_OFFER_POLICY,\n  extendedTrialEnd,\n  isCancelReason,\n  isWithinRefundWindow,\n  pickOffer,\n  type CancelReason,\n  type OfferPolicy,\n  type SaveOffer,\n} from \"@/lib/cancel-offer\";\n\n// The cancel flow's only server code. Call it from your own server action\n// after you have authenticated the user and looked up THEIR subscription id;\n// never take a subscription id from the browser.\n//\n// Everything is recorded on Stripe itself, so there is no table to migrate:\n// the reason goes into Stripe's own `cancellation_details` and the offer shown,\n// and what the customer did with it, into the subscription's metadata.\n// Cancelling cancels here instead of sending people to the billing portal,\n// where cancellations can silently fail to land.\n\nexport interface CancelRequest {\n  reason: string;\n  // The answer to the reason's follow-up question, if it has one.\n  followUp?: string | null;\n  comment?: string | null;\n  decision: \"accept_offer\" | \"refund\" | \"cancel\";\n}\n\nexport type CancelResult =\n  | { outcome: \"saved\"; offer: SaveOffer }\n  | { outcome: \"refunded\"; amountCents: number; currency: string }\n  | { outcome: \"cancelled\"; accessEndsAt: Date | null }\n  | {\n      outcome: \"invalid\";\n      error: \"not_cancellable\" | \"invalid_reason\" | \"offer_unavailable\" | \"refund_unavailable\";\n    };\n\nexport interface RefundableCharge {\n  amountCents: number;\n  currency: string;\n  paidAt: Date;\n}\n\nconst METADATA = {\n  shown: \"retention_offer_shown\",\n  accepted: \"retention_offer_accepted\",\n  coupon: \"retention_offer_coupon\",\n  reason: \"cancel_reason\",\n  followUp: \"cancel_follow_up\",\n} as const;\n\n// One save offer per customer, ever: a cancelled-and-restarted subscription\n// does not earn a second one.\nexport async function offerUsed(stripe: Stripe, customerId: string): Promise<boolean> {\n  for await (const subscription of stripe.subscriptions.list({ customer: customerId, status: \"all\" })) {\n    if (subscription.metadata?.[METADATA.accepted]) return true;\n  }\n  return false;\n}\n\nexport async function cancelSubscription(\n  stripe: Stripe,\n  subscriptionId: string,\n  request: CancelRequest,\n  policy: OfferPolicy = DEFAULT_OFFER_POLICY,\n): Promise<CancelResult> {\n  const subscription = await stripe.subscriptions.retrieve(subscriptionId);\n  const state = subscriptionState(subscription);\n  if (!canCancel(state)) return { outcome: \"invalid\", error: \"not_cancellable\" };\n  if (!isCancelReason(state, request.reason)) return { outcome: \"invalid\", error: \"invalid_reason\" };\n  const reason = request.reason;\n  const followUp = request.followUp?.trim().slice(0, 200) || null;\n  const comment = [followUp, request.comment?.trim()].filter(Boolean).join(\"\\n\").slice(0, 1000) || null;\n  const customerId = typeof subscription.customer === \"string\" ? subscription.customer : subscription.customer.id;\n  const offer = pickOffer({ state, reason, offerUsed: await offerUsed(stripe, customerId), policy });\n  const shown = offer ? offerKey(offer) : null;\n  const metadata = {\n    ...(shown ? { [METADATA.shown]: shown } : {}),\n    [METADATA.reason]: reason,\n    ...(followUp ? { [METADATA.followUp]: followUp } : {}),\n  };\n  const details = { feedback: stripeFeedback(reason), ...(comment ? { comment } : {}) };\n\n  if (request.decision === \"accept_offer\") {\n    // Someone who clicked \"accept\" is never cancelled because the offer went\n    // away in the meantime (used in another tab, or the subscription changed).\n    if (!offer) return { outcome: \"invalid\", error: \"offer_unavailable\" };\n    const params = await offerParams(stripe, subscription, offer, policy);\n    await stripe.subscriptions.update(subscriptionId, {\n      ...params.update,\n      metadata: {\n        ...metadata,\n        [METADATA.accepted]: `${shown}@${new Date().toISOString()}`,\n        ...(params.couponId ? { [METADATA.coupon]: params.couponId } : {}),\n      },\n    });\n    return { outcome: \"saved\", offer };\n  }\n\n  if (request.decision === \"refund\") {\n    // Rechecked here, so a stale page cannot refund an old charge.\n    const charge = await latestPaidCharge(stripe, subscription);\n    if (!charge || !isWithinRefundWindow(charge.paidAt, new Date(), policy.refundWindowHours)) {\n      return { outcome: \"invalid\", error: \"refund_unavailable\" };\n    }\n    // One refund per payment, however many times the button is pressed.\n    await stripe.refunds.create(\n      { ...charge.target, reason: \"requested_by_customer\" },\n      { idempotencyKey: `cancel-refund:${charge.paymentId}` },\n    );\n    // A refunded period keeps no access.\n    await endNow(stripe, subscriptionId, metadata, details);\n    return { outcome: \"refunded\", amountCents: charge.amountCents, currency: charge.currency };\n  }\n\n  // A failed payment is not a period to run out: void what it owes so Stripe\n  // stops retrying the card, and end it now.\n  if (state === \"past_due\") {\n    await voidOpenInvoice(stripe, subscription);\n    await endNow(stripe, subscriptionId, metadata, details);\n    return { outcome: \"cancelled\", accessEndsAt: new Date() };\n  }\n  const updated = await stripe.subscriptions.update(subscriptionId, {\n    cancel_at_period_end: true,\n    cancellation_details: details,\n    metadata,\n    // A paused subscription that cancels must not stay paused forever.\n    ...(state === \"paused\" ? { pause_collection: \"\" as const } : {}),\n  });\n  return {\n    outcome: \"cancelled\",\n    accessEndsAt: updated.cancel_at ? new Date(updated.cancel_at * 1000) : null,\n  };\n}\n\n// The charge a cancelling customer may still get back, for the dialog's\n// `refund` prop. Null when there is none inside the policy's window.\nexport async function refundableCharge(\n  stripe: Stripe,\n  subscriptionId: string,\n  policy: OfferPolicy = DEFAULT_OFFER_POLICY,\n): Promise<RefundableCharge | null> {\n  const subscription = await stripe.subscriptions.retrieve(subscriptionId);\n  if (!canCancel(subscriptionState(subscription))) return null;\n  const charge = await latestPaidCharge(stripe, subscription);\n  if (!charge || !isWithinRefundWindow(charge.paidAt, new Date(), policy.refundWindowHours)) return null;\n  return { amountCents: charge.amountCents, currency: charge.currency, paidAt: charge.paidAt };\n}\n\n// Takes back a scheduled cancellation, for the \"Keep my subscription\" button a\n// cancelling customer sees instead of the cancel flow. Clears both forms:\n// this flow sets cancel_at_period_end, the Stripe portal may set cancel_at.\nexport async function resumeSubscription(stripe: Stripe, subscriptionId: string): Promise<void> {\n  const subscription = await stripe.subscriptions.retrieve(subscriptionId);\n  await stripe.subscriptions.update(\n    subscriptionId,\n    subscription.cancel_at_period_end ? { cancel_at_period_end: false } : { cancel_at: \"\" },\n  );\n}\n\n// A customer who took a free month and cancelled before any invoice used it\n// still has that month. Pass the returned coupon id to the Checkout session\n// that restarts them; null when there is nothing to carry over. The original\n// coupon is single-use, so a fresh one is created.\nexport async function unusedFreeMonthCoupon(\n  stripe: Stripe,\n  endedSubscriptionId: string,\n): Promise<string | null> {\n  const ended = await stripe.subscriptions.retrieve(endedSubscriptionId, { expand: [\"discounts\"] });\n  const couponId = ended.metadata?.[METADATA.coupon];\n  if (!couponId || !ended.metadata?.[METADATA.accepted]?.startsWith(\"discount_100pct_1m\")) return null;\n  // Stripe removes a once-coupon from the subscription when an invoice uses it.\n  const stillAttached = (ended.discounts ?? []).some((discount) => {\n    const coupon = typeof discount === \"string\" ? null : discount.source?.coupon;\n    return (typeof coupon === \"string\" ? coupon : coupon?.id) === couponId;\n  });\n  if (!stillAttached) return null;\n  return (await createSaveCoupon(stripe, 100, 1)).id;\n}\n\nasync function offerParams(\n  stripe: Stripe,\n  subscription: Stripe.Subscription,\n  offer: SaveOffer,\n  policy: OfferPolicy,\n): Promise<{ update: Stripe.SubscriptionUpdateParams; couponId?: string }> {\n  switch (offer.kind) {\n    case \"extend_trial\":\n      return {\n        update: {\n          trial_end: extendedTrialEnd(subscription, offer.days, policy.maxTrialDays),\n          proration_behavior: \"none\",\n        },\n      };\n    case \"pause\": {\n      const resumesAt = new Date();\n      resumesAt.setMonth(resumesAt.getMonth() + offer.months);\n      return {\n        update: {\n          pause_collection: { behavior: \"void\", resumes_at: Math.floor(resumesAt.getTime() / 1000) },\n        },\n      };\n    }\n    case \"waive_invoice\":\n      // Voiding the failed invoice forgives this month and returns the\n      // subscription to active; the next renewal bills as usual.\n      await voidOpenInvoice(stripe, subscription);\n      return { update: {} };\n    case \"discount\": {\n      const coupon = await createSaveCoupon(stripe, offer.percentOff, offer.months);\n      return {\n        update: { discounts: [...existingDiscounts(subscription), { coupon: coupon.id }] },\n        couponId: coupon.id,\n      };\n    }\n  }\n}\n\n// Ends the subscription now. A second request racing the first (another tab)\n// finds it already ended and reports the same outcome instead of an error.\nasync function endNow(\n  stripe: Stripe,\n  subscriptionId: string,\n  metadata: Record<string, string>,\n  details: Stripe.SubscriptionCancelParams.CancellationDetails,\n): Promise<void> {\n  try {\n    await stripe.subscriptions.update(subscriptionId, { metadata });\n    await stripe.subscriptions.cancel(subscriptionId, { cancellation_details: details });\n  } catch (error) {\n    const current = await stripe.subscriptions.retrieve(subscriptionId);\n    if (current.status !== \"canceled\") throw error;\n  }\n}\n\nfunction createSaveCoupon(stripe: Stripe, percentOff: number, months: number) {\n  return stripe.coupons.create({\n    percent_off: percentOff,\n    duration: months === 1 ? \"once\" : \"repeating\",\n    ...(months === 1 ? {} : { duration_in_months: months }),\n    max_redemptions: 1,\n    name: `Save offer: ${percentOff}% off`,\n  });\n}\n\nasync function voidOpenInvoice(stripe: Stripe, subscription: Stripe.Subscription): Promise<void> {\n  const invoiceId =\n    typeof subscription.latest_invoice === \"string\" ? subscription.latest_invoice : subscription.latest_invoice?.id;\n  if (!invoiceId) return;\n  const invoice = await stripe.invoices.retrieve(invoiceId);\n  if (invoice.status === \"open\") await stripe.invoices.voidInvoice(invoiceId);\n}\n\n// The latest invoice's successful payment, if it has not been refunded.\nasync function latestPaidCharge(stripe: Stripe, subscription: Stripe.Subscription) {\n  const invoiceId =\n    typeof subscription.latest_invoice === \"string\" ? subscription.latest_invoice : subscription.latest_invoice?.id;\n  if (!invoiceId) return null;\n  const invoice = await stripe.invoices.retrieve(invoiceId);\n  const paidAt = invoice.status_transitions?.paid_at;\n  if (invoice.status !== \"paid\" || !paidAt || invoice.amount_paid <= 0) return null;\n  const payments = await stripe.invoicePayments.list({ invoice: invoiceId, status: \"paid\", limit: 1 });\n  const payment = payments.data[0]?.payment;\n  const intent = typeof payment?.payment_intent === \"string\" ? payment.payment_intent : payment?.payment_intent?.id;\n  const chargeId = typeof payment?.charge === \"string\" ? payment.charge : payment?.charge?.id;\n  const target = intent ? { payment_intent: intent } : chargeId ? { charge: chargeId } : null;\n  if (!target) return null;\n  const refunds = await stripe.refunds.list({ ...target, limit: 1 });\n  if (refunds.data.length > 0) return null;\n  return {\n    target,\n    paymentId: intent ?? chargeId!,\n    amountCents: invoice.amount_paid,\n    currency: invoice.currency,\n    paidAt: new Date(paidAt * 1000),\n  };\n}\n\nfunction existingDiscounts(subscription: Stripe.Subscription): Array<{ discount: string }> {\n  return (subscription.discounts ?? []).map((discount) => ({\n    discount: typeof discount === \"string\" ? discount : discount.id,\n  }));\n}\n\nfunction offerKey(offer: SaveOffer): string {\n  switch (offer.kind) {\n    case \"extend_trial\":\n      return `extend_trial_${offer.days}d`;\n    case \"pause\":\n      return `pause_${offer.months}m`;\n    case \"waive_invoice\":\n      return \"waive_invoice\";\n    case \"discount\":\n      return `discount_${offer.percentOff}pct_${offer.months}m`;\n  }\n}\n\n// Stripe's own vocabulary, so the reason shows up in the Dashboard and in\n// Stripe's churn reporting without any work on your side.\nfunction stripeFeedback(\n  reason: CancelReason,\n): Stripe.SubscriptionUpdateParams.CancellationDetails.Feedback {\n  switch (reason) {\n    case \"too_expensive\":\n      return \"too_expensive\";\n    case \"switched\":\n      return \"switched_service\";\n    case \"missing_feature\":\n      return \"missing_features\";\n    case \"hard_to_use\":\n    case \"setup\":\n      return \"too_complex\";\n    case \"no_time\":\n    case \"pausing\":\n      return \"unused\";\n    case \"no_results\":\n    case \"no_results_yet\":\n    case \"not_expected\":\n      return \"low_quality\";\n    default:\n      return \"other\";\n  }\n}\n",
      "type": "registry:lib"
    }
  ],
  "docs": "Cancel flow by PumpGTM. PumpGTM finds buyers who need your product now and runs your LinkedIn outreach: https://pumpgtm.com",
  "type": "registry:block"
}