Skip to content

Organization switching & active org management #173

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_UserToOrg" (
"joinedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"orgId" INTEGER NOT NULL,
"userId" TEXT NOT NULL,
"role" TEXT NOT NULL DEFAULT 'MEMBER',

PRIMARY KEY ("orgId", "userId"),
CONSTRAINT "UserToOrg_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "UserToOrg_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_UserToOrg" ("joinedAt", "orgId", "userId") SELECT "joinedAt", "orgId", "userId" FROM "UserToOrg";
DROP TABLE "UserToOrg";
ALTER TABLE "new_UserToOrg" RENAME TO "UserToOrg";
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "activeOrgId" INTEGER;
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_Repo" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"indexedAt" DATETIME,
"isFork" BOOLEAN NOT NULL,
"isArchived" BOOLEAN NOT NULL,
"metadata" JSONB NOT NULL,
"cloneUrl" TEXT NOT NULL,
"tenantId" INTEGER NOT NULL,
"repoIndexingStatus" TEXT NOT NULL DEFAULT 'NEW',
"external_id" TEXT NOT NULL,
"external_codeHostType" TEXT NOT NULL,
"external_codeHostUrl" TEXT NOT NULL,
"orgId" INTEGER,
CONSTRAINT "Repo_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "Org" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_Repo" ("cloneUrl", "createdAt", "external_codeHostType", "external_codeHostUrl", "external_id", "id", "indexedAt", "isArchived", "isFork", "metadata", "name", "repoIndexingStatus", "tenantId", "updatedAt") SELECT "cloneUrl", "createdAt", "external_codeHostType", "external_codeHostUrl", "external_id", "id", "indexedAt", "isArchived", "isFork", "metadata", "name", "repoIndexingStatus", "tenantId", "updatedAt" FROM "Repo";
DROP TABLE "Repo";
ALTER TABLE "new_Repo" RENAME TO "Repo";
CREATE UNIQUE INDEX "Repo_external_id_external_codeHostUrl_key" ON "Repo"("external_id", "external_codeHostUrl");
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;
16 changes: 14 additions & 2 deletions packages/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ model Repo {
// The base url of the external service (e.g., https://github.com)
external_codeHostUrl String

org Org? @relation(fields: [orgId], references: [id], onDelete: Cascade)
orgId Int?

@@unique([external_id, external_codeHostUrl])
}

Expand All @@ -71,6 +74,12 @@ model Org {
updatedAt DateTime @updatedAt
members UserToOrg[]
configs Config[]
repos Repo[]
}

enum OrgRole {
OWNER
MEMBER
}

model UserToOrg {
Expand All @@ -84,18 +93,21 @@ model UserToOrg {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId String

role OrgRole @default(MEMBER)

@@id([orgId, userId])
}

// @see : https://authjs.dev/concepts/database-models#user
model User {
id String @id @default(cuid())
id String @id @default(cuid())
name String?
email String? @unique
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
orgs UserToOrg[]
activeOrgId Int?

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand Down
6 changes: 4 additions & 2 deletions packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"@iconify/react": "^5.1.0",
"@iizukak/codemirror-lang-wgsl": "^0.3.0",
"@radix-ui/react-avatar": "^1.1.2",
"@radix-ui/react-dialog": "^1.1.4",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.1.0",
Expand Down Expand Up @@ -69,6 +70,7 @@
"client-only": "^0.0.1",
"clsx": "^2.1.1",
"cm6-graphql": "^0.2.0",
"cmdk": "1.0.0",
"codemirror": "^5.65.3",
"codemirror-lang-brainfuck": "^0.1.0",
"codemirror-lang-elixir": "^4.0.0",
Expand Down Expand Up @@ -110,6 +112,7 @@
"zod": "^3.23.8"
},
"devDependencies": {
"@sourcebot/db": "^0.1.0",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
Expand All @@ -122,10 +125,9 @@
"jsdom": "^25.0.1",
"npm-run-all": "^4.1.5",
"postcss": "^8",
"@sourcebot/db": "^0.1.0",
"tailwindcss": "^3.4.1",
"typescript": "^5",
"vite-tsconfig-paths": "^5.1.3",
"vitest": "^2.1.5"
}
}
}
Binary file added packages/web/public/placeholder_avatar.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
64 changes: 64 additions & 0 deletions packages/web/src/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use server';

import { auth } from "./auth";
import { notAuthenticated, notFound } from "./lib/serviceError";
import { prisma } from "@/prisma";


export const createOrg = async (name: string) => {
const session = await auth();
if (!session) {
return notAuthenticated();
}

// Create the org
const org = await prisma.org.create({
data: {
name,
members: {
create: {
userId: session.user.id,
role: "OWNER",
},
},
}
});

return {
id: org.id,
}
}

export const switchActiveOrg = async (orgId: number) => {
const session = await auth();
if (!session) {
return notAuthenticated();
}

// Check to see if the user is a member of the org
const membership = await prisma.userToOrg.findUnique({
where: {
orgId_userId: {
userId: session.user.id,
orgId,
}
},
});
if (!membership) {
return notFound();
}

// Update the user's active org
await prisma.user.update({
where: {
id: session.user.id,
},
data: {
activeOrgId: orgId,
}
});

return {
id: orgId,
}
}
4 changes: 4 additions & 0 deletions packages/web/src/app/components/navigationMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import logoLight from "../../../public/sb_logo_light_small.png";
import { SettingsDropdown } from "./settingsDropdown";
import { GitHubLogoIcon, DiscordLogoIcon } from "@radix-ui/react-icons";
import { redirect } from "next/navigation";
import { OrgSelector } from "./orgSelector";

const SOURCEBOT_DISCORD_URL = "https://discord.gg/6Fhp27x7Pb";
const SOURCEBOT_GITHUB_URL = "https://github.com/sourcebot-dev/sourcebot";
Expand Down Expand Up @@ -36,6 +37,9 @@ export const NavigationMenu = async () => {
/>
</Link>

<OrgSelector />
<Separator orientation="vertical" className="h-6 mx-2" />

<NavigationMenuBase>
<NavigationMenuList>
<NavigationMenuItem>
Expand Down
31 changes: 31 additions & 0 deletions packages/web/src/app/components/orgSelector/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { auth } from "@/auth";
import { getUser, getUserOrgs } from "../../data/user";
import { OrgSelectorDropdown } from "./orgSelectorDropdown";

export const OrgSelector = async () => {
const session = await auth();
if (!session) {
return null;
}

const user = await getUser(session.user.id);
if (!user) {
return null;
}

const orgs = await getUserOrgs(session.user.id);
const activeOrg = orgs.find((org) => org.id === user.activeOrgId);
if (!activeOrg) {
return null;
}

return (
<OrgSelectorDropdown
orgs={orgs.map((org) => ({
name: org.name,
id: org.id,
}))}
activeOrgId={activeOrg.id}
/>
)
}
80 changes: 80 additions & 0 deletions packages/web/src/app/components/orgSelector/orgCreationDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
'use client';
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { zodResolver } from "@hookform/resolvers/zod";
import { PlusCircledIcon } from "@radix-ui/react-icons";
import { useForm } from "react-hook-form";
import { z } from "zod";

const formSchema = z.object({
name: z.string().min(2).max(40),
});


interface OrgCreationDialogProps {
onSubmit: (data: z.infer<typeof formSchema>) => void;
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
}

export const OrgCreationDialog = ({
onSubmit,
isOpen,
onOpenChange,
}: OrgCreationDialogProps) => {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
name: "",
},
});

return (
<Dialog
open={isOpen}
onOpenChange={onOpenChange}
>
<DialogTrigger asChild>
<DropdownMenuItem
onSelect={(e) => e.preventDefault()}
>
<Button
variant="ghost"
size="default"
className="w-full justify-start gap-1.5 p-0"
>
<PlusCircledIcon className="h-5 w-5 text-muted-foreground" />
Create organization
</Button>
</DropdownMenuItem>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create an organization</DialogTitle>
<DialogDescription>Organizations allow you to collaborate with team members.</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Organization name</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button className="mt-5" type="submit">Submit</Button>
</form>
</Form>
</DialogContent>
</Dialog>
)
}
36 changes: 36 additions & 0 deletions packages/web/src/app/components/orgSelector/orgIcon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { cn } from "@/lib/utils";
import placeholderAvatar from "@/public/placeholder_avatar.png";
import { cva } from "class-variance-authority";
import Image from "next/image";

interface OrgIconProps {
className?: string;
size?: "default";
}

const iconVariants = cva(
"rounded-full",
{
variants: {
size: {
default: "w-5 h-5"
}
},
defaultVariants: {
size: "default"
}
},
)

export const OrgIcon = ({
className,
size,
}: OrgIconProps) => {
return (
<Image
src={placeholderAvatar}
alt="Organization avatar"
className={cn(iconVariants({ size, className }))}
/>
)
}
Loading