feat: start work on change tier workflow

This commit is contained in:
Arman committed 2023-07-20 13:48:00 +02:00
1 parent 3d403bafd1
commit 20bc7e3dfa
12 files changed
+605 -31

No files matched your search

+31 -23
View File
@@ -260,31 +260,39 @@ export const eventServices: Array<EventService> = [
export const usageRates = {
'tier-0': [
{ resource: 'Organization members', limit: '1', rate: 'lorem' },
{ resource: 'Bandwidth', limit: '1', rate: 'lorem' },
{ resource: 'Storage', limit: '1', rate: 'lorem' },
{ resource: 'Function executions', limit: '1', rate: 'lorem' },
{ resource: 'Active users', limit: '1', rate: 'lorem' },
{ resource: 'Concurrent connections', limit: '1', rate: 'lorem' }
],
'tier-1': [
{ resource: 'Organization members', limit: '1', rate: 'lorem' },
{ resource: 'Bandwidth', limit: '1', rate: 'lorem' },
{ resource: 'Storage', limit: '1', rate: 'lorem' },
{ resource: 'Function executions', limit: '1', rate: 'lorem' },
{ resource: 'Active users', limit: '1', rate: 'lorem' },
{ resource: 'Concurrent connections', limit: '1', rate: 'lorem' }
],
'tier-2': [
{ resource: 'Organization members', limit: 'Unlimited', rate: '20$/member' },
{ resource: 'Organization members', limit: 'Unlimited', rate: '$20/member' },
{ resource: 'Bandwidth', limit: '1TB', rate: '$0.04/GB' },
{ resource: 'Storage', limit: '150GB', rate: '$0.025/GB' },
{ resource: 'Function executions', limit: '3500000 executions', rate: '$2/1M executions' },
{ resource: 'Active users', limit: '200000', rate: '$0.0012/users' },
{
resource: 'Concurrent connections',
limit: '750 connections',
rate: '$5/1000 connections'
}
resource: 'Function executions',
limit: '3,500,000 executions',
rate: '$2/1M executions'
},
{ resource: 'Active users', limit: '200,000 AU', rate: '$0.0012/user' },
{ resource: 'Concurrent connections', limit: '750 connections', rate: '$5/1K connections' }
],
'tier-1': [
{ resource: 'Organization members', limit: 'Unlimited', rate: '$20/member' },
{ resource: 'Bandwidth', limit: '1TB', rate: '$0.04/GB' },
{ resource: 'Storage', limit: '150GB', rate: '$0.025/GB' },
{
resource: 'Function executions',
limit: '3,500,000 executions',
rate: '$2/1M executions'
},
{ resource: 'Active users', limit: '200,000 AU', rate: '$0.0012/user' },
{ resource: 'Concurrent connections', limit: '750 connections', rate: '$5/1K connections' }
],
'tier-2': [
{ resource: 'Organization members', limit: 'Unlimited', rate: '$20/member' },
{ resource: 'Bandwidth', limit: '1TB', rate: '$0.04/GB' },
{ resource: 'Storage', limit: '150GB', rate: '$0.025/GB' },
{
resource: 'Function executions',
limit: '3,500,000 executions',
rate: '$2/1M executions'
},
{ resource: 'Active users', limit: '200,000 AU', rate: '$0.0012/user' },
{ resource: 'Concurrent connections', limit: '750 connections', rate: '$5/1K connections' }
]
};
+2 -1
View File
@@ -30,6 +30,7 @@ export type Invoice = {
from: string;
to: string;
status: string;
dueAt: string;
};
export type InvoiceList = {
@@ -176,7 +177,7 @@ export class Billing {
organizationId: string,
billingPlan: string,
paymentMethodId: string
): Promise<string> {
): Promise<Organization> {
const path = `/organizations/${organizationId}/plan`;
const params = {
organizationId,
@@ -0,0 +1,107 @@
<script lang="ts">
import { Wizard } from '$lib/layout';
import { sdk } from '$lib/stores/sdk';
import { createEventDispatcher, onDestroy } from 'svelte';
import { addNotification } from '$lib/stores/notifications';
import Step1 from './wizard/cloudOrganizationChangeTier/step1.svelte';
import Step2 from './wizard/cloudOrganizationChangeTier/step2.svelte';
import Step3 from './wizard/cloudOrganizationChangeTier/step3.svelte';
import Step4 from './wizard/cloudOrganizationChangeTier/step4.svelte';
import { changeOrganizationTier } from './wizard/cloudOrganizationChangeTier/store';
import type { WizardStepsType } from '$lib/layout/wizard.svelte';
import { goto, invalidate } from '$app/navigation';
import { Dependencies } from '$lib/constants';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
import { page } from '$app/stores';
import { organization } from '$lib/stores/organization';
const dispatch = createEventDispatcher();
async function onFinish() {
await invalidate(Dependencies.FUNCTIONS);
}
async function upgrade() {
try {
const org = await sdk.forConsole.billing.updatePlan(
$organization.$id,
$changeOrganizationTier.billingPlan,
$changeOrganizationTier.paymentMethodId
);
//Add budget
if ($changeOrganizationTier?.billingBudget) {
await sdk.forConsole.billing.updateBudget(
org.$id,
$changeOrganizationTier.billingBudget,
[75]
);
}
//Add collaborators
if ($changeOrganizationTier?.collaborators?.length) {
$changeOrganizationTier.collaborators.forEach(async (collaborator) => {
await sdk.forConsole.teams.createMembership(
org.$id,
['collaborator'],
`${$page.url.origin}/console/organization-${org.$id}`,
collaborator
);
});
}
await invalidate(Dependencies.ACCOUNT);
dispatch('created');
await goto(`/console/organization-${org.$id}`);
addNotification({
type: 'success',
isHtml: true,
message: `
<b>Your organization has been upgraded</b>
Make the most of your increased resource capacity and continue building great things with Appwrite.`
});
trackEvent(Submit.OrganizationCreate, {
customId: !!$changeOrganizationTier.id
});
} catch (e) {
addNotification({
type: 'error',
message: e.mesage
});
trackError(e, Submit.OrganizationCreate);
}
}
onDestroy(() => {
$changeOrganizationTier = {
id: null,
billingPlan: 'tier-1',
paymentMethodId: null,
collaborators: []
};
});
const stepsComponents: WizardStepsType = new Map();
stepsComponents.set(1, {
label: 'Change plan',
component: Step1
});
stepsComponents.set(2, {
label: 'Payment details',
component: Step2
});
stepsComponents.set(3, {
label: 'Invite collaborators',
component: Step3
});
stepsComponents.set(4, {
label: 'Review & confirm',
component: Step4
});
</script>
<Wizard
title="Change plan"
steps={stepsComponents}
finalAction="Start trial"
on:finish={upgrade}
on:exit={onFinish} />
@@ -72,7 +72,7 @@
$createOrganization = {
id: null,
name: null,
billingPlan: 'tier-2',
billingPlan: 'tier-1',
paymentMethodId: null,
collaborators: []
};
@@ -99,7 +99,7 @@
</script>
<Wizard
title="Create organization "
title="Create organization"
steps={stepsComponents}
finalAction="Start trial"
on:finish={create}
@@ -64,11 +64,11 @@
<TableRow>
<TableCellText title="date">{toLocaleDate(invoice.from)}</TableCellText>
<TableCell title="status">
<Pill>test</Pill>
<Pill>{invoice.status}</Pill>
</TableCell>
<TableCellText title="due">{invoice.amount}</TableCellText>
<TableCellText title="invoice number"
>{invoice.aggregationId}
<TableCellText title="invoice number">
{invoice.$id}
</TableCellText>
<TableCell showOverflow>
<DropList
@@ -6,6 +6,8 @@
import { toLocaleDate } from '$lib/helpers/date';
import { tierFree, tierPro, tierScale } from '$lib/stores/billing';
import { organization } from '$lib/stores/organization';
import { wizard } from '$lib/stores/wizard';
import ChangeOrganizationTierCloud from '$routes/console/changeOrganizationTierCloud.svelte';
// import { sdk } from '$lib/stores/sdk';
import UsageRates from '$routes/console/wizard/cloudOrganization/usageRates.svelte';
@@ -58,7 +60,7 @@
</svelte:fragment>
<svelte:fragment slot="actions">
<!-- TODO: add change plan method -->
<Button text>Change plan</Button>
<Button text on:click={() => wizard.start(ChangeOrganizationTierCloud)}>Change plan</Button>
<Button secondary href={`${base}/console/organization-${$organization.$id}/usage`}
>View estimated usage</Button>
</svelte:fragment>
@@ -181,4 +181,4 @@
</FormList>
</WizardStep>
<UsageRates bind:show={showRates} tier={$createOrganization?.billingPlan} />
<UsageRates bind:show={showRates} tier={$organization?.billingPlan} />
@@ -0,0 +1,84 @@
<script lang="ts">
import { LabelCard } from '$lib/components';
import { Pill } from '$lib/elements';
import { WizardStep } from '$lib/layout';
import { tierFree, tierPro, tierScale } from '$lib/stores/billing';
import { organization } from '$lib/stores/organization';
import { changeOrganizationTier } from './store';
</script>
<WizardStep>
<svelte:fragment slot="title">Choose a plan</svelte:fragment>
<p class="body-text-1 u-bold common-section">Plan</p>
<p class="text">
For more details on our plans, visit our <a
class="link"
href="http://#"
target="_blank"
rel="noopener noreferrer">pricing page</a
>.
</p>
<ul
class="u-flex u-flex-vertical u-gap-16 u-margin-block-start-16"
style="--p-grid-item-size:16em; --p-grid-item-size-small-screens:16rem; --grid-gap: 1rem;">
{#if $organization.billingPlan !== 'tier-0'}
<li>
<LabelCard
name="plan"
bind:group={$changeOrganizationTier.billingPlan}
value="tier-0">
<svelte:fragment slot="custom">
<div class="u-flex u-flex-vertical u-gap-4 u-width-full-line">
<h4 class="body-text-2 u-bold">
{tierFree.name} - ${tierFree.price}/month
</h4>
<p class="u-color-text-gray u-small">{tierFree.description}</p>
</div>
</svelte:fragment>
</LabelCard>
</li>
{/if}
{#if $organization.billingPlan !== 'tier-1'}
<li>
<LabelCard
name="plan"
bind:group={$changeOrganizationTier.billingPlan}
value="tier-1">
<svelte:fragment slot="custom">
<div class="u-flex u-flex-vertical u-gap-4 u-width-full-line">
<h4 class="body-text-2 u-bold">
{tierPro.name} - ${tierPro.price}/month per organization member +
exta usage
</h4>
<p class="u-color-text-gray u-small">
{tierPro.description}
</p>
</div>
<Pill>14 DAY FREE TRIAL</Pill>
</svelte:fragment>
</LabelCard>
</li>
{/if}
{#if $organization.billingPlan !== 'tier-2'}
<li>
<LabelCard
name="plan"
bind:group={$changeOrganizationTier.billingPlan}
value="tier-2">
<svelte:fragment slot="custom">
<div class="u-flex u-flex-vertical u-gap-4 u-width-full-line">
<h4 class="body-text-2 u-bold">
{tierScale.name} - ${tierScale.price}/month + exta usage
</h4>
<p class="u-color-text-gray u-small">
{tierScale.description}
</p>
</div>
<Pill>14 DAY FREE TRIAL</Pill>
</svelte:fragment>
</LabelCard>
</li>
{/if}
</ul>
</WizardStep>
@@ -0,0 +1,182 @@
<script lang="ts">
import { FormList, InputNumber, InputRadio, InputText } from '$lib/elements/forms';
import InputChoice from '$lib/elements/forms/inputChoice.svelte';
import { WizardStep } from '$lib/layout';
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { changeOrganizationTier } from './store';
import UsageRates from '../cloudOrganization/usageRates.svelte';
import type { PaymentList, PaymentMethodData } from '$lib/sdk/billing';
import { loadStripe, type Stripe, type StripeElements } from '@stripe/stripe-js';
import { organization } from '$lib/stores/organization';
import { invalidate } from '$app/navigation';
import { Dependencies } from '$lib/constants';
import { app } from '$lib/stores/app';
import { apperanceDark, apperanceLight } from '$lib/stores/billing';
import { VARS, hasStripePublicKey } from '$lib/system';
let methods: PaymentList;
let name: string;
let budgetEnabled = false;
let showRates = false;
// let error: string;
let elements: StripeElements;
let stripe: Stripe;
let clientSecret: string;
let paymentMethod: PaymentMethodData;
let isStripeInitialized = false;
onMount(async () => {
methods = await sdk.forConsole.billing.listPaymentMethods();
console.log(methods);
if (methods?.total) {
clientSecret = methods.paymentMethods[0]?.clientSecret;
$changeOrganizationTier.paymentMethodId = methods.paymentMethods[0].$id;
} else if (!isStripeInitialized) {
initialize();
}
});
async function initialize() {
if (!hasStripePublicKey) return;
stripe = await loadStripe(VARS.STRIPE_PUBLIC_KEY);
isStripeInitialized = true;
try {
clientSecret = methods.paymentMethods[0]?.clientSecret;
if (!clientSecret) {
paymentMethod = await sdk.forConsole.billing.createPaymentMethod();
}
const options = {
clientSecret: clientSecret ? clientSecret : paymentMethod.clientSecret,
appearance: $app.themeInUse === 'dark' ? apperanceDark : apperanceLight
};
console.log(clientSecret);
// Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in step 3
elements = stripe.elements(options);
createForm();
} catch (e) {
// error = e.message;
console.log(e);
}
}
async function createForm() {
const paymentElement = elements.create('payment');
paymentElement.mount('#payment-element');
}
async function handleSubmit() {
try {
await stripe.confirmSetup({
elements,
confirmParams: {
return_url: 'http://localhost:3000'
},
redirect: 'if_required'
});
console.log(clientSecret);
if (!clientSecret) {
console.log('test2');
paymentMethod = await sdk.forConsole.billing.createPaymentMethod();
}
const { setupIntent } = await stripe.retrieveSetupIntent(paymentMethod.clientSecret);
if (setupIntent && setupIntent.status === 'succeeded') {
await sdk.forConsole.billing.setOrganizationPaymentMethod(
$organization.$id,
paymentMethod.$id
);
await invalidate(Dependencies.PAYMENT_METHODS);
console.log('test');
// const paymentElement = elements.getElement('payment');
// paymentElement.destroy();
} else console.log('test2');
} catch (e) {
console.log(e);
// trackError(StripeError, Submit.ProjectCreate);
}
}
$: if ($changeOrganizationTier.paymentMethodId === null && !isStripeInitialized) {
initialize();
}
$: if ($changeOrganizationTier.paymentMethodId) {
isStripeInitialized = false;
}
</script>
<WizardStep beforeSubmit={handleSubmit}>
<svelte:fragment slot="title">Payment details</svelte:fragment>
<svelte:fragment slot="subtitle">Add a payment method to your organization.</svelte:fragment>
<FormList>
<div class:boxes-wrapper={methods?.total}>
{#if methods?.total}
{#each methods.paymentMethods as method}
<div class="box">
<InputRadio
id={`payment-method-${method.last4}`}
label={`${method.brand} ending in ${method.last4}`}
value={method.$id}
name="payment"
bind:group={$changeOrganizationTier.paymentMethodId} />
</div>
{/each}
{/if}
<div class="box">
{#if methods?.total}
<InputRadio
id="payment-method"
label="Add new payment method"
value={null}
name="payment"
bind:group={$changeOrganizationTier.paymentMethodId} />
{/if}
{#if $changeOrganizationTier.paymentMethodId === null}
<FormList>
<InputText
id="name"
label="Cardholder name"
placeholder="Cardholder name"
bind:value={name}
required
autofocus={true} />
<div id="payment-element">
<!-- Elements will create form elements here -->
</div>
</FormList>
{/if}
</div>
</div>
<InputChoice
type="switchbox"
id="budget"
label="Enable budget cap"
tooltip="If enabled, you will be notified by email when your project spend reaches 75% of the cap you set. Update your budget cap alerts in Organization Settings."
bind:value={budgetEnabled}>
<p class="text">
Restrict your resource usage by setting a budget cap. <button
class="link"
type="button"
on:click={() => (showRates = true)}>
Learn more about usage rates</button
>.
</p>
</InputChoice>
{#if budgetEnabled}
<InputNumber
id="budget"
label="Budget cap"
placeholder="0"
bind:value={$changeOrganizationTier.billingBudget} />
{/if}
</FormList>
</WizardStep>
<UsageRates bind:show={showRates} tier={$changeOrganizationTier?.billingPlan} />
@@ -0,0 +1,97 @@
<script lang="ts">
import { Alert } from '$lib/components';
import { Button, Form, FormList, InputEmail } from '$lib/elements/forms';
import {
Table,
TableBody,
TableCell,
TableCellHead,
TableCellText,
TableHeader,
TableRow
} from '$lib/elements/table';
import { WizardStep } from '$lib/layout';
import { changeOrganizationTier } from './store';
let email: string;
function addCollaborator() {
if (!email) return;
$changeOrganizationTier.collaborators.push(email);
$changeOrganizationTier = $changeOrganizationTier;
email = '';
}
function removeCollaborator(email: string) {
$changeOrganizationTier.collaborators = $changeOrganizationTier.collaborators.filter(
(collaborator) => collaborator !== email
);
}
</script>
<WizardStep>
<svelte:fragment slot="title">Invite collaborators</svelte:fragment>
<svelte:fragment slot="subtitle">
Invite team members to collaborate with you in the Appwrite console. Members will have
access to all services and payment data within your organization.
</svelte:fragment>
<Alert type="info">
{#if $changeOrganizationTier.billingPlan === 'tier-2'}
You can add unlimited organization members on the Scale plan at no cost. Each member
added will receive an email invite to your organization on completion.
{:else if $changeOrganizationTier.billingPlan === 'tier-1'}
You can add unlimited organization members on the Pro plan for $15 each. Each member
added will receive an email invite to your organization on completion.
{/if}
</Alert>
<div class="u-margin-block-start-24">
<Form onSubmit={addCollaborator}>
<FormList>
<InputEmail
label="Email address"
id="email"
placeholder="Email address"
bind:value={email}
required>
<Button secondary submit>Add</Button>
</InputEmail>
</FormList>
</Form>
</div>
{#if $changeOrganizationTier?.collaborators?.length}
<div class="u-margin-block-start-24">
<Table noStyles noMargin>
<TableHeader>
<TableCellHead>Collaborator</TableCellHead>
{#if $changeOrganizationTier.billingPlan === 'tier-1'}
<TableCellHead width={80}>Cost</TableCellHead>
{/if}
<TableCellHead width={40} />
</TableHeader>
<TableBody>
{#each $changeOrganizationTier.collaborators as collaborator}
<TableRow>
<TableCellText title="collaborator">{collaborator}</TableCellText>
{#if $changeOrganizationTier.billingPlan === 'tier-1'}
<TableCellText title="cost">15$</TableCellText>
{/if}
<TableCell>
<button
type="button"
class="button is-text is-only-icon"
style="--button-size:1.5rem;"
aria-label="remove collaborator"
on:click={() => removeCollaborator(collaborator)}>
<span class="icon-x" aria-hidden="true" />
</button>
</TableCell>
</TableRow>
{/each}
</TableBody>
</Table>
</div>
{/if}
</WizardStep>
@@ -0,0 +1,78 @@
<script lang="ts">
import { Pill } from '$lib/elements';
import { toLocaleDate } from '$lib/helpers/date';
import { WizardStep } from '$lib/layout';
import { tierToPlan } from '$lib/stores/billing';
import { organization } from '$lib/stores/organization';
import { sdk } from '$lib/stores/sdk';
import { changeOrganizationTier } from './store';
const plan = tierToPlan($changeOrganizationTier.billingPlan);
const collaboratorsNumber = $changeOrganizationTier?.collaborators?.length ?? 0;
const totalExpences = plan.price + plan.collaboratorPrice * collaboratorsNumber;
const today = new Date();
const billingPayDate = new Date(today.getTime() + 44 * 24 * 60 * 60 * 1000);
async function fetchCard() {
try {
const card = await sdk.forConsole.billing.getPaymentMethod(
$changeOrganizationTier.paymentMethodId
);
return card;
} catch (error) {
console.log(error);
}
}
</script>
<WizardStep>
<svelte:fragment slot="title">Confirm your details</svelte:fragment>
<svelte:fragment slot="subtitle">
Confirm the details of your new organization and start your free trial.
</svelte:fragment>
<p class="body-text-1 u-bold">Organization name</p>
<div class="u-flex u-gap-8 u-cross-center">
<p class="text">{$organization.name}</p>
{#if $changeOrganizationTier?.id}
<Pill>{$changeOrganizationTier.id}</Pill>
{/if}
</div>
<div class="u-margin-block-start-32">
<p class="body-text-1 u-bold">Organization members</p>
<p class="text">{collaboratorsNumber} invited</p>
</div>
<div class="u-margin-block-start-32">
<p class="body-text-1 u-bold">Payment</p>
{#await fetchCard()}
<div class="u-flex u-margin-block-start-4">
<div class="loader is-small" />
</div>
{:then card}
<p class="text">Card ending in {card.last4} {card.brand}</p>
{/await}
</div>
<div class="box u-margin-block-start-32 u-flex u-flex-vertical u-gap-16">
<span class="u-flex u-main-space-between">
<p class="text">{plan.name} plan</p>
<p class="text">${plan.price}</p>
</span>
<span class="u-flex u-main-space-between">
<p class="text">Invited members</p>
<p class="text">${plan.collaboratorPrice * collaboratorsNumber}</p>
</span>
<div class="u-sep-block-start" />
<span class="u-flex u-main-space-between">
<p class="text">Estimated total</p>
<p class="text">${totalExpences}</p>
</span>
<p class="text u-margin-block-start-16">
This amount and any extra usage fees will be charged on a recurring 30 day billing cycle
after your trial period ends on <b>{toLocaleDate(billingPayDate.toString())}</b>.
</p>
</div>
</WizardStep>
@@ -0,0 +1,15 @@
import type { Tier } from '$lib/stores/billing';
import { writable } from 'svelte/store';
export const changeOrganizationTier = writable<{
id?: string;
billingPlan: Tier;
paymentMethodId: string;
billingBudget?: number;
collaborators?: string[];
}>({
id: null,
billingPlan: 'tier-1',
paymentMethodId: null,
collaborators: []
});