SpendCapSidePanel.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { PermissionAction } from '@supabase/shared-types/out/constants'
  2. import { useParams } from 'common'
  3. import { ChevronRight, ExternalLink } from 'lucide-react'
  4. import { useTheme } from 'next-themes'
  5. import Image from 'next/image'
  6. import Link from 'next/link'
  7. import { useEffect, useState } from 'react'
  8. import { pricing } from 'shared-data/pricing'
  9. import { toast } from 'sonner'
  10. import { Button, cn, Collapsible, CollapsibleContent, CollapsibleTrigger, SidePanel } from 'ui'
  11. import { Admonition } from 'ui-patterns/admonition'
  12. import Table from '@/components/to-be-cleaned/Table'
  13. import { useOrgSubscriptionQuery } from '@/data/subscriptions/org-subscription-query'
  14. import { useOrgSubscriptionUpdateMutation } from '@/data/subscriptions/org-subscription-update-mutation'
  15. import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
  16. import { BASE_PATH, DOCS_URL, PRICING_TIER_PRODUCT_IDS } from '@/lib/constants'
  17. import { useOrgSettingsPageStateSnapshot } from '@/state/organization-settings'
  18. const SPEND_CAP_OPTIONS: {
  19. name: string
  20. value: 'on' | 'off'
  21. imageUrl: string
  22. imageUrlLight: string
  23. }[] = [
  24. {
  25. name: 'Spend cap enabled',
  26. value: 'on',
  27. imageUrl: `${BASE_PATH}/img/spend-cap-on.png`,
  28. imageUrlLight: `${BASE_PATH}/img/spend-cap-on--light.png`,
  29. },
  30. {
  31. name: 'Spend cap disabled',
  32. value: 'off',
  33. imageUrl: `${BASE_PATH}/img/spend-cap-off.png`,
  34. imageUrlLight: `${BASE_PATH}/img/spend-cap-off--light.png`,
  35. },
  36. ]
  37. const SpendCapSidePanel = () => {
  38. const { slug } = useParams()
  39. const { resolvedTheme } = useTheme()
  40. const [showUsageCosts, setShowUsageCosts] = useState(false)
  41. const [selectedOption, setSelectedOption] = useState<'on' | 'off'>()
  42. const { can: canUpdateSpendCap } = useAsyncCheckPermissions(
  43. PermissionAction.BILLING_WRITE,
  44. 'stripe.subscriptions'
  45. )
  46. const snap = useOrgSettingsPageStateSnapshot()
  47. const visible = snap.panelKey === 'costControl'
  48. const onClose = () => snap.setPanelKey(undefined)
  49. const { data: subscription, isPending: isLoading } = useOrgSubscriptionQuery({ orgSlug: slug })
  50. const { mutate: updateOrgSubscription, isPending: isUpdating } = useOrgSubscriptionUpdateMutation(
  51. {
  52. onSuccess: () => {
  53. toast.success(`Successfully ${isTurningOnCap ? 'enabled' : 'disabled'} spend cap`)
  54. onClose()
  55. },
  56. onError: (error) => {
  57. toast.error(`Failed to toggle spend cap: ${error.message}`)
  58. },
  59. }
  60. )
  61. const isFreePlan = subscription?.plan?.id === 'free'
  62. const isSpendCapOn = !subscription?.usage_billing_enabled
  63. const isTurningOnCap = !isSpendCapOn && selectedOption === 'on'
  64. const hasChanges = selectedOption !== (isSpendCapOn ? 'on' : 'off')
  65. useEffect(() => {
  66. if (visible && subscription !== undefined) {
  67. setSelectedOption(isSpendCapOn ? 'on' : 'off')
  68. }
  69. }, [visible, isLoading, subscription, isSpendCapOn])
  70. const onConfirm = async () => {
  71. if (!slug) return console.error('Org slug is required')
  72. const tier = (
  73. selectedOption === 'on' ? PRICING_TIER_PRODUCT_IDS.PRO : PRICING_TIER_PRODUCT_IDS.PAYG
  74. ) as 'tier_pro' | 'tier_payg'
  75. updateOrgSubscription({ slug, tier })
  76. }
  77. const billingMetricCategories: (keyof typeof pricing)[] = [
  78. 'database',
  79. 'auth',
  80. 'storage',
  81. 'realtime',
  82. 'edge_functions',
  83. ]
  84. return (
  85. <SidePanel
  86. size="large"
  87. loading={isLoading || isUpdating}
  88. disabled={isFreePlan || isLoading || !hasChanges || isUpdating || !canUpdateSpendCap}
  89. visible={visible}
  90. onCancel={onClose}
  91. onConfirm={onConfirm}
  92. header={
  93. <div className="flex items-center justify-between w-full">
  94. <h4>Spend cap</h4>
  95. <Button asChild type="default" icon={<ExternalLink strokeWidth={1.5} />}>
  96. <Link
  97. href={`${DOCS_URL}/guides/platform/cost-control#spend-cap`}
  98. target="_blank"
  99. rel="noreferrer"
  100. >
  101. About spend cap
  102. </Link>
  103. </Button>
  104. </div>
  105. }
  106. tooltip={!canUpdateSpendCap ? 'You do not have permission to update spend cap' : undefined}
  107. >
  108. <SidePanel.Content>
  109. <div className="py-6 space-y-4">
  110. <p className="text-sm">
  111. Use the spend cap to manage project usage and costs, and control whether the project can
  112. exceed the included quota allowance of any billed line item in a billing cycle
  113. </p>
  114. <Collapsible open={showUsageCosts} onOpenChange={setShowUsageCosts}>
  115. <CollapsibleTrigger asChild>
  116. <div className="flex items-center space-x-2 cursor-pointer">
  117. <ChevronRight
  118. strokeWidth={1.5}
  119. size={16}
  120. className={showUsageCosts ? 'rotate-90' : ''}
  121. />
  122. <p className="text-sm text-foreground-light">
  123. How are each resource charged after exceeding the included quota?
  124. </p>
  125. </div>
  126. </CollapsibleTrigger>
  127. <CollapsibleContent asChild>
  128. <Table
  129. className="mt-4"
  130. head={
  131. <>
  132. <Table.th>
  133. <p className="text-xs">Item</p>
  134. </Table.th>
  135. <Table.th>
  136. <p className="text-xs">Rate</p>
  137. </Table.th>
  138. </>
  139. }
  140. body={billingMetricCategories.map((categoryId) => {
  141. const category = pricing[categoryId]
  142. const usageItems = category.features.filter((it: any) => it.usage_based)
  143. return (
  144. <>
  145. <Table.tr key={categoryId}>
  146. <Table.td>
  147. <p className="text-xs text-foreground">{category.title}</p>
  148. </Table.td>
  149. <Table.td>{null}</Table.td>
  150. </Table.tr>
  151. {usageItems.map((item: any) => {
  152. return (
  153. <Table.tr key={item.title}>
  154. <Table.td>
  155. <p className="text-xs pl-4">{item.title}</p>
  156. </Table.td>
  157. <Table.td>
  158. <p className="text-xs pl-4">
  159. {Array.isArray(item.plans['pro'])
  160. ? item.plans['pro']?.join(', ')
  161. : item.plans['pro']}
  162. </p>
  163. </Table.td>
  164. </Table.tr>
  165. )
  166. })}
  167. </>
  168. )
  169. })}
  170. />
  171. </CollapsibleContent>
  172. </Collapsible>
  173. {isFreePlan && (
  174. <Admonition
  175. type="note"
  176. layout="horizontal"
  177. title="Toggling of the spend cap is only available on the Pro Plan"
  178. description="Upgrade your plan to disable the spend cap"
  179. actions={
  180. <Button type="default" onClick={() => snap.setPanelKey('subscriptionPlan')}>
  181. View available plans
  182. </Button>
  183. }
  184. />
  185. )}
  186. <div className="mt-8! pb-4">
  187. <div className="flex gap-3">
  188. {SPEND_CAP_OPTIONS.map((option) => {
  189. const isSelected = selectedOption === option.value
  190. return (
  191. <div
  192. key={option.value}
  193. className={cn('col-span-4 group space-y-1', isFreePlan && 'opacity-75')}
  194. onClick={() => !isFreePlan && setSelectedOption(option.value)}
  195. >
  196. <Image
  197. alt="Spend Cap"
  198. className={cn(
  199. 'relative rounded-xl transition border bg-no-repeat bg-center bg-cover w-[160px] h-[96px]',
  200. isSelected
  201. ? 'border-foreground'
  202. : 'border-foreground-muted opacity-50 group-hover:border-foreground-lighter group-hover:opacity-100',
  203. !isFreePlan && 'cursor-pointer',
  204. !isFreePlan && !isSelected && 'group-hover:border-foreground-light'
  205. )}
  206. width={160}
  207. height={96}
  208. src={resolvedTheme?.includes('dark') ? option.imageUrl : option.imageUrlLight}
  209. />
  210. <p
  211. className={cn(
  212. 'text-sm transition',
  213. !isFreePlan && 'group-hover:text-foreground',
  214. isSelected ? 'text-foreground' : 'text-foreground-light'
  215. )}
  216. >
  217. {option.name}
  218. </p>
  219. </div>
  220. )
  221. })}
  222. </div>
  223. </div>
  224. {selectedOption === 'on' ? (
  225. <Admonition
  226. type="warning"
  227. title="Your projects could become unresponsive or enter read only mode"
  228. description="Exceeding the included quota allowance with spend cap enabled can cause your projects
  229. to become unresponsive or enter read only mode."
  230. />
  231. ) : (
  232. <Admonition
  233. type="note"
  234. title="Charges apply for usage beyond included quota allowance"
  235. description="Your projects will always remain responsive and active, and charges only apply when
  236. exceeding the included quota limit."
  237. />
  238. )}
  239. {hasChanges && (
  240. <>
  241. <p className="text-sm">
  242. {selectedOption === 'on'
  243. ? 'Upon clicking confirm, spend cap will be enabled for your organization and you will no longer be charged any extra for usage.'
  244. : 'Upon clicking confirm, spend cap will be disabled for your organization and you will be charged for any usage beyond the included quota.'}
  245. </p>
  246. <p className="text-sm">
  247. Toggling spend cap triggers an invoice and there might be prorated charges for any
  248. usage beyond the Pro Plans quota during this billing cycle.
  249. </p>
  250. </>
  251. )}
  252. </div>
  253. </SidePanel.Content>
  254. </SidePanel>
  255. )
  256. }
  257. export default SpendCapSidePanel