mirror of
https://github.com/documenso/documenso.git
synced 2026-07-25 09:25:08 +10:00
feat: add admin org deletion (#2795)
This commit is contained in:
@@ -10,8 +10,10 @@ import { SEND_RECIPIENT_SIGNED_EMAIL_JOB_DEFINITION } from './definitions/emails
|
||||
import { SEND_SIGNING_REJECTION_EMAILS_JOB_DEFINITION } from './definitions/emails/send-rejection-emails';
|
||||
import { SEND_SIGNING_EMAIL_JOB_DEFINITION } from './definitions/emails/send-signing-email';
|
||||
import { SEND_TEAM_DELETED_EMAIL_JOB_DEFINITION } from './definitions/emails/send-team-deleted-email';
|
||||
import { ADMIN_DELETE_ORGANISATION_JOB_DEFINITION } from './definitions/internal/admin-delete-organisation';
|
||||
import { BACKPORT_SUBSCRIPTION_CLAIM_JOB_DEFINITION } from './definitions/internal/backport-subscription-claims';
|
||||
import { BULK_SEND_TEMPLATE_JOB_DEFINITION } from './definitions/internal/bulk-send-template';
|
||||
import { CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION } from './definitions/internal/cancel-organisation-subscription';
|
||||
import { CLEANUP_RATE_LIMITS_JOB_DEFINITION } from './definitions/internal/cleanup-rate-limits';
|
||||
import { EXECUTE_WEBHOOK_JOB_DEFINITION } from './definitions/internal/execute-webhook';
|
||||
import { EXPIRE_RECIPIENTS_SWEEP_JOB_DEFINITION } from './definitions/internal/expire-recipients-sweep';
|
||||
@@ -49,6 +51,8 @@ export const jobsClient = new JobClient([
|
||||
PROCESS_SIGNING_REMINDER_JOB_DEFINITION,
|
||||
CLEANUP_RATE_LIMITS_JOB_DEFINITION,
|
||||
SYNC_EMAIL_DOMAINS_JOB_DEFINITION,
|
||||
ADMIN_DELETE_ORGANISATION_JOB_DEFINITION,
|
||||
CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION,
|
||||
] as const);
|
||||
|
||||
export const jobs = jobsClient;
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { prisma } from '@documenso/prisma';
|
||||
|
||||
import { ORGANISATION_USER_ACCOUNT_TYPE } from '../../../constants/organisations';
|
||||
import { getEmailContext } from '../../../server-only/email/get-email-context';
|
||||
import { orphanEnvelopes } from '../../../server-only/envelope/orphan-envelopes';
|
||||
import { sendOrganisationDeleteEmail } from '../../../server-only/organisation/delete-organisation-email';
|
||||
import { jobs } from '../../client';
|
||||
import type { JobRunIO } from '../../client/_internal/job';
|
||||
import type { TAdminDeleteOrganisationJobDefinition } from './admin-delete-organisation';
|
||||
|
||||
export const run = async ({ payload, io }: { payload: TAdminDeleteOrganisationJobDefinition; io: JobRunIO }) => {
|
||||
const { organisationId, sendEmailToOwner, requestedByUserId } = payload;
|
||||
|
||||
// Get/store the organisation in a task so it can be accessed by subsequent tasks.
|
||||
const organisation = await io.runTask('get-organisation', async () => {
|
||||
io.logger.info(`User ${requestedByUserId} is deleting organisation ${organisationId}`);
|
||||
|
||||
return await prisma.organisation.findUnique({
|
||||
where: {
|
||||
id: organisationId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
subscription: {
|
||||
select: {
|
||||
planId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
if (!organisation) {
|
||||
// The organisation may have already been deleted by a prior run / another
|
||||
// pathway. Treat as a no-op so the job doesn't retry forever.
|
||||
return;
|
||||
}
|
||||
|
||||
const ownerEmail = organisation.owner.email;
|
||||
|
||||
const emailContext = await io.runTask('get-email-context', async () => {
|
||||
return await getEmailContext({
|
||||
emailType: 'INTERNAL',
|
||||
source: {
|
||||
type: 'organisation',
|
||||
organisationId: organisation.id,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// 1. Orphan all envelopes for every team.
|
||||
for (const team of organisation.teams) {
|
||||
await io.runTask(`orphan-envelopes--team-${team.id}`, async () => {
|
||||
await orphanEnvelopes({ teamId: team.id });
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Delete the organisation. Matches the transaction in organisation-router/delete-organisation.ts.
|
||||
await io.runTask('delete-organisation', async () => {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.account.deleteMany({
|
||||
where: {
|
||||
type: ORGANISATION_USER_ACCOUNT_TYPE,
|
||||
provider: organisation.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.organisation.delete({
|
||||
where: {
|
||||
id: organisation.id,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 3. Send the owner notification.
|
||||
if (sendEmailToOwner) {
|
||||
await io.runTask('send-organisation-deleted-email', async () => {
|
||||
await sendOrganisationDeleteEmail({
|
||||
email: ownerEmail,
|
||||
organisationName: organisation.name,
|
||||
deletedByAdmin: true,
|
||||
emailContext,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 4. If the organisation has a Stripe subscription, schedule it to be cancelled at the end of the current billing period.
|
||||
if (organisation.subscription) {
|
||||
const stripeSubscriptionId = organisation.subscription.planId;
|
||||
|
||||
await jobs.triggerJob({
|
||||
name: 'internal.cancel-organisation-subscription',
|
||||
payload: {
|
||||
stripeSubscriptionId,
|
||||
organisationId: organisation.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import type { JobDefinition } from '../../client/_internal/job';
|
||||
|
||||
const ADMIN_DELETE_ORGANISATION_JOB_DEFINITION_ID = 'internal.admin-delete-organisation';
|
||||
|
||||
const ADMIN_DELETE_ORGANISATION_JOB_DEFINITION_SCHEMA = z.object({
|
||||
organisationId: z.string(),
|
||||
/**
|
||||
* Whether to email the organisation owner notifying them of the deletion.
|
||||
*/
|
||||
sendEmailToOwner: z.boolean(),
|
||||
/**
|
||||
* The id of the admin user who requested the deletion (for audit/logging).
|
||||
*/
|
||||
requestedByUserId: z.number(),
|
||||
});
|
||||
|
||||
export type TAdminDeleteOrganisationJobDefinition = z.infer<typeof ADMIN_DELETE_ORGANISATION_JOB_DEFINITION_SCHEMA>;
|
||||
|
||||
export const ADMIN_DELETE_ORGANISATION_JOB_DEFINITION = {
|
||||
id: ADMIN_DELETE_ORGANISATION_JOB_DEFINITION_ID,
|
||||
name: 'Admin Delete Organisation',
|
||||
version: '1.0.0',
|
||||
trigger: {
|
||||
name: ADMIN_DELETE_ORGANISATION_JOB_DEFINITION_ID,
|
||||
schema: ADMIN_DELETE_ORGANISATION_JOB_DEFINITION_SCHEMA,
|
||||
},
|
||||
handler: async ({ payload, io }) => {
|
||||
const handler = await import('./admin-delete-organisation.handler');
|
||||
|
||||
await handler.run({ payload, io });
|
||||
},
|
||||
} as const satisfies JobDefinition<
|
||||
typeof ADMIN_DELETE_ORGANISATION_JOB_DEFINITION_ID,
|
||||
TAdminDeleteOrganisationJobDefinition
|
||||
>;
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Stripe, stripe } from '../../../server-only/stripe';
|
||||
import type { JobRunIO } from '../../client/_internal/job';
|
||||
import type { TCancelOrganisationSubscriptionJobDefinition } from './cancel-organisation-subscription';
|
||||
|
||||
/**
|
||||
* Marks the given Stripe subscription for cancellation at the end of the
|
||||
* current billing period.
|
||||
*
|
||||
* Idempotent: calling this on an already-cancel-at-period-end subscription is
|
||||
* a no-op for Stripe and returns the same shape, so re-running the job after
|
||||
* a partial failure is safe.
|
||||
*
|
||||
* If the subscription no longer exists in Stripe (`resource_missing`), the
|
||||
* job treats it as a no-op rather than retrying forever \u2014 nothing further
|
||||
* can be done.
|
||||
*/
|
||||
export const run = async ({ payload }: { payload: TCancelOrganisationSubscriptionJobDefinition; io: JobRunIO }) => {
|
||||
const { stripeSubscriptionId } = payload;
|
||||
|
||||
try {
|
||||
await stripe.subscriptions.update(stripeSubscriptionId, {
|
||||
cancel_at_period_end: true,
|
||||
});
|
||||
} catch (error) {
|
||||
// Subscription no longer exists in Stripe \u2014 nothing to cancel. Treat as
|
||||
// success so the job doesn't retry indefinitely.
|
||||
if (error instanceof Stripe.errors.StripeInvalidRequestError && error.code === 'resource_missing') {
|
||||
console.warn(
|
||||
`[CANCEL_ORGANISATION_SUBSCRIPTION] Stripe subscription ${stripeSubscriptionId} no longer exists; skipping.`,
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Anything else: rethrow so the job runner retries.
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import type { JobDefinition } from '../../client/_internal/job';
|
||||
|
||||
const CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION_ID = 'internal.cancel-organisation-subscription';
|
||||
|
||||
const CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION_SCHEMA = z.object({
|
||||
/**
|
||||
* The Stripe subscription id (Subscription.planId in our schema).
|
||||
*
|
||||
* This must be captured before the local organisation row is deleted,
|
||||
* because the Subscription row cascades away when the organisation is
|
||||
* removed.
|
||||
*/
|
||||
stripeSubscriptionId: z.string(),
|
||||
/**
|
||||
* The organisation id, for logging only. The organisation may no longer
|
||||
* exist by the time this job runs.
|
||||
*/
|
||||
organisationId: z.string(),
|
||||
});
|
||||
|
||||
export type TCancelOrganisationSubscriptionJobDefinition = z.infer<
|
||||
typeof CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION_SCHEMA
|
||||
>;
|
||||
|
||||
export const CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION = {
|
||||
id: CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION_ID,
|
||||
name: 'Cancel Organisation Subscription',
|
||||
version: '1.0.0',
|
||||
trigger: {
|
||||
name: CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION_ID,
|
||||
schema: CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION_SCHEMA,
|
||||
},
|
||||
handler: async ({ payload, io }) => {
|
||||
const handler = await import('./cancel-organisation-subscription.handler');
|
||||
|
||||
await handler.run({ payload, io });
|
||||
},
|
||||
} as const satisfies JobDefinition<
|
||||
typeof CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION_ID,
|
||||
TCancelOrganisationSubscriptionJobDefinition
|
||||
>;
|
||||
@@ -61,7 +61,7 @@ type RecipientGetEmailContextOptions = BaseGetEmailContextOptions & {
|
||||
|
||||
type GetEmailContextOptions = InternalGetEmailContextOptions | RecipientGetEmailContextOptions;
|
||||
|
||||
type EmailContextResponse = {
|
||||
export type EmailContextResponse = {
|
||||
allowedEmails: OrganisationEmail[];
|
||||
branding: BrandingSettings;
|
||||
settings: Omit<OrganisationGlobalSettings, 'id'>;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { mailer } from '@documenso/email/mailer';
|
||||
import { OrganisationDeleteEmailTemplate } from '@documenso/email/templates/organisation-delete';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { createElement } from 'react';
|
||||
|
||||
import { getI18nInstance } from '../../client-only/providers/i18n-server';
|
||||
import { NEXT_PUBLIC_WEBAPP_URL } from '../../constants/app';
|
||||
import { renderEmailWithI18N } from '../../utils/render-email-with-i18n';
|
||||
import type { EmailContextResponse } from '../email/get-email-context';
|
||||
|
||||
export type SendOrganisationDeleteEmailOptions = {
|
||||
email: string;
|
||||
organisationName: string;
|
||||
deletedByAdmin?: boolean;
|
||||
emailContext: EmailContextResponse;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sends an "organisation deleted" notification email.
|
||||
*/
|
||||
export const sendOrganisationDeleteEmail = async ({
|
||||
email,
|
||||
organisationName,
|
||||
deletedByAdmin = false,
|
||||
emailContext,
|
||||
}: SendOrganisationDeleteEmailOptions) => {
|
||||
const template = createElement(OrganisationDeleteEmailTemplate, {
|
||||
assetBaseUrl: NEXT_PUBLIC_WEBAPP_URL(),
|
||||
organisationName,
|
||||
deletedByAdmin,
|
||||
});
|
||||
|
||||
const { branding, emailLanguage, senderEmail } = emailContext;
|
||||
|
||||
const [html, text] = await Promise.all([
|
||||
renderEmailWithI18N(template, { lang: emailLanguage, branding }),
|
||||
renderEmailWithI18N(template, { lang: emailLanguage, branding, plainText: true }),
|
||||
]);
|
||||
|
||||
const i18n = await getI18nInstance(emailLanguage);
|
||||
|
||||
await mailer.sendMail({
|
||||
to: email,
|
||||
from: senderEmail,
|
||||
subject: i18n._(msg`Organisation "${organisationName}" has been deleted`),
|
||||
html,
|
||||
text,
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user