From 7b68969af9d1ff14b8342983e5f4fa98a3fb229b Mon Sep 17 00:00:00 2001 From: Harsh Mahajan <127186841+HarshMN2345@users.noreply.github.com> Date: Sun, 31 Aug 2025 15:57:42 +0530 Subject: [PATCH] fix: fix logic and added cost of additional projects --- .../billing/+page.ts | 49 ++++-- .../billing/planSummary.svelte | 156 +++++++++++++----- .../settings/usage/[[invoice]]/+page.svelte | 2 +- .../settings/usage/[[invoice]]/+page.ts | 37 ++++- 4 files changed, 185 insertions(+), 59 deletions(-) diff --git a/src/routes/(console)/organization-[organization]/billing/+page.ts b/src/routes/(console)/organization-[organization]/billing/+page.ts index d8bc09887..2e8c12916 100644 --- a/src/routes/(console)/organization-[organization]/billing/+page.ts +++ b/src/routes/(console)/organization-[organization]/billing/+page.ts @@ -63,27 +63,52 @@ export const load: PageLoad = async ({ parent, depends }) => { let organizationUsage = null; let usageProjects: Record = {}; - try { - organizationUsage = await sdk.forConsole.billing.listUsage(organization.$id); - } catch (e) { - organizationUsage = null; + // Dont fetch organization usage if the plan uses per-project pricing + if (!currentPlan?.usagePerProject) { + try { + organizationUsage = await sdk.forConsole.billing.listUsage(organization.$id); + } catch (e) { + organizationUsage = null; + } } try { const neededIds = new Set(); const addId = (id?: string) => id && neededIds.add(id); - if (organizationUsage?.projects?.length) { - for (const p of organizationUsage.projects) addId(p.projectId); - } else if (billingAggregation?.projectBreakdown?.length) { - for (const p of billingAggregation.projectBreakdown) addId(p.$id); + if (currentPlan?.usagePerProject) { + if (billingAggregation?.projectBreakdown?.length) { + for (const p of billingAggregation.projectBreakdown) addId(p.$id); + } + } else { + // For organization pricing, fetch all projects + const allProjectsResponse = await sdk.forConsole.projects.list([ + Query.equal('teamId', organization.$id), + Query.limit(1000) // get all projects + ]); + + for (const project of allProjectsResponse.projects) { + usageProjects[project.$id] = { + name: project.name, + region: project.region + }; + } + + if (organizationUsage?.projects?.length) { + for (const p of organizationUsage.projects) addId(p.projectId); + } else if (billingAggregation?.projectBreakdown?.length) { + for (const p of billingAggregation.projectBreakdown) addId(p.$id); + } } - if (neededIds.size > 0) { - const ids = Array.from(neededIds); + // Fetch project metadata for projects that need it + const missingIds = + neededIds.size > 0 ? Array.from(neededIds).filter((id) => !usageProjects[id]) : []; + + if (missingIds.length > 0) { const projectsResponse = await sdk.forConsole.projects.list([ - Query.equal('$id', ids), - Query.limit(ids.length) + Query.equal('$id', missingIds), + Query.limit(missingIds.length) ]); for (const project of projectsResponse.projects) { usageProjects[project.$id] = { diff --git a/src/routes/(console)/organization-[organization]/billing/planSummary.svelte b/src/routes/(console)/organization-[organization]/billing/planSummary.svelte index d58232c4c..d308f380d 100644 --- a/src/routes/(console)/organization-[organization]/billing/planSummary.svelte +++ b/src/routes/(console)/organization-[organization]/billing/planSummary.svelte @@ -31,8 +31,16 @@ { id: 'price', align: 'right' as const, width: '0fr' } ]; - $: projectIdToBreakdown = new Map( - (currentAggregation?.projectBreakdown || []).map((p) => [p.$id, p]) + // Create a map for all projects to their breakdown data + $: allProjectsBreakdown = new Map( + projectsList.map((project) => [ + project.projectId, + project.breakdown || { + $id: project.projectId, + amount: 0, + resources: {} + } + ]) ); function formatHumanSize(bytes: number): string { @@ -65,6 +73,16 @@ return resource?.amount || 0; } + function getResourceUsage(projectBreakdown: any, resourceId: string): number { + if (!projectBreakdown?.resources) return 0; + + const resource = Array.isArray(projectBreakdown.resources) + ? projectBreakdown.resources.find((r: any) => r.resourceId === resourceId) + : projectBreakdown.resources[resourceId]; + + return resource?.value || 0; + } + function getProgressColor(_percentage: number): string { return 'var(--bgcolor-neutral-invert)'; } @@ -123,28 +141,40 @@ ]; } - $: projectsList = organizationUsage?.projects?.length - ? organizationUsage.projects - : (currentAggregation?.projectBreakdown || []).map((p) => { - // Find the corresponding project data from organizationUsage - const projectData = organizationUsage?.projects?.find( - (proj: any) => proj.projectId === p.$id - ); + $: projectsList = (() => { + // Get all projects from usageProjects (which now contains all organization projects) + const allProjectIds = Object.keys(usageProjects); - return { - projectId: p.$id, - storage: projectData?.storage || 0, - executions: projectData?.executions || 0, - executionsMBSeconds: projectData?.executionsMBSeconds || 0, - bandwidth: projectData?.bandwidth || 0, - databasesReads: projectData?.databasesReads || 0, - databasesWrites: projectData?.databasesWrites || 0, - users: projectData?.users || 0, - authPhoneTotal: projectData?.authPhoneTotal || 0, - authPhoneEstimate: projectData?.authPhoneEstimate || 0, - breakdown: p - }; - }); + if (allProjectIds.length === 0) { + return []; + } + + return allProjectIds.map((projectId) => { + // Find the corresponding project data from organizationUsage + const projectData = organizationUsage?.projects?.find( + (proj: any) => proj.projectId === projectId + ); + + // Find the corresponding breakdown data + const breakdownData = currentAggregation?.projectBreakdown?.find( + (p: any) => p.$id === projectId + ); + + return { + projectId: projectId, + storage: projectData?.storage || 0, + executions: projectData?.executions || 0, + executionsMBSeconds: projectData?.executionsMBSeconds || 0, + bandwidth: projectData?.bandwidth || 0, + databasesReads: projectData?.databasesReads || 0, + databasesWrites: projectData?.databasesWrites || 0, + users: projectData?.users || 0, + authPhoneTotal: projectData?.authPhoneTotal || 0, + authPhoneEstimate: projectData?.authPhoneEstimate || 0, + breakdown: breakdownData + }; + }); + })(); $: billingData = [ { @@ -154,10 +184,34 @@ item: 'Base plan', usage: '', price: formatCurrency(currentPlan?.price || 0) - } + }, + children: [] }, + ...(currentAggregation?.resources + ?.filter( + (r) => + r.amount && + r.amount > 0 && + Object.keys(currentPlan.addons || {}).includes(r.resourceId) && + currentPlan.addons[r.resourceId]?.price > 0 + ) + ?.map((excess) => ({ + id: `addon-${excess.resourceId}`, + expandable: false, + cells: { + item: + excess.resourceId === 'seats' + ? 'Additional members' + : excess.resourceId === 'projects' + ? `Additional Projects (${formatNum(excess.value)})` + : `${excess.resourceId} overage (${formatNum(excess.value)})`, + usage: '', + price: formatCurrency(excess.amount) + }, + children: [] + })) || []), ...(projectsList?.map((project) => { - const projectBreakdown = projectIdToBreakdown.get(project.projectId); + const projectBreakdown = allProjectsBreakdown.get(project.projectId); return { id: `project-${project.projectId}`, @@ -178,11 +232,13 @@ id: `project-${project.projectId}-bandwidth`, cells: { item: 'Bandwidth', - usage: `${formatBandwidthUsage(project.bandwidth || 0, currentPlan?.bandwidth)}`, + usage: `${formatBandwidthUsage(getResourceUsage(projectBreakdown, 'bandwidth') || project.bandwidth || 0, currentPlan?.bandwidth)}`, price: formatCurrency(getResourceAmount(projectBreakdown, 'bandwidth')) }, progressData: createStorageProgressData( - project.bandwidth || 0, + getResourceUsage(projectBreakdown, 'bandwidth') || + project.bandwidth || + 0, currentPlan?.bandwidth || 0 ), maxValue: currentPlan?.bandwidth @@ -194,10 +250,13 @@ id: `project-${project.projectId}-users`, cells: { item: 'Users', - usage: `${formatNum(project.users || 0)} / ${currentPlan?.users ? formatNum(currentPlan.users) : 'Unlimited'}`, + usage: `${formatNum(getResourceUsage(projectBreakdown, 'users') || project.users || 0)} / ${currentPlan?.users ? formatNum(currentPlan.users) : 'Unlimited'}`, price: formatCurrency(getResourceAmount(projectBreakdown, 'users')) }, - progressData: createProgressData(project.users || 0, currentPlan?.users), + progressData: createProgressData( + getResourceUsage(projectBreakdown, 'users') || project.users || 0, + currentPlan?.users + ), maxValue: currentPlan?.users }, // Database reads @@ -205,13 +264,15 @@ id: `project-${project.projectId}-reads`, cells: { item: 'Database reads', - usage: `${formatNum(project.databasesReads || 0)} / ${currentPlan?.databasesReads ? formatNum(currentPlan.databasesReads) : 'Unlimited'}`, + usage: `${formatNum(getResourceUsage(projectBreakdown, 'databasesReads') || project.databasesReads || 0)} / ${currentPlan?.databasesReads ? formatNum(currentPlan.databasesReads) : 'Unlimited'}`, price: formatCurrency( getResourceAmount(projectBreakdown, 'databasesReads') ) }, progressData: createProgressData( - project.databasesReads || 0, + getResourceUsage(projectBreakdown, 'databasesReads') || + project.databasesReads || + 0, currentPlan?.databasesReads ), maxValue: currentPlan?.databasesReads @@ -221,13 +282,15 @@ id: `project-${project.projectId}-writes`, cells: { item: 'Database writes', - usage: `${formatNum(project.databasesWrites || 0)} / ${currentPlan?.databasesWrites ? formatNum(currentPlan.databasesWrites) : 'Unlimited'}`, + usage: `${formatNum(getResourceUsage(projectBreakdown, 'databasesWrites') || project.databasesWrites || 0)} / ${currentPlan?.databasesWrites ? formatNum(currentPlan.databasesWrites) : 'Unlimited'}`, price: formatCurrency( getResourceAmount(projectBreakdown, 'databasesWrites') ) }, progressData: createProgressData( - project.databasesWrites || 0, + getResourceUsage(projectBreakdown, 'databasesWrites') || + project.databasesWrites || + 0, currentPlan?.databasesWrites ), maxValue: currentPlan?.databasesWrites @@ -237,11 +300,13 @@ id: `project-${project.projectId}-executions`, cells: { item: 'Executions', - usage: `${formatNum(project.executions || 0)} / ${currentPlan?.executions ? formatNum(currentPlan.executions) : 'Unlimited'}`, + usage: `${formatNum(getResourceUsage(projectBreakdown, 'executions') || project.executions || 0)} / ${currentPlan?.executions ? formatNum(currentPlan.executions) : 'Unlimited'}`, price: formatCurrency(getResourceAmount(projectBreakdown, 'executions')) }, progressData: createProgressData( - project.executions || 0, + getResourceUsage(projectBreakdown, 'executions') || + project.executions || + 0, currentPlan?.executions ), maxValue: currentPlan?.executions @@ -251,11 +316,11 @@ id: `project-${project.projectId}-storage`, cells: { item: 'Storage', - usage: `${formatHumanSize(project.storage || 0)} / ${currentPlan?.storage?.toString() || '0'} GB`, + usage: `${formatHumanSize(getResourceUsage(projectBreakdown, 'storage') || project.storage || 0)} / ${currentPlan?.storage?.toString() || '0'} GB`, price: formatCurrency(getResourceAmount(projectBreakdown, 'storage')) }, progressData: createStorageProgressData( - project.storage || 0, + getResourceUsage(projectBreakdown, 'storage') || project.storage || 0, currentPlan?.storage || 0 ), maxValue: currentPlan?.storage @@ -267,12 +332,16 @@ id: `project-${project.projectId}-gb-hours`, cells: { item: 'GB-hours', - usage: `${formatNum((project.executionsMBSeconds || 0) / 1000 / 3600 || 0)} / ${currentPlan?.executions ? formatNum((currentPlan.executions * 1000 * 3600) / 1000 / 3600) : 'Unlimited'}`, + usage: `${formatNum((getResourceUsage(projectBreakdown, 'GBHours') || project.executionsMBSeconds || 0) / 1000 / 3600 || 0)} / ${currentPlan?.executions ? formatNum((currentPlan.executions * 1000 * 3600) / 1000 / 3600) : 'Unlimited'}`, price: formatCurrency(getResourceAmount(projectBreakdown, 'GBHours')) }, progressData: currentPlan?.executions ? createProgressData( - (project.executionsMBSeconds || 0) / 1000 / 3600, + (getResourceUsage(projectBreakdown, 'GBHours') || + project.executionsMBSeconds || + 0) / + 1000 / + 3600, (currentPlan.executions * 1000 * 3600) / 1000 / 3600 ) : [], @@ -311,7 +380,8 @@ item: 'No projects found', usage: '', price: formatCurrency(0) - } + }, + children: [] } ] : []) @@ -703,6 +773,12 @@ gap: 8px; } + :global([data-expandable-row-id='additional-projects']), + :global([data-expandable-row-id^='addon-']) { + background-color: var(--bgcolor-neutral-tertiary); + border-left: 3px solid var(--bgcolor-accent-neutral); + } + :global(.card-only-on-desktop) { padding: 0.5rem; box-shadow: unset; diff --git a/src/routes/(console)/project-[region]-[project]/settings/usage/[[invoice]]/+page.svelte b/src/routes/(console)/project-[region]-[project]/settings/usage/[[invoice]]/+page.svelte index 24b82ae7b..31fc89017 100644 --- a/src/routes/(console)/project-[region]-[project]/settings/usage/[[invoice]]/+page.svelte +++ b/src/routes/(console)/project-[region]-[project]/settings/usage/[[invoice]]/+page.svelte @@ -243,7 +243,7 @@ Executions - Calculated for all functions that are executed in all projects in your project. + Calculated for all functions that are executed in this project. {#if executions} {@const current = formatNum(executionsTotal)} diff --git a/src/routes/(console)/project-[region]-[project]/settings/usage/[[invoice]]/+page.ts b/src/routes/(console)/project-[region]-[project]/settings/usage/[[invoice]]/+page.ts index 4afa9181a..8c92b6d92 100644 --- a/src/routes/(console)/project-[region]-[project]/settings/usage/[[invoice]]/+page.ts +++ b/src/routes/(console)/project-[region]-[project]/settings/usage/[[invoice]]/+page.ts @@ -1,4 +1,4 @@ -import type { Aggregation, Invoice } from '$lib/sdk/billing'; +import type { AggregationTeam, Invoice } from '$lib/sdk/billing'; import { accumulateUsage } from '$lib/sdk/usage'; import { sdk } from '$lib/stores/sdk'; import { Query } from '@appwrite.io/console'; @@ -11,7 +11,7 @@ export const load: PageLoad = async ({ params, parent }) => { let startDate: string = organization.billingCurrentInvoiceDate; let endDate: string = organization.billingNextInvoiceDate; let currentInvoice: Invoice = undefined; - let currentAggregation: Aggregation = undefined; + let currentAggregation: AggregationTeam = undefined; if (invoice) { currentInvoice = await sdk.forConsole.billing.getInvoice(organization.$id, invoice); @@ -22,6 +22,15 @@ export const load: PageLoad = async ({ params, parent }) => { startDate = currentInvoice.from; endDate = currentInvoice.to; + } else { + try { + currentAggregation = await sdk.forConsole.billing.getAggregation( + organization.$id, + organization.billingAggregationId + ); + } catch (e) { + // ignore error if no aggregation found + } } const [invoices, usage] = await Promise.all([ @@ -29,10 +38,26 @@ export const load: PageLoad = async ({ params, parent }) => { sdk.forProject(region, project).project.getUsage({ startDate, endDate }) ]); - if (invoice) { - usage.usersTotal = currentAggregation.usageUsers; - usage.executionsTotal = currentAggregation.usageExecutions; - usage.filesStorageTotal = currentAggregation.usageStorage; + if (currentAggregation) { + let projectSpecificData = null; + if (currentAggregation.projectBreakdown) { + projectSpecificData = currentAggregation.projectBreakdown.find( + (p) => p.$id === project + ); + } + + if (projectSpecificData) { + const executionsResource = projectSpecificData.resources?.find?.( + (r: any) => r.resourceId === 'executions' + ); + if (executionsResource) { + usage.executionsTotal = executionsResource.value || usage.executionsTotal; + } + } else { + usage.usersTotal = currentAggregation.usageUsers; + usage.executionsTotal = currentAggregation.usageExecutions; + usage.filesStorageTotal = currentAggregation.usageStorage; + } } usage.users = accumulateUsage(usage.users, usage.usersTotal);