The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Update based on new org usage endpoint
Joshen Limabc05d8e5687
diff --git a/studio/components/interfaces/Organization/Usage/Activity.tsx b/studio/components/interfaces/Organization/Usage/Activity.tsxindex f6d4976042c..f801ef519c6 100644--- a/studio/components/interfaces/Organization/Usage/Activity.tsx+++ b/studio/components/interfaces/Organization/Usage/Activity.tsx@@ -74,37 +74,37 @@ const Activity = ({const chartMeta: {[key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }} = {- monthly_active_users: {+ [PricingMetric.MONTHLY_ACTIVE_USERS]: {data: mauData?.data ?? [],margin: 18,isLoading: isLoadingMauData,hasNoData: mauData?.hasNoData ?? false,},- monthly_active_sso_users: {+ [PricingMetric.MONTHLY_ACTIVE_SSO_USERS]: {data: mauSSOData?.data ?? [],margin: 20,isLoading: isLoadingMauSSOData,hasNoData: mauSSOData?.hasNoData ?? false,},- storage_image_render_count: {+ [PricingMetric.STORAGE_IMAGES_TRANSFORMED]: {data: assetTransformationsData?.data ?? [],margin: 0,isLoading: isLoadingAssetTransformationsData,hasNoData: assetTransformationsData?.hasNoData ?? false,},- func_invocations: {+ [PricingMetric.FUNCTION_INVOCATIONS]: {data: funcInvocationsData?.data ?? [],margin: 26,isLoading: isLoadingFuncInvocationsData,hasNoData: funcInvocationsData?.hasNoData ?? false,},- realtime_message_count: {+ [PricingMetric.REALTIME_MESSAGE_COUNT]: {data: realtimeMessagesData?.data ?? [],margin: 38,isLoading: isLoadingRealtimeMessagesData,hasNoData: realtimeMessagesData?.hasNoData ?? false,},- realtime_peak_connection: {+ [PricingMetric.REALTIME_PEAK_CONNECTIONS]: {data: realtimeConnectionsData?.data ?? [],margin: 0,isLoading: isLoadingRealtimeConnectionsData,diff --git a/studio/components/interfaces/Organization/Usage/Bandwidth.tsx b/studio/components/interfaces/Organization/Usage/Bandwidth.tsxindex d201afb1445..066df624791 100644--- a/studio/components/interfaces/Organization/Usage/Bandwidth.tsx+++ b/studio/components/interfaces/Organization/Usage/Bandwidth.tsx@@ -1,96 +1,223 @@import { DataPoint } from 'data/analytics/constants'-import { useDailyStatsQuery } from 'data/analytics/daily-stats-query'+import { PricingMetric, useOrgDailyStatsQuery } from 'data/analytics/org-daily-stats-query'import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'import UsageSection from './UsageSection'-import { PricingMetric, useOrgDailyStatsQuery } from 'data/analytics/org-daily-stats-query'const GB = 1073741824-const MOCK_DATA = [++const MOCK_DATA_2 = [+ {+ period_start: '2023-06-01',+ egress: 8678929619,+ egress_database: 7283483597,+ egress_auth: 435216776,+ egress_storage: 481432155,+ egress_realtime: 478797091,+ },+ {+ period_start: '2023-06-02',+ egress: 6446889468,+ egress_database: 5284341572,+ egress_auth: 425272306,+ egress_storage: 368536397,+ egress_realtime: 368739193,+ },+ {+ period_start: '2023-06-03',+ egress: 7940650326,+ egress_database: 6743975946,+ egress_auth: 359361673,+ egress_storage: 351855389,+ egress_realtime: 485457318,+ },+ {+ period_start: '2023-06-04',+ egress: 7595077017,+ egress_database: 6654607743,+ egress_auth: 308779823,+ egress_storage: 139644836,+ egress_realtime: 492044615,+ },+ {+ period_start: '2023-06-05',+ egress: 7830613275,+ egress_database: 6957932956,+ egress_auth: 475208724,+ egress_storage: 123853608,+ egress_realtime: 273617987,+ },+ {+ period_start: '2023-06-06',+ egress: 6361397604,+ egress_database: 5219239997,+ egress_auth: 371950767,+ egress_storage: 477655193,+ egress_realtime: 292551647,+ },+ {+ period_start: '2023-06-07',+ egress: 8119115718,+ egress_database: 7060114070,+ egress_auth: 402873931,+ egress_storage: 286106674,+ egress_realtime: 370021043,+ },+ {+ period_start: '2023-06-08',+ egress: 9354738273,+ egress_database: 8209195125,+ egress_auth: 205419959,+ egress_storage: 456027425,+ egress_realtime: 484095764,+ },+ {+ period_start: '2023-06-09',+ egress: 10204993748,+ egress_database: 9166932029,+ egress_auth: 449361248,+ egress_storage: 307493054,+ egress_realtime: 281207417,+ },+ {+ period_start: '2023-06-10',+ egress: 8838625357,+ egress_database: 7895700317,+ egress_auth: 297427767,+ egress_storage: 284882171,+ egress_realtime: 360615102,+ },+ {+ period_start: '2023-06-11',+ egress: 7543652486,+ egress_database: 6750703440,+ egress_auth: 305554257,+ egress_storage: 236963257,+ egress_realtime: 250431532,+ },+ {+ period_start: '2023-06-12',+ egress: 9086498661,+ egress_database: 7866207720,+ egress_auth: 389609413,+ egress_storage: 402935419,+ egress_realtime: 427746109,+ },+ {+ period_start: '2023-06-13',+ egress: 10121072311,+ egress_database: 9003849634,+ egress_auth: 234444930,+ egress_storage: 498282627,+ egress_realtime: 384495120,+ },+ {+ period_start: '2023-06-14',+ egress: 10137754419,+ egress_database: 9236420539,+ egress_auth: 244698555,+ egress_storage: 184916493,+ egress_realtime: 471718832,+ },+ {+ period_start: '2023-06-15',+ egress: 9388496424,+ egress_database: 8444365130,+ egress_auth: 375347308,+ egress_storage: 157868811,+ egress_realtime: 410915175,+ },+ {+ period_start: '2023-06-16',+ egress: 10115543729,+ egress_database: 9127516223,+ egress_auth: 284643497,+ egress_storage: 415070455,+ egress_realtime: 288313554,+ },{- id: '1',- loopId: '1',- period_start: '2023-06-29T07:05:12Z',- periodStartFormatted: '29 Jun 2023',- total_storage_egress: (1.53 * GB).toString(),- total_egress_modified: (1.12 * GB).toString(),+ period_start: '2023-06-17',+ egress: 6269152878,+ egress_database: 5190467136,+ egress_auth: 479372335,+ egress_storage: 262200598,+ egress_realtime: 337112809,},{- id: '2',- loopId: '2',- period_start: '2023-06-30T07:05:12Z',- periodStartFormatted: '30 Jun 2023',- total_storage_egress: (1 * GB).toString(),- total_egress_modified: (1.1 * GB).toString(),+ period_start: '2023-06-18',+ egress: 8140229692,+ egress_database: 7068203737,+ egress_auth: 371277477,+ egress_storage: 281662911,+ egress_realtime: 419085567,},{- id: '3',- loopId: '3',- period_start: '2023-07-01T07:05:12Z',- periodStartFormatted: '01 Jul 2023',- total_storage_egress: (1 * GB).toString(),- total_egress_modified: (1.2 * GB).toString(),+ period_start: '2023-06-19',+ egress: 9962259043,+ egress_database: 8764804798,+ egress_auth: 459538891,+ egress_storage: 443083594,+ egress_realtime: 294831760,},{- id: '4',- loopId: '4',- period_start: '2023-07-02T07:05:12Z',- periodStartFormatted: '02 Jul 2023',- total_storage_egress: (1 * GB).toString(),- total_egress_modified: (1.5 * GB).toString(),+ period_start: '2023-06-20',+ egress: 6781133823,+ egress_database: 6100566484,+ egress_auth: 234685038,+ egress_storage: 216755352,+ egress_realtime: 229126949,},{- id: '5',- loopId: '5',- period_start: '2023-07-03T07:05:12Z',- periodStartFormatted: '03 Jul 2023',- total_storage_egress: (1 * GB).toString(),- total_egress_modified: (2 * GB).toString(),+ period_start: '2023-06-21',+ egress: 10907104106,+ egress_database: 9828947491,+ egress_auth: 242570435,+ egress_storage: 387368954,+ egress_realtime: 448217226,},{- id: '6',- loopId: '6',- period_start: '2023-07-04T07:05:12Z',- periodStartFormatted: '04 Jul 2023',- total_storage_egress: (1 * GB).toString(),- total_egress_modified: (3 * GB).toString(),+ period_start: '2023-06-22',+ egress: 7074396542,+ egress_database: 6144364141,+ egress_auth: 436239765,+ egress_storage: 231784945,+ egress_realtime: 262007691,},{- id: '7',- loopId: '7',- period_start: '2023-07-05T07:05:12Z',- periodStartFormatted: '05 Jul 2023',- total_storage_egress: (1 * GB).toString(),- total_egress_modified: (4.5 * GB).toString(),+ period_start: '2023-06-23',+ egress: 7464749639,+ egress_database: 6594269898,+ egress_auth: 263127587,+ egress_storage: 272203780,+ egress_realtime: 335148374,},{- id: '8',- loopId: '8',- period_start: '2023-07-06T07:05:12Z',- periodStartFormatted: '06 Jul 2023',- total_storage_egress: (1 * GB).toString(),- total_egress_modified: (4 * GB).toString(),+ period_start: '2023-06-24',+ egress: 9288513914,+ egress_database: 8401011152,+ egress_auth: 362579381,+ egress_storage: 167061172,+ egress_realtime: 357862209,},{- id: '9',- loopId: '9',- period_start: '2023-07-07T07:05:12Z',- periodStartFormatted: '07 Jul 2023',- total_storage_egress: (1 * GB).toString(),- total_egress_modified: (3.8 * GB).toString(),+ period_start: '2023-06-25',+ egress: 7361708068,+ egress_database: 6415122839,+ egress_auth: 234278289,+ egress_storage: 466094668,+ egress_realtime: 246212272,},{- id: '10',- loopId: '10',- period_start: '2023-07-08T07:05:12Z',- periodStartFormatted: '08 Jul 2023',- total_storage_egress: (1 * GB).toString(),- total_egress_modified: (3.5 * GB).toString(),+ period_start: '2023-06-26',+ egress: 6789453179,+ egress_database: 5618461937,+ egress_auth: 479805982,+ egress_storage: 301891269,+ egress_realtime: 389293991,},]export interface BandwidthProps {orgSlug: string- projectRef: string // [Joshen TODO] RemovestartDate: string | undefinedendDate: string | undefinedsubscription: ProjectSubscriptionResponse | undefined@@ -100,35 +227,33 @@ export interface BandwidthProps {// [Joshen TODO] Needs to take in org slug and eventually use daily stats org queryconst Bandwidth = ({orgSlug,- projectRef,subscription,startDate,endDate,currentBillingCycleSelected,}: BandwidthProps) => {- // const { data: dbEgressData, isLoading: isLoadingDbEgressData } = useOrgDailyStatsQuery({- // orgSlug,- // metric: PricingMetric.EGRESS,- // interval: '1d',- // startDate,- // endDate,- // })+ const { data: egressData, isLoading: isLoadingDbEgressData } = useOrgDailyStatsQuery({+ orgSlug,+ metric: PricingMetric.EGRESS,+ interval: '1d',+ startDate,+ endDate,+ })const chartMeta: {[key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }} = {- db_egress: {- data: MOCK_DATA, // dbEgressData?.data ?? [],+ [PricingMetric.EGRESS]: {+ data: MOCK_DATA_2, // egressData?.data ?? [],margin: 16,- isLoading: false, // isLoadingDbEgressData,- hasNoData: false, // dbEgressData?.hasNoData ?? false,+ isLoading: isLoadingDbEgressData,+ hasNoData: egressData?.hasNoData ?? false,},}return (<UsageSectionorgSlug={orgSlug}- projectRef={projectRef}categoryKey="bandwidth"chartMeta={chartMeta}subscription={subscription}diff --git a/studio/components/interfaces/Organization/Usage/SectionHeader.tsx b/studio/components/interfaces/Organization/Usage/SectionHeader.tsxindex 3f453ece07d..0b7a5c43bb7 100644--- a/studio/components/interfaces/Organization/Usage/SectionHeader.tsx+++ b/studio/components/interfaces/Organization/Usage/SectionHeader.tsx@@ -5,7 +5,7 @@ export interface SectionHeaderProps {const SectionHeader = ({ title, description }: SectionHeaderProps) => {return (- <div className="mx-auto flex flex-col gap-10 py-16">+ <div className="mx-auto flex flex-col gap-10 py-14"><div><p className="text-xl">{title}</p><p className="text-sm text-scale-1000">{description}</p>diff --git a/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsx b/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsxindex 8932b0bbe8f..10aaa9c60b9 100644--- a/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsx+++ b/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsx@@ -1,14 +1,13 @@-import { useDailyStatsQuery } from 'data/analytics/daily-stats-query'import { DataPoint } from 'data/analytics/constants'-import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'-import UsageSection from './UsageSection'import { PricingMetric, useOrgDailyStatsQuery } from 'data/analytics/org-daily-stats-query'+import { OrgSubscription } from 'data/subscriptions/org-subscription-query'+import UsageSection from './UsageSection'export interface SizeAndCountsProps {orgSlug: stringstartDate: string | undefinedendDate: string | undefined- subscription: ProjectSubscriptionResponse | undefined+ subscription: OrgSubscription | undefinedcurrentBillingCycleSelected: boolean}@@ -46,19 +45,19 @@ const SizeAndCounts = ({const chartMeta: {[key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }} = {- db_size: {+ [PricingMetric.DATABASE_SIZE]: {isLoading: isLoadingDbSizeData,margin: 14,data: dbSizeData?.data ?? [],hasNoData: dbSizeData?.hasNoData ?? false,},- storage_size: {+ [PricingMetric.STORAGE_SIZE]: {isLoading: isLoadingStorageSizeData,margin: 14,data: storageSizeData?.data ?? [],hasNoData: storageSizeData?.hasNoData ?? false,},- func_count: {+ [PricingMetric.FUNCTION_COUNT]: {isLoading: isLoadingFunctionCountData,margin: 0,data: functionCountData?.data ?? [],diff --git a/studio/components/interfaces/Organization/Usage/Usage.constants.tsx b/studio/components/interfaces/Organization/Usage/Usage.constants.tsxindex 69268f3d829..8f03f3ed833 100644--- a/studio/components/interfaces/Organization/Usage/Usage.constants.tsx+++ b/studio/components/interfaces/Organization/Usage/Usage.constants.tsx@@ -1,14 +1,14 @@-import Link from 'next/link'-import { USAGE_APPROACHING_THRESHOLD } from 'components/interfaces/BillingV2/Billing.constants'-import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'-import { ProjectUsageData } from 'data/usage/project-usage-query'-import { Alert, Badge, Button, IconExternalLink } from 'ui'+import { EgressType, PricingMetric } from 'data/analytics/org-daily-stats-query'+import { OrgUsageResponse } from 'data/usage/org-usage-query'+import { Alert } from 'ui'export const COLOR_MAP = {white: { bar: 'fill-scale-1200', marker: 'bg-scale-1200' },green: { bar: 'fill-green-1000', marker: 'bg-green-1000' },blue: { bar: 'fill-blue-1000', marker: 'bg-blue-1000' },+ yellow: { bar: 'fill-amber-1000', marker: 'bg-amber-1000' },+ orange: { bar: 'fill-orange-1000', marker: 'bg-orange-1000' },}export const Y_DOMAIN_CEILING_MULTIPLIER = 4 / 3@@ -22,26 +22,22 @@ export const USAGE_STATUS = {export interface Attribute {key: stringname?: string- color: 'white' | 'blue' | 'green'+ color: 'white' | 'blue' | 'green' | 'yellow' | 'orange'}export interface CategoryAttribute {anchor: string- key: string // Property from project usage+ key: string // Property from organization usageattributes: Attribute[] // For querying against stats-daily / infra-monitoringname: string- chartPrefix?: stringunit: 'bytes' | 'absolute' | 'percentage'links?: {name: stringurl: string}[]description: string+ chartPrefix?: 'Max' | 'Average'chartDescription: string- additionalInfo?: (- slug: string,- subscription?: ProjectSubscriptionResponse,- usage?: ProjectUsageData- ) => JSX.Element | null+ additionalInfo?: (usage?: OrgUsageResponse) => JSX.Element | null}export type CategoryMetaKey = 'bandwidth' | 'sizeCount' | 'activity'@@ -53,7 +49,6 @@ export interface CategoryMeta {attributes: CategoryAttribute[]}-// [Joshen TODO] We need to update thisexport const USAGE_CATEGORIES: CategoryMeta[] = [{key: 'bandwidth',@@ -62,10 +57,12 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [attributes: [{anchor: 'dbEgress',- key: 'db_egress', // This needs to be updated based on the new org usage endpoint+ key: PricingMetric.EGRESS,attributes: [- { key: 'total_egress_modified', name: 'DB Egress', color: 'green' },- { key: 'total_storage_egress', name: 'Storage Egress', color: 'blue' },+ { key: EgressType.AUTH, name: 'Auth Egress', color: 'yellow' },+ { key: EgressType.DATABASE, name: 'Database Egress', color: 'green' },+ { key: EgressType.STORAGE, name: 'Storage Egress', color: 'blue' },+ { key: EgressType.REALTIME, name: 'Realtime Egress', color: 'orange' },],name: 'Total Egress',unit: 'bytes',@@ -82,10 +79,10 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [attributes: [{anchor: 'dbSize',- key: 'db_size',- attributes: [{ key: 'total_db_size_bytes', color: 'white' }],+ key: PricingMetric.DATABASE_SIZE,+ attributes: [{ key: PricingMetric.DATABASE_SIZE, color: 'white' }],name: 'Database size',- chartPrefix: 'Average ',+ chartPrefix: 'Average',unit: 'bytes',description:'Database size refers to the monthly average storage usage, as reported by Postgres. Paid plans use auto-scaling disks.\nBilling is based on the average daily database size used in GB throughout the billing period. Billing is independent of the provisioned disk size.',@@ -96,49 +93,18 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [},],chartDescription: 'The data refreshes every 24 hours.',- additionalInfo: (- ref: string,- subscription?: ProjectSubscriptionResponse,- usage?: ProjectUsageData- ) => {- const usageMeta = usage?.['db_size'] ?? undefined+ additionalInfo: (usage?: OrgUsageResponse) => {+ const usageMeta = usage?.usages.find((x) => x.metric === PricingMetric.DATABASE_SIZE)const usageRatio =- typeof usageMeta !== 'number' ? (usageMeta?.usage ?? 0) / (usageMeta?.limit ?? 0) : 0- const hasLimit = usageMeta && usageMeta.limit > 0+ typeof usageMeta !== 'number'+ ? (usageMeta?.usage ?? 0) / (usageMeta?.pricing_free_units ?? 0)+ : 0+ const hasLimit = usageMeta && (usageMeta?.pricing_free_units ?? 0) > 0const isApproachingLimit = hasLimit && usageRatio >= USAGE_APPROACHING_THRESHOLDconst isExceededLimit = hasLimit && usageRatio >= 1- return subscription?.plan?.id !== 'free' ? (- <div>- <div className="flex items-center justify-between">- <div className="flex items-center space-x-2">- <p className="text-sm">Disk size:</p>- <p className="text-sm">{usage?.disk_volume_size_gb} GB</p>- <Badge color="green" size="small">- Auto-scaling- </Badge>- </div>- <Link href="https://supabase.com/docs/guides/platform/database-usage#disk-management">- <a>- <Button size="tiny" type="default" icon={<IconExternalLink size={14} />}>- What is disk size?- </Button>- </a>- </Link>- </div>- <p className="text-sm text-scale-1000 mt-3">- If you reach 95% of the disk space, your project will enter read-only mode. Your- disk storage expands automatically when the database reaches 90% of the disk size.- The disk is expanded to be 50% larger. Auto-scaling can only take place once every 6- hours. You can also{' '}- <Link passHref href={`/project/${ref}/settings/database#diskManagement`}>- <a className="text-brand-900 transition hover:text-brand-1000">preprovision</a>- </Link>{' '}- disk for loading larger amounts of data.- </p>- </div>- ) : (+ return (<div>{(isApproachingLimit || isExceededLimit) && (<Alert@@ -164,10 +130,10 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [},{anchor: 'storageSize',- key: 'storage_size',- attributes: [{ key: 'total_storage_size_bytes', color: 'white' }],+ key: PricingMetric.STORAGE_SIZE,+ attributes: [{ key: PricingMetric.STORAGE_SIZE, color: 'white' }],name: 'Storage Size',- chartPrefix: 'Max ',+ chartPrefix: 'Max',unit: 'bytes',description:'Sum of all objects in your storage buckets.\nBilling is based on the average daily size in GB throughout your billing period.',@@ -181,10 +147,10 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [},{anchor: 'funcCount',- key: 'func_count',- attributes: [{ key: 'total_func_count', color: 'white' }],+ key: PricingMetric.FUNCTION_COUNT,+ attributes: [{ key: PricingMetric.FUNCTION_COUNT, color: 'white' }],name: 'Edge Function Count',- chartPrefix: 'Max ',+ chartPrefix: 'Max',unit: 'absolute',description:'Number of serverless functions in your project.\nBilling is based on the maximum amount of functions at any point in time throughout your billing period.',@@ -199,8 +165,8 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [attributes: [{anchor: 'mau',- key: 'monthly_active_users',- attributes: [{ key: 'total_auth_billing_period_mau', color: 'white' }],+ key: PricingMetric.MONTHLY_ACTIVE_USERS,+ attributes: [{ key: PricingMetric.MONTHLY_ACTIVE_USERS, color: 'white' }],name: 'Monthly Active Users',unit: 'absolute',description:@@ -216,8 +182,8 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [},{anchor: 'mauSso',- key: 'monthly_active_sso_users',- attributes: [{ key: 'total_auth_billing_period_sso_mau', color: 'white' }],+ key: PricingMetric.MONTHLY_ACTIVE_SSO_USERS,+ attributes: [{ key: PricingMetric.MONTHLY_ACTIVE_SSO_USERS, color: 'white' }],name: 'Monthly Active SSO Users',unit: 'absolute',description:@@ -233,8 +199,8 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [},{anchor: 'storageImageTransformations',- key: 'storage_image_render_count',- attributes: [{ key: 'total_storage_image_render_count', color: 'white' }],+ key: PricingMetric.STORAGE_IMAGES_TRANSFORMED,+ attributes: [{ key: PricingMetric.STORAGE_IMAGES_TRANSFORMED, color: 'white' }],name: 'Storage Image Transformations',unit: 'absolute',description:@@ -250,8 +216,8 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [},{anchor: 'functionInvocations',- key: 'func_invocations',- attributes: [{ key: 'total_func_invocations', color: 'white' }],+ key: PricingMetric.FUNCTION_INVOCATIONS,+ attributes: [{ key: PricingMetric.FUNCTION_INVOCATIONS, color: 'white' }],name: 'Edge Function Invocations',unit: 'absolute',description:@@ -266,8 +232,8 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [},{anchor: 'realtimeMessageCount',- key: 'realtime_message_count',- attributes: [{ key: 'total_realtime_message_count', color: 'white' }],+ key: PricingMetric.REALTIME_MESSAGE_COUNT,+ attributes: [{ key: PricingMetric.REALTIME_MESSAGE_COUNT, color: 'white' }],name: 'Realtime Message Count',unit: 'absolute',description:@@ -282,10 +248,10 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [},{anchor: 'realtimePeakConnection',- key: 'realtime_peak_connection',- attributes: [{ key: 'total_realtime_peak_connection', color: 'white' }],+ key: PricingMetric.REALTIME_PEAK_CONNECTIONS,+ attributes: [{ key: PricingMetric.REALTIME_PEAK_CONNECTIONS, color: 'white' }],name: 'Realtime Peak Connections',- chartPrefix: 'Max ',+ chartPrefix: 'Max',unit: 'absolute',description:'Total number of successful connections. Connections attempts are not counted towards usage.\nBilling is based on the maximum amount of concurrent peak connections throughout your billing period.',diff --git a/studio/components/interfaces/Organization/Usage/Usage.tsx b/studio/components/interfaces/Organization/Usage/Usage.tsxindex 9b333974260..e823c33df35 100644--- a/studio/components/interfaces/Organization/Usage/Usage.tsx+++ b/studio/components/interfaces/Organization/Usage/Usage.tsx@@ -3,15 +3,15 @@ import dayjs from 'dayjs'import { useMemo, useState } from 'react'import { useParams } from 'common'-import Bandwidth from './Bandwidth'-import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'+import { ScaffoldContainer, ScaffoldDivider } from 'components/layouts/Scaffold'import DateRangePicker from 'components/to-be-cleaned/DateRangePicker'+import AlertError from 'components/ui/AlertError'+import ShimmeringLoader from 'components/ui/ShimmeringLoader'+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'import { TIME_PERIODS_BILLING, TIME_PERIODS_REPORTS } from 'lib/constants'-import SizeAndCounts from './SizeAndCounts'import Activity from './Activity'-import { IconLoader } from 'ui'-import { useOrgUsageQuery } from 'data/usage/org-usage-query'-import { ScaffoldContainer, ScaffoldDivider, ScaffoldSection } from 'components/layouts/Scaffold'+import Bandwidth from './Bandwidth'+import SizeAndCounts from './SizeAndCounts'const Usage = () => {const { slug } = useParams()@@ -19,14 +19,12 @@ const Usage = () => {const {data: subscription,+ error: subscriptionError,isLoading: isLoadingSubscription,- isError,- isSuccess,+ isError: isErrorSubscription,+ isSuccess: isSuccessSubscription,} = useOrgSubscriptionQuery({ orgSlug: slug })- // const { data: usage, isLoading: isLoadingUsage } = useOrgUsageQuery({ orgSlug: slug })- // console.log({ usage })- const selectedProjectRef = 'kojplftaeiavuneadgix'const billingCycleStart = dayjs.unix(subscription?.current_period_start ?? 0).utc()const billingCycleEnd = dayjs.unix(subscription?.current_period_end ?? 0).utc()@@ -71,31 +69,39 @@ const Usage = () => {<><ScaffoldContainer><div className="py-4 flex items-center space-x-4">- {!isLoadingSubscription && (- <DateRangePicker- id="billingCycle"- name="billingCycle"- onChange={setDateRange}- value={TIME_PERIODS_BILLING[0].key}- options={[...TIME_PERIODS_BILLING, ...TIME_PERIODS_REPORTS]}- loading={isLoadingSubscription}- currentBillingPeriodStart={subscription?.current_period_start}- className="!w-[200px]"+ {isLoadingSubscription && <ShimmeringLoader className="w-[250px]" />}++ {isErrorSubscription && (+ <AlertError+ className="w-full"+ subject="Unable to retrieve usage data"+ error={subscriptionError}/>)}- {isLoadingSubscription ? (- <IconLoader className="animate-spin" size={14} />- ) : subscription !== undefined ? (- <div className="flex flex-col xl:flex-row xl:gap-3">- <p className={clsx('text-sm transition', isLoadingSubscription && 'opacity-50')}>- Organization is on the {subscription.plan.name} plan- </p>- <p className="text-sm text-scale-1000">- {billingCycleStart.format('DD MMM YYYY')} - {billingCycleEnd.format('DD MMM YYYY')}- </p>- </div>- ) : null}+ {isSuccessSubscription && (+ <>+ <DateRangePicker+ id="billingCycle"+ name="billingCycle"+ onChange={setDateRange}+ value={TIME_PERIODS_BILLING[0].key}+ options={[...TIME_PERIODS_BILLING, ...TIME_PERIODS_REPORTS]}+ loading={isLoadingSubscription}+ currentBillingPeriodStart={subscription?.current_period_start}+ className="!w-[200px]"+ />+ <div className="flex flex-col xl:flex-row xl:gap-3">+ <p className={clsx('text-sm transition', isLoadingSubscription && 'opacity-50')}>+ Organization is on the {subscription.plan.name} plan+ </p>+ <p className="text-sm text-scale-1000">+ {billingCycleStart.format('DD MMM YYYY')} -{' '}+ {billingCycleEnd.format('DD MMM YYYY')}+ </p>+ </div>+ </>+ )}</div></ScaffoldContainer>@@ -103,7 +109,6 @@ const Usage = () => {<BandwidthorgSlug={slug as string}- projectRef={selectedProjectRef}subscription={subscription}startDate={startDate}endDate={endDate}@@ -117,6 +122,7 @@ const Usage = () => {endDate={endDate}currentBillingCycleSelected={currentBillingCycleSelected}/>+<ActivityorgSlug={slug as string}subscription={subscription}diff --git a/studio/components/interfaces/Organization/Usage/Usage.utils.ts b/studio/components/interfaces/Organization/Usage/Usage.utils.tsindex 6bc5eb09712..8ec8d3d9f8e 100644--- a/studio/components/interfaces/Organization/Usage/Usage.utils.ts+++ b/studio/components/interfaces/Organization/Usage/Usage.utils.ts@@ -34,14 +34,14 @@ export const getUsageStatus = (attributes: CategoryAttribute[], usage?: ProjectUelse return USAGE_STATUS.NORMAL}-export const getUpgradeUrl = (projectRef: string, subscription?: ProjectSubscriptionResponse) => {+export const getUpgradeUrl = (slug: string, subscription?: ProjectSubscriptionResponse) => {if (!subscription) {- return `/project/${projectRef}/settings/billing/subscription`+ return `/org/${slug}/billing`}return subscription?.plan?.id === 'pro' && subscription?.usage_billing_enabled === false- ? `/project/${projectRef}/settings/billing/subscription#cost-control`- : `/project/${projectRef}/settings/billing/subscription?panel=subscriptionPlan`+ ? `/org/${slug}/billing#cost-control`+ : `/org/${slug}/billing?panel=subscriptionPlan`}const compactNumberFormatter = new Intl.NumberFormat('en-US', {diff --git a/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx b/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsxindex 3bddb5f962e..0c69d6a91ba 100644--- a/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx+++ b/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx@@ -63,11 +63,11 @@ export const MultiAttributeTooltipContent = ({<divclassName={clsx('w-3 h-3 rounded-full border', COLOR_MAP[attr.color].marker)}/>- <p className="text-sm prose">+ <p className="text-xs prose">{attr.name} ({percentageContribution}%):{' '}</p></div>- <p className="text-sm tabular-nums">+ <p className="text-xs tabular-nums">{tooltipFormatter !== undefined ? tooltipFormatter(attrValue) : attrValue}</p></div>diff --git a/studio/components/interfaces/Organization/Usage/UsageSection.tsx b/studio/components/interfaces/Organization/Usage/UsageSection.tsxindex 1c623761d23..817ca264286 100644--- a/studio/components/interfaces/Organization/Usage/UsageSection.tsx+++ b/studio/components/interfaces/Organization/Usage/UsageSection.tsx@@ -3,17 +3,13 @@ import clsx from 'clsx'import Link from 'next/link'import { USAGE_APPROACHING_THRESHOLD } from 'components/interfaces/BillingV2/Billing.constants'+import { ScaffoldContainer, ScaffoldDivider } from 'components/layouts/Scaffold'import Panel from 'components/ui/Panel'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import SparkBar from 'components/ui/SparkBar'import { DataPoint } from 'data/analytics/constants'-import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'-import {- ProjectUsageResponse,- UsageMetric,- useProjectUsageQuery,-} from 'data/usage/project-usage-query'-import { formatBytes } from 'lib/helpers'+import { OrgSubscription } from 'data/subscriptions/org-subscription-query'+import { useOrgUsageQuery } from 'data/usage/org-usage-query'import { Button, IconAlertTriangle, IconBarChart2 } from 'ui'import SectionContent from './SectionContent'import SectionHeader from './SectionHeader'@@ -24,37 +20,39 @@ import {getUpgradeUrl,} from './Usage.utils'import UsageBarChart from './UsageBarChart'-import { ScaffoldContainer, ScaffoldDivider } from 'components/layouts/Scaffold'+import AlertError from 'components/ui/AlertError'interface UsageSectionProps {orgSlug: string- projectRef?: string // [Joshen TODO] removecategoryKey: CategoryMetaKey- subscription: ProjectSubscriptionResponse | undefined+ subscription: OrgSubscription | undefinedchartMeta: {[key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }}currentBillingCycleSelected: boolean}-// [Joshen TODO] Needs to change to use org slug, and eventually call useOrganizationUsageQueryconst UsageSection = ({orgSlug,- projectRef,categoryKey,chartMeta,subscription,currentBillingCycleSelected,}: UsageSectionProps) => {- const { data: usage } = useProjectUsageQuery({ projectRef })- const categoryMeta = USAGE_CATEGORIES.find((category) => category.key === categoryKey)+ const {+ data: usage,+ error: usageError,+ isLoading: isLoadingUsage,+ isError: isErrorUsage,+ isSuccess: isSuccessUsage,+ } = useOrgUsageQuery({ orgSlug })+ const categoryMeta = USAGE_CATEGORIES.find((category) => category.key === categoryKey)if (!categoryMeta) return nullconst usageBasedBilling = subscription?.usage_billing_enabledconst exceededLimitStyle = !usageBasedBilling ? 'text-red-900' : 'text-amber-900'-- const upgradeUrl = getUpgradeUrl(projectRef ?? '', subscription)+ const upgradeUrl = getUpgradeUrl(orgSlug ?? '', subscription)return (<>@@ -65,224 +63,237 @@ const UsageSection = ({<ScaffoldDivider />{categoryMeta.attributes.map((attribute) => {- const usageMeta = usage?.[attribute.key as keyof ProjectUsageResponse] as UsageMetric- const usageRatio =- typeof usageMeta !== 'number' ? (usageMeta?.usage ?? 0) / (usageMeta?.limit ?? 0) : 0- const usageExcess = (usageMeta?.usage ?? 0) - (usageMeta?.limit ?? 0)+ const usageMeta = usage?.usages.find((x) => x.metric === attribute.key)+ const usageRatio = (usageMeta?.usage ?? 0) / (usageMeta?.pricing_free_units ?? 0)+ const usageExcess = (usageMeta?.usage ?? 0) - (usageMeta?.pricing_free_units ?? 0)const chartData = chartMeta[attribute.key]?.data ?? []-const notAllValuesZero =attribute.attributes?.map((attr) => {return chartData.some((dataPoint) => Number(dataPoint[attr.key]) !== 0)}).some((x) => !!x) ?? false+ const showUsageWarning =+ currentBillingCycleSelected &&+ usageBasedBilling === false &&+ usageRatio >= USAGE_APPROACHING_THRESHOLDreturn (<div id={attribute.anchor} key={attribute.key}><SectionContent section={attribute}>- {usageMeta?.available_in_plan ? (+ {isLoadingUsage && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ )}++ {isErrorUsage && <AlertError subject="Unable to retrieve usage" error={usageError} />}++ {isSuccessUsage && (<>- <div className="space-y-2">- <div className="flex items-center justify-between">- <div className="flex items-center space-x-4">- <p className="text-sm">{attribute.name} usage</p>- {currentBillingCycleSelected &&- usageBasedBilling === false &&- usageRatio >= USAGE_APPROACHING_THRESHOLD && (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- {!usageBasedBilling && usageRatio >= 1 ? (- <div className="flex items-center space-x-2 min-w-[115px] cursor-help">- <IconAlertTriangle- size={14}- strokeWidth={2}- className={exceededLimitStyle}- />- <p className={`text-sm ${exceededLimitStyle}`}>- Exceeded limit- </p>- </div>- ) : (- !usageBasedBilling &&- usageRatio >= USAGE_APPROACHING_THRESHOLD && (+ {usageMeta?.available_in_plan ? (+ <>+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <div className="flex items-center space-x-4">+ <p className="text-sm">{attribute.name} usage</p>+ {showUsageWarning && (+ <Tooltip.Root delayDuration={0}>+ <Tooltip.Trigger asChild>+ {usageRatio >= 1 ? (<div className="flex items-center space-x-2 min-w-[115px] cursor-help"><IconAlertTrianglesize={14}strokeWidth={2}- className="text-amber-900"+ className={exceededLimitStyle}/>- <p className="text-sm text-amber-900">Approaching limit</p>+ <p className={`text-sm ${exceededLimitStyle}`}>+ Exceeded limit+ </p></div>- )- )}- </Tooltip.Trigger>- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-scale-100 py-1 px-2 leading-none shadow',- 'border border-scale-200',- ].join(' ')}- >- <p className="text-xs text-scale-1200">- Exceeding your plans included usage will lead to restrictions- to your project.- </p>- <p className="text-xs text-scale-1200">- Upgrade to a usage-based plan or disable the spend cap to- avoid restrictions.- </p>- </div>- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Root>+ ) : (+ usageRatio >= USAGE_APPROACHING_THRESHOLD && (+ <div className="flex items-center space-x-2 min-w-[115px] cursor-help">+ <IconAlertTriangle+ size={14}+ strokeWidth={2}+ className="text-amber-900"+ />+ <p className="text-sm text-amber-900">Approaching limit</p>+ </div>+ )+ )}+ </Tooltip.Trigger>+ <Tooltip.Portal>+ <Tooltip.Content side="bottom">+ <Tooltip.Arrow className="radix-tooltip-arrow" />+ <div+ className={[+ 'rounded bg-scale-100 py-1 px-2 leading-none shadow',+ 'border border-scale-200',+ ].join(' ')}+ >+ <p className="text-xs text-scale-1200">+ Exceeding your plans included usage will lead to+ restrictions to your project.+ </p>+ <p className="text-xs text-scale-1200">+ Upgrade to a usage-based plan or disable the spend cap to+ avoid restrictions.+ </p>+ </div>+ </Tooltip.Content>+ </Tooltip.Portal>+ </Tooltip.Root>+ )}+ </div>++ {showUsageWarning && (+ <Link href={upgradeUrl}>+ <a className="pb-1">+ <Button type="default" size="tiny">+ {subscription?.plan?.id === 'free'+ ? 'Upgrade plan'+ : 'Change spend cap'}+ </Button>+ </a>+ </Link>)}- </div>+ </div>- {currentBillingCycleSelected &&- !usageBasedBilling &&- usageRatio >= USAGE_APPROACHING_THRESHOLD && (- <Link href={upgradeUrl}>- <a className="pb-1">- <Button type="default" size="tiny">- {subscription?.plan?.id === 'free'- ? 'Upgrade plan'- : 'Change spend cap'}- </Button>- </a>- </Link>- )}- </div>- {currentBillingCycleSelected && usageMeta?.limit > 0 && (- <SparkBar- type="horizontal"- barClass={clsx(- usageRatio >= 1- ? usageBasedBilling- ? 'bg-scale-1100'- : 'bg-red-900'- : usageBasedBilling === false &&- usageRatio >= USAGE_APPROACHING_THRESHOLD- ? 'bg-amber-900'- : 'bg-scale-1100'+ {currentBillingCycleSelected && !usageMeta.unlimited && (+ <SparkBar+ type="horizontal"+ barClass={clsx(+ usageRatio >= 1+ ? usageBasedBilling+ ? 'bg-scale-1100'+ : 'bg-red-900'+ : usageBasedBilling === false &&+ usageRatio >= USAGE_APPROACHING_THRESHOLD+ ? 'bg-amber-900'+ : 'bg-scale-1100'+ )}+ bgClass="bg-gray-300 dark:bg-gray-600"+ value={usageMeta?.usage ?? 0}+ max={usageMeta?.pricing_free_units || 1}+ />)}- bgClass="bg-gray-300 dark:bg-gray-600"- value={usageMeta?.usage ?? 0}- max={usageMeta?.limit || 1}- />- )}- <div>- <div className="flex items-center justify-between border-b py-1">- <p className="text-xs text-scale-1000">- Included in {subscription?.plan?.name.toLowerCase()} plan++ <div>+ <div className="flex items-center justify-between border-b py-1">+ <p className="text-xs text-scale-1000">+ Included in {subscription?.plan?.name.toLowerCase()} plan+ </p>+ {usageMeta.unlimited ? (+ <p className="text-xs">Unlimited</p>+ ) : (+ <p className="text-xs">+ {attribute.unit === 'bytes'+ ? `${usageMeta.pricing_free_units ?? 0} GB`+ : (usageMeta.pricing_free_units ?? 0).toLocaleString()}+ </p>+ )}+ </div>+ {currentBillingCycleSelected && (+ <div className="flex items-center justify-between py-1">+ <p className="text-xs text-scale-1000">+ {attribute.chartPrefix || 'Used '} in period+ </p>+ <p className="text-xs">+ {attribute.unit === 'bytes'+ ? `${usageMeta?.usage ?? 0} GB`+ : (usageMeta?.usage ?? 0).toLocaleString()}+ </p>+ </div>+ )}+ {currentBillingCycleSelected &&+ (usageMeta?.pricing_free_units ?? 0) > 0 && (+ <div className="flex items-center justify-between border-t py-1">+ <p className="text-xs text-scale-1000">Overage in period</p>+ <p className="text-xs">+ {(usageMeta?.pricing_free_units ?? 0) === -1 || usageExcess < 0+ ? `0${attribute.unit === 'bytes' ? ' GB' : ''}`+ : attribute.unit === 'bytes'+ ? `${usageExcess} GB`+ : usageExcess.toLocaleString()}+ </p>+ </div>+ )}+ </div>+ </div>++ {attribute.additionalInfo?.(usage)}++ <div className="space-y-1">+ <p className="text-sm">+ {attribute.chartPrefix || ''} {attribute.name} per day</p>- {usageMeta?.limit === -1 ? (- <p className="text-xs">None</p>- ) : usageMeta?.limit === 0 ? (- <p className="text-xs">Unlimited</p>- ) : (- <p className="text-xs">- {attribute.unit === 'bytes'- ? formatBytes(usageMeta?.limit ?? 0)- : (usageMeta?.limit ?? 0).toLocaleString()}+ {attribute.chartDescription.split('\n').map((paragraph, idx) => (+ <p key={`para-${idx}`} className="text-sm text-scale-1000">+ {paragraph}</p>- )}+ ))}</div>- {currentBillingCycleSelected && (- <div className="flex items-center justify-between py-1">- <p className="text-xs text-scale-1000">- {attribute.chartPrefix || 'Used '}in period- </p>- <p className="text-xs">- {attribute.unit === 'bytes'- ? formatBytes(usageMeta?.usage ?? 0)- : (usageMeta?.usage ?? 0).toLocaleString()}- </p>- </div>- )}- {currentBillingCycleSelected && usageMeta?.limit > 0 && (- <div className="flex items-center justify-between border-t py-1">- <p className="text-xs text-scale-1000">Overage in period</p>- <p className="text-xs">- {(usageMeta?.limit ?? 0) === -1 || usageExcess < 0- ? 0- : attribute.unit === 'bytes'- ? formatBytes(usageExcess)- : usageExcess.toLocaleString()}- </p>+ {chartMeta[attribute.key].isLoading ? (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" /></div>+ ) : chartData.length > 0 && notAllValuesZero ? (+ <UsageBarChart+ name={`${attribute.chartPrefix || ''}${attribute.name}`}+ unit={attribute.unit}+ attributes={attribute.attributes}+ data={chartData}+ yLeftMargin={chartMeta[attribute.key].margin}+ yFormatter={(value) =>+ ChartYFormatterCompactNumber(value, attribute.unit)+ }+ tooltipFormatter={(value) =>+ ChartTooltipValueFormatter(value, attribute.unit)+ }+ />+ ) : (+ <Panel>+ <Panel.Content>+ <div className="flex flex-col items-center justify-center">+ <IconBarChart2 className="text-scale-1100 mb-2" />+ <p className="text-sm">No data in period</p>+ <p className="text-sm text-scale-1000">+ May take up to 24 hours to show+ </p>+ </div>+ </Panel.Content>+ </Panel>)}- </div>- </div>-- {attribute.additionalInfo?.(projectRef ?? '', subscription, usage)}-- <div className="space-y-1">- <p>- {attribute.chartPrefix || ''}- {attribute.name} per day- </p>- {attribute.chartDescription.split('\n').map((paragraph, idx) => (- <p key={`para-${idx}`} className="text-sm text-scale-1000">- {paragraph}- </p>- ))}- </div>- {chartMeta[attribute.key].isLoading ? (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- ) : chartData.length > 0 && notAllValuesZero ? (- <UsageBarChart- name={`${attribute.chartPrefix || ''}${attribute.name}`}- unit={attribute.unit}- attributes={attribute.attributes}- data={chartData}- yLeftMargin={chartMeta[attribute.key].margin}- yFormatter={(value) => ChartYFormatterCompactNumber(value, attribute.unit)}- tooltipFormatter={(value) =>- ChartTooltipValueFormatter(value, attribute.unit)- }- />+ </>) : (<Panel><Panel.Content>- <div className="flex flex-col items-center justify-center">- <IconBarChart2 className="text-scale-1100 mb-2" />- <p className="text-sm">No data in period</p>- <p className="text-sm text-scale-1000">May take up to 24 hours to show</p>+ <div className="flex w-full items-center flex-col justify-center space-y-2 md:flex-row md:justify-between">+ <div className="space-y-1">+ <p className="text-sm">Not included in plan</p>+ <div>+ <p className="text-sm text-scale-1100">+ You need to be on a higher plan in order to use this feature.+ </p>+ </div>+ </div>+ <Link href={`/org/${orgSlug}/billing?panel=subscriptionPlan`}>+ <a>+ <Button type="primary">Upgrade plan</Button>+ </a>+ </Link></div></Panel.Content></Panel>)}</>- ) : (- <Panel>- <Panel.Content>- <div className="flex w-full items-center flex-col justify-center space-y-2 md:flex-row md:justify-between">- <div className="space-y-1">- <p className="text-sm">Not included in plan</p>- <div>- <p className="text-sm text-scale-1100">- You need to be on a higher plan in order to use this feature.- </p>- </div>- </div>- <Link- href={`/project/${projectRef}/settings/billing/subscription?panel=subscriptionPlan`}- >- <a>- <Button type="primary">Upgrade plan</Button>- </a>- </Link>- </div>- </Panel.Content>- </Panel>)}</SectionContent></div>diff --git a/studio/data/analytics/constants.ts b/studio/data/analytics/constants.tsindex c559cef9d87..2ae4371e2fe 100644--- a/studio/data/analytics/constants.ts+++ b/studio/data/analytics/constants.ts@@ -1,11 +1,11 @@export type DataPoint = {id?: string- loopId: number | string+ loopId?: number | stringperiod_start: stringperiodStartFormatted?: string} & {// Attribute name will be the key- [key: string]: string+ [key: string]: string | number}export interface AnalyticsData {diff --git a/studio/data/analytics/org-daily-stats-query.ts b/studio/data/analytics/org-daily-stats-query.tsindex 319eb0e6d9f..0e08bd6fdd6 100644--- a/studio/data/analytics/org-daily-stats-query.ts+++ b/studio/data/analytics/org-daily-stats-query.ts@@ -6,6 +6,14 @@ import { useCallback } from 'react'import { AnalyticsData } from './constants'import { analyticsKeys } from './keys'+export enum EgressType {+ DATABASE = 'egress_database',+ AUTH = 'egress_auth',+ STORAGE = 'egress_storage',+ REALTIME = 'egress_realtime',+ UNIFIED = 'egress',+}+// [Joshen] Get this from common package instead of API and dashboard having one copy eachexport enum PricingMetric {EGRESS = 'EGRESS',@@ -20,7 +28,9 @@ export enum PricingMetric {STORAGE_IMAGES_TRANSFORMED = 'STORAGE_IMAGES_TRANSFORMED',REALTIME_MESSAGE_COUNT = 'REALTIME_MESSAGE_COUNT',REALTIME_PEAK_CONNECTIONS = 'REALTIME_PEAK_CONNECTIONS',+}+export enum ComputeUsageMetric {COMPUTE_HOURS_XS = 'COMPUTE_HOURS_XS',COMPUTE_HOURS_SM = 'COMPUTE_HOURS_SM',COMPUTE_HOURS_MD = 'COMPUTE_HOURS_MD',diff --git a/studio/data/subscriptions/org-subscription-query.ts b/studio/data/subscriptions/org-subscription-query.tsindex 8b3d6c9ccb8..1705bff47f5 100644--- a/studio/data/subscriptions/org-subscription-query.ts+++ b/studio/data/subscriptions/org-subscription-query.ts@@ -11,7 +11,7 @@ export type OrgSubscriptionVariables = {export type PlanId = 'free' | 'pro' | 'team' | 'enterprise'-export type OrgSubscriptionResponse = {+export type OrgSubscription = {billing_cycle_anchor: numbercurrent_period_start: numbercurrent_period_end: number@@ -56,7 +56,7 @@ export async function getOrgSubscription(const response = await get(`${API_URL}/organizations/${orgSlug}/billing/subscription`, { signal })if (response.error) throw response.error- return response as OrgSubscriptionResponse+ return response as OrgSubscription}export type OrgSubscriptionData = Awaited<ReturnType<typeof getOrgSubscription>>@@ -87,5 +87,6 @@ export const useOrgSubscriptionPrefetch = ({ orgSlug }: OrgSubscriptionVariablesgetOrgSubscription({ orgSlug }, signal))}+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [orgSlug])}diff --git a/studio/data/usage/org-usage-query.ts b/studio/data/usage/org-usage-query.tsindex 1465de4f9c1..15c8a8cc57f 100644--- a/studio/data/usage/org-usage-query.ts+++ b/studio/data/usage/org-usage-query.ts@@ -3,39 +3,36 @@ import { get } from 'lib/common/fetch'import { API_URL } from 'lib/constants'import { useCallback } from 'react'import { usageKeys } from './keys'+import { ResponseError } from 'types'+import { PricingMetric } from 'data/analytics/org-daily-stats-query'export type OrgUsageVariables = {orgSlug?: string}export interface UsageMetric {- usage: number- limit: number- cost: number+ /** Determines if the metric is available based on the plan */available_in_plan: boolean- // [Joshen] can we verify if this is still getting passed?- // Only for database and storage size- current?: number+ cost: number+ metric: PricingMetric+ unlimited: boolean+ /** Determines if over-usage is allowed or not */+ capped: boolean+ /** Refers to the included quota, in GB by default for bytes */+ pricing_free_units?: number+ pricing_package_price?: number+ pricing_package_size?: number+ pricing_per_unit_price?: number+ pricing_strategy: 'UNIT' | 'PACKAGE' | 'NONE'+ usage: number}-// [Joshen TODO] Go update thisexport type OrgUsageResponse = {- db_size: UsageMetric- db_egress: UsageMetric- storage_size: UsageMetric- storage_egress: UsageMetric- storage_image_render_count: UsageMetric- monthly_active_users: UsageMetric- monthly_active_sso_users: UsageMetric- realtime_message_count: UsageMetric- realtime_peak_connection: UsageMetric- func_count: UsageMetric- func_invocations: UsageMetric- disk_volume_size_gb: number+ slugs: string[]+ usage_billing_enabled: boolean+ usages: UsageMetric[]}-export type OrgUsageResponseUsageKeys = keyof Omit<OrgUsageResponse, 'disk_volume_size_gb'>-export async function getOrgUsage({ orgSlug }: OrgUsageVariables, signal?: AbortSignal) {if (!orgSlug) throw new Error('orgSlug is required')const response = await get(`${API_URL}/organizations/${orgSlug}/usage`, { signal })@@ -44,7 +41,7 @@ export async function getOrgUsage({ orgSlug }: OrgUsageVariables, signal?: Abort}export type OrgUsageData = Awaited<ReturnType<typeof getOrgUsage>>-export type OrgUsageError = unknown+export type OrgUsageError = ResponseErrorexport const useOrgUsageQuery = <TData = OrgUsageData>({ orgSlug }: OrgUsageVariables,@@ -55,22 +52,6 @@ export const useOrgUsageQuery = <TData = OrgUsageData>(({ signal }) => getOrgUsage({ orgSlug }, signal),{enabled: enabled && typeof orgSlug !== 'undefined',- // select(data) {- // return Object.fromEntries(- // Object.entries(data).map(([key, value]) => {- // if (typeof value === 'object') {- // const formattedValue = {- // ...value,- // usage: Number(value.usage),- // }-- // return [key, formattedValue]- // } else {- // return [key, value]- // }- // })- // )- // },...options,})@@ -84,5 +65,6 @@ export const useOrgUsagePrefetch = ({ orgSlug }: OrgUsageVariables) => {getOrgUsage({ orgSlug }, signal))}+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [orgSlug])}