Refactored classes according to new convention

This commit is contained in:
giancarlo
2024-04-23 00:10:12 +08:00
parent 70da6ef1fa
commit 17e0781581
30 changed files with 351 additions and 131 deletions

View File

@@ -6,7 +6,7 @@ import { enhanceAction } from '@kit/next/actions';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import { PersonalAccountCheckoutSchema } from '../schema/personal-account-checkout.schema';
import { UserBillingService } from './user-billing.service';
import { createUserBillingService } from './user-billing.service';
/**
* @name createPersonalAccountCheckoutSession
@@ -14,7 +14,8 @@ import { UserBillingService } from './user-billing.service';
*/
export const createPersonalAccountCheckoutSession = enhanceAction(
async function (data) {
const service = new UserBillingService(getSupabaseServerActionClient());
const client = getSupabaseServerActionClient();
const service = createUserBillingService(client);
return await service.createCheckoutSession(data);
},
@@ -24,10 +25,14 @@ export const createPersonalAccountCheckoutSession = enhanceAction(
);
/**
* @name createPersonalAccountBillingPortalSession
* @description Creates a billing Portal session for a personal account
*/
export async function createPersonalAccountBillingPortalSession() {
const service = new UserBillingService(getSupabaseServerActionClient());
const client = getSupabaseServerActionClient();
const service = createUserBillingService(client);
// get url to billing portal
const url = await service.createBillingPortalSession();
return redirect(url);

View File

@@ -17,7 +17,15 @@ import { Database } from '~/lib/database.types';
import { PersonalAccountCheckoutSchema } from '../schema/personal-account-checkout.schema';
export class UserBillingService {
export function createUserBillingService(client: SupabaseClient<Database>) {
return new UserBillingService(client);
}
/**
* @name UserBillingService
* @description Service for managing billing for personal accounts.
*/
class UserBillingService {
private readonly namespace = 'billing.personal-account';
constructor(private readonly client: SupabaseClient<Database>) {}

View File

@@ -11,7 +11,7 @@ import {
TeamBillingPortalSchema,
TeamCheckoutSchema,
} from '../schema/team-billing.schema';
import { TeamBillingService } from './team-billing.service';
import { createTeamBillingService } from './team-billing.service';
/**
* @name createTeamAccountCheckoutSession
@@ -21,7 +21,9 @@ export async function createTeamAccountCheckoutSession(
params: z.infer<typeof TeamCheckoutSchema>,
) {
const data = TeamCheckoutSchema.parse(params);
const service = new TeamBillingService(getSupabaseServerActionClient());
const client = getSupabaseServerActionClient();
const service = createTeamBillingService(client);
return service.createCheckout(data);
}
@@ -33,7 +35,9 @@ export async function createTeamAccountCheckoutSession(
*/
export async function createBillingPortalSession(formData: FormData) {
const params = TeamBillingPortalSchema.parse(Object.fromEntries(formData));
const service = new TeamBillingService(getSupabaseServerActionClient());
const client = getSupabaseServerActionClient();
const service = createTeamBillingService(client);
// get url to billing portal
const url = await service.createBillingPortalSession(params);

View File

@@ -18,7 +18,15 @@ import { Database } from '~/lib/database.types';
import { TeamCheckoutSchema } from '../schema/team-billing.schema';
export class TeamBillingService {
export function createTeamBillingService(client: SupabaseClient<Database>) {
return new TeamBillingService(client);
}
/**
* @name TeamBillingService
* @description Service for managing billing for team accounts.
*/
class TeamBillingService {
private readonly namespace = 'billing.team-account';
constructor(private readonly client: SupabaseClient<Database>) {}

View File

@@ -0,0 +1,91 @@
import 'server-only';
import { SupabaseClient } from '@supabase/supabase-js';
import { Database } from '~/lib/database.types';
import { loadTeamWorkspace } from '../../../_lib/server/team-account-workspace.loader';
/**
* Load data for the members page
* @param client
* @param slug
*/
export async function loadMembersPageData(
client: SupabaseClient<Database>,
slug: string,
) {
return Promise.all([
loadTeamWorkspace(slug),
loadAccountMembers(client, slug),
loadInvitations(client, slug),
loadUser(client),
canAddMember,
]);
}
/**
* @name canAddMember
* @description Check if the current user can add a member to the account
*
* This needs additional logic to determine if the user can add a member to the account
* Please implement the logic and return a boolean value
*
* The same check needs to be added when creating an invitation
*
*/
async function canAddMember() {
return Promise.resolve(true);
}
async function loadUser(client: SupabaseClient<Database>) {
const { data, error } = await client.auth.getUser();
if (error) {
throw error;
}
return data.user;
}
/**
* Load account members
* @param client
* @param account
*/
async function loadAccountMembers(
client: SupabaseClient<Database>,
account: string,
) {
const { data, error } = await client.rpc('get_account_members', {
account_slug: account,
});
if (error) {
console.error(error);
throw error;
}
return data ?? [];
}
/**
* Load account invitations
* @param client
* @param account
*/
async function loadInvitations(
client: SupabaseClient<Database>,
account: string,
) {
const { data, error } = await client.rpc('get_account_invitations', {
account_slug: account,
});
if (error) {
console.error(error);
throw error;
}
return data ?? [];
}

View File

@@ -1,5 +1,3 @@
import { SupabaseClient } from '@supabase/supabase-js';
import { PlusCircle } from 'lucide-react';
import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client';
@@ -20,12 +18,11 @@ import { If } from '@kit/ui/if';
import { PageBody } from '@kit/ui/page';
import { Trans } from '@kit/ui/trans';
import { Database } from '~/lib/database.types';
import { createI18nServerInstance } from '~/lib/i18n/i18n.server';
import { withI18n } from '~/lib/i18n/with-i18n';
import { AccountLayoutHeader } from '../_components/account-layout-header';
import { loadTeamWorkspace } from '../_lib/server/team-account-workspace.loader';
import { loadMembersPageData } from './_lib/server/members-page.loader';
interface Params {
params: {
@@ -33,57 +30,6 @@ interface Params {
};
}
async function loadUser(client: SupabaseClient<Database>) {
const { data, error } = await client.auth.getUser();
if (error) {
throw error;
}
return data.user;
}
async function loadAccountMembers(
client: SupabaseClient<Database>,
account: string,
) {
const { data, error } = await client.rpc('get_account_members', {
account_slug: account,
});
if (error) {
console.error(error);
throw error;
}
return data ?? [];
}
async function loadInvitations(
client: SupabaseClient<Database>,
account: string,
) {
const { data, error } = await client.rpc('get_account_invitations', {
account_slug: account,
});
if (error) {
console.error(error);
throw error;
}
return data ?? [];
}
async function loadData(client: SupabaseClient<Database>, slug: string) {
return Promise.all([
loadTeamWorkspace(slug),
loadAccountMembers(client, slug),
loadInvitations(client, slug),
loadUser(client),
]);
}
export const generateMetadata = async () => {
const i18n = await createI18nServerInstance();
const title = i18n.t('teams:members.pageTitle');
@@ -96,10 +42,8 @@ export const generateMetadata = async () => {
async function TeamAccountMembersPage({ params }: Params) {
const client = getSupabaseServerComponentClient();
const [{ account }, members, invitations, user] = await loadData(
client,
params.account,
);
const [{ account }, members, invitations, user, canAddMember] =
await loadMembersPageData(client, params.account);
const canManageRoles = account.permissions.includes('roles.manage');
const canManageInvitations = account.permissions.includes('invites.manage');
@@ -131,7 +75,7 @@ async function TeamAccountMembersPage({ params }: Params) {
</CardDescription>
</div>
<If condition={canManageInvitations}>
<If condition={canManageInvitations && canAddMember}>
<InviteMembersDialogContainer
userRoleHierarchy={currentUserRoleHierarchy}
accountId={account.id}

View File

@@ -3,7 +3,7 @@ import 'server-only';
import { Database } from '@kit/supabase/database';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import { BillingGatewayService } from './billing-gateway.service';
import { createBillingGatewayService } from './billing-gateway.service';
/**
* @description This function retrieves the billing provider from the database and returns a
@@ -15,7 +15,7 @@ export async function getBillingGatewayProvider(
) {
const provider = await getBillingProvider(client);
return new BillingGatewayService(provider);
return createBillingGatewayService(provider);
}
async function getBillingProvider(

View File

@@ -14,6 +14,12 @@ import {
import { BillingGatewayFactoryService } from './billing-gateway-factory.service';
export function createBillingGatewayService(
provider: z.infer<typeof BillingProviderSchema>,
) {
return new BillingGatewayService(provider);
}
/**
* @description The billing gateway service to interact with the billing provider of choice (e.g. Stripe)
* @class BillingGatewayService
@@ -23,7 +29,7 @@ import { BillingGatewayFactoryService } from './billing-gateway-factory.service'
* const provider = 'stripe';
* const billingGatewayService = new BillingGatewayService(provider);
*/
export class BillingGatewayService {
class BillingGatewayService {
constructor(
private readonly provider: z.infer<typeof BillingProviderSchema>,
) {}

View File

@@ -2,13 +2,26 @@ import 'server-only';
import { Database } from '@kit/supabase/database';
import { BillingGatewayService } from '../billing-gateway/billing-gateway.service';
import { createBillingGatewayService } from '../billing-gateway/billing-gateway.service';
type Subscription = Database['public']['Tables']['subscriptions']['Row'];
export class BillingWebhooksService {
export function createBillingWebhooksService() {
return new BillingWebhooksService();
}
/**
* @name BillingWebhooksService
* @description Service for handling billing webhooks.
*/
class BillingWebhooksService {
/**
* @name handleSubscriptionDeletedWebhook
* @description Handles the webhook for when a subscription is deleted.
* @param subscription
*/
async handleSubscriptionDeletedWebhook(subscription: Subscription) {
const gateway = new BillingGatewayService(subscription.billing_provider);
const gateway = createBillingGatewayService(subscription.billing_provider);
await gateway.cancelSubscription({
subscriptionId: subscription.id,

View File

@@ -1,5 +1,6 @@
import { SupabaseClient } from '@supabase/supabase-js';
import { createBillingWebhooksService } from '@kit/billing-gateway';
import { getLogger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
@@ -42,11 +43,11 @@ export class DatabaseWebhookRouterService {
}
private async handleInvitationsWebhook(body: RecordChange<'invitations'>) {
const { AccountInvitationsWebhookService } = await import(
const { createAccountInvitationsWebhookService } = await import(
'@kit/team-accounts/webhooks'
);
const service = new AccountInvitationsWebhookService(this.adminClient);
const service = createAccountInvitationsWebhookService(this.adminClient);
return service.handleInvitationWebhook(body.record);
}
@@ -54,22 +55,25 @@ export class DatabaseWebhookRouterService {
private async handleSubscriptionsWebhook(
body: RecordChange<'subscriptions'>,
) {
const { BillingWebhooksService } = await import('@kit/billing-gateway');
const service = new BillingWebhooksService();
if (body.type === 'DELETE' && body.old_record) {
const { createBillingWebhooksService } = await import(
'@kit/billing-gateway'
);
const service = createBillingWebhooksService();
return service.handleSubscriptionDeletedWebhook(body.old_record);
}
}
private async handleAccountsWebhook(body: RecordChange<'accounts'>) {
const { AccountWebhooksService } = await import(
'@kit/team-accounts/webhooks'
);
const service = new AccountWebhooksService();
if (body.type === 'DELETE' && body.old_record) {
const { createAccountWebhooksService } = await import(
'@kit/team-accounts/webhooks'
);
const service = createAccountWebhooksService();
return service.handleAccountDeletedWebhook(body.old_record);
}
}

View File

@@ -10,7 +10,7 @@ import { requireUser } from '@kit/supabase/require-user';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import { DeletePersonalAccountSchema } from '../schema/delete-personal-account.schema';
import { DeletePersonalAccountService } from './services/delete-personal-account.service';
import { createDeletePersonalAccountService } from './services/delete-personal-account.service';
const emailSettings = getEmailSettingsFromEnvironment();
@@ -53,7 +53,7 @@ export async function deletePersonalAccountAction(formData: FormData) {
const userEmail = auth.data.email ?? null;
// create a new instance of the personal accounts service
const service = new DeletePersonalAccountService();
const service = createDeletePersonalAccountService();
// delete the user's account and cancel all subscriptions
await service.deletePersonalAccount({

View File

@@ -5,6 +5,10 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { getLogger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
export function createDeletePersonalAccountService() {
return new DeletePersonalAccountService();
}
/**
* @name DeletePersonalAccountService
* @description Service for managing accounts in the application
@@ -13,7 +17,7 @@ import { Database } from '@kit/supabase/database';
* const client = getSupabaseClient();
* const accountsService = new DeletePersonalAccountService();
*/
export class DeletePersonalAccountService {
class DeletePersonalAccountService {
private namespace = 'accounts.delete';
/**

View File

@@ -13,8 +13,8 @@ import {
ImpersonateUserSchema,
ReactivateUserSchema,
} from './schema/admin-actions.schema';
import { AdminAccountsService } from './services/admin-accounts.service';
import { AdminAuthUserService } from './services/admin-auth-user.service';
import { createAdminAccountsService } from './services/admin-accounts.service';
import { createAdminAuthUserService } from './services/admin-auth-user.service';
import { adminAction } from './utils/admin-action';
/**
@@ -126,13 +126,13 @@ function getAdminAuthService() {
const client = getSupabaseServerActionClient();
const adminClient = getSupabaseServerActionClient({ admin: true });
return new AdminAuthUserService(client, adminClient);
return createAdminAuthUserService(client, adminClient);
}
function getAdminAccountsService() {
const adminClient = getSupabaseServerActionClient({ admin: true });
return new AdminAccountsService(adminClient);
return createAdminAccountsService(adminClient);
}
function revalidateAdmin() {

View File

@@ -4,7 +4,7 @@ import { cache } from 'react';
import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client';
import { AdminDashboardService } from '../services/admin-dashboard.service';
import { createAdminDashboardService } from '../services/admin-dashboard.service';
/**
* @name loadAdminDashboard
@@ -13,7 +13,7 @@ import { AdminDashboardService } from '../services/admin-dashboard.service';
*/
export const loadAdminDashboard = cache(() => {
const client = getSupabaseServerComponentClient({ admin: true });
const service = new AdminDashboardService(client);
const service = createAdminDashboardService(client);
return service.getDashboardData();
});

View File

@@ -4,7 +4,11 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { Database } from '@kit/supabase/database';
export class AdminAccountsService {
export function createAdminAccountsService(client: SupabaseClient<Database>) {
return new AdminAccountsService(client);
}
class AdminAccountsService {
constructor(private adminClient: SupabaseClient<Database>) {}
async deleteAccount(accountId: string) {

View File

@@ -4,12 +4,19 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { Database } from '@kit/supabase/database';
export function createAdminAuthUserService(
client: SupabaseClient<Database>,
adminClient: SupabaseClient<Database>,
) {
return new AdminAuthUserService(client, adminClient);
}
/**
* @name AdminAuthUserService
* @description Service for performing admin actions on users in the system.
* This service only interacts with the Supabase Auth Admin API.
*/
export class AdminAuthUserService {
class AdminAuthUserService {
constructor(
private readonly client: SupabaseClient<Database>,
private readonly adminClient: SupabaseClient<Database>,

View File

@@ -2,9 +2,17 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { Database } from '@kit/supabase/database';
export function createAdminDashboardService(client: SupabaseClient<Database>) {
return new AdminDashboardService(client);
}
export class AdminDashboardService {
constructor(private readonly client: SupabaseClient<Database>) {}
/**
* Get the dashboard data for the admin dashboard
* @param count
*/
async getDashboardData(
{ count }: { count: 'exact' | 'estimated' | 'planned' } = {
count: 'estimated',

View File

@@ -8,7 +8,7 @@ import { requireUser } from '@kit/supabase/require-user';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import { CreateTeamSchema } from '../../schema/create-team.schema';
import { CreateTeamAccountService } from '../services/create-team-account.service';
import { createCreateTeamAccountService } from '../services/create-team-account.service';
const TEAM_ACCOUNTS_HOME_PATH = z
.string({
@@ -23,7 +23,6 @@ export async function createOrganizationAccountAction(
const { name: accountName } = CreateTeamSchema.parse(params);
const client = getSupabaseServerActionClient();
const service = new CreateTeamAccountService(client);
const auth = await requireUser(client);
if (auth.error) {
@@ -31,6 +30,7 @@ export async function createOrganizationAccountAction(
}
const userId = auth.data.id;
const service = createCreateTeamAccountService(client);
const { data, error } = await service.createNewOrganizationAccount({
name: accountName,

View File

@@ -9,7 +9,7 @@ import { requireUser } from '@kit/supabase/require-user';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import { DeleteTeamAccountSchema } from '../../schema/delete-team-account.schema';
import { DeleteTeamAccountService } from '../services/delete-team-account.service';
import { createDeleteTeamAccountService } from '../services/delete-team-account.service';
export async function deleteTeamAccountAction(formData: FormData) {
const params = DeleteTeamAccountSchema.parse(
@@ -27,7 +27,7 @@ export async function deleteTeamAccountAction(formData: FormData) {
await assertUserPermissionsToDeleteTeamAccount(client, params.accountId);
// Get the Supabase client and create a new service instance.
const service = new DeleteTeamAccountService();
const service = createDeleteTeamAccountService();
// Delete the team account and all associated data.
await service.deleteTeamAccount(

View File

@@ -7,7 +7,7 @@ import { requireUser } from '@kit/supabase/require-user';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import { LeaveTeamAccountSchema } from '../../schema/leave-team-account.schema';
import { LeaveTeamAccountService } from '../services/leave-team-account.service';
import { createLeaveTeamAccountService } from '../services/leave-team-account.service';
export async function leaveTeamAccountAction(formData: FormData) {
const body = Object.fromEntries(formData.entries());
@@ -20,7 +20,7 @@ export async function leaveTeamAccountAction(formData: FormData) {
throw new Error('Authentication required');
}
const service = new LeaveTeamAccountService(
const service = createLeaveTeamAccountService(
getSupabaseServerActionClient({ admin: true }),
);

View File

@@ -16,8 +16,8 @@ import { DeleteInvitationSchema } from '../../schema/delete-invitation.schema';
import { InviteMembersSchema } from '../../schema/invite-members.schema';
import { RenewInvitationSchema } from '../../schema/renew-invitation.schema';
import { UpdateInvitationSchema } from '../../schema/update-invitation.schema';
import { AccountInvitationsService } from '../services/account-invitations.service';
import { AccountPerSeatBillingService } from '../services/account-per-seat-billing.service';
import { createAccountInvitationsService } from '../services/account-invitations.service';
import { createAccountPerSeatBillingService } from '../services/account-per-seat-billing.service';
/**
* Creates invitations for inviting members.
@@ -34,8 +34,10 @@ export async function createInvitationsAction(params: {
invitations: params.invitations,
});
const service = new AccountInvitationsService(client);
// Create the service
const service = createAccountInvitationsService(client);
// send invitations
await service.sendInvitations({
invitations,
accountSlug: params.accountSlug,
@@ -43,7 +45,9 @@ export async function createInvitationsAction(params: {
revalidateMemberPage();
return { success: true };
return {
success: true,
};
}
/**
@@ -66,8 +70,9 @@ export async function deleteInvitationAction(
throw new Error(`Authentication required`);
}
const service = new AccountInvitationsService(client);
const service = createAccountInvitationsService(client);
// Delete the invitation
await service.deleteInvitation(invitation);
revalidateMemberPage();
@@ -83,7 +88,7 @@ export async function updateInvitationAction(
await assertSession(client);
const service = new AccountInvitationsService(client);
const service = createAccountInvitationsService(client);
await service.updateInvitation(invitation);
@@ -99,10 +104,12 @@ export async function acceptInvitationAction(data: FormData) {
Object.fromEntries(data),
);
const accountPerSeatBillingService = new AccountPerSeatBillingService(client);
// Ensure the user is authenticated
const user = await assertSession(client);
const service = new AccountInvitationsService(client);
// create the services
const perSeatBillingService = createAccountPerSeatBillingService(client);
const service = createAccountInvitationsService(client);
// Accept the invitation
const accountId = await service.acceptInvitationToTeam(
@@ -113,7 +120,13 @@ export async function acceptInvitationAction(data: FormData) {
},
);
await accountPerSeatBillingService.increaseSeats(accountId);
// If the account ID is not present, throw an error
if (!accountId) {
throw new Error('Failed to accept invitation');
}
// Increase the seats for the account
await perSeatBillingService.increaseSeats(accountId);
return redirect(nextPath);
}
@@ -126,13 +139,16 @@ export async function renewInvitationAction(
await assertSession(client);
const service = new AccountInvitationsService(client);
const service = createAccountInvitationsService(client);
// Renew the invitation
await service.renewInvitation(invitationId);
revalidateMemberPage();
return { success: true };
return {
success: true,
};
}
async function assertSession(client: SupabaseClient<Database>) {

View File

@@ -12,7 +12,7 @@ import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-clie
import { RemoveMemberSchema } from '../../schema/remove-member.schema';
import { TransferOwnershipConfirmationSchema } from '../../schema/transfer-ownership-confirmation.schema';
import { UpdateMemberRoleSchema } from '../../schema/update-member-role.schema';
import { AccountMembersService } from '../services/account-members.service';
import { createAccountMembersService } from '../services/account-members.service';
export async function removeMemberFromAccountAction(
params: z.infer<typeof RemoveMemberSchema>,
@@ -26,7 +26,7 @@ export async function removeMemberFromAccountAction(
const { accountId, userId } = RemoveMemberSchema.parse(params);
const service = new AccountMembersService(client);
const service = createAccountMembersService(client);
await service.removeMemberFromAccount({
accountId,
@@ -46,7 +46,7 @@ export async function updateMemberRoleAction(
await assertSession(client);
const service = new AccountMembersService(client);
const service = createAccountMembersService(client);
const adminClient = getSupabaseServerActionClient({ admin: true });
// update the role of the member
@@ -87,7 +87,7 @@ export async function transferOwnershipAction(
);
}
const service = new AccountMembersService(client);
const service = createAccountMembersService(client);
// at this point, the user is authenticated and is the owner of the account
// so we proceed with the transfer of ownership with admin privileges
@@ -105,7 +105,9 @@ export async function transferOwnershipAction(
// revalidate all pages that depend on the account
revalidatePath('/home/[account]', 'layout');
return { success: true };
return {
success: true,
};
}
async function assertSession(client: SupabaseClient<Database>) {

View File

@@ -12,7 +12,17 @@ import { DeleteInvitationSchema } from '../../schema/delete-invitation.schema';
import { InviteMembersSchema } from '../../schema/invite-members.schema';
import { UpdateInvitationSchema } from '../../schema/update-invitation.schema';
export class AccountInvitationsService {
export function createAccountInvitationsService(
client: SupabaseClient<Database>,
) {
return new AccountInvitationsService(client);
}
/**
* @name AccountInvitationsService
* @description Service for managing account invitations.
*/
class AccountInvitationsService {
private readonly namespace = 'invitations';
constructor(private readonly client: SupabaseClient<Database>) {}
@@ -50,6 +60,11 @@ export class AccountInvitationsService {
return data;
}
/**
* @name updateInvitation
* @param params
* @description Updates an invitation in the database.
*/
async updateInvitation(params: z.infer<typeof UpdateInvitationSchema>) {
const logger = await getLogger();

View File

@@ -10,13 +10,22 @@ import { Database } from '@kit/supabase/database';
import { RemoveMemberSchema } from '../../schema/remove-member.schema';
import { TransferOwnershipConfirmationSchema } from '../../schema/transfer-ownership-confirmation.schema';
import { UpdateMemberRoleSchema } from '../../schema/update-member-role.schema';
import { AccountPerSeatBillingService } from './account-per-seat-billing.service';
import { createAccountPerSeatBillingService } from './account-per-seat-billing.service';
export class AccountMembersService {
export function createAccountMembersService(client: SupabaseClient<Database>) {
return new AccountMembersService(client);
}
class AccountMembersService {
private readonly namespace = 'account-members';
constructor(private readonly client: SupabaseClient<Database>) {}
/**
* @name removeMemberFromAccount
* @description Removes a member from an account.
* @param params
*/
async removeMemberFromAccount(params: z.infer<typeof RemoveMemberSchema>) {
const logger = await getLogger();
@@ -52,13 +61,19 @@ export class AccountMembersService {
`Successfully removed member from account. Verifying seat count...`,
);
const service = new AccountPerSeatBillingService(this.client);
const service = createAccountPerSeatBillingService(this.client);
await service.decreaseSeats(params.accountId);
return data;
}
/**
* @name updateMemberRole
* @description Updates the role of a member in an account.
* @param params
* @param adminClient
*/
async updateMemberRole(
params: z.infer<typeof UpdateMemberRoleSchema>,
adminClient: SupabaseClient<Database>,
@@ -123,6 +138,12 @@ export class AccountMembersService {
return data;
}
/**
* @name transferOwnership
* @description Transfers ownership of an account to another user.
* @param params
* @param adminClient
*/
async transferOwnership(
params: z.infer<typeof TransferOwnershipConfirmationSchema>,
adminClient: SupabaseClient<Database>,

View File

@@ -2,15 +2,30 @@ import 'server-only';
import { SupabaseClient } from '@supabase/supabase-js';
import { BillingGatewayService } from '@kit/billing-gateway';
import { createBillingGatewayService } from '@kit/billing-gateway';
import { getLogger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
export class AccountPerSeatBillingService {
export function createAccountPerSeatBillingService(
client: SupabaseClient<Database>,
) {
return new AccountPerSeatBillingService(client);
}
/**
* @name AccountPerSeatBillingService
* @description Service for managing per-seat billing for accounts.
*/
class AccountPerSeatBillingService {
private readonly namespace = 'accounts.per-seat-billing';
constructor(private readonly client: SupabaseClient<Database>) {}
/**
* @name getPerSeatSubscriptionItem
* @description Retrieves the per-seat subscription item for an account.
* @param accountId
*/
async getPerSeatSubscriptionItem(accountId: string) {
const logger = await getLogger();
const ctx = { accountId, name: this.namespace };
@@ -66,6 +81,11 @@ export class AccountPerSeatBillingService {
return data;
}
/**
* @name increaseSeats
* @description Increases the number of seats for an account.
* @param accountId
*/
async increaseSeats(accountId: string) {
const logger = await getLogger();
const subscription = await this.getPerSeatSubscriptionItem(accountId);
@@ -82,7 +102,7 @@ export class AccountPerSeatBillingService {
return;
}
const billingGateway = new BillingGatewayService(subscription.provider);
const billingGateway = createBillingGatewayService(subscription.provider);
const ctx = {
name: this.namespace,
@@ -133,6 +153,11 @@ export class AccountPerSeatBillingService {
await Promise.all(promises);
}
/**
* @name decreaseSeats
* @description Decreases the number of seats for an account.
* @param accountId
*/
async decreaseSeats(accountId: string) {
const logger = await getLogger();
const subscription = await this.getPerSeatSubscriptionItem(accountId);
@@ -157,7 +182,7 @@ export class AccountPerSeatBillingService {
logger.info(ctx, `Decreasing seats for account ${accountId}...`);
const billingGateway = new BillingGatewayService(subscription.provider);
const billingGateway = createBillingGatewayService(subscription.provider);
const promises = subscriptionItems.map(async (item) => {
try {

View File

@@ -5,7 +5,13 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { getLogger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
export class CreateTeamAccountService {
export function createCreateTeamAccountService(
client: SupabaseClient<Database>,
) {
return new CreateTeamAccountService(client);
}
class CreateTeamAccountService {
private readonly namespace = 'accounts.create-team-account';
constructor(private readonly client: SupabaseClient<Database>) {}

View File

@@ -5,7 +5,11 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { getLogger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
export class DeleteTeamAccountService {
export function createDeleteTeamAccountService() {
return new DeleteTeamAccountService();
}
class DeleteTeamAccountService {
private readonly namespace = 'accounts.delete-team-account';
/**

View File

@@ -12,11 +12,26 @@ const Schema = z.object({
userId: z.string().uuid(),
});
export class LeaveTeamAccountService {
export function createLeaveTeamAccountService(
client: SupabaseClient<Database>,
) {
return new LeaveTeamAccountService(client);
}
/**
* @name LeaveTeamAccountService
* @description Service for leaving a team account.
*/
class LeaveTeamAccountService {
private readonly namespace = 'leave-team-account';
constructor(private readonly adminClient: SupabaseClient<Database>) {}
/**
* @name leaveTeamAccount
* @description Leave a team account
* @param params
*/
async leaveTeamAccount(params: z.infer<typeof Schema>) {
const logger = await getLogger();

View File

@@ -26,7 +26,13 @@ const env = z
emailSender,
});
export class AccountInvitationsWebhookService {
export function createAccountInvitationsWebhookService(
client: SupabaseClient<Database>,
) {
return new AccountInvitationsWebhookService(client);
}
class AccountInvitationsWebhookService {
private namespace = 'accounts.invitations.webhook';
constructor(private readonly adminClient: SupabaseClient<Database>) {}

View File

@@ -5,7 +5,11 @@ import { Database } from '@kit/supabase/database';
type Account = Database['public']['Tables']['accounts']['Row'];
export class AccountWebhooksService {
export function createAccountWebhooksService() {
return new AccountWebhooksService();
}
class AccountWebhooksService {
private readonly namespace = 'accounts.webhooks';
async handleAccountDeletedWebhook(account: Account) {