Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat: let a team owner delete a team (#486)

Ilija Matoskia952a0daa07f
diff --git a/apps/api/src/modules/agents/skills/service.ts b/apps/api/src/modules/agents/skills/service.ts
index 673df01d..95cfb16a 100644
--- a/apps/api/src/modules/agents/skills/service.ts
+++ b/apps/api/src/modules/agents/skills/service.ts
@@ -326,12 +326,25 @@ export async function deleteSkill(id: number, teamId: number): Promise<boolean>
.where(and(eq(agentSkill.id, id), eq(agentSkill.teamId, teamId)));
const skill = rows[0];
if (!skill) return false;
- const keys = [skillMdKey(skill.s3Prefix), ...(skill.files as SkillRef[]).map((f) => f.s3Key)];
- await deleteObjects(keys);
+ await deleteObjects(skillObjectKeys(skill));
await db.delete(agentSkill).where(eq(agentSkill.id, id));
return true;
}
+function skillObjectKeys(skill: { s3Prefix: string; files: unknown }): string[] {
+ return [skillMdKey(skill.s3Prefix), ...(skill.files as SkillRef[]).map((f) => f.s3Key)];
+}
+
+// The object-store keys of every skill of the team. Read them before the team is
+// deleted: the cascade removes the rows that name them.
+export async function teamSkillObjectKeys(teamId: number): Promise<string[]> {
+ const skills = await db
+ .select({ s3Prefix: agentSkill.s3Prefix, files: agentSkill.files })
+ .from(agentSkill)
+ .where(eq(agentSkill.teamId, teamId));
+ return skills.flatMap(skillObjectKeys);
+}
+
// The skills enabled on an agent, as DTOs. Used by the agent editor and the runtime.
export async function listAgentSkills(agentId: number): Promise<SkillRow[]> {
const rows = await db
diff --git a/apps/api/src/modules/teams/__tests__/integration/teams.test.ts b/apps/api/src/modules/teams/__tests__/integration/teams.test.ts
index 3fe86279..8dcc80cf 100644
--- a/apps/api/src/modules/teams/__tests__/integration/teams.test.ts
+++ b/apps/api/src/modules/teams/__tests__/integration/teams.test.ts
@@ -5,6 +5,8 @@ import { resetDb } from '#tests/helpers/db';
import { addProjectMember } from '#tests/helpers/members';
import { createAgent } from '#tests/helpers/agents';
import { clearLimits, setLimits } from '#tests/helpers/limits';
+import { teamSkillObjectKeys } from '#modules/agents/skills/service';
+import { getObjectText } from '@repo/storage';
// The teams feature owns list, create, detail, rename, and leave. Every account is
// given a team at registration, named after its username, so a fresh account already
@@ -1282,6 +1284,72 @@ describe('teams', () => {
});
});
+ describe('delete', () => {
+ // The first account owns the instance workspace, which reaches every team in it, so
+ // the team owner is the second.
+ async function teamOwner() {
+ await signUpTestUser();
+ const owner = await signUpClient();
+ const teamId = (await owner.api.teams.get()).data![0].id;
+ return { owner, teamId };
+ }
+
+ it('lets the owner delete a team that holds no work', async () => {
+ const { owner, teamId } = await teamOwner();
+ await addTeamMember(owner, teamId);
+
+ expect((await owner.api.teams({ teamId }).delete()).status).toBe(204);
+ expect((await owner.api.teams.get()).data).toEqual([]);
+ expect((await owner.api.teams({ teamId }).get()).status).toBe(404);
+ });
+
+ it("removes the team's skill files from the object store", async () => {
+ const { owner, teamId } = await teamOwner();
+ await owner.api
+ .teams({ teamId })
+ ['agent-skills'].post({ source: 'inline', name: 'Triage', markdown: 'Set a priority.' });
+ const keys = await teamSkillObjectKeys(teamId);
+ expect(keys).not.toHaveLength(0);
+
+ expect((await owner.api.teams({ teamId }).delete()).status).toBe(204);
+ for (const key of keys) await expect(getObjectText(key)).rejects.toThrow();
+ });
+
+ it('keeps a team that holds a project', async () => {
+ const { owner, teamId } = await teamOwner();
+ await owner.api.teams({ teamId }).projects.post({ key: 'OPS', name: 'Operations' });
+
+ expect((await owner.api.teams({ teamId }).delete()).status).toBe(409);
+ expect((await owner.api.teams({ teamId }).get()).status).toBe(200);
+ });
+
+ it('keeps a team that holds an AI agent', async () => {
+ const { owner, teamId } = await teamOwner();
+ const created = await owner.api.teams({ teamId }).projects.post({ key: 'OPS', name: 'Ops' });
+ await createAgent(owner.api, 'OPS', { name: 'Triage', username: 'triage', kind: 'external' });
+ await owner.api.teams({ teamId }).projects({ projectId: created.data!.id }).delete();
+
+ expect((await owner.api.teams({ teamId }).delete()).status).toBe(409);
+ expect((await owner.api.teams({ teamId }).get()).status).toBe(200);
+ });
+
+ it('leaves deleting to an owner', async () => {
+ const { owner, teamId } = await teamOwner();
+ const manager = await addTeamMember(owner, teamId, 'manager');
+
+ expect((await manager.api.teams({ teamId }).delete()).status).toBe(403);
+ expect((await owner.api.teams({ teamId }).get()).status).toBe(200);
+ });
+
+ it('404s for a team the caller is not a member of', async () => {
+ const { owner, teamId } = await teamOwner();
+ const outsider = await signUpClient();
+
+ expect((await outsider.api.teams({ teamId }).delete()).status).toBe(404);
+ expect((await owner.api.teams({ teamId }).get()).status).toBe(200);
+ });
+ });
+
describe('leave', () => {
it('rejects the last owner leaving', async () => {
const { api } = await signUpClient();
diff --git a/apps/api/src/modules/teams/index.ts b/apps/api/src/modules/teams/index.ts
index 5b740978..95f054d1 100644
--- a/apps/api/src/modules/teams/index.ts
+++ b/apps/api/src/modules/teams/index.ts
@@ -45,6 +45,7 @@ import {
} from './model';
import {
createTeam,
+ deleteTeam,
getTeam,
getTeamProject,
leaveTeam,
@@ -311,6 +312,26 @@ export const teamRoutes = new Elysia({ name: 'teams', detail: { tags: ['Teams']
},
)
+ .delete(
+ '/teams/:teamId',
+ async ({ membership }) => {
+ await deleteTeam(membership.teamId);
+ return noContent();
+ },
+ {
+ teamOwner: true,
+ params: teamParams,
+ response: { 204: t.Void(), ...errors(401, 403, 404, 409) },
+ detail: {
+ summary: 'Delete a team',
+ description:
+ 'Delete a team you own, with its members, roles, invites, skills, tools and ' +
+ 'integrations. A team that holds a project or an AI agent is refused until those ' +
+ 'are gone. Irreversible.',
+ },
+ },
+ )
+
.post(
'/teams/:teamId/projects',
async ({ body, membership, set }) => {
diff --git a/apps/api/src/modules/teams/service.ts b/apps/api/src/modules/teams/service.ts
index 8c65970e..dddfa357 100644
--- a/apps/api/src/modules/teams/service.ts
+++ b/apps/api/src/modules/teams/service.ts
@@ -35,6 +35,8 @@ import {
type MemberSource,
} from '#modules/members/service';
import { getStats, type StatsDto } from '#modules/analytics/service';
+import { teamSkillObjectKeys } from '#modules/agents/skills/service';
+import { deleteObjects } from '@repo/storage';
import {
assertMayCreateTeam,
projectWorkspaceGrant,
@@ -898,6 +900,26 @@ export async function updateTeam(
return row;
}
+// A team holding a project or an AI agent is kept: those are people's work, and the
+// delete cascades to everything the team owns.
+export async function deleteTeam(teamId: number): Promise<void> {
+ const skillKeys = await teamSkillObjectKeys(teamId);
+ const deleted = await db
+ .delete(team)
+ .where(
+ and(
+ eq(team.id, teamId),
+ sql`not exists (select 1 from ${project} where ${project.teamId} = ${team.id})`,
+ sql`not exists (select 1 from ${aiAgent} where ${aiAgent.teamId} = ${team.id})`,
+ ),
+ )
+ .returning({ id: team.id });
+ if (deleted.length === 0) {
+ throw new HttpError(409, 'Delete the projects and AI agents of the team first');
+ }
+ await deleteObjects(skillKeys);
+}
+
async function membershipInTransaction(
tx: Transaction,
teamId: number,
diff --git a/apps/api/src/modules/workspaces/__tests__/integration/workspace-access.test.ts b/apps/api/src/modules/workspaces/__tests__/integration/workspace-access.test.ts
index 71077276..e3730642 100644
--- a/apps/api/src/modules/workspaces/__tests__/integration/workspace-access.test.ts
+++ b/apps/api/src/modules/workspaces/__tests__/integration/workspace-access.test.ts
@@ -42,6 +42,15 @@ describe('workspace access', () => {
beforeEach(resetDb);
afterEach(() => setWorkspaceRoleGrant('admin', readOnlyPermissions()));
+ it('lets the workspace owner delete a team, and not an admin', async () => {
+ const { asOwner, asAdmin, teamId } = await setup();
+ const project = (await asOwner.projects({ projectKey: 'MKT' }).get()).data!.project;
+ await asOwner.teams({ teamId }).projects({ projectId: project.id }).delete();
+
+ expect((await asAdmin.teams({ teamId }).delete()).status).toBe(403);
+ expect((await asOwner.teams({ teamId }).delete()).status).toBe(204);
+ });
+
it('lets the workspace owner work in every project as its owner', async () => {
const { asOwner, teamId, columnId } = await setup();
diff --git a/apps/web/messages/ar/teams.json b/apps/web/messages/ar/teams.json
index 39ae8f43..33a26a31 100644
--- a/apps/web/messages/ar/teams.json
+++ b/apps/web/messages/ar/teams.json
@@ -64,7 +64,15 @@
"leads": "المالكون والمديرون",
"leadsHint": "الأشخاص الذين يمكنهم إدارة هذا الفريق ومشاريعه.",
"saved": "تم حفظ الفريق",
- "leaveHint": "تحتفظ بالمشاريع التي أنت عضو فيها. للانضمام مجددًا يجب أن يضيفك أحد المالكين."
+ "leaveHint": "تحتفظ بالمشاريع التي أنت عضو فيها. للانضمام مجددًا يجب أن يضيفك أحد المالكين.",
+ "delete": {
+ "action": "حذف الفريق",
+ "hint": "يُحذف معه أعضاؤه وأدواره ودعواته ومهاراته وأدواته وتكاملاته. يحتفظ الأشخاص بحساباتهم وفرقهم الأخرى.",
+ "blocked": "احذف مشاريع الفريق ووكلاء الذكاء الاصطناعي الخاصين به أولاً.",
+ "title": "حذف {name}؟",
+ "description": "يُحذف <strong>{name}</strong> مع أعضائه وأدواره ودعواته ومهاراته وأدواته وتكاملاته. يحتفظ الأشخاص بحساباتهم وفرقهم الأخرى. لا يمكن التراجع عن ذلك.",
+ "deleted": "تم حذف الفريق"
+ }
},
"columns": {
"project": "المشروع",
diff --git a/apps/web/messages/en/teams.json b/apps/web/messages/en/teams.json
index e032d416..bdf8f147 100644
--- a/apps/web/messages/en/teams.json
+++ b/apps/web/messages/en/teams.json
@@ -64,7 +64,15 @@
"leads": "Owners and managers",
"leadsHint": "People who can manage this team and its projects.",
"saved": "Team saved",
- "leaveHint": "You keep the projects you are a member of. To join again an owner has to add you back."
+ "leaveHint": "You keep the projects you are a member of. To join again an owner has to add you back.",
+ "delete": {
+ "action": "Delete team",
+ "hint": "Its members, roles, invites, skills, tools and integrations are deleted with it. People keep their accounts and their other teams.",
+ "blocked": "Delete the projects and AI agents of the team first.",
+ "title": "Delete {name}?",
+ "description": "<strong>{name}</strong> is deleted with its members, roles, invites, skills, tools and integrations. People keep their accounts and their other teams. This cannot be undone.",
+ "deleted": "Team deleted"
+ }
},
"columns": {
"project": "Project",
diff --git a/apps/web/messages/es-ES/teams.json b/apps/web/messages/es-ES/teams.json
index f610b3d7..611db178 100644
--- a/apps/web/messages/es-ES/teams.json
+++ b/apps/web/messages/es-ES/teams.json
@@ -64,7 +64,15 @@
"leads": "Propietarios y administradores",
"leadsHint": "Personas que pueden gestionar este equipo y sus proyectos.",
"saved": "Equipo guardado",
- "leaveHint": "Conservas los proyectos de los que eres miembro. Para volver a unirte, un propietario tiene que añadirte de vuelta."
+ "leaveHint": "Conservas los proyectos de los que eres miembro. Para volver a unirte, un propietario tiene que añadirte de vuelta.",
+ "delete": {
+ "action": "Eliminar equipo",
+ "hint": "Se eliminan con él sus miembros, roles, invitaciones, habilidades, herramientas e integraciones. Las personas conservan sus cuentas y sus otros equipos.",
+ "blocked": "Elimina primero los proyectos y los agentes de IA del equipo.",
+ "title": "¿Eliminar {name}?",
+ "description": "<strong>{name}</strong> se elimina junto con sus miembros, roles, invitaciones, habilidades, herramientas e integraciones. Las personas conservan sus cuentas y sus otros equipos. No se puede deshacer.",
+ "deleted": "Equipo eliminado"
+ }
},
"columns": {
"project": "Proyecto",
diff --git a/apps/web/messages/fr/teams.json b/apps/web/messages/fr/teams.json
index 911f7e28..48eec9f6 100644
--- a/apps/web/messages/fr/teams.json
+++ b/apps/web/messages/fr/teams.json
@@ -64,7 +64,15 @@
"leads": "Propriétaires et responsables",
"leadsHint": "Les personnes qui peuvent gérer cette équipe et ses projets.",
"saved": "Équipe enregistrée",
- "leaveHint": "Vous conservez les projets dont vous êtes membre. Pour revenir, un propriétaire doit vous ajouter à nouveau."
+ "leaveHint": "Vous conservez les projets dont vous êtes membre. Pour revenir, un propriétaire doit vous ajouter à nouveau.",
+ "delete": {
+ "action": "Supprimer l'équipe",
+ "hint": "Ses membres, rôles, invitations, compétences, outils et intégrations sont supprimés avec elle. Les personnes conservent leur compte et leurs autres équipes.",
+ "blocked": "Supprimez d'abord les projets et les agents IA de l'équipe.",
+ "title": "Supprimer {name} ?",
+ "description": "<strong>{name}</strong> est supprimée avec ses membres, rôles, invitations, compétences, outils et intégrations. Les personnes conservent leur compte et leurs autres équipes. Cette action est irréversible.",
+ "deleted": "Équipe supprimée"
+ }
},
"columns": {
"project": "Projet",
diff --git a/apps/web/messages/id/teams.json b/apps/web/messages/id/teams.json
index 2e75606c..73df458d 100644
--- a/apps/web/messages/id/teams.json
+++ b/apps/web/messages/id/teams.json
@@ -64,7 +64,15 @@
"leads": "Pemilik dan manajer",
"leadsHint": "Orang yang dapat mengelola tim ini beserta proyeknya.",
"saved": "Tim disimpan",
- "leaveHint": "Anda tetap menjadi anggota proyek yang Anda ikuti. Untuk bergabung kembali, pemilik harus menambahkan Anda lagi."
+ "leaveHint": "Anda tetap menjadi anggota proyek yang Anda ikuti. Untuk bergabung kembali, pemilik harus menambahkan Anda lagi.",
+ "delete": {
+ "action": "Hapus tim",
+ "hint": "Anggota, peran, undangan, keterampilan, alat, dan integrasinya ikut dihapus. Orang-orang tetap memiliki akun dan tim lain mereka.",
+ "blocked": "Hapus dulu proyek dan agen AI milik tim.",
+ "title": "Hapus {name}?",
+ "description": "<strong>{name}</strong> dihapus beserta anggota, peran, undangan, keterampilan, alat, dan integrasinya. Orang-orang tetap memiliki akun dan tim lain mereka. Tindakan ini tidak dapat dibatalkan.",
+ "deleted": "Tim dihapus"
+ }
},
"columns": {
"project": "Proyek",
diff --git a/apps/web/messages/pt-BR/teams.json b/apps/web/messages/pt-BR/teams.json
index 7e5cc557..72f20fad 100644
--- a/apps/web/messages/pt-BR/teams.json
+++ b/apps/web/messages/pt-BR/teams.json
@@ -64,7 +64,15 @@
"leads": "Donos e gerentes",
"leadsHint": "Pessoas que podem gerenciar este time e seus projetos.",
"saved": "Equipe salva",
- "leaveHint": "Você mantém os projetos de que é membro. Para entrar de novo, um dono precisa readicioná-lo."
+ "leaveHint": "Você mantém os projetos de que é membro. Para entrar de novo, um dono precisa readicioná-lo.",
+ "delete": {
+ "action": "Excluir equipe",
+ "hint": "Seus membros, funções, convites, habilidades, ferramentas e integrações são excluídos com ela. As pessoas mantêm suas contas e suas outras equipes.",
+ "blocked": "Exclua primeiro os projetos e os agentes de IA da equipe.",
+ "title": "Excluir {name}?",
+ "description": "<strong>{name}</strong> é excluída com seus membros, funções, convites, habilidades, ferramentas e integrações. As pessoas mantêm suas contas e suas outras equipes. Isso não pode ser desfeito.",
+ "deleted": "Equipe excluída"
+ }
},
"columns": {
"project": "Projeto",
diff --git a/apps/web/messages/ru/teams.json b/apps/web/messages/ru/teams.json
index 0e0ff5f9..781a980d 100644
--- a/apps/web/messages/ru/teams.json
+++ b/apps/web/messages/ru/teams.json
@@ -64,7 +64,15 @@
"leads": "Владельцы и менеджеры",
"leadsHint": "Люди, которые могут управлять этой командой и её проектами.",
"saved": "Команда сохранена",
- "leaveHint": "Проекты, в которых вы участвуете, остаются у вас. Чтобы вернуться, владелец должен добавить вас снова."
+ "leaveHint": "Проекты, в которых вы участвуете, остаются у вас. Чтобы вернуться, владелец должен добавить вас снова.",
+ "delete": {
+ "action": "Удалить команду",
+ "hint": "Вместе с ней удаляются участники, роли, приглашения, навыки, инструменты и интеграции. Люди сохраняют свои аккаунты и другие команды.",
+ "blocked": "Сначала удалите проекты и ИИ-агентов команды.",
+ "title": "Удалить {name}?",
+ "description": "<strong>{name}</strong> удаляется вместе с участниками, ролями, приглашениями, навыками, инструментами и интеграциями. Люди сохраняют свои аккаунты и другие команды. Это действие нельзя отменить.",
+ "deleted": "Команда удалена"
+ }
},
"columns": {
"project": "Проект",
diff --git a/apps/web/messages/uk/teams.json b/apps/web/messages/uk/teams.json
index 3df2f1b1..eff27605 100644
--- a/apps/web/messages/uk/teams.json
+++ b/apps/web/messages/uk/teams.json
@@ -64,7 +64,15 @@
"leads": "Власники та менеджери",
"leadsHint": "Люди, які можуть керувати цією командою та її проєктами.",
"saved": "Команду збережено",
- "leaveHint": "Проєкти, у яких ви берете участь, залишаються у вас. Щоб повернутися, власник має додати вас знову."
+ "leaveHint": "Проєкти, у яких ви берете участь, залишаються у вас. Щоб повернутися, власник має додати вас знову.",
+ "delete": {
+ "action": "Видалити команду",
+ "hint": "Разом із нею видаляються учасники, ролі, запрошення, навички, інструменти та інтеграції. Люди зберігають свої облікові записи та інші команди.",
+ "blocked": "Спочатку видаліть проєкти та ШІ-агентів команди.",
+ "title": "Видалити {name}?",
+ "description": "<strong>{name}</strong> видаляється разом з учасниками, ролями, запрошеннями, навичками, інструментами та інтеграціями. Люди зберігають свої облікові записи та інші команди. Цю дію не можна скасувати.",
+ "deleted": "Команду видалено"
+ }
},
"columns": {
"project": "Проєкт",
diff --git a/apps/web/messages/zh-CN/teams.json b/apps/web/messages/zh-CN/teams.json
index c190dfb3..9c9f6ce8 100644
--- a/apps/web/messages/zh-CN/teams.json
+++ b/apps/web/messages/zh-CN/teams.json
@@ -64,7 +64,15 @@
"leads": "所有者和管理员",
"leadsHint": "可以管理此团队及其项目的成员。",
"saved": "团队已保存",
- "leaveHint": "你仍保留你参与的项目。若要重新加入,需由所有者再次添加你。"
+ "leaveHint": "你仍保留你参与的项目。若要重新加入,需由所有者再次添加你。",
+ "delete": {
+ "action": "删除团队",
+ "hint": "其成员、角色、邀请、技能、工具和集成会一并删除。成员会保留自己的账户和其他团队。",
+ "blocked": "请先删除该团队的项目和 AI 代理。",
+ "title": "删除 {name}?",
+ "description": "<strong>{name}</strong> 及其成员、角色、邀请、技能、工具和集成将被删除。成员会保留自己的账户和其他团队。此操作无法撤销。",
+ "deleted": "团队已删除"
+ }
},
"columns": {
"project": "项目",
diff --git a/apps/web/src/features/teams/components/info/TeamDeleteSection.tsx b/apps/web/src/features/teams/components/info/TeamDeleteSection.tsx
new file mode 100644
index 00000000..4a3f823e
--- /dev/null
+++ b/apps/web/src/features/teams/components/info/TeamDeleteSection.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { useState } from 'react';
+import { useRouter } from 'next/navigation';
+import { toast } from 'sonner';
+import { useTranslations } from 'next-intl';
+import type { Team } from '@/lib/api/endpoints/teams';
+import { manageTeamsPath } from '@/utils/paths';
+import { useDeleteTeam } from '@/services/teams.service';
+import ConfirmDialog from '@/components/common/overlay/ConfirmDialog';
+import SettingsSection from '@/components/common/page/SettingsSection';
+import { Button } from '@/components/ui/button';
+
+export default function TeamDeleteSection({ team }: { team: Team }) {
+ const t = useTranslations('teams.info.delete');
+ const router = useRouter();
+ const remove = useDeleteTeam();
+ const [deleting, setDeleting] = useState(false);
+ const blocked = team.projectCount > 0 || team.agentCount > 0;
+
+ return (
+ <>
+ <SettingsSection
+ title={t('action')}
+ description={t(blocked ? 'blocked' : 'hint')}
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8 text-destructive hover:text-destructive"
+ disabled={blocked}
+ onClick={() => setDeleting(true)}
+ >
+ {t('action')}
+ </Button>
+ }
+ />
+
+ {deleting && (
+ <ConfirmDialog
+ title={t('title', { name: team.name })}
+ confirmLabel={t('action')}
+ onClose={() => setDeleting(false)}
+ onConfirm={async () => {
+ await remove.mutateAsync(team.id);
+ toast.success(t('deleted'));
+ router.replace(manageTeamsPath());
+ }}
+ >
+ <p className="text-sm text-muted-foreground">
+ {t.rich('description', {
+ name: team.name,
+ strong: (chunks) => <span className="font-medium text-foreground">{chunks}</span>,
+ })}
+ </p>
+ </ConfirmDialog>
+ )}
+ </>
+ );
+}
diff --git a/apps/web/src/features/teams/components/info/TeamInfoSection.tsx b/apps/web/src/features/teams/components/info/TeamInfoSection.tsx
index 739b2b50..730d15cc 100644
--- a/apps/web/src/features/teams/components/info/TeamInfoSection.tsx
+++ b/apps/web/src/features/teams/components/info/TeamInfoSection.tsx
@@ -17,6 +17,7 @@ import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
+import TeamDeleteSection from './TeamDeleteSection';
import TeamLeadsSection from './TeamLeadsSection';
import TeamLeaveDialog from './TeamLeaveDialog';
import { TEAM_SLUG_PATTERN } from '../../utils/teamSlug';
@@ -31,7 +32,7 @@ function canLeave(team: Team): boolean {
}
// The team itself: the name and the URL slug its owner edits here, the caller's rank
-// in it, and the way out of it. Everything it shows comes with the team list.
+// in it, and leaving or deleting it. Everything it shows comes with the team list.
export default function TeamInfoSection({ teamId }: { teamId: number }) {
const t = useTranslations('teams.info');
const tSection = useTranslations('teams.sections.info');
@@ -148,6 +149,8 @@ export default function TeamInfoSection({ teamId }: { teamId: number }) {
}
/>
)}
+
+ {isOwner && <TeamDeleteSection team={team} />}
</div>
{leaving && <TeamLeaveDialog team={team} onClose={() => setLeaving(false)} />}
diff --git a/apps/web/src/lib/api/endpoints/teams.ts b/apps/web/src/lib/api/endpoints/teams.ts
index 6c05cef4..22018871 100644
--- a/apps/web/src/lib/api/endpoints/teams.ts
+++ b/apps/web/src/lib/api/endpoints/teams.ts
@@ -222,6 +222,9 @@ export const createTeam = (input: { name: string; slug: string; workspaceId: num
export const updateTeam = (teamId: number, input: { name?: string; slug?: string }) =>
request<Team>(`/teams/${teamId}`, { method: 'PATCH', body: JSON.stringify(input) });
+export const deleteTeam = (teamId: number) =>
+ request<void>(`/teams/${teamId}`, { method: 'DELETE' });
+
export const leaveTeam = (teamId: number) =>
request<void>(`/teams/${teamId}/leave`, { method: 'POST' });
diff --git a/apps/web/src/services/teams.service.ts b/apps/web/src/services/teams.service.ts
index 8df506e8..e6972b13 100644
--- a/apps/web/src/services/teams.service.ts
+++ b/apps/web/src/services/teams.service.ts
@@ -30,6 +30,7 @@ import {
updateTeam,
setTeamMemberRole,
removeTeamMember,
+ deleteTeam,
leaveTeam,
} from '@/lib/api/endpoints/teams';
import { nextPageParam } from '@/lib/api/core/paging';
@@ -216,6 +217,17 @@ export function useRemoveTeamMember(teamId: number) {
});
}
+export function useDeleteTeam() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (teamId: number) => deleteTeam(teamId),
+ onSuccess: (_result, teamId) => {
+ qc.setQueryData<Team[]>(qk.teams, (prev) => prev?.filter((t) => t.id !== teamId));
+ void qc.invalidateQueries({ queryKey: qk.teams });
+ },
+ });
+}
+
// Leaving a team takes the caller's projects in it with them, so the project list is
// refreshed along with the teams.
export function useLeaveTeam() {