Merge pull request #2981 from appwrite/feat/project-premium-geo-db-addon

feat: add Premium Geo DB addon to project settings
This commit is contained in:
Damodar Lohani authored and GitHub committed 2026-07-16 08:26:40 +05:45
commit 241dde86de
7 files changed
+573 -16

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@ const config: PlaywrightTestConfig = {
webServer: {
timeout: 120000,
env: {
PUBLIC_APPWRITE_ENDPOINT: 'https://stage.cloud.appwrite.io/v1',
PUBLIC_APPWRITE_ENDPOINT: 'https://cloud.staging.appwrite.io/v1',
PUBLIC_CONSOLE_MODE: 'cloud',
PUBLIC_APPWRITE_MULTI_REGION: 'true',
PUBLIC_STRIPE_KEY:
@@ -299,7 +299,9 @@
// on the resource entry. Once the cloud rollout is complete this map can
// be removed entirely.
const billingAddonNamesFallback: Record<string, string> = {
addon_baa: 'HIPAA BAA'
addon_baa: 'HIPAA BAA',
addon_premiumGeoDB: 'Premium Geo DB',
addon_premiumGeoDBOrg: 'Premium Geo DB'
};
const addons = (currentAggregation?.resources || [])
@@ -466,6 +468,21 @@
priceFormatter: ({ amount }) => formatCurrency(amount),
includeProgress: false
}),
...resources
.filter((r) => r.resourceId?.startsWith('addon_') && (r.amount ?? 0) > 0)
.map((addon) =>
createRow({
id: `addon-${addon.resourceId}`,
label:
addon.name ||
billingAddonNamesFallback[addon.resourceId] ||
addon.resourceId,
resource: addon,
usageFormatter: ({ value }) => formatNum(value),
priceFormatter: ({ amount }) => formatCurrency(amount),
includeProgress: false
})
),
createRow({
id: 'usage-details',
label: `<a href="${base}/project-${String(projectData.region || 'default')}-${projectData.$id}/settings/usage" style="text-decoration: underline; color: var(--fgcolor-accent-neutral);">Usage details</a>`,
@@ -18,7 +18,9 @@
import UpdateVariables from '../updateVariables.svelte';
import { page } from '$app/state';
import UpdateLabels from './updateLabels.svelte';
import PremiumGeoDB from './premiumGeoDB.svelte';
import UpdateOAuth2Server from './updateOAuth2Server.svelte';
import { isCloud } from '$lib/system';
import type { PageData } from './$types';
import { Alert } from '@appwrite.io/pink-svelte';
import { flags } from '$lib/flags';
@@ -104,6 +106,9 @@
{/if}
<UpdateServices />
<UpdateInstallations {...data.installations} limit={data.limit} offset={data.offset} />
{#if isCloud && $canWriteProjects}
<PremiumGeoDB addons={data.addons} addonPrice={data.addonPrice} />
{/if}
<UpdateVariables
{sdkCreateVariable}
{sdkUpdateVariable}
@@ -1,6 +1,7 @@
import { Dependencies, PAGE_LIMIT } from '$lib/constants';
import { isCloud } from '$lib/system';
import { sdk } from '$lib/stores/sdk';
import { Query } from '@appwrite.io/console';
import { Addon, Query } from '@appwrite.io/console';
import type { PageLoad } from './$types';
function isReadonlySettingsPermissionError(error: unknown): boolean {
@@ -11,26 +12,41 @@ function isReadonlySettingsPermissionError(error: unknown): boolean {
export const load: PageLoad = async ({ depends, url, params }) => {
depends(Dependencies.PROJECT_VARIABLES);
depends(Dependencies.PROJECT_INSTALLATIONS);
depends(Dependencies.ADDONS);
const limit = PAGE_LIMIT;
const offset = Number(url.searchParams.get('offset') ?? 0);
const variablesOffset = Number(url.searchParams.get('variablesOffset') ?? 0);
const projectSdk = sdk.forProject(params.region, params.project);
const [variablesResult, installationsResult] = await Promise.allSettled([
projectSdk.projectApi.listVariables({
queries: [Query.limit(limit), Query.offset(variablesOffset)]
}),
projectSdk.vcs.listInstallations({
queries: [Query.limit(limit), Query.offset(offset)]
})
]);
const [variablesResult, installationsResult, addonsResult, addonPriceResult] =
await Promise.allSettled([
projectSdk.projectApi.listVariables({
queries: [Query.limit(limit), Query.offset(variablesOffset)]
}),
projectSdk.vcs.listInstallations({
queries: [Query.limit(limit), Query.offset(offset)]
}),
isCloud
? sdk
.forConsoleIn(params.region)
.projects.listAddons({ projectId: params.project })
.catch(() => null)
: Promise.resolve(null),
isCloud
? sdk
.forConsoleIn(params.region)
.projects.getAddonPrice({
projectId: params.project,
addon: Addon.Premiumgeodb
})
.catch(() => null)
: Promise.resolve(null)
]);
const variables =
variablesResult.status === 'fulfilled'
? variablesResult.value
: (() => {
// Read-only users can be blocked from write-adjacent settings APIs.
// Only silence those permission errors so genuine load failures still surface.
if (!isReadonlySettingsPermissionError(variablesResult.reason)) {
throw variablesResult.reason;
}
@@ -45,8 +61,6 @@ export const load: PageLoad = async ({ depends, url, params }) => {
installationsResult.status === 'fulfilled'
? installationsResult.value
: (() => {
// Read-only users can be blocked from write-adjacent settings APIs.
// Only silence those permission errors so genuine load failures still surface.
if (!isReadonlySettingsPermissionError(installationsResult.reason)) {
throw installationsResult.reason;
}
@@ -57,11 +71,16 @@ export const load: PageLoad = async ({ depends, url, params }) => {
};
})();
const addons = addonsResult.status === 'fulfilled' ? addonsResult.value : null;
const addonPrice = addonPriceResult.status === 'fulfilled' ? addonPriceResult.value : null;
return {
limit,
offset,
variablesOffset,
variables,
installations
installations,
addons,
addonPrice
};
};
@@ -0,0 +1,280 @@
<script lang="ts">
import { onMount } from 'svelte';
import { Box, CardGrid } from '$lib/components';
import { Button } from '$lib/elements/forms';
import { getChangePlanUrl, plansInfo } from '$lib/stores/billing';
import { currentPlan, organization } from '$lib/stores/organization';
import { page } from '$app/state';
import { get } from 'svelte/store';
import { goto, invalidate } from '$app/navigation';
import { resolve } from '$app/paths';
import { Dependencies } from '$lib/constants';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { confirmPayment } from '$lib/stores/stripe';
import { formatCurrency } from '$lib/helpers/numbers';
import { Badge } from '@appwrite.io/pink-svelte';
import type { Models } from '@appwrite.io/console';
import PremiumGeoDBEnableModal from './premiumGeoDBEnableModal.svelte';
import PremiumGeoDBDisableModal from './premiumGeoDBDisableModal.svelte';
export let addons: Models.AddonList | null = null;
export let addonPrice: Models.AddonPrice | null = null;
let showEnable = false;
let showDisable = false;
let reEnabling = false;
let refreshing = false;
$: planSupportsPremiumGeoDB = $currentPlan?.supportedAddons?.premiumGeoDB === true;
$: canUpgradeToPremiumGeoDB =
!planSupportsPremiumGeoDB && hasUpgradeablePlanWithPremiumGeoDB($currentPlan);
$: premiumGeoDBAddon = addons?.addons?.find(
(a) => a.key === 'premiumGeoDB' && (a.status === 'active' || a.status === 'pending')
);
$: isPending = premiumGeoDBAddon?.status === 'pending';
$: isActive = premiumGeoDBAddon?.status === 'active';
$: isScheduledForRemoval = isActive && premiumGeoDBAddon?.nextValue === 0;
$: monthlyPriceLabel = addonPrice ? formatCurrency(addonPrice.monthlyPrice) : null;
function hasUpgradeablePlanWithPremiumGeoDB(plan: Models.BillingPlan): boolean {
if (!plan) return false;
const plans = get(plansInfo);
for (const [, p] of plans) {
if (p.order > plan.order && p.supportedAddons?.premiumGeoDB) {
return true;
}
}
return false;
}
onMount(async () => {
if (page.url.searchParams.get('type') === 'confirm-addon') {
let addonId = page.url.searchParams.get('addonId');
// Fall back to listing pending addons if addonId is missing
if (!addonId || addonId === 'undefined') {
try {
const addonList = await sdk
.forConsoleIn(page.params.region)
.projects.listAddons({ projectId: page.params.project });
const pending = addonList.addons.find(
(a) => a.key === 'premiumGeoDB' && a.status === 'pending'
);
addonId = pending?.$id ?? null;
} catch (e) {
addNotification({
message:
e?.message ??
'Unable to verify Premium Geo DB addon status. Please retry.',
type: 'error'
});
addonId = null;
}
}
if (addonId) {
await confirmAddon(addonId);
}
const settingsUrl = resolve('/(console)/project-[region]-[project]/settings', {
region: page.params.region,
project: page.params.project
});
await goto(settingsUrl, { replaceState: true });
}
});
async function confirmAddon(addonId: string) {
try {
await sdk.forConsoleIn(page.params.region).projects.confirmAddonPayment({
projectId: page.params.project,
addonId
});
await Promise.all([invalidate(Dependencies.ADDONS), invalidate(Dependencies.PROJECT)]);
addNotification({
message: 'Premium Geo DB addon has been enabled',
type: 'success'
});
} catch (e) {
// Webhook may have already activated it — sync state and assume success
if (e?.type === 'addon_not_found' || e?.code === 404) {
await Promise.all([
invalidate(Dependencies.ADDONS),
invalidate(Dependencies.PROJECT)
]);
addNotification({
message: 'Premium Geo DB addon has been enabled',
type: 'success'
});
} else if (e?.code === 402) {
// Payment failed — the backend has cleaned up; offer to retry from scratch
await invalidate(Dependencies.ADDONS);
addNotification({
message:
e?.message ??
'Payment could not be authorized. Please try enabling the addon again.',
type: 'error'
});
} else {
addNotification({
message: e.message,
type: 'error'
});
}
}
}
async function handleRefresh() {
if (!premiumGeoDBAddon) return;
refreshing = true;
try {
await confirmAddon(premiumGeoDBAddon.$id);
} finally {
refreshing = false;
}
}
async function handleReEnable() {
reEnabling = true;
try {
const result: Models.Addon | Models.PaymentAuthentication = await sdk
.forConsoleIn(page.params.region)
.projects.createPremiumGeoDBAddon({
projectId: page.params.project
});
// Re-enabling a scheduled-for-removal addon is normally free (already paid for
// the cycle), but the endpoint can still return a PaymentAuthentication if a
// charge is required. Mirror the enable modal so 3DS is not silently dropped.
if ('clientSecret' in result) {
const paymentAuth = result as unknown as Models.PaymentAuthentication;
const settingsUrl = resolve('/(console)/project-[region]-[project]/settings', {
region: page.params.region,
project: page.params.project
});
await confirmPayment({
clientSecret: paymentAuth.clientSecret,
paymentMethodId: $organization.paymentMethodId,
orgId: $organization.$id,
route: `${settingsUrl}?type=confirm-addon&addonId=${paymentAuth.addonId}`
});
return;
}
await Promise.all([invalidate(Dependencies.ADDONS), invalidate(Dependencies.PROJECT)]);
addNotification({
message: 'Premium Geo DB addon has been re-enabled',
type: 'success'
});
} catch (e) {
addNotification({
message: e.message,
type: 'error'
});
} finally {
reEnabling = false;
}
}
</script>
<CardGrid>
<svelte:fragment slot="title">Premium Geo DB</svelte:fragment>
Give your project richer location intelligence on every user. Tailor pricing by region, surface the
right currency and language, comply with local regulations, and spot suspicious sign-ins before they
cause damage — all without leaving Appwrite.
<svelte:fragment slot="aside">
<Box>
<h6>
<b>Premium Geo DB</b>
</h6>
{#if !planSupportsPremiumGeoDB && canUpgradeToPremiumGeoDB}
<p class="text u-margin-block-start-8">
Premium Geo DB is not available on your current plan. Upgrade your plan to
enable it.
</p>
<Button
secondary
class="u-margin-block-start-16"
href={getChangePlanUrl($organization?.$id)}>
<span class="text">Upgrade plan</span>
</Button>
{:else if !planSupportsPremiumGeoDB}
<p class="text u-margin-block-start-8">
Premium Geo DB is not available on your current plan.
</p>
{:else if isPending}
<div class="u-flex u-cross-center u-gap-8 u-margin-block-start-8">
<Badge variant="secondary" type="warning" content="Payment pending" />
</div>
<p class="text u-margin-block-start-8">
A payment is awaiting confirmation. If you've completed authentication, click
refresh to check the payment status.
</p>
<Button
secondary
class="u-margin-block-start-16"
disabled={refreshing}
on:click={handleRefresh}>
<span class="text">Refresh</span>
</Button>
{:else if isActive}
<div class="u-flex u-cross-center u-gap-8 u-margin-block-start-8">
{#if isScheduledForRemoval}
<Badge variant="secondary" type="warning" content="Scheduled for removal" />
{:else}
<Badge variant="secondary" type="success" content="Active" />
{/if}
</div>
<p class="text u-margin-block-start-8">
{#if monthlyPriceLabel}
Premium Geo DB is enabled for this project at {monthlyPriceLabel}/month.
{:else}
Premium Geo DB is enabled for this project.
{/if}
</p>
{#if isScheduledForRemoval}
<p class="text u-margin-block-start-8">
Premium Geo DB will be removed at the end of your current billing cycle.
</p>
<Button
secondary
class="u-margin-block-start-16"
disabled={reEnabling}
on:click={handleReEnable}>
<span class="text">Keep Premium Geo DB</span>
</Button>
{:else}
<Button
secondary
class="u-margin-block-start-16"
on:click={() => (showDisable = true)}>
<span class="text">Disable Premium Geo DB</span>
</Button>
{/if}
{:else}
<p class="text u-margin-block-start-8">
Enable Premium Geo DB for this project to collect detailed geolocation data on
every request.{#if monthlyPriceLabel}
This addon costs {monthlyPriceLabel}/month, prorated for your current
billing cycle.
{:else}
Billed prorated for your current cycle.
{/if}
</p>
<Button
secondary
class="u-margin-block-start-16"
on:click={() => (showEnable = true)}>
<span class="text">Enable Premium Geo DB</span>
</Button>
{/if}
</Box>
</svelte:fragment>
</CardGrid>
<PremiumGeoDBEnableModal bind:show={showEnable} {addonPrice} />
{#if premiumGeoDBAddon}
<PremiumGeoDBDisableModal bind:show={showDisable} addonId={premiumGeoDBAddon.$id} />
{/if}
@@ -0,0 +1,54 @@
<script lang="ts">
import { page } from '$app/state';
import { invalidate } from '$app/navigation';
import { Modal } from '$lib/components';
import { Button } from '$lib/elements/forms';
import { Dependencies } from '$lib/constants';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
let {
show = $bindable(false),
addonId
}: {
show: boolean;
addonId: string;
} = $props();
let error = $state<string | null>(null);
let submitting = $state(false);
async function handleSubmit() {
submitting = true;
error = null;
try {
await sdk.forConsoleIn(page.params.region).projects.deleteAddon({
projectId: page.params.project,
addonId
});
await Promise.all([invalidate(Dependencies.ADDONS), invalidate(Dependencies.PROJECT)]);
addNotification({
message:
'Premium Geo DB addon will be removed at the end of your current billing cycle',
type: 'success'
});
show = false;
} catch (e) {
error = e.message;
} finally {
submitting = false;
}
}
</script>
<Modal bind:error bind:show onSubmit={handleSubmit} title="Disable Premium Geo DB">
<p class="text">
Are you sure you want to disable the Premium Geo DB addon? The addon will remain active
until the end of your current billing cycle and will not be renewed.
</p>
<svelte:fragment slot="footer">
<Button text on:click={() => (show = false)}>Cancel</Button>
<Button secondary submit disabled={submitting}>Disable Premium Geo DB</Button>
</svelte:fragment>
</Modal>
@@ -0,0 +1,182 @@
<script lang="ts">
import { page } from '$app/state';
import { invalidate } from '$app/navigation';
import { resolve } from '$app/paths';
import { Modal } from '$lib/components';
import { Button } from '$lib/elements/forms';
import { Dependencies } from '$lib/constants';
import { addNotification } from '$lib/stores/notifications';
import { confirmPayment } from '$lib/stores/stripe';
import { organization } from '$lib/stores/organization';
import { sdk } from '$lib/stores/sdk';
import { formatCurrency } from '$lib/helpers/numbers';
import type { Models } from '@appwrite.io/console';
let {
show = $bindable(false),
addonPrice = null
}: {
show: boolean;
addonPrice: Models.AddonPrice | null;
} = $props();
let error = $state<string | null>(null);
let submitting = $state(false);
async function handleSubmit() {
submitting = true;
error = null;
try {
const result: Models.Addon | Models.PaymentAuthentication = await sdk
.forConsoleIn(page.params.region)
.projects.createPremiumGeoDBAddon({
projectId: page.params.project
});
if ('clientSecret' in result) {
const paymentAuth = result as unknown as Models.PaymentAuthentication;
const settingsUrl = resolve('/(console)/project-[region]-[project]/settings', {
region: page.params.region,
project: page.params.project
});
const outcome = await confirmPayment({
clientSecret: paymentAuth.clientSecret,
paymentMethodId: $organization.paymentMethodId,
orgId: $organization.$id,
route: `${settingsUrl}?type=confirm-addon&addonId=${paymentAuth.addonId}`,
redirectIfRequired: true
});
if (!outcome || outcome.status === 'error') {
if (outcome?.status === 'error') {
error = outcome.message;
}
return;
}
// 3DS challenge required — Stripe redirects; the settings onMount
// handler finalizes on return via ?type=confirm-addon.
if (outcome.status === 'requires_action') {
return;
}
await sdk.forConsoleIn(page.params.region).projects.confirmAddonPayment({
projectId: page.params.project,
addonId: paymentAuth.addonId
});
await Promise.all([
invalidate(Dependencies.ADDONS),
invalidate(Dependencies.PROJECT)
]);
if (outcome.status === 'processing') {
addNotification({
message:
"Premium Geo DB addon payment is processing — we'll activate it shortly.",
type: 'info'
});
} else {
addNotification({
message: 'Premium Geo DB addon has been enabled',
type: 'success'
});
}
show = false;
return;
}
await Promise.all([invalidate(Dependencies.ADDONS), invalidate(Dependencies.PROJECT)]);
addNotification({
message: 'Premium Geo DB addon has been enabled',
type: 'success'
});
show = false;
} catch (e) {
// 409 means addon already exists (pending or active from prior attempt)
if (e?.code === 409) {
await Promise.all([
invalidate(Dependencies.ADDONS),
invalidate(Dependencies.PROJECT)
]);
addNotification({
message: 'Premium Geo DB addon is already active for this project',
type: 'success'
});
show = false;
} else {
error = e.message;
}
} finally {
submitting = false;
}
}
</script>
<Modal bind:error bind:show onSubmit={handleSubmit} title="Enable Premium Geo DB">
{#if addonPrice}
<p class="text">
By clicking <b>Enable</b>, the amount of
<b>{formatCurrency(addonPrice.monthlyPrice)}</b> will be added to your subscription and
your payment method will be charged
<b>{formatCurrency(addonPrice.proratedAmount)} immediately</b> for the remaining days in your
billing cycle.
</p>
{:else}
<p class="text">
By clicking <b>Enable</b>, your payment method will be charged for the prorated amount
for the remaining days in your billing cycle, and the addon will be added to this
project's subscription for future cycles.
</p>
{/if}
<p class="text u-margin-block-start-16">
Premium Geo DB enriches session and request data with premium geolocation details including
timezone, postal code, ISP, connection type, and organization.
</p>
{#if addonPrice}
<div class="price-breakdown u-margin-block-start-24">
<div class="price-row">
<span class="text">{addonPrice.name}</span>
<span class="text">{formatCurrency(addonPrice.monthlyPrice)} / month</span>
</div>
<hr class="divider" />
<div class="price-row u-bold">
<span class="text">Due today (prorated)</span>
<span class="text">{formatCurrency(addonPrice.proratedAmount)}</span>
</div>
<p class="text u-color-text-offline u-margin-block-start-8 u-text-end">
* Plus applicable tax and fees
</p>
</div>
{/if}
<svelte:fragment slot="footer">
<Button text on:click={() => (show = false)}>Cancel</Button>
<Button secondary submit disabled={submitting}>Enable</Button>
</svelte:fragment>
</Modal>
<style>
.price-breakdown {
border: 1px solid hsl(var(--color-border));
border-radius: var(--border-radius-small);
padding: 1rem;
}
.price-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.divider {
border: none;
border-top: 1px solid hsl(var(--color-border));
margin-block: 0.75rem;
}
.u-text-end {
text-align: end;
}
</style>