Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: project usage #649

Merged
merged 2 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"e2e": "playwright test tests/e2e"
},
"dependencies": {
"@appwrite.io/console": "^0.3.0",
"@appwrite.io/console": "^0.4.1",
"@appwrite.io/pink": "0.2.0",
"@appwrite.io/pink-icons": "0.2.0",
"@popperjs/core": "^2.11.8",
Expand Down
2 changes: 1 addition & 1 deletion src/lib/components/progressBarBig.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
export let progressMax: number;
export let showBar = true;

$: progress = Math.round((progressValue / progressMax) * 100);
$: progress = Math.min(Math.max(Math.round((progressValue / progressMax) * 100), 0), 100);
</script>

<section class="progress-bar">
Expand Down
1 change: 1 addition & 0 deletions src/lib/helpers/project.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export function getProjectId() {
const pathname = window.location.pathname + '/';
const projectMatch = pathname.match(/\/project-(.*?)\//);

return projectMatch?.[1] || null;
}
27 changes: 26 additions & 1 deletion src/lib/layout/usage.svelte
Original file line number Diff line number Diff line change
@@ -1,13 +1,38 @@
<script context="module" lang="ts">
export type UsagePeriods = '24h' | '30d' | '90d';

export function periodToDates(period: UsagePeriods): {
start: string;
end: string;
period: '1h' | '1d';
} {
const end = new Date();
switch (period) {
case '24h':
end.setHours(end.getHours() + 24);
break;
case '30d':
end.setDate(end.getDate() + 30);
break;
case '90d':
end.setDate(end.getDate() + 90);
break;
}

return {
start: new Date().toISOString(),
end: end.toISOString(),
period: period === '24h' ? '1h' : '1d'
};
}

export function last(set: Models.Metric[]): Models.Metric | null {
if (!set) return null;
return set.slice(-1)[0] ?? null;
}

export function total(set: Models.Metric[]): number {
return set.reduce((prev, curr) => prev + curr.value, 0);
return set?.reduce((prev, curr) => prev + curr.value, 0) ?? 0;
}
</script>

Expand Down
16 changes: 11 additions & 5 deletions src/lib/sdk/billing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -512,15 +512,21 @@ export class Billing {

async listUsage(
organizationId: string,
startDate: string = null,
endDate: string = null
startDate: string = undefined,
endDate: string = undefined
): Promise<OrganizationUsage> {
const path = `/organizations/${organizationId}/usage`;
const params = {
organizationId,
startDate,
endDate
organizationId
};

if (startDate !== undefined) {
params['startDate'] = startDate;
}
if (endDate !== undefined) {
params['endDate'] = endDate;
}

const uri = new URL(this.client.config.endpoint + path);
return await this.client.call(
'get',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
import { goto } from '$app/navigation';
import { toLocaleDate } from '$lib/helpers/date.js';
import { bytesToSize, humanFileSize } from '$lib/helpers/sizeConvertion';
import { abbreviateNumber } from '$lib/helpers/numbers';
import { BarChart } from '$lib/charts';
import ChangeOrganizationTierCloud from '$routes/console/changeOrganizationTierCloud.svelte';
import ProjectBreakdown from './ProjectBreakdown.svelte';
import { last } from '$lib/helpers/array';
import { formatNum } from '$lib/helpers/string';

export let data;

Expand Down Expand Up @@ -94,7 +95,7 @@
</p>

<svelte:fragment slot="aside">
{@const current = data.organizationUsage.bandwidth[0]?.value ?? 0}
{@const current = last(data.organizationUsage.bandwidth)?.value ?? 0}
{@const currentHumanized = humanFileSize(current)}
{@const max = getServiceLimit('bandwidth', tier)}
<ProgressBarBig
Expand All @@ -106,10 +107,24 @@
progressMax={max}
showBar={false} />
<BarChart
options={{
yAxis: {
axisLabel: {
formatter: (value) =>
value
? `${humanFileSize(+value).value} ${humanFileSize(+value).unit}`
: '0'
}
}
}}
series={[
{
name: 'Bandwidth',
data: [...data.organizationUsage.bandwidth.map((e) => [e.date, e.value])]
data: [...data.organizationUsage.bandwidth.map((e) => [e.date, e.value])],
tooltip: {
valueFormatter: (value) =>
`${humanFileSize(+value).value} ${humanFileSize(+value).unit}`
}
}
]} />
<ProjectBreakdown
Expand All @@ -125,17 +140,24 @@
<p class="text">The total number of users across all projects in your organization.</p>

<svelte:fragment slot="aside">
{@const current = data.organizationUsage.users[0]?.value ?? 0}
{@const current = last(data.organizationUsage.users)?.value ?? 0}
{@const max = getServiceLimit('users', tier)}
<ProgressBarBig
currentUnit="Users"
currentValue={current.toString()}
currentValue={formatNum(current)}
maxUnit="Users"
maxValue={abbreviateNumber(max)}
maxValue={formatNum(max)}
progressValue={current}
progressMax={max}
showBar={false} />
<BarChart
options={{
yAxis: {
axisLabel: {
formatter: formatNum
}
}
}}
series={[
{
name: 'Users',
Expand All @@ -160,7 +182,7 @@
currentUnit="Executions"
currentValue={current.toString()}
maxUnit="Executions"
maxValue={abbreviateNumber(max)}
maxValue={formatNum(max)}
progressValue={current}
progressMax={max} />
<ProjectBreakdown
Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,26 @@
import { sdk } from '$lib/stores/sdk';
import { Query } from '@appwrite.io/console';
import type { PageLoad } from './$types';
import type { Organization } from '$lib/stores/organization';
import type { Invoice } from '$lib/sdk/billing';
import { getTomorrow } from '$lib/helpers/date';
import { Query } from '@appwrite.io/console';

export const load: PageLoad = async ({ params, parent }) => {
const { invoice } = params;
const parentData = await parent();
const org = parentData.organization as Organization;
const tomorrow = getTomorrow(new Date());

let startDate: string;
let endDate: string;
let currentInvoice: Invoice | null = null;
let startDate: string = undefined;
let endDate: string = undefined;
let currentInvoice: Invoice = undefined;

if (invoice) {
currentInvoice = await sdk.forConsole.billing.getInvoice(org.$id, invoice);
startDate = currentInvoice.from;
endDate = currentInvoice.to;
} else {
startDate = org.billingCurrentInvoiceDate;
endDate = tomorrow.toISOString();
}

const [invoices, usage] = await Promise.all([
sdk.forConsole.billing.listInvoices(org.$id),
sdk.forConsole.billing.listInvoices(org.$id, [Query.orderDesc('from')]),
sdk.forConsole.billing.listUsage(params.organization, startDate, endDate)
]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@

<Collapsible>
<CollapsibleItem>
<svelte:fragment slot="tgit restore --stageditle">Project breakdown</svelte:fragment>
<div class="table-wrapper">
<svelte:fragment slot="title">Project breakdown</svelte:fragment>
<div class="table-wrapper" data-sveltekit-preload-data="off">
<Table noMargin noStyles>
<TableHeader>
<TableCellHead width={285}>Project</TableCellHead>
Expand All @@ -71,8 +71,9 @@
<TableCell title="Usage">{format(project.usage)}</TableCell>
<TableCellLink
title="Go to project usage"
href={getProjectUsageLink(project.projectId)}
>View project usage</TableCellLink>
href={getProjectUsageLink(project.projectId)}>
View project usage
</TableCellLink>
</TableRow>
{/each}
</TableBody>
Expand Down
6 changes: 4 additions & 2 deletions src/routes/console/project-[project]/overview/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import { formatNum } from '$lib/helpers/string';
import { total } from '$lib/helpers/array';
import type { Metric } from '$lib/sdk/usage';
import { periodToDates } from '$lib/layout/usage.svelte';

$: projectId = $page.params.project;
$: path = `/console/project-${projectId}/overview`;
Expand All @@ -34,7 +35,7 @@
afterNavigate(handle);

async function handle() {
const promise = usage.load(period);
const promise = changePeriod(period);

if ($usage) {
await promise;
Expand All @@ -43,7 +44,8 @@

function changePeriod(newPeriod: UsagePeriods) {
period = newPeriod;
usage.load(period);
const dates = periodToDates(newPeriod);
return usage.load(dates.start, dates.end, dates.period);
}

$: $registerCommands([
Expand Down
12 changes: 5 additions & 7 deletions src/routes/console/project-[project]/overview/store.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import { sdk } from '$lib/stores/sdk';
import { cachedStore } from '$lib/helpers/cache';
import type { UsageProject } from '$lib/sdk/usage';
import { writable, type Writable } from 'svelte/store';
import type { Models } from '@appwrite.io/console';

export const usage = cachedStore<
UsageProject,
Models.UsageProject,
{
load: (range: string) => Promise<void>;
load: (start: string, end: string, period: '1h' | '1d') => Promise<void>;
}
>('projectUsage', function ({ set }) {
return {
load: async (range) => {
const usages: UsageProject = (await sdk.forProject.project.getUsage(
range
)) as unknown as UsageProject;
load: async (start, end, period) => {
const usages = await sdk.forProject.project.getUsage(start, end, period);
set(usages);
}
};
Expand Down
Loading