OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat: delete account & delete organization
Carl-Gerhard Lindesvärdc6809295dc76
diff --git a/apps/start/src/components/settings/delete-account.tsx b/apps/start/src/components/settings/delete-account.tsxnew file mode 100644index 000000000..8f5bab951--- /dev/null+++ b/apps/start/src/components/settings/delete-account.tsx@@ -0,0 +1,66 @@+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';+import { Button } from '@/components/ui/button';+import { Widget, WidgetBody, WidgetHead } from '@/components/widget';+import { useTRPC } from '@/integrations/trpc/react';+import { pushModal } from '@/modals';+import { useQuery } from '@tanstack/react-query';+import { Link } from '@tanstack/react-router';+import { TrashIcon } from 'lucide-react';++export default function DeleteAccount() {+ const trpc = useTRPC();+ const { data: blockers = [] } = useQuery(+ trpc.user.deletionBlockers.queryOptions(),+ );++ const blocked = blockers.length > 0;++ return (+ <Widget className="max-w-screen-md w-full">+ <WidgetHead>+ <span className="title">Delete account</span>+ </WidgetHead>+ <WidgetBody className="space-y-4">+ <p>+ Deleting your account will permanently remove your personal data.+ Organizations you created that have no other admin will also be+ deleted, along with their projects and events.+ </p>+ {blocked && (+ <Alert variant="destructive">+ <AlertTitle>Cancel your subscriptions first</AlertTitle>+ <AlertDescription>+ These organizations you created have an active subscription. Cancel+ each one before deleting your account:+ <ul className="mt-2 list-disc pl-5">+ {blockers.map((organization) => (+ <li key={organization.id}>+ <Link+ className="underline"+ params={{ organizationId: organization.id }}+ to="/$organizationId/billing"+ >+ {organization.name}+ </Link>+ </li>+ ))}+ </ul>+ </AlertDescription>+ </Alert>+ )}+ <div className="flex gap-4 justify-start">+ <Button+ disabled={blocked}+ icon={TrashIcon}+ onClick={() => {+ pushModal('ConfirmDeleteAccount');+ }}+ variant="destructive"+ >+ Delete account+ </Button>+ </div>+ </WidgetBody>+ </Widget>+ );+}diff --git a/apps/start/src/components/settings/delete-organization.tsx b/apps/start/src/components/settings/delete-organization.tsxnew file mode 100644index 000000000..39afd112d--- /dev/null+++ b/apps/start/src/components/settings/delete-organization.tsx@@ -0,0 +1,111 @@+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';+import { Button } from '@/components/ui/button';+import { Widget, WidgetBody, WidgetHead } from '@/components/widget';+import { handleError, useTRPC } from '@/integrations/trpc/react';+import { pushModal } from '@/modals';+import type { IServiceOrganization } from '@openpanel/db';+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { addHours, format, startOfHour } from 'date-fns';+import { TrashIcon } from 'lucide-react';+import { toast } from 'sonner';++type Props = { organization: IServiceOrganization };++export default function DeleteOrganization({ organization }: Props) {+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const { data: myAccess } = useQuery(+ trpc.organization.myAccess.queryOptions({+ organizationId: organization.id,+ }),+ );++ const cancelDeletionMutation = useMutation(+ trpc.organization.cancelDeletion.mutationOptions({+ onError: handleError,+ onSuccess: () => {+ toast.success('Organization deletion cancelled');+ queryClient.invalidateQueries(+ trpc.organization.get.queryFilter({+ organizationId: organization.id,+ }),+ );+ },+ }),+ );++ // Only admins can delete the organization. The server enforces this too.+ if (myAccess?.role !== 'org:admin') {+ return null;+ }++ // Block deletion while a paid subscription is still active and not cancelled.+ const blockDeletion =+ organization.hasSubscription && !organization.isWillBeCanceled;++ return (+ <Widget className="max-w-screen-md w-full">+ <WidgetHead>+ <span className="title">Delete Organization</span>+ </WidgetHead>+ <WidgetBody className="space-y-4">+ <p>+ Deleting this organization will remove it and all of its projects and+ their data. It will be permanently deleted after 24 hours.+ </p>+ {organization.deleteAt && (+ <Alert variant="destructive">+ <AlertTitle>Organization scheduled for deletion</AlertTitle>+ <AlertDescription>+ This organization will be deleted on{' '}+ <span className="font-medium">+ {format(+ startOfHour(addHours(organization.deleteAt, 1)),+ 'yyyy-MM-dd HH:mm:ss',+ )}+ </span>+ . All of its projects and their events will be deleted.+ </AlertDescription>+ </Alert>+ )}+ {blockDeletion && !organization.deleteAt && (+ <Alert variant="destructive">+ <AlertTitle>Cancel your subscription first</AlertTitle>+ <AlertDescription>+ This organization has an active subscription. Cancel it from the+ billing settings before you delete the organization.+ </AlertDescription>+ </Alert>+ )}+ <div className="flex gap-4 justify-start">+ {organization.deleteAt && (+ <Button+ loading={cancelDeletionMutation.isPending}+ onClick={() => {+ cancelDeletionMutation.mutate({+ organizationId: organization.id,+ });+ }}+ variant="outline"+ >+ Cancel deletion+ </Button>+ )}+ <Button+ disabled={blockDeletion || !!organization.deleteAt}+ icon={TrashIcon}+ onClick={() => {+ pushModal('ConfirmDeleteOrganization', {+ organizationId: organization.id,+ organizationName: organization.name,+ });+ }}+ variant="destructive"+ >+ Delete Organization+ </Button>+ </div>+ </WidgetBody>+ </Widget>+ );+}diff --git a/apps/start/src/components/settings/delete-project.tsx b/apps/start/src/components/settings/delete-project.tsxindex 2fdf7ec6b..2a60c1486 100644--- a/apps/start/src/components/settings/delete-project.tsx+++ b/apps/start/src/components/settings/delete-project.tsx@@ -4,7 +4,7 @@ import { Widget, WidgetBody, WidgetHead } from '@/components/widget';import { handleError, useTRPC } from '@/integrations/trpc/react';import { showConfirm } from '@/modals';import type { IServiceProjectWithClients } from '@openpanel/db';-import { useMutation, useQueryClient } from '@tanstack/react-query';+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { useRouter } from '@tanstack/react-router';import { addHours, format, startOfHour } from 'date-fns';import { TrashIcon } from 'lucide-react';@@ -17,6 +17,14 @@ export default function DeleteProject({ project }: Props) {const trpc = useTRPC();const queryClient = useQueryClient();+ const { data: organization } = useQuery(+ trpc.organization.get.queryOptions({+ organizationId: project.organizationId,+ }),+ );+ // When the whole organization is scheduled for deletion, this project's+ // deletion is part of it and can only be cancelled at the organization level.+ const isOrgScheduledForDeletion = !!organization?.deleteAt;const mutation = useMutation(trpc.project.delete.mutationOptions({onError: handleError,@@ -71,6 +79,13 @@ export default function DeleteProject({ project }: Props) {}</span>. Any event associated with this project will be deleted.+ {isOrgScheduledForDeletion && (+ <>+ {' '}+ The whole organization is scheduled for deletion. To keep this+ project, cancel the deletion from the organization settings.+ </>+ )}</AlertDescription></Alert>)}@@ -78,6 +93,7 @@ export default function DeleteProject({ project }: Props) {{project?.deleteAt && (<Buttonvariant="outline"+ disabled={isOrgScheduledForDeletion}onClick={() => {cancelDeletionMutation.mutate({ projectId: project.id });}}diff --git a/apps/start/src/modals/confirm-delete-account.tsx b/apps/start/src/modals/confirm-delete-account.tsxnew file mode 100644index 000000000..473a69d44--- /dev/null+++ b/apps/start/src/modals/confirm-delete-account.tsx@@ -0,0 +1,64 @@+import { Button } from '@/components/ui/button';+import { DialogFooter } from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { handleError, useTRPC } from '@/integrations/trpc/react';+import { useMutation } from '@tanstack/react-query';+import { useState } from 'react';+import { toast } from 'sonner';+import { popModal } from '.';+import { ModalContent, ModalHeader } from './Modal/Container';++const CONFIRMATION = 'DELETE';++export default function ConfirmDeleteAccount() {+ const trpc = useTRPC();+ const [confirmation, setConfirmation] = useState('');++ const mutation = useMutation(+ trpc.user.delete.mutationOptions({+ onError: handleError,+ onSuccess: () => {+ toast.success('Your account has been deleted');+ // The session is now gone server-side; send the user back to the start.+ window.location.href = '/';+ },+ }),+ );++ const canDelete = confirmation.trim() === CONFIRMATION;++ return (+ <ModalContent>+ <ModalHeader+ title="Delete account"+ text="Your account and all of your personal data will be permanently deleted. Organizations you created that have no other admin will also be removed, along with their projects and events. This cannot be undone."+ />+ <div className="col gap-2">+ <label className="text-sm font-medium" htmlFor="confirm-delete-account">+ Type <span className="font-bold">{CONFIRMATION}</span> to confirm+ </label>+ <Input+ autoComplete="off"+ autoFocus+ id="confirm-delete-account"+ onChange={(e) => setConfirmation(e.target.value)}+ placeholder={CONFIRMATION}+ value={confirmation}+ />+ </div>+ <DialogFooter>+ <Button onClick={() => popModal()} variant="secondary">+ Cancel+ </Button>+ <Button+ disabled={!canDelete}+ loading={mutation.isPending}+ onClick={() => mutation.mutate()}+ variant="destructive"+ >+ Delete account+ </Button>+ </DialogFooter>+ </ModalContent>+ );+}diff --git a/apps/start/src/modals/confirm-delete-organization.tsx b/apps/start/src/modals/confirm-delete-organization.tsxnew file mode 100644index 000000000..a847f9ed4--- /dev/null+++ b/apps/start/src/modals/confirm-delete-organization.tsx@@ -0,0 +1,73 @@+import { Button } from '@/components/ui/button';+import { DialogFooter } from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { handleError, useTRPC } from '@/integrations/trpc/react';+import { useMutation, useQueryClient } from '@tanstack/react-query';+import { useState } from 'react';+import { toast } from 'sonner';+import { popModal } from '.';+import { ModalContent, ModalHeader } from './Modal/Container';++type Props = {+ organizationId: string;+ organizationName: string;+};++export default function ConfirmDeleteOrganization({+ organizationId,+ organizationName,+}: Props) {+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const [confirmation, setConfirmation] = useState('');++ const mutation = useMutation(+ trpc.organization.delete.mutationOptions({+ onError: handleError,+ onSuccess: () => {+ toast.success('Organization scheduled for deletion');+ queryClient.invalidateQueries(+ trpc.organization.get.queryFilter({ organizationId }),+ );+ popModal();+ },+ }),+ );++ const canDelete = confirmation.trim() === organizationName.trim();++ return (+ <ModalContent>+ <ModalHeader+ title="Delete organization"+ text={`${organizationName} and all of its projects and events will be permanently deleted after 24 hours. You can cancel before then.`}+ />+ <div className="col gap-2">+ <label className="text-sm font-medium" htmlFor="confirm-org-name">+ Type <span className="font-bold">{organizationName}</span> to confirm+ </label>+ <Input+ autoComplete="off"+ autoFocus+ id="confirm-org-name"+ onChange={(e) => setConfirmation(e.target.value)}+ placeholder={organizationName}+ value={confirmation}+ />+ </div>+ <DialogFooter>+ <Button onClick={() => popModal()} variant="secondary">+ Cancel+ </Button>+ <Button+ disabled={!canDelete}+ loading={mutation.isPending}+ onClick={() => mutation.mutate({ organizationId })}+ variant="destructive"+ >+ Delete organization+ </Button>+ </DialogFooter>+ </ModalContent>+ );+}diff --git a/apps/start/src/modals/index.tsx b/apps/start/src/modals/index.tsxindex ee8ec038b..3901989dc 100644--- a/apps/start/src/modals/index.tsx+++ b/apps/start/src/modals/index.tsx@@ -11,6 +11,8 @@ import AddReference from './add-reference';import BillingSuccess from './billing-success';import type { ConfirmProps } from './confirm';import Confirm from './confirm';+import ConfirmDeleteAccount from './confirm-delete-account';+import ConfirmDeleteOrganization from './confirm-delete-organization';import CreateInvite from './create-invite';import DateRangerPicker from './date-ranger-picker';import DateTimePicker from './date-time-picker';@@ -59,6 +61,8 @@ const modals = {AddClient,AddImport,Confirm,+ ConfirmDeleteAccount,+ ConfirmDeleteOrganization,SaveReport,AddDashboard,EditDashboard,diff --git a/apps/start/src/routes/_app.$organizationId.account._tabs.index.tsx b/apps/start/src/routes/_app.$organizationId.account._tabs.index.tsxindex 714fc69c2..8203b37b0 100644--- a/apps/start/src/routes/_app.$organizationId.account._tabs.index.tsx+++ b/apps/start/src/routes/_app.$organizationId.account._tabs.index.tsx@@ -1,5 +1,6 @@import { InputWithLabel } from '@/components/forms/input-with-label';import FullPageLoadingState from '@/components/full-page-loading-state';+import DeleteAccount from '@/components/settings/delete-account';import { Button } from '@/components/ui/button';import { Widget, WidgetBody, WidgetHead } from '@/components/widget';import { handleError, useTRPC } from '@/integrations/trpc/react';@@ -57,12 +58,13 @@ function Component() {}return (- <form- onSubmit={handleSubmit((values) => {- mutation.mutate(values);- })}- >- <Widget className="max-w-screen-md w-full">+ <div className="space-y-8">+ <form+ onSubmit={handleSubmit((values) => {+ mutation.mutate(values);+ })}+ >+ <Widget className="max-w-screen-md w-full"><WidgetHead><span className="title">Profile</span></WidgetHead>@@ -95,6 +97,8 @@ function Component() {</Button></WidgetBody></Widget>- </form>+ </form>+ <DeleteAccount />+ </div>);}diff --git a/apps/start/src/routes/_app.$organizationId.settings.tsx b/apps/start/src/routes/_app.$organizationId.settings.tsxindex 04034f255..ed408a49a 100644--- a/apps/start/src/routes/_app.$organizationId.settings.tsx+++ b/apps/start/src/routes/_app.$organizationId.settings.tsx@@ -4,6 +4,7 @@ import FullPageLoadingState from '@/components/full-page-loading-state';import { PageHeader } from '@/components/page-header';import { Button } from '@/components/ui/button';import { Combobox } from '@/components/ui/combobox';+import DeleteOrganization from '@/components/settings/delete-organization';import { Widget, WidgetBody, WidgetHead } from '@/components/widget';import { handleError, useTRPC } from '@/integrations/trpc/react';import { PAGE_TITLES, createOrganizationTitle } from '@/utils/title';@@ -129,6 +130,10 @@ function Component() {</WidgetBody></Widget></form>++ <div className="mt-8">+ <DeleteOrganization organization={organization} />+ </div></div>);}diff --git a/apps/worker/src/boot-cron.ts b/apps/worker/src/boot-cron.tsindex c621aa5b3..d2458076e 100644--- a/apps/worker/src/boot-cron.ts+++ b/apps/worker/src/boot-cron.ts@@ -39,8 +39,8 @@ export async function bootCron() {pattern: '0 0 * * *',},{- name: 'deleteProjects',- type: 'deleteProjects',+ name: 'delete',+ type: 'delete',pattern: '0 * * * *',},{diff --git a/apps/worker/src/boot-debug.ts b/apps/worker/src/boot-debug.tsnew file mode 100644index 000000000..58a7d6a84--- /dev/null+++ b/apps/worker/src/boot-debug.ts@@ -0,0 +1,129 @@+import type { CronQueuePayload, CronQueueType } from '@openpanel/queue';+import type { Job } from 'bullmq';+import type { Express, Request } from 'express';+import { cronJob } from './jobs/cron';+import { logger } from './utils/logger';++const CRON_TYPES = [+ 'salt',+ 'flushEvents',+ 'flushProfiles',+ 'flushSessions',+ 'flushProfileBackfill',+ 'flushReplay',+ 'flushGroups',+ 'ping',+ 'delete',+ 'insightsDaily',+ 'onboarding',+ 'gscSync',+ 'cohortRefresh',+] as const satisfies readonly CronQueueType[];++function escapeHtml(value: string) {+ return value+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++function buildJobs(req: Request) {+ const baseUrl = `${req.protocol}://${req.get('host')}`;+ return CRON_TYPES.map((type) => ({+ type,+ url: `${baseUrl}/debug/cron/${type}`,+ }));+}++// Browsers send an explicit `text/html` accept, curl sends `*/*`. Listing json+// first means the wildcard falls back to json while a browser still gets html.+function wantsHtml(req: Request) {+ return req.accepts(['json', 'html']) === 'html';+}++function renderHtml(jobs: { type: string; url: string }[], message?: string) {+ const links = jobs+ .map((job) => `<li><a href="${job.url}">${escapeHtml(job.type)}</a></li>`)+ .join('');+ const note = message+ ? `<pre>${escapeHtml(message)}</pre>`+ : '<p>Click a job to run it now.</p>';+ return `<!doctype html>+<html lang="en">+<head><meta charset="utf-8"><title>Debug cron</title></head>+<body style="font-family: ui-monospace, monospace; max-width: 40rem; margin: 2rem auto;">+<h1>Trigger a cron job</h1>+${note}+<ul>${links}</ul>+</body>+</html>`;+}++// Local-only debug routes to run a cron job on demand instead of waiting for+// its schedule. Runs the job in this process through the same dispatcher the+// scheduler uses, so it reuses the worker's db, redis and clickhouse clients.+// Returns clickable links: an HTML page in a browser, full URLs in JSON for+// curl. Only mounted when NODE_ENV !== 'production'.+export function bootDebugRoutes(app: Express) {+ app.get('/debug/cron', (req, res) => {+ const jobs = buildJobs(req);+ if (wantsHtml(req)) {+ res.type('html').send(renderHtml(jobs));+ return;+ }+ res.json({+ message: 'Run a cron job now with GET or POST /debug/cron/:type',+ jobs,+ });+ });++ app.all('/debug/cron/:type', async (req, res) => {+ const type = req.params.type;+ const jobs = buildJobs(req);+ const html = wantsHtml(req);++ if (!CRON_TYPES.includes(type as CronQueueType)) {+ const message = `Unknown cron type "${type}"`;+ if (html) {+ res.status(400).type('html').send(renderHtml(jobs, message));+ return;+ }+ res.status(400).json({ ok: false, error: message, jobs });+ return;+ }++ logger.info({ type }, 'Manually triggering cron job');++ try {+ const result = await cronJob({+ data: { type: type as CronQueueType, payload: undefined },+ } as Job<CronQueuePayload>);+ if (html) {+ res+ .type('html')+ .send(+ renderHtml(+ jobs,+ `${type} ran. Result: ${JSON.stringify(result ?? null)}. Check the worker logs for details.`,+ ),+ );+ return;+ }+ res.json({ ok: true, type, result: result ?? null });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ logger.error({ err: error, type }, 'Manual cron trigger failed');+ if (html) {+ res+ .status(500)+ .type('html')+ .send(renderHtml(jobs, `Error running ${type}: ${message}`));+ return;+ }+ res.status(500).json({ ok: false, type, error: message });+ }+ });++ logger.info('Debug cron endpoint enabled: /debug/cron/:type');+}diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.tsindex c1ff173c6..622434d44 100644--- a/apps/worker/src/index.ts+++ b/apps/worker/src/index.ts@@ -20,6 +20,7 @@ import { BullBoardGroupMQAdapter } from 'groupmq';import client from 'prom-client';import sourceMapSupport from 'source-map-support';import { bootCron } from './boot-cron';+import { bootDebugRoutes } from './boot-debug';import { bootWorkers } from './boot-workers';import { register } from './metrics';import { isShuttingDown } from './utils/graceful-shutdown';@@ -37,6 +38,12 @@ async function start() {const PORT = Number.parseInt(process.env.WORKER_PORT || '3000', 10);const app = express();+ // Local-only: trigger cron jobs on demand. Disabled in production. Mounted+ // before bull-board so its routes take precedence.+ if (process.env.NODE_ENV !== 'production') {+ bootDebugRoutes(app);+ }+if (process.env.DISABLE_BULLBOARD !== '1' &&process.env.DISABLE_BULLBOARD !== 'true'diff --git a/apps/worker/src/jobs/cron.delete-projects.ts b/apps/worker/src/jobs/cron.delete-projects.tsdeleted file mode 100644index 472428cf4..000000000--- a/apps/worker/src/jobs/cron.delete-projects.ts+++ /dev/null@@ -1,26 +0,0 @@-import { logger } from '@/utils/logger';-import { db, deleteFromClickhouse, deleteProjects } from '@openpanel/db';-import type { CronQueuePayload } from '@openpanel/queue';-import type { Job } from 'bullmq';--export async function jobdeleteProjects(job: Job<CronQueuePayload>) {- const projects = await db.project.findMany({- where: {- deleteAt: {- lte: new Date(),- },- },- });-- if (projects.length === 0) {- return;- }-- await deleteProjects(projects.map((project) => project.id));-- logger.info({ projects }, 'Deleting projects');-- await deleteFromClickhouse(projects.map((project) => project.id));-- logger.info({ projects }, `Deleted ${projects.length} projects`);-}diff --git a/apps/worker/src/jobs/cron.delete.ts b/apps/worker/src/jobs/cron.delete.tsnew file mode 100644index 000000000..d310330a5--- /dev/null+++ b/apps/worker/src/jobs/cron.delete.ts@@ -0,0 +1,63 @@+import {+ db,+ deleteFromClickhouse,+ deleteOrganization,+ deleteProjects,+} from '@openpanel/db';+import { logger } from '@/utils/logger';++export async function jobDelete() {+ const now = new Date();++ // Orgs to delete: explicitly scheduled OR ownerless (no org:admin member left).+ const organizations = await db.organization.findMany({+ where: {+ OR: [+ { deleteAt: { lte: now } },+ { members: { none: { role: 'org:admin' } } },+ ],+ },+ select: { id: true, name: true, projects: { select: { id: true } } },+ });+ const orgIds = organizations.map((organization) => organization.id);+ const orgProjectIds = organizations.flatMap((organization) =>+ organization.projects.map((project) => project.id),+ );++ // Standalone projects scheduled for deletion (skip ones already covered by an+ // org delete, since deleting the org cascades its projects in Postgres).+ const scheduledProjects = await db.project.findMany({+ where: {+ deleteAt: { lte: now },+ organizationId: { notIn: orgIds },+ },+ select: { id: true },+ });+ const standaloneProjectIds = scheduledProjects.map((project) => project.id);++ const allProjectIds = [...orgProjectIds, ...standaloneProjectIds];++ if (allProjectIds.length === 0 && organizations.length === 0) {+ return;+ }++ // ClickHouse first: Postgres cascades projects when an org is deleted, but the+ // ClickHouse events are not cascade-deleted, so they must be cleaned for every+ // project that is about to disappear.+ if (allProjectIds.length > 0) {+ await deleteFromClickhouse(allProjectIds);+ }++ if (standaloneProjectIds.length > 0) {+ await deleteProjects(standaloneProjectIds);+ }++ for (const organization of organizations) {+ await deleteOrganization(organization.id);+ }++ logger.info(+ { organizations: organizations.length, projects: allProjectIds.length },+ 'Delete cron complete',+ );+}diff --git a/apps/worker/src/jobs/cron.ts b/apps/worker/src/jobs/cron.tsindex d1e68be85..305c30471 100644--- a/apps/worker/src/jobs/cron.ts+++ b/apps/worker/src/jobs/cron.ts@@ -4,7 +4,7 @@ import { eventBuffer, groupBuffer, profileBackfillBuffer, profileBuffer, replayBimport type { CronQueuePayload } from '@openpanel/queue';import { cohortRefreshCronJob } from './cron.cohort-refresh';-import { jobdeleteProjects } from './cron.delete-projects';+import { jobDelete } from './cron.delete';import { gscSyncAllJob } from './gsc';import { onboardingJob } from './cron.onboarding';import { ping } from './cron.ping';@@ -37,8 +37,8 @@ export async function cronJob(job: Job<CronQueuePayload>) {case 'ping': {return await ping();}- case 'deleteProjects': {- return await jobdeleteProjects(job);+ case 'delete': {+ return await jobDelete();}case 'insightsDaily': {return await insightsDailyJob(job);diff --git a/packages/queue/src/queues.ts b/packages/queue/src/queues.tsindex bb7b8cb45..88398b9e7 100644--- a/packages/queue/src/queues.ts+++ b/packages/queue/src/queues.ts@@ -106,8 +106,8 @@ export type CronQueuePayloadPing = {type: 'ping';payload: undefined;};-export type CronQueuePayloadProject = {- type: 'deleteProjects';+export type CronQueuePayloadDelete = {+ type: 'delete';payload: undefined;};export type CronQueuePayloadInsightsDaily = {@@ -147,7 +147,7 @@ export type CronQueuePayload =| CronQueuePayloadFlushReplay| CronQueuePayloadFlushGroups| CronQueuePayloadPing- | CronQueuePayloadProject+ | CronQueuePayloadDelete| CronQueuePayloadInsightsDaily| CronQueuePayloadOnboarding| CronQueuePayloadGscSyncdiff --git a/packages/trpc/src/routers/onboarding.ts b/packages/trpc/src/routers/onboarding.tsindex 12494bc5e..65f5949b6 100644--- a/packages/trpc/src/routers/onboarding.ts+++ b/packages/trpc/src/routers/onboarding.ts@@ -21,17 +21,32 @@ async function createOrGetOrganization(const TRIAL_DURATION_IN_DAYS = 30;if (input.organization) {- const organization = await db.organization.create({- data: {- id: await getId('organization', input.organization),- name: input.organization,- createdByUserId: user.id,- subscriptionEndsAt: addDays(new Date(), TRIAL_DURATION_IN_DAYS),- subscriptionStatus: 'trialing',- timezone: input.timezone,- onboarding: '',- },- });+ const organizationId = await getId('organization', input.organization);++ // Create the organization and its owner (org:admin member) atomically. The+ // `delete` cron treats an organization with no org:admin member as ownerless+ // and removes it, so an organization must never exist without one.+ const [organization] = await db.$transaction([+ db.organization.create({+ data: {+ id: organizationId,+ name: input.organization,+ createdByUserId: user.id,+ subscriptionEndsAt: addDays(new Date(), TRIAL_DURATION_IN_DAYS),+ subscriptionStatus: 'trialing',+ timezone: input.timezone,+ onboarding: '',+ },+ }),+ db.member.create({+ data: {+ email: user.email,+ organizationId,+ role: 'org:admin',+ userId: user.id,+ },+ }),+ ]);return organization;}@@ -86,17 +101,6 @@ export const onboardingRouter = createTRPCRouter({throw new Error('Organization slug is missing');}- if (input.organization) {- await db.member.create({- data: {- email: user.email,- organizationId: organization.id,- role: 'org:admin',- userId: user.id,- },- });- }-if (input.cors.length === 0 && input.website) {input.cors.push('*');}diff --git a/packages/trpc/src/routers/organization.ts b/packages/trpc/src/routers/organization.tsindex 30e567ee0..68a53ca98 100644--- a/packages/trpc/src/routers/organization.ts+++ b/packages/trpc/src/routers/organization.ts@@ -13,7 +13,7 @@ import { zEditOrganization, zInviteUser } from '@openpanel/validation';import { generateSecureId } from '@openpanel/common/server';import { sendEmail } from '@openpanel/email';-import { addDays } from 'date-fns';+import { addDays, addHours } from 'date-fns';import { getOrganizationAccess } from '../access';import { TRPCAccessError, TRPCBadRequestError } from '../errors';import {@@ -68,6 +68,90 @@ export const organizationRouter = createTRPCRouter({});}),+ delete: protectedProcedure+ .input(z.object({ organizationId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const access = await getOrganizationAccess({+ userId: ctx.session.userId,+ organizationId: input.organizationId,+ });++ if (access?.role !== 'org:admin') {+ throw TRPCAccessError('You do not have access to this organization');+ }++ const organization = await getOrganizationById(input.organizationId);++ // Require billing to be cancelled first. We don't want to delete an+ // organization that still has a live paid subscription. Once the user has+ // cancelled (the subscription is scheduled to end), deletion is allowed.+ if (organization.hasSubscription && !organization.isWillBeCanceled) {+ throw TRPCBadRequestError(+ 'Please cancel your subscription before deleting this organization.',+ );+ }++ // Schedule the organization and all of its projects for deletion in 24+ // hours (cancelable until then). The hourly `delete` cron removes the+ // projects (and their ClickHouse events) and the organization in a single+ // pass once their `deleteAt` has passed.+ const deleteAt = addHours(new Date(), 24);+ await db.$transaction([+ db.project.updateMany({+ where: {+ organizationId: input.organizationId,+ },+ data: {+ deleteAt,+ },+ }),+ db.organization.update({+ where: {+ id: input.organizationId,+ },+ data: {+ deleteAt,+ },+ }),+ ]);++ return true;+ }),++ cancelDeletion: protectedProcedure+ .input(z.object({ organizationId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const access = await getOrganizationAccess({+ userId: ctx.session.userId,+ organizationId: input.organizationId,+ });++ if (access?.role !== 'org:admin') {+ throw TRPCAccessError('You do not have access to this organization');+ }++ await db.$transaction([+ db.project.updateMany({+ where: {+ organizationId: input.organizationId,+ },+ data: {+ deleteAt: null,+ },+ }),+ db.organization.update({+ where: {+ id: input.organizationId,+ },+ data: {+ deleteAt: null,+ },+ }),+ ]);++ return true;+ }),+inviteUser: protectedProcedure.input(zInviteUser).mutation(async ({ input, ctx }) => {diff --git a/packages/trpc/src/routers/project.ts b/packages/trpc/src/routers/project.tsindex 0b3ffcebf..a10c9a2fe 100644--- a/packages/trpc/src/routers/project.ts+++ b/packages/trpc/src/routers/project.ts@@ -200,6 +200,28 @@ export const projectRouter = createTRPCRouter({throw TRPCAccessError('You do not have access to this project');}+ const project = await db.project.findUnique({+ where: {+ id: input.projectId,+ },+ select: {+ organization: {+ select: {+ deleteAt: true,+ },+ },+ },+ });++ // If the whole organization is scheduled for deletion, this project's+ // deletion is part of it and can only be cancelled at the organization+ // level. Cancelling it here would leave the organization unable to delete.+ if (project?.organization?.deleteAt) {+ throw TRPCBadRequestError(+ 'This organization is scheduled for deletion. Cancel the deletion from the organization settings.',+ );+ }+await db.project.update({where: {id: input.projectId,diff --git a/packages/trpc/src/routers/user.ts b/packages/trpc/src/routers/user.tsindex f74a428a1..93465f85b 100644--- a/packages/trpc/src/routers/user.ts+++ b/packages/trpc/src/routers/user.ts@@ -1,10 +1,58 @@import { z } from 'zod';+import { deleteSessionTokenCookie } from '@openpanel/auth';import { db } from '@openpanel/db';+import { TRPCBadRequestError } from '../errors';import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';export const userRouter = createTRPCRouter({+ // Organizations the user created that still have a blocking subscription+ // (active and not scheduled to cancel). The account cannot be deleted while+ // any of these exist.+ deletionBlockers: protectedProcedure.query(async ({ ctx }) => {+ const organizations = await db.organization.findMany({+ where: { createdByUserId: ctx.session.userId },+ });+ return organizations+ .filter(+ (organization) =>+ organization.hasSubscription && !organization.isWillBeCanceled,+ )+ .map((organization) => ({+ id: organization.id,+ name: organization.name,+ }));+ }),++ delete: protectedProcedure.mutation(async ({ ctx }) => {+ const organizations = await db.organization.findMany({+ where: { createdByUserId: ctx.session.userId },+ });+ const blocking = organizations.filter(+ (organization) =>+ organization.hasSubscription && !organization.isWillBeCanceled,+ );++ if (blocking.length > 0) {+ throw TRPCBadRequestError(+ `Please cancel the subscription for ${blocking+ .map((organization) => organization.name)+ .join(', ')} before deleting your account.`,+ );+ }++ // Hard delete the user. Cascades clean up sessions, accounts, totp,+ // twoFactorChallenges, members, projectAccess, invites and conversations.+ // Organizations the user created have `createdByUserId`/`subscriptionCreatedByUserId`+ // set to null (SetNull); any org left without an org:admin member is then+ // removed by the `delete` cron.+ await db.user.delete({ where: { id: ctx.session.userId } });+ deleteSessionTokenCookie(ctx.setCookie);++ return true;+ }),+update: protectedProcedure.input(z.object({