This repository was archived by the owner on Sep 21, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathbilling.ts
More file actions
628 lines (559 loc) 路 20.2 KB
/
Copy pathbilling.ts
File metadata and controls
628 lines (559 loc) 路 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
import { browser } from '$app/environment';
import { goto } from '$app/navigation';
import { base } from '$app/paths';
import { Click, trackEvent } from '$lib/actions/analytics';
import { page } from '$app/stores';
import LimitReached from '$lib/components/billing/alerts/limitReached.svelte';
import MarkedForDeletion from '$lib/components/billing/alerts/markedForDeletion.svelte';
import MissingPaymentMethod from '$lib/components/billing/alerts/missingPaymentMethod.svelte';
import newDevUpgradePro from '$lib/components/billing/alerts/newDevUpgradePro.svelte';
import PaymentAuthRequired from '$lib/components/billing/alerts/paymentAuthRequired.svelte';
import PaymentMandate from '$lib/components/billing/alerts/paymentMandate.svelte';
import { BillingPlan, NEW_DEV_PRO_UPGRADE_COUPON } from '$lib/constants';
import { cachedStore } from '$lib/helpers/cache';
import { type Size, sizeToBytes } from '$lib/helpers/sizeConvertion';
import type {
AddressesList,
AggregationTeam,
Invoice,
InvoiceList,
PaymentList,
PaymentMethodData,
Plan,
PlansMap
} from '$lib/sdk/billing';
import { isBillingEnabled } from '$lib/profiles/index.svelte';
import { activeHeaderAlert, orgMissingPaymentMethod } from '$routes/(console)/store';
import { AppwriteException, Query } from '@appwrite.io/console';
import { derived, get, writable } from 'svelte/store';
import { headerAlert } from './headerAlert';
import { addNotification, notifications } from './notifications';
import {
currentPlan,
organization,
type Organization,
type OrganizationError
} from './organization';
import { canSeeBilling } from './roles';
import { sdk } from './sdk';
import { user } from './user';
import BudgetLimitAlert from '$routes/(console)/organization-[organization]/budgetLimitAlert.svelte';
import TeamReadonlyAlert from '$routes/(console)/organization-[organization]/teamReadonlyAlert.svelte';
import ProjectsLimit from '$lib/components/billing/alerts/projectsLimit.svelte';
import { ProfileMode, resolvedProfile } from '$lib/profiles/index.svelte';
import { isFreePlan, isPaidPlan } from '$lib/helpers/billing';
import { BillingPlan as CloudSdkBillingPlan } from '@appwrite.io/console';
export type Tier = 'tier-0' | 'tier-1' | 'tier-2' | 'auto-1' | 'cont-1' | 'ent-1';
export const roles = [
{
label: 'Owner',
value: 'owner'
},
{
label: 'Developer',
value: 'developer'
},
{
label: 'Editor',
value: 'editor'
},
{
label: 'Analyst',
value: 'analyst'
},
{
label: 'Billing',
value: 'billing'
}
];
export const teamStatusReadonly = 'readonly';
export const billingLimitOutstandingInvoice = 'outstanding_invoice';
export const paymentMethods = derived(page, ($page) => $page.data.paymentMethods as PaymentList);
export const addressList = derived(page, ($page) => $page.data.addressList as AddressesList);
export const plansInfo = derived(page, ($page) => $page.data.plansInfo as PlansMap);
export const daysLeftInTrial = writable<number>(0);
export const readOnly = writable<boolean>(false);
export const showBudgetAlert = derived(
page,
($page) => ($page.data.organization?.billingLimits.budgetLimit ?? 0) >= 100
);
export function getRoleLabel(role: string) {
return roles.find((r) => r.value === role)?.label ?? role;
}
export function tierToPlan(tier: Tier) {
switch (tier) {
case BillingPlan.FREE:
return tierFree;
case BillingPlan.PRO:
return tierPro;
case BillingPlan.SCALE:
return tierScale;
case BillingPlan.GITHUB_EDUCATION:
return tierGitHubEducation;
case BillingPlan.CUSTOM:
return tierCustom;
case BillingPlan.ENTERPRISE:
return tierEnterprise;
default:
return tierCustom;
}
}
export function getNextTier(tier: Tier) {
switch (tier) {
case BillingPlan.FREE:
return BillingPlan.PRO;
case BillingPlan.PRO:
return BillingPlan.SCALE;
default:
return BillingPlan.PRO;
}
}
export function getPreviousTier(tier: Tier) {
switch (tier) {
case BillingPlan.PRO:
return BillingPlan.FREE;
case BillingPlan.SCALE:
return BillingPlan.PRO;
default:
return BillingPlan.FREE;
}
}
export type PlanServices =
| 'bandwidth'
| 'bandwidthAddon'
| 'buckets'
| 'databases'
| 'executions'
| 'executionsAddon'
| 'fileSize'
| 'functions'
| 'logs'
| 'memberAddon'
| 'members'
| 'projects'
| 'platforms'
| 'realtime'
| 'realtimeAddon'
| 'storage'
| 'storageAddon'
| 'teams'
| 'users'
| 'usersAddon'
| 'webhooks'
| 'sites'
| 'authPhone'
| 'imageTransformations';
export function getServiceLimit(
serviceId: PlanServices,
tier: Tier | CloudSdkBillingPlan = null,
plan?: Plan
): number {
if (!isBillingEnabled) return 0;
if (!serviceId) return 0;
plan ??= get(currentPlan);
if (tier) {
const info = get(plansInfo);
if (!info) return 0;
plan ??= info.get(tier);
}
if (serviceId === 'members') {
if (!plan?.addons?.seats) return Infinity;
return plan.addons.seats?.limit ?? 1;
}
if (serviceId === 'projects') {
if (!plan?.addons?.projects) return Infinity;
return plan.addons.projects?.limit ?? 1;
}
return plan?.[serviceId] ?? 0;
}
export const failedInvoice = cachedStore<
Invoice,
{
load: (orgId: string) => Promise<void>;
}
>('failedInvoice', function ({ set }) {
return {
load: async (orgId) => {
if (!isBillingEnabled) set(null);
if (!get(canSeeBilling)) set(null);
const failedInvoices = await sdk.forConsole.billing.listInvoices(orgId, [
Query.equal('status', 'failed')
]);
// const failedInvoices = invoices.invoices;
if (failedInvoices?.invoices?.length > 0) {
const firstFailed = failedInvoices.invoices[0];
const today = new Date();
const thirtyDaysAgo = new Date(today.setDate(today.getDate() - 30));
const failedDate = new Date(firstFailed.$createdAt);
if (failedDate < thirtyDaysAgo) {
readOnly.set(true);
}
} else set(null);
}
};
});
export const actionRequiredInvoices = writable<InvoiceList>(null);
export type TierData = {
name: string;
description: string;
};
export const tierFree: TierData = {
name: 'Free',
description: 'A great fit for passion projects and small applications.'
};
export const tierGitHubEducation: TierData = {
name: 'GitHub Education',
description: 'For members of GitHub student developers program.'
};
export const tierPro: TierData = {
name: 'Pro',
description:
'For production applications that need powerful functionality and resources to scale.'
};
export const tierScale: TierData = {
name: 'Scale',
description:
'For teams that handle more complex and large projects and need more control and support.'
};
export const tierCustom: TierData = {
name: 'Custom',
description: 'Team on a custom contract'
};
export const tierEnterprise: TierData = {
name: 'Enterprise',
description: 'For enterprises that need more power and premium support.'
};
export const showUsageRatesModal = writable<boolean>(false);
export const useNewPricingModal = derived(currentPlan, ($plan) => $plan?.usagePerProject === true);
export function checkForUsageFees(plan: Tier, id: PlanServices) {
if (plan === BillingPlan.PRO || plan === BillingPlan.SCALE) {
switch (id) {
case 'bandwidth':
case 'storage':
case 'users':
case 'executions':
case 'realtime':
return true;
default:
return false;
}
} else return false;
}
export function checkForProjectLimitation(id: PlanServices) {
// Members are no longer limited on Pro and Scale plans (unlimited seats)
if (id === 'members') {
const currentTier = get(organization)?.billingPlan;
if (isPaidPlan(currentTier)) {
return false; // No project limitation for members on Pro/Scale plans
}
}
switch (id) {
case 'databases':
case 'functions':
case 'buckets':
case 'members': // Only applies to Free plan now
case 'platforms':
case 'webhooks':
case 'teams':
return true;
default:
return false;
}
}
export function isServiceLimited(serviceId: PlanServices, plan: Tier, total: number) {
if (!total) return false;
const limit = getServiceLimit(serviceId) || Infinity;
const isLimited = limit !== 0 && limit < Infinity;
const hasUsageFees = checkForUsageFees(plan, serviceId);
return isLimited && total >= limit && !hasUsageFees;
}
export function calculateTrialDay(org: Organization) {
if (isFreePlan(org?.billingPlan)) return false;
const endDate = new Date(org?.billingStartDate);
const today = new Date();
let diffTime = endDate.getTime() - today.getTime();
diffTime = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
const days = diffTime < 1 ? 0 : diffTime;
daysLeftInTrial.set(days);
return days;
}
export async function checkForProjectsLimit(org: Organization, orgProjectCount?: number) {
if (!isBillingEnabled) return;
if (!org) return;
const plan = await sdk.forConsole.billing.getOrganizationPlan(org.$id);
if (!plan) return;
if (!isFreePlan(plan.$id)) return;
if (!org.projects) return;
if (org.projects.length > 0) return;
const projectCount = orgProjectCount;
if (projectCount === undefined) return;
if (plan.projects > 0 && projectCount > plan.projects) {
headerAlert.add({
id: 'projectsLimitReached',
component: ProjectsLimit,
show: true,
importance: 12
});
}
}
export async function checkForUsageLimit(org: Organization) {
if (org?.status === teamStatusReadonly && org?.remarks === billingLimitOutstandingInvoice) {
headerAlert.add({
id: 'teamReadOnlyFailedInvoices',
component: TeamReadonlyAlert,
show: true,
importance: 11
});
readOnly.set(true);
return;
}
if (!org?.billingLimits && org?.status !== teamStatusReadonly) {
readOnly.set(false);
return;
}
if (!isFreePlan(org?.billingPlan)) {
const { budgetLimit } = org?.billingLimits ?? {};
if (budgetLimit && budgetLimit >= 100) {
readOnly.set(false);
headerAlert.add({
id: 'budgetLimit',
component: BudgetLimitAlert,
show: true,
importance: 10
});
readOnly.set(true);
return;
}
}
// TODO: @itznotabug - check with @abnegate, what do we do here? this is billing!
const { bandwidth, documents, executions, storage, users } = org?.billingLimits ?? {};
const resources = [
{ value: bandwidth, name: 'bandwidth' },
{ value: documents, name: 'documents' },
{ value: executions, name: 'executions' },
{ value: storage, name: 'storage' },
{ value: users, name: 'users' }
];
const members = org.total;
const memberLimit = getServiceLimit('members');
const membersOverflow = memberLimit === Infinity ? 0 : Math.max(0, members - memberLimit);
if (resources.some((r) => r.value >= 100) || membersOverflow > 0) {
readOnly.set(true);
headerAlert.add({
id: 'limitReached',
component: LimitReached,
show: true,
importance: 7
});
} else if (resources.some((r) => r.value >= 75)) {
readOnly.set(false);
const lastNotification = parseInt(localStorage.getItem('limitReachedNotification')) ?? 0;
const now = new Date().getTime();
if (now - lastNotification < 1000 * 60 * 60 * 24) return;
localStorage.setItem('limitReachedNotification', now.toString());
let message = `<b>${org.name}</b> has reached <b>75%</b> of the ${tierToPlan(BillingPlan.FREE).name} plan's ${resources.find((r) => r.value >= 75).name} limit. Upgrade to ensure there are no service disruptions.`;
if (resources.filter((r) => r.value >= 75)?.length > 1) {
message = `Usage for <b>${org.name}</b> has reached 75% of the ${tierToPlan(BillingPlan.FREE).name} plan limit. Upgrade to ensure there are no service disruptions.`;
}
addNotification({
type: 'warning',
isHtml: true,
timeout: 0,
message,
buttons: [
{
name: 'View usage',
method: () => {
goto(`${base}/organization-${org.$id}/usage`);
}
},
{
name: 'Upgrade plan',
method: () => {
goto(`${base}/organization-${org.$id}/change-plan`);
trackEvent(Click.OrganizationClickUpgrade, {
from: 'button',
source: 'limit_reached_notification'
});
}
}
]
});
} else {
readOnly.set(false);
}
}
export async function checkPaymentAuthorizationRequired(org: Organization) {
if (isFreePlan(org.billingPlan)) return;
const invoices = await sdk.forConsole.billing.listInvoices(org.$id, [
Query.equal('status', 'requires_authentication')
]);
if (invoices?.invoices?.length > 0) {
headerAlert.add({
id: 'paymentAuthRequired',
component: PaymentAuthRequired,
show: true,
importance: 8
});
}
activeHeaderAlert.set(headerAlert.get());
actionRequiredInvoices.set(invoices);
}
export async function paymentExpired(org: Organization) {
if (!org?.paymentMethodId) return;
const payment = await sdk.forConsole.billing.getOrganizationPaymentMethod(
org.$id,
org.paymentMethodId
);
if (!payment?.expiryYear) return;
const sessionStorageNotification = sessionStorage.getItem('expiredPaymentNotification');
if (sessionStorageNotification === 'true') return;
const year = new Date().getFullYear();
const month = new Date().getMonth();
const expiredMessage = `The default payment method for <b>${org.name}</b> has expired`;
const expiringMessage = `The default payment method for <b>${org.name}</b> will expire soon`;
const nots = get(notifications);
const expiredNotification = nots.some((n) => n.message === expiredMessage);
const expiringNotification = nots.some((n) => n.message === expiringMessage);
const cardExpiry = new Date(payment.expiryYear, payment.expiryMonth, 1);
const nextMonth = new Date(year, month + 1, 1);
const isExpiringNextMonth = cardExpiry.getTime() === nextMonth.getTime();
if (payment.expired && !expiredNotification) {
addNotification({
type: 'error',
isHtml: true,
timeout: 0,
message: expiredMessage,
buttons: [
{
name: 'Update payment details',
method: () => {
goto(`${base}/account/payments`);
}
}
]
});
} else if (!expiringNotification && !payment.expired && isExpiringNextMonth) {
addNotification({
type: 'warning',
isHtml: true,
message: expiringMessage,
buttons: [
{
name: 'Update payment details',
method: () => {
goto(`${base}/account/payments`);
}
}
]
});
}
sessionStorage.setItem('expiredPaymentNotification', 'true');
}
export function checkForMarkedForDeletion(org: Organization) {
if (org?.markedForDeletion) {
headerAlert.add({
id: 'markedForDeletion',
component: MarkedForDeletion,
show: true,
importance: 10
});
}
}
export const paymentMissingMandate = writable<PaymentMethodData>(null);
export async function checkForMandate(org: Organization) {
const paymentId = org.paymentMethodId ?? org.backupPaymentMethodId;
if (!paymentId) return;
const paymentMethod = await sdk.forConsole.billing.getPaymentMethod(paymentId);
if (paymentMethod?.mandateId === null && paymentMethod?.country.toLowerCase() === 'in') {
headerAlert.add({
id: 'paymentMandate',
component: PaymentMandate,
show: true,
importance: 8
});
activeHeaderAlert.set(headerAlert.get());
paymentMissingMandate.set(paymentMethod);
}
}
export async function checkForMissingPaymentMethod() {
const orgs = await sdk.forConsole.billing.listOrganization([
Query.notEqual('billingPlan', resolvedProfile.freeTier),
Query.isNull('paymentMethodId'),
Query.isNull('backupPaymentMethodId'),
Query.equal('platform', resolvedProfile.organizationPlatform)
]);
if (orgs?.total) {
orgMissingPaymentMethod.set(orgs.teams[0]);
headerAlert.add({
id: 'missingPaymentMethod',
component: MissingPaymentMethod,
show: true,
importance: 8
});
}
}
// Display upgrade banner for new users after 1 week for 30 days
export async function checkForNewDevUpgradePro(org: Organization) {
if (resolvedProfile.id !== ProfileMode.CONSOLE) return;
// browser or plan check.
if (!browser || !isFreePlan(org?.billingPlan)) return;
// already dismissed by user!
if (localStorage.getItem('newDevUpgradePro')) return;
// saves one trip to backend!
const notValidKey = `${org.$id}:isNotValid`;
if (localStorage.getItem(notValidKey)) return;
const now = new Date().getTime();
const account = get(user);
const accountCreated = new Date(account.$createdAt).getTime();
if (now - accountCreated < 1000 * 60 * 60 * 24 * 7) return;
const organizations = await sdk.forConsole.billing.listOrganization([
Query.notEqual('billingPlan', resolvedProfile.freeTier),
Query.equal('platform', resolvedProfile.organizationPlatform)
]);
if (organizations?.total) return;
try {
await sdk.forConsole.billing.getCouponAccount(NEW_DEV_PRO_UPGRADE_COUPON);
} catch (error) {
if (
// already utilized if error is 409
error instanceof AppwriteException &&
error?.code === 409 &&
error.type === 'billing_coupon_already_used'
) {
localStorage.setItem(notValidKey, 'true');
}
return;
}
headerAlert.add({
id: 'newDevUpgradePro',
component: newDevUpgradePro,
show: true,
importance: 1
});
}
export const upgradeURL = derived(
page,
($page) => `${base}/organization-${$page.data?.organization?.$id}/change-plan`
);
export const billingURL = derived(
page,
($page) => `${base}/organization-${$page.data?.organization?.$id}/billing`
);
export const hideBillingHeaderRoutes = [base + '/create-organization', base + '/account'];
export function calculateExcess(addon: AggregationTeam, plan: Plan) {
return {
bandwidth: calculateResourceSurplus(addon.usageBandwidth, plan.bandwidth),
storage: calculateResourceSurplus(addon.usageStorage, plan.storage, 'GB'),
executions: calculateResourceSurplus(addon.usageExecutions, plan.executions, 'GB'),
members: addon.additionalMembers
};
}
export function calculateResourceSurplus(total: number, limit: number, limitUnit: Size = null) {
if (total === undefined || limit === undefined) return 0;
const realLimit = (limitUnit ? sizeToBytes(limit, limitUnit) : limit) || Infinity;
return total > realLimit ? total - realLimit : 0;
}
export function isOrganization(org: Organization | OrganizationError): org is Organization {
return (org as Organization).$id !== undefined;
}