Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: better insights for upcoming invoice (#19409)

Kevin Grüneberg8a70f199de98
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx
index 4dc57851cdc..57dcb12650d 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx
@@ -16,6 +16,7 @@ import { BILLING_BREAKDOWN_METRICS } from './BillingBreakdown.constants'
import BillingMetric from './BillingMetric'
import UpcomingInvoice from './UpcomingInvoice'
import { useIsFeatureEnabled } from 'hooks'
+import Link from 'next/link'
const BillingBreakdown = () => {
const snap = useOrgSettingsPageStateSnapshot()
@@ -152,12 +153,19 @@ const BillingBreakdown = () => {
<>
<p className="!mt-10 text-sm">Upcoming cost for next invoice</p>
<p className="text-sm text-foreground-light">
- The following table shows your upcoming costs. Depending on your usage, the final
- amount may vary. Next invoice on{' '}
+ The following table shows your upcoming costs excluding credits. Depending on your
+ usage, the final amount may vary. Next invoice on{' '}
<span className="text-foreground-light whitespace-nowrap">
{billingCycleEnd.format('MMM DD, YYYY')}
</span>
- .
+ . See&nbsp;
+ <Link
+ className="text-green-900 transition hover:text-green-1000"
+ href={`/org/${orgSlug}/usage`}
+ >
+ usage page
+ </Link>{' '}
+ for a more detailed usage breakdown.
</p>
<UpcomingInvoice slug={orgSlug} />
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/UpcomingInvoice.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/UpcomingInvoice.tsx
index 507f9ddc836..19179f04acf 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/UpcomingInvoice.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/UpcomingInvoice.tsx
@@ -1,11 +1,12 @@
import clsx from 'clsx'
-import { partition } from 'lodash'
import AlertError from 'components/ui/AlertError'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useOrgUpcomingInvoiceQuery } from 'data/invoices/org-invoice-upcoming-query'
-import { useState } from 'react'
-import { Button, Collapsible, IconChevronRight } from 'ui'
+import { useMemo, useState } from 'react'
+import { Button, Collapsible, IconChevronRight, IconInfo } from 'ui'
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { billingMetricUnit, formatUsage } from '../helpers'
export interface UpcomingInvoiceProps {
slug?: string
@@ -20,9 +21,42 @@ const UpcomingInvoice = ({ slug }: UpcomingInvoiceProps) => {
isSuccess,
} = useOrgUpcomingInvoiceQuery({ orgSlug: slug })
- const [showUsageFees, setShowUsageFees] = useState(false)
- const [usageFees, fixedFees] = partition(upcomingInvoice?.lines ?? [], (item) => item.usage_based)
- const totalUsageFees = Number(usageFees.reduce((a, b) => a + b.amount, 0).toFixed(2))
+ const [usageFeesExpanded, setUsageFeesExpanded] = useState<string[]>([])
+
+ const fixedFees = useMemo(() => {
+ return (upcomingInvoice?.lines || [])
+ .filter((item) => !item.breakdown)
+ .sort((a, b) => {
+ // Prorations should be below regular usage fees
+ return Number(a.proration) - Number(b.proration)
+ })
+ }, [upcomingInvoice])
+
+ const feesWithBreakdown = useMemo(() => {
+ return (upcomingInvoice?.lines || [])
+ .filter((item) => item.breakdown?.length)
+ .sort((a, b) => Number(a.usage_based) - Number(b.usage_based) || b.amount - a.amount)
+ }, [upcomingInvoice])
+
+ const expandUsageFee = (fee: string) => {
+ setUsageFeesExpanded([...usageFeesExpanded, fee])
+ }
+
+ const collapseUsageFee = (fee: string) => {
+ setUsageFeesExpanded(usageFeesExpanded.filter((item) => item !== fee))
+ }
+
+ const allFeesExpanded = useMemo(() => {
+ return feesWithBreakdown.length === usageFeesExpanded.length
+ }, [feesWithBreakdown, usageFeesExpanded])
+
+ const toggleAllFees = () => {
+ if (allFeesExpanded) {
+ setUsageFeesExpanded([])
+ } else {
+ setUsageFeesExpanded(feesWithBreakdown.map((item) => item.description))
+ }
+ }
return (
<>
@@ -37,83 +71,161 @@ const UpcomingInvoice = ({ slug }: UpcomingInvoiceProps) => {
{isError && <AlertError subject="Failed to retrieve upcoming invoice" error={error} />}
{isSuccess && (
- <table className="w-full">
- <thead>
- <tr className="border-b">
- <th className="py-2 font-normal text-left text-sm text-foreground-light w-1/2">
- Item
- </th>
- <th className="py-2 font-normal text-left text-sm text-foreground-light">Count</th>
- <th className="py-2 font-normal text-left text-sm text-foreground-light">
- Unit price
- </th>
- <th className="py-2 font-normal text-right text-sm text-foreground-light">Price</th>
- </tr>
- </thead>
- <tbody>
- {fixedFees.map((item) => (
- <tr key={item.description} className="border-b">
- <td className="py-2 text-sm">{item.description ?? 'Unknown'}</td>
- <td className="py-2 text-sm">{item.quantity}</td>
- <td className="py-2 text-sm">
- {item.unit_price === 0 ? 'FREE' : `$${item.unit_price}`}
- </td>
- <td className="py-2 text-sm text-right">${item.amount}</td>
+ <div>
+ {feesWithBreakdown.length > 0 && (
+ <div className="mb-2">
+ <Button size="tiny" type="default" onClick={toggleAllFees}>
+ {allFeesExpanded ? 'Collapse All' : 'Expand All'}
+ </Button>
+ </div>
+ )}
+
+ <table className="w-full">
+ <thead>
+ <tr className="border-b">
+ <th className="py-2 font-medium text-left text-sm text-foreground-light max-w-[200px]">
+ Item
+ </th>
+ <th className="py-2 font-medium text-right text-sm text-foreground-light pr-4">
+ Usage
+ </th>
+ <th className="py-2 font-medium text-left text-sm text-foreground-light">
+ Unit price
+ </th>
+ <th className="py-2 font-medium text-right text-sm text-foreground-light">Cost</th>
</tr>
- ))}
- </tbody>
-
- {usageFees.length > 0 && (
- <Collapsible asChild open={showUsageFees} onOpenChange={setShowUsageFees}>
- <tbody>
- <Collapsible.Trigger asChild>
- <tr className="border-b cursor-pointer" style={{ WebkitAppearance: 'initial' }}>
- <td className="py-2 text-sm flex items-center space-x-2">
- <Button
- type="text"
- className="!px-1"
- icon={
- <IconChevronRight
- className={clsx('transition', showUsageFees && 'rotate-90')}
- />
- }
- />
- <p>Usage items</p>
- </td>
- <td />
- <td />
- <td className="text-sm text-right">
- {!showUsageFees ? `$${totalUsageFees}` : null}
+ </thead>
+ <tbody>
+ {fixedFees.map((item) => (
+ <tr key={item.description} className="border-b">
+ <td className="py-2 text-sm max-w-[200px]" colSpan={item.proration ? 3 : 1}>
+ {item.description ?? 'Unknown'}
+ </td>
+ {!item.proration && (
+ <td className="py-2 text-sm text-right pr-4">{item.quantity}</td>
+ )}
+ {!item.proration && (
+ <td className="py-2 text-sm">
+ {item.unit_price === 0 ? 'FREE' : `$${item.unit_price}`}
</td>
- </tr>
- </Collapsible.Trigger>
- <Collapsible.Content asChild>
- <>
- {usageFees.map((fee) => (
- <tr className="border-b" key={fee.description}>
- <td className="py-2 text-sm pl-8">{fee.description}</td>
- <td className="py-2 text-sm"></td>
+ )}
+ <td className="py-2 text-sm text-right">${item.amount}</td>
+ </tr>
+ ))}
+ </tbody>
+
+ {feesWithBreakdown.length > 0 &&
+ feesWithBreakdown.map((fee) => (
+ <Collapsible
+ asChild
+ open={usageFeesExpanded.includes(fee.description)}
+ onOpenChange={(open) =>
+ open ? expandUsageFee(fee.description) : collapseUsageFee(fee.description)
+ }
+ key={fee.description}
+ >
+ <tbody>
+ <Collapsible.Trigger asChild>
+ <tr
+ className={usageFeesExpanded.includes(fee.description) ? '' : 'border-b'}
+ key={fee.description}
+ style={{ WebkitAppearance: 'initial' }}
+ >
+ <td className="py-2 text-sm max-w-[200px]">
+ <Button
+ type="text"
+ className="!px-1"
+ icon={
+ <IconChevronRight
+ className={clsx(
+ 'transition',
+ usageFeesExpanded.includes(fee.description) && 'rotate-90'
+ )}
+ />
+ }
+ />{' '}
+ <span>
+ {fee.description}
+ {fee.usage_metric &&
+ billingMetricUnit(fee.usage_metric) &&
+ ` (${billingMetricUnit(fee.usage_metric)})`}
+ </span>
+ </td>
+ <td className="py-2 pr-4 text-sm text-right tabular-nums max-w-[100px]">
+ {fee.usage_original
+ ? `${formatUsage(fee.usage_metric!, fee.usage_original)}`
+ : fee.quantity
+ ? fee.quantity
+ : null}
+ </td>
<td className="py-2 text-sm">
- {fee.unit_price ? `$${fee.unit_price}` : null}
+ {fee.unit_price_desc
+ ? `${fee.unit_price_desc}`
+ : fee.unit_price
+ ? `$${fee.unit_price}`
+ : null}
</td>
- <td className="py-2 text-sm text-right">${fee.amount ?? 0}</td>
+ <td className="py-2 text-sm text-right max-w-[70px]">${fee.amount ?? 0}</td>
</tr>
- ))}
- </>
- </Collapsible.Content>
- </tbody>
- </Collapsible>
- )}
+ </Collapsible.Trigger>
+
+ <Collapsible.Content asChild>
+ <>
+ {fee.breakdown?.map((breakdown) => (
+ <tr
+ className="last:border-b cursor-pointer"
+ style={{ WebkitAppearance: 'initial' }}
+ key={breakdown.project_ref}
+ >
+ <td className="pb-1 text-xs pl-8 max-w-[200px]">
+ {breakdown.project_name}
+ </td>
+ <td className="pb-1 text-xs tabular-nums text-right pr-4">
+ {formatUsage(fee.usage_metric!, breakdown.usage)}
+ </td>
+ <td />
+ <td />
+ </tr>
+ ))}
+ </>
+ </Collapsible.Content>
+ </tbody>
+ </Collapsible>
+ ))}
- <tbody>
- <tr>
- <td className="py-2 text-sm">Total</td>
- <td className="py-2 text-sm" />
- <td className="py-2 text-sm" />
- <td className="py-2 text-sm text-right">${upcomingInvoice?.amount_total ?? 0}</td>
- </tr>
- </tbody>
- </table>
+ <tfoot>
+ <tr>
+ <td className="py-4 text-sm font-medium">
+ <span className="mr-2">Projected Costs</span>
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger>
+ <IconInfo size={12} strokeWidth={2} />
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">
+ Estimated costs at the end of the billing cycle. Final amounts may vary
+ depending on your usage.
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ </td>
+ <td className="py-4 text-sm text-right font-medium" colSpan={3}>
+ ${upcomingInvoice?.amount_projected ?? '-'}
+ </td>
+ </tr>
+ </tfoot>
+ </table>
+ </div>
)}
</>
)
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/SpendCapSidePanel.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/SpendCapSidePanel.tsx
index d5321ab17e3..f30acf2548d 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/SpendCapSidePanel.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/SpendCapSidePanel.tsx
@@ -301,7 +301,7 @@ const SpendCapSidePanel = () => {
<p className="text-sm">
{selectedOption === 'on'
? 'Upon clicking confirm, spend cap will be enabled for your organization and you will no longer be charged any extra for usage.'
- : 'Upon clicking confirm, spend cap will be disabled for your organization and you will be charged for any usage beyong the included quota.'}
+ : 'Upon clicking confirm, spend cap will be disabled for your organization and you will be charged for any usage beyond the included quota.'}
</p>
</>
)}
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/helpers.ts b/apps/studio/components/interfaces/Organization/BillingSettings/helpers.ts
new file mode 100644
index 00000000000..b09cfe2b7b8
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/helpers.ts
@@ -0,0 +1,25 @@
+import { PricingMetric } from 'data/analytics/org-daily-stats-query'
+
+export const pricingMetricBytes = [
+ PricingMetric.DATABASE_SIZE,
+ PricingMetric.EGRESS,
+ PricingMetric.STORAGE_SIZE,
+]
+
+export const formatUsage = (pricingMetric: PricingMetric, usage: number) => {
+ if (pricingMetricBytes.includes(pricingMetric)) {
+ return +(usage / 1e9).toFixed(2).toLocaleString()
+ } else {
+ return usage.toLocaleString()
+ }
+}
+
+export const billingMetricUnit = (pricingMetric: PricingMetric) => {
+ if (pricingMetricBytes.includes(pricingMetric)) {
+ return 'GB'
+ } else if (pricingMetric.startsWith('COMPUTE_HOURS')) {
+ return 'Hours'
+ } else {
+ return null
+ }
+}
diff --git a/apps/studio/components/interfaces/Organization/Usage/SectionContent.tsx b/apps/studio/components/interfaces/Organization/Usage/SectionContent.tsx
index a34967d9322..1f049b2497b 100644
--- a/apps/studio/components/interfaces/Organization/Usage/SectionContent.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/SectionContent.tsx
@@ -36,7 +36,7 @@ const SectionContent = ({
))}
</div>
</div>
- {links && links.length && (
+ {links && links.length > 0 && (
<div className="space-y-2">
<p className="text-sm text-foreground mb-2">More information</p>
{links.map((link) => (
diff --git a/apps/studio/data/invoices/invoice-upcoming-query.ts b/apps/studio/data/invoices/invoice-upcoming-query.ts
deleted file mode 100644
index daa5957c59a..00000000000
--- a/apps/studio/data/invoices/invoice-upcoming-query.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
-import { useCallback } from 'react'
-import { invoicesKeys } from './keys'
-import { UpcomingInvoiceResponse } from './org-invoice-upcoming-query'
-
-export type UpcomingInvoiceVariables = {
- projectRef?: string
-}
-
-export async function getUpcomingInvoice(
- { projectRef }: UpcomingInvoiceVariables,
- signal?: AbortSignal
-) {
- if (!projectRef) throw new Error('projectRef is required')
-
- const response = await get(`${API_URL}/projects/${projectRef}/billing/invoices/upcoming`, {
- signal,
- })
- if (response.error) throw response.error
-
- return response as UpcomingInvoiceResponse
-}
-
-export type UpcomingInvoiceData = Awaited<ReturnType<typeof getUpcomingInvoice>>
-export type UpcomingInvoiceError = unknown
-
-export const useUpcomingInvoiceQuery = <TData = UpcomingInvoiceData>(
- { projectRef }: UpcomingInvoiceVariables,
- {
- enabled = true,
- ...options
- }: UseQueryOptions<UpcomingInvoiceData, UpcomingInvoiceError, TData> = {}
-) =>
- useQuery<UpcomingInvoiceData, UpcomingInvoiceError, TData>(
- invoicesKeys.upcomingPreview(projectRef),
- ({ signal }) => getUpcomingInvoice({ projectRef }, signal),
- {
- enabled: enabled && typeof projectRef !== 'undefined',
- ...options,
- }
- )
-
-export const useUpcomingInvoicePrefetch = ({ projectRef }: UpcomingInvoiceVariables) => {
- const client = useQueryClient()
-
- return useCallback(() => {
- if (projectRef) {
- client.prefetchQuery(invoicesKeys.upcomingPreview(projectRef), ({ signal }) =>
- getUpcomingInvoice({ projectRef }, signal)
- )
- }
- }, [projectRef])
-}
diff --git a/apps/studio/data/invoices/keys.ts b/apps/studio/data/invoices/keys.ts
index 5b1a5a482a8..4c4ebe67a92 100644
--- a/apps/studio/data/invoices/keys.ts
+++ b/apps/studio/data/invoices/keys.ts
@@ -11,8 +11,5 @@ export const invoicesKeys = {
['invoices', projectRef, offset] as const,
projectInvoicesCount: (projectRef: string | undefined) =>
['invoices', projectRef, 'count'] as const,
- upcomingPreview: (projectRef: string | undefined) =>
- ['invoices', projectRef, 'upcoming-preview'] as const,
- orgUpcomingPreview: (projectRef: string | undefined) =>
- ['invoices', projectRef, 'upcoming-preview'] as const,
+ orgUpcomingPreview: (slug: string | undefined) => ['invoices', slug, 'upcoming-preview'] as const,
}
diff --git a/apps/studio/data/invoices/org-invoice-upcoming-query.ts b/apps/studio/data/invoices/org-invoice-upcoming-query.ts
index b20563cf0ee..3d745db6a4c 100644
--- a/apps/studio/data/invoices/org-invoice-upcoming-query.ts
+++ b/apps/studio/data/invoices/org-invoice-upcoming-query.ts
@@ -1,18 +1,15 @@
-import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
-import { useCallback } from 'react'
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'data/fetchers'
import { invoicesKeys } from './keys'
import { ResponseError } from 'types'
-
-// [Joshen] This can eventually superseded and overwrite invoice-upcoming-query once we completely move to org billing
+import { PricingMetric } from 'data/analytics/org-daily-stats-query'
export type UpcomingInvoiceVariables = {
orgSlug?: string
}
export type UpcomingInvoiceResponse = {
- amount_total: number
+ amount_projected: number
currency: string
customer_balance: number
subscription_id: string
@@ -21,10 +18,19 @@ export type UpcomingInvoiceResponse = {
lines: {
amount: number
description: string
+ proration: boolean
period: { start: string; end: string }
quantity: number
unit_price: number
+ unit_price_desc: string
usage_based: boolean
+ usage_metric?: PricingMetric
+ usage_original?: number
+ breakdown: {
+ project_ref: string
+ project_name: string
+ usage: number
+ }[]
}[]
}
@@ -34,11 +40,16 @@ export async function getUpcomingInvoice(
) {
if (!orgSlug) throw new Error('orgSlug is required')
- const response = await get(`${API_URL}/organizations/${orgSlug}/billing/invoices/upcoming`, {
+ const { data, error } = await get(`/platform/organizations/{slug}/billing/invoices/upcoming`, {
+ params: { path: { slug: orgSlug } },
+ headers: {
+ Version: '2',
+ },
signal,
})
- if (response.error) throw response.error
- return response as UpcomingInvoiceResponse
+
+ if (error) throw error
+ return data as unknown as UpcomingInvoiceResponse
}
export type UpcomingInvoiceData = Awaited<ReturnType<typeof getUpcomingInvoice>>
@@ -59,15 +70,3 @@ export const useOrgUpcomingInvoiceQuery = <TData = UpcomingInvoiceData>(
...options,
}
)
-
-export const useOrgUpcomingInvoicePrefetch = ({ orgSlug }: UpcomingInvoiceVariables) => {
- const client = useQueryClient()
-
- return useCallback(() => {
- if (orgSlug) {
- client.prefetchQuery(invoicesKeys.orgUpcomingPreview(orgSlug), ({ signal }) =>
- getUpcomingInvoice({ orgSlug }, signal)
- )
- }
- }, [client, orgSlug])
-}
diff --git a/apps/studio/data/subscriptions/org-subscription-update-mutation.ts b/apps/studio/data/subscriptions/org-subscription-update-mutation.ts
index ad6cae5e40a..464dbe8c88d 100644
--- a/apps/studio/data/subscriptions/org-subscription-update-mutation.ts
+++ b/apps/studio/data/subscriptions/org-subscription-update-mutation.ts
@@ -6,6 +6,7 @@ import { ResponseError } from 'types/base'
import { subscriptionKeys } from './keys'
import { usageKeys } from 'data/usage/keys'
import { SubscriptionTier } from './types'
+import { invoicesKeys } from 'data/invoices/keys'
export type OrgSubscriptionUpdateVariables = {
slug: string
@@ -58,6 +59,7 @@ export const useOrgSubscriptionUpdateMutation = ({
queryClient.invalidateQueries(subscriptionKeys.orgSubscription(slug)),
queryClient.invalidateQueries(subscriptionKeys.orgPlans(slug)),
queryClient.invalidateQueries(usageKeys.orgUsage(slug)),
+ queryClient.invalidateQueries(invoicesKeys.orgUpcomingPreview(slug)),
])
await onSuccess?.(data, variables, context)