Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Populate `orgId` col on `videos` table (#1066)

Oscar Beaumont9054998fe509
diff --git a/apps/web/actions/video/upload.ts b/apps/web/actions/video/upload.ts
index 2bfa2f541..9bcd05a7c 100644
--- a/apps/web/actions/video/upload.ts
+++ b/apps/web/actions/video/upload.ts
@@ -164,6 +164,7 @@ export async function createVideoAndGetUploadUrl({
isScreenshot = false,
isUpload = false,
folderId,
+ orgId,
}: {
videoId?: Video.VideoId;
duration?: number;
@@ -173,6 +174,7 @@ export async function createVideoAndGetUploadUrl({
isScreenshot?: boolean;
isUpload?: boolean;
folderId?: Folder.FolderId;
+ orgId: string;
}) {
const user = await getCurrentUser();
@@ -228,6 +230,7 @@ export async function createVideoAndGetUploadUrl({
isScreenshot ? "Screenshot" : isUpload ? "Upload" : "Recording"
} - ${formattedDate}`,
ownerId: user.id,
+ orgId,
source: { type: "desktopMP4" as const },
isScreenshot,
bucket: customBucket?.id,
diff --git a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
index 80931b4c3..085d0dfb9 100644
--- a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
@@ -27,7 +27,7 @@ export const UploadCapButton = ({
grey?: boolean;
folderId?: Folder.FolderId;
}) => {
- const { user } = useDashboardContext();
+ const { user, activeOrganization } = useDashboardContext();
const inputRef = useRef<HTMLInputElement>(null);
const { uploadingStore, setUploadStatus } = useUploadingContext();
const isUploading = useStore(uploadingStore, (s) => !!s.uploadStatus);
@@ -52,9 +52,16 @@ export const UploadCapButton = ({
const file = e.target.files?.[0];
if (!file || !user) return;
+ // This should be unreachable.
+ if (activeOrganization === null) {
+ alert("No organization active!");
+ return;
+ }
+
const ok = await legacyUploadCap(
file,
folderId,
+ activeOrganization.organization.id,
setUploadStatus,
queryClient,
);
@@ -93,6 +100,7 @@ export const UploadCapButton = ({
async function legacyUploadCap(
file: File,
folderId: Folder.FolderId | undefined,
+ orgId: string,
setUploadStatus: (state: UploadStatus | undefined) => void,
queryClient: QueryClient,
) {
@@ -127,6 +135,7 @@ async function legacyUploadCap(
isScreenshot: false,
isUpload: true,
folderId,
+ orgId,
});
const uploadId = videoData.id;
@@ -451,6 +460,7 @@ async function legacyUploadCap(
videoId: uploadId,
isScreenshot: true,
isUpload: true,
+ orgId,
});
const screenshotFormData = new FormData();
diff --git a/apps/web/app/(org)/dashboard/dashboard-data.ts b/apps/web/app/(org)/dashboard/dashboard-data.ts
index 7b8392c38..c581a783d 100644
--- a/apps/web/app/(org)/dashboard/dashboard-data.ts
+++ b/apps/web/app/(org)/dashboard/dashboard-data.ts
@@ -48,6 +48,7 @@ export async function getDashboardData(user: typeof userSelectProps) {
email: users.email,
inviteQuota: users.inviteQuota,
image: users.image,
+ defaultOrgId: users.defaultOrgId,
},
})
.from(organizations)
diff --git a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx b/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
index e97793dfe..384c78438 100644
--- a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
+++ b/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
@@ -1,34 +1,47 @@
"use client";
import type { users } from "@cap/database/schema";
-import { Button, Card, CardDescription, CardTitle, Input } from "@cap/ui";
+import {
+ Button,
+ Card,
+ CardDescription,
+ CardTitle,
+ Input,
+ Select,
+} from "@cap/ui";
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { toast } from "sonner";
+import { useDashboardContext } from "../../Contexts";
+import { patchAccountSettings } from "./server";
export const Settings = ({
user,
}: {
user?: typeof users.$inferSelect | null;
}) => {
+ const router = useRouter();
+ const { organizationData } = useDashboardContext();
const [firstName, setFirstName] = useState(user?.name || "");
const [lastName, setLastName] = useState(user?.lastName || "");
- const router = useRouter();
+ const [defaultOrgId, setDefaultOrgId] = useState<string | undefined>(
+ user?.defaultOrgId || undefined,
+ );
+
+ // Track if form has unsaved changes
+ const hasChanges =
+ firstName !== (user?.name || "") ||
+ lastName !== (user?.lastName || "") ||
+ defaultOrgId !== user?.defaultOrgId;
const { mutate: updateName, isPending: updateNamePending } = useMutation({
mutationFn: async () => {
- const res = await fetch("/api/settings/user/name", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- firstName: firstName.trim(),
- lastName: lastName.trim() ? lastName.trim() : null,
- }),
- });
- if (!res.ok) {
- throw new Error("Failed to update name");
- }
+ await patchAccountSettings(
+ firstName.trim(),
+ lastName.trim() ? lastName.trim() : undefined,
+ defaultOrgId,
+ );
},
onSuccess: () => {
toast.success("Name updated successfully");
@@ -39,6 +52,19 @@ export const Settings = ({
},
});
+ // Prevent navigation when there are unsaved changes
+ useEffect(() => {
+ const handleBeforeUnload = (e: BeforeUnloadEvent) => {
+ if (hasChanges) {
+ e.preventDefault();
+ e.returnValue = "";
+ }
+ };
+
+ window.addEventListener("beforeunload", handleBeforeUnload);
+ return () => window.removeEventListener("beforeunload", handleBeforeUnload);
+ }, [hasChanges]);
+
return (
<form
onSubmit={(e) => {
@@ -91,9 +117,30 @@ export const Settings = ({
disabled
/>
</Card>
+ <Card className="flex flex-col flex-1 gap-4 justify-between items-stretch">
+ <div className="space-y-1">
+ <CardTitle>Default organization</CardTitle>
+ <CardDescription>This is the default organization</CardDescription>
+ </div>
+
+ <Select
+ placeholder="Default organization"
+ value={
+ defaultOrgId ??
+ user?.defaultOrgId ??
+ organizationData?.[0]?.organization.id ??
+ ""
+ }
+ onValueChange={(value) => setDefaultOrgId(value)}
+ options={(organizationData || []).map((org) => ({
+ value: org.organization.id,
+ label: org.organization.name,
+ }))}
+ />
+ </Card>
</div>
<Button
- disabled={!firstName || updateNamePending}
+ disabled={!firstName || updateNamePending || !hasChanges}
className="mt-6"
type="submit"
size="sm"
diff --git a/apps/web/app/(org)/dashboard/settings/account/server.ts b/apps/web/app/(org)/dashboard/settings/account/server.ts
new file mode 100644
index 000000000..b0a8bceae
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/settings/account/server.ts
@@ -0,0 +1,66 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import {
+ organizationMembers,
+ organizations,
+ users,
+} from "@cap/database/schema";
+import { eq, or } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+
+export async function patchAccountSettings(
+ firstName?: string,
+ lastName?: string,
+ defaultOrgId?: string,
+) {
+ const currentUser = await getCurrentUser();
+ if (!currentUser) throw new Error("Unauthorized");
+
+ const updatePayload: Partial<{
+ name: string;
+ lastName: string;
+ defaultOrgId: string;
+ }> = {};
+
+ if (firstName !== undefined) updatePayload.name = firstName;
+ if (lastName !== undefined) updatePayload.lastName = lastName;
+ if (defaultOrgId !== undefined) {
+ const userOrganizations = await db()
+ .select({
+ id: organizations.id,
+ })
+ .from(organizations)
+ .leftJoin(
+ organizationMembers,
+ eq(organizations.id, organizationMembers.organizationId),
+ )
+ .where(
+ or(
+ // User owns the organization
+ eq(organizations.ownerId, currentUser.id),
+ // User is a member of the organization
+ eq(organizationMembers.userId, currentUser.id),
+ ),
+ )
+ // Remove duplicates if user is both owner and member
+ .groupBy(organizations.id);
+
+ const userOrgIds = userOrganizations.map((org) => org.id);
+
+ if (!userOrgIds.includes(defaultOrgId))
+ throw new Error(
+ "Forbidden: User does not have access to the specified organization",
+ );
+
+ updatePayload.defaultOrgId = defaultOrgId;
+ }
+
+ await db()
+ .update(users)
+ .set(updatePayload)
+ .where(eq(users.id, currentUser.id));
+
+ revalidatePath("/dashboard/settings/account");
+}
diff --git a/apps/web/app/api/desktop/[...route]/video.ts b/apps/web/app/api/desktop/[...route]/video.ts
index 29a007422..3f4d7d22b 100644
--- a/apps/web/app/api/desktop/[...route]/video.ts
+++ b/apps/web/app/api/desktop/[...route]/video.ts
@@ -2,13 +2,20 @@ import { db } from "@cap/database";
import { sendEmail } from "@cap/database/emails/config";
import { FirstShareableLink } from "@cap/database/emails/first-shareable-link";
import { nanoId } from "@cap/database/helpers";
-import { s3Buckets, videos, videoUploads } from "@cap/database/schema";
+import {
+ organizationMembers,
+ organizations,
+ s3Buckets,
+ users,
+ videos,
+ videoUploads,
+} from "@cap/database/schema";
import { buildEnv, NODE_ENV, serverEnv } from "@cap/env";
import { userIsPro } from "@cap/utils";
import { S3Buckets } from "@cap/web-backend";
import { Video } from "@cap/web-domain";
import { zValidator } from "@hono/zod-validator";
-import { and, count, eq, gt, gte, lt, lte } from "drizzle-orm";
+import { and, count, eq, gt, gte, lt, lte, or } from "drizzle-orm";
import { Effect, Option } from "effect";
import { Hono } from "hono";
import { z } from "zod";
@@ -34,6 +41,7 @@ app.get(
width: stringOrNumberOptional,
height: stringOrNumberOptional,
fps: stringOrNumberOptional,
+ orgId: z.string().optional(),
}),
),
async (c) => {
@@ -47,6 +55,7 @@ app.get(
width,
height,
fps,
+ orgId,
} = c.req.valid("query");
const user = c.get("user");
@@ -71,8 +80,6 @@ app.get(
.from(s3Buckets)
.where(eq(s3Buckets.ownerId, user.id));
- console.log("User bucket:", customBucket ? "found" : "not found");
-
const date = new Date();
const formattedDate = `${date.getDate()} ${date.toLocaleString(
"default",
@@ -85,7 +92,7 @@ app.get(
.from(videos)
.where(eq(videos.id, Video.VideoId.make(videoId)));
- if (video) {
+ if (video)
return c.json({
id: video.id,
// All deprecated
@@ -93,7 +100,58 @@ app.get(
aws_region: "n/a",
aws_bucket: "n/a",
});
- }
+ }
+
+ const userOrganizations = await db()
+ .select({
+ id: organizations.id,
+ name: organizations.name,
+ })
+ .from(organizations)
+ .leftJoin(
+ organizationMembers,
+ eq(organizations.id, organizationMembers.organizationId),
+ )
+ .where(
+ or(
+ // User owns the organization
+ eq(organizations.ownerId, user.id),
+ // User is a member of the organization
+ eq(organizationMembers.userId, user.id),
+ ),
+ )
+ // Remove duplicates if user is both owner and member
+ .groupBy(organizations.id, organizations.name)
+ .orderBy(organizations.createdAt);
+ const userOrgIds = userOrganizations.map((org) => org.id);
+
+ let videoOrgId: string;
+ if (orgId) {
+ // Hard error if the user requested org is non-existent or they don't have access.
+ if (!userOrgIds.includes(orgId))
+ return c.json({ error: "forbidden_org" }, { status: 403 });
+ videoOrgId = orgId;
+ } else if (user.defaultOrgId) {
+ // User's defaultOrgId is no longer valid, switch to first available org
+ if (!userOrgIds.includes(user.defaultOrgId)) {
+ if (!userOrganizations[0])
+ return c.json({ error: "no_valid_org" }, { status: 403 });
+
+ videoOrgId = userOrganizations[0].id;
+
+ // Update user's defaultOrgId to the new valid org
+ await db()
+ .update(users)
+ .set({
+ defaultOrgId: videoOrgId,
+ })
+ .where(eq(users.id, user.id));
+ } else videoOrgId = user.defaultOrgId;
+ } else {
+ // No orgId provided and no defaultOrgId, use first available org
+ if (!userOrganizations[0])
+ return c.json({ error: "no_valid_org" }, { status: 403 });
+ videoOrgId = userOrganizations[0].id;
}
const idToUse = Video.VideoId.make(nanoId());
@@ -108,6 +166,7 @@ app.get(
id: idToUse,
name: videoName,
ownerId: user.id,
+ orgId: videoOrgId,
source:
recordingMode === "hls"
? { type: "local" as const }
diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css
index 02c080b22..bff65ab6a 100644
--- a/apps/web/app/globals.css
+++ b/apps/web/app/globals.css
@@ -342,7 +342,7 @@ span,
input,
label,
button {
- @apply tracking-normal text-gray-10 font-normal leading-[1.5rem];
+ @apply tracking-normal font-normal leading-[1.5rem];
}
a {
diff --git a/packages/database/drizzle.config.ts b/packages/database/drizzle.config.ts
index 9cc481386..ebd65b350 100644
--- a/packages/database/drizzle.config.ts
+++ b/packages/database/drizzle.config.ts
@@ -15,4 +15,5 @@ export default {
dialect: "mysql",
dbCredentials: { url: URL },
casing: "snake_case",
+ tablesFilter: ["*", "!cluster_*"],
} satisfies Config;
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index c4e4e6d87..26a49e575 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -11,7 +11,6 @@ import {
primaryKey,
text,
timestamp,
- tinyint,
uniqueIndex,
varchar,
} from "drizzle-orm/mysql-core";
@@ -89,6 +88,7 @@ export const users = mysqlTable(
onboarding_completed_at: timestamp("onboarding_completed_at"),
customBucket: nanoIdNullable("customBucket"),
inviteQuota: int("inviteQuota").notNull().default(1),
+ defaultOrgId: nanoIdNullable("defaultOrgId"),
},
(table) => ({
emailIndex: uniqueIndex("email_idx").on(table.email),
diff --git a/packages/ui/src/components/Select.tsx b/packages/ui/src/components/Select.tsx
index 3a7fcaa40..b438b088c 100644
--- a/packages/ui/src/components/Select.tsx
+++ b/packages/ui/src/components/Select.tsx
@@ -1,66 +1,234 @@
"use client";
-import * as RadixSelect from "@radix-ui/react-select";
-import clsx from "clsx";
-import { ChevronDown } from "lucide-react";
+import { classNames } from "@cap/utils";
+import * as SelectPrimitive from "@radix-ui/react-select";
+import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import type * as React from "react";
-export interface SelectOption {
- value: string;
- label: string;
- icon?: React.ReactNode;
+function Select({
+ options,
+ placeholder,
+ onValueChange,
+ value,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Root> & {
+ options: { value: string; label: string }[];
+ onValueChange: (value: string) => void;
+ placeholder: string;
+}) {
+ return (
+ <SelectRoot
+ onValueChange={onValueChange}
+ value={value}
+ data-slot="select"
+ {...props}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder={placeholder} />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </SelectRoot>
+ );
}
-export interface SelectProps {
- value: string;
- onChange: (value: string) => void;
- options: SelectOption[];
- placeholder?: string;
- disabled?: boolean;
- className?: string;
+function SelectRoot({
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Root>) {
+ return <SelectPrimitive.Root data-slot="select" {...props} />;
}
-export const Select: React.FC<SelectProps> = ({
- value,
- onChange,
- options,
- placeholder = "Select...",
- disabled = false,
- className = "",
-}) => {
+function SelectGroup({
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Group>) {
+ return <SelectPrimitive.Group data-slot="select-group" {...props} />;
+}
+
+function SelectValue({
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Value>) {
+ return <SelectPrimitive.Value data-slot="select-value" {...props} />;
+}
+
+function SelectTrigger({
+ className,
+ size = "default",
+ children,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
+ size?: "sm" | "default";
+}) {
return (
- <RadixSelect.Root
- value={value}
- onValueChange={onChange}
- disabled={disabled}
+ <SelectPrimitive.Trigger
+ data-slot="select-trigger"
+ data-size={size}
+ className={classNames(
+ "flex px-4 w-full font-thin transition-all duration-200 text-[13px] text-gray-12 bg-gray-2 border-gray-5 outline-0 focus:bg-gray-3",
+ "rounded-xl hover:bg-gray-3 hover:border-gray-6 border-[1px] focus:border-gray-6 items-center justify-between gap-2 whitespace-nowrap",
+ "disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-gray-3 disabled:text-gray-9",
+ "ring-0 ring-gray-3 focus:ring-1 focus:ring-gray-12 focus:ring-offset-2 ring-offset-gray-4",
+ "data-[placeholder]:text-gray-9 data-[size=default]:h-[44px] data-[size=sm]:h-[40px]",
+ "*:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2",
+ "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
>
- <RadixSelect.Trigger
- className={clsx(
- "flex items-center px-2 h-10 rounded-xl border bg-gray-3 border-gray-4 hover:bg-gray-5 group hover:border-gray-6 focus:ring-0 focus:ring-offset-0 focus:outline-0 text-[15px]",
- disabled && "opacity-50 cursor-not-allowed",
+ {children}
+ <SelectPrimitive.Icon asChild>
+ <ChevronDownIcon className="opacity-50 size-4" />
+ </SelectPrimitive.Icon>
+ </SelectPrimitive.Trigger>
+ );
+}
+
+function SelectContent({
+ className,
+ children,
+ position = "popper",
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Content>) {
+ return (
+ <SelectPrimitive.Portal>
+ <SelectPrimitive.Content
+ data-slot="select-content"
+ className={classNames(
+ "bg-gray-2 text-gray-12 border-gray-5 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem]",
+ "origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-xl border-[1px] shadow-md",
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ "data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
+ "data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ position === "popper" &&
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className,
)}
- aria-label={placeholder}
+ position={position}
+ {...props}
>
- <RadixSelect.Value placeholder={placeholder} />
- <RadixSelect.Icon asChild>
- <ChevronDown className="ml-2 text-gray-9" size={18} />
- </RadixSelect.Icon>
- </RadixSelect.Trigger>
- <RadixSelect.Content className="z-50 mt-2 rounded-xl border shadow-lg bg-gray-3 border-gray-4">
- <RadixSelect.Viewport>
- {options.map((opt) => (
- <RadixSelect.Item
- key={opt.value}
- value={opt.value}
- className="flex gap-2 items-center justify-start p-2 text-[15px] rounded-xl cursor-pointer text-gray-12 hover:bg-gray-4"
- >
- {opt.icon && <span className="mr-2">{opt.icon}</span>}
- <RadixSelect.ItemText>{opt.label}</RadixSelect.ItemText>
- </RadixSelect.Item>
- ))}
- </RadixSelect.Viewport>
- </RadixSelect.Content>
- </RadixSelect.Root>
+ <SelectScrollUpButton />
+ <SelectPrimitive.Viewport
+ className={classNames(
+ "p-1",
+ position === "popper" &&
+ "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
+ )}
+ >
+ {children}
+ </SelectPrimitive.Viewport>
+ <SelectScrollDownButton />
+ </SelectPrimitive.Content>
+ </SelectPrimitive.Portal>
+ );
+}
+
+function SelectLabel({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Label>) {
+ return (
+ <SelectPrimitive.Label
+ data-slot="select-label"
+ className={classNames("text-gray-10 px-3 py-1.5 text-xs", className)}
+ {...props}
+ />
);
+}
+
+function SelectItem({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Item>) {
+ return (
+ <SelectPrimitive.Item
+ data-slot="select-item"
+ className={classNames(
+ "relative flex w-full cursor-default items-center gap-2 py-2 pr-8 pl-3 text-[13px] text-gray-12",
+ "rounded-lg outline-none select-none transition-colors duration-200",
+ "hover:bg-gray-3 focus:bg-gray-3",
+ "data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[disabled]:text-gray-9",
+ "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className,
+ )}
+ {...props}
+ >
+ <span className="absolute right-2 flex size-3.5 items-center justify-center">
+ <SelectPrimitive.ItemIndicator>
+ <CheckIcon className="size-4" />
+ </SelectPrimitive.ItemIndicator>
+ </span>
+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
+ </SelectPrimitive.Item>
+ );
+}
+
+function SelectSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
+ return (
+ <SelectPrimitive.Separator
+ data-slot="select-separator"
+ className={classNames(
+ "-mx-1 my-1 h-px pointer-events-none bg-gray-5",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function SelectScrollUpButton({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
+ return (
+ <SelectPrimitive.ScrollUpButton
+ data-slot="select-scroll-up-button"
+ className={classNames(
+ "flex justify-center items-center py-1 cursor-default",
+ className,
+ )}
+ {...props}
+ >
+ <ChevronUpIcon className="size-4" />
+ </SelectPrimitive.ScrollUpButton>
+ );
+}
+
+function SelectScrollDownButton({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
+ return (
+ <SelectPrimitive.ScrollDownButton
+ data-slot="select-scroll-down-button"
+ className={classNames(
+ "flex justify-center items-center py-1 cursor-default",
+ className,
+ )}
+ {...props}
+ >
+ <ChevronDownIcon className="size-4" />
+ </SelectPrimitive.ScrollDownButton>
+ );
+}
+
+export {
+ Select,
+ SelectRoot,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectScrollDownButton,
+ SelectScrollUpButton,
+ SelectSeparator,
+ SelectTrigger,
+ SelectValue,
};
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 474890b30..614993f77 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -3,3 +3,4 @@ packages:
- "packages/*"
- "crates/tauri-plugin-*"
- "infra"
+ - "scripts/orgIdBackfill"
diff --git a/scripts/orgid_backfill/index.ts b/scripts/orgid_backfill/index.ts
new file mode 100644
index 000000000..50d52bfec
--- /dev/null
+++ b/scripts/orgid_backfill/index.ts
@@ -0,0 +1,207 @@
+import { db } from "@cap/database";
+import { users, videos } from "@cap/database/schema";
+import { and, eq, isNotNull, isNull, sql } from "drizzle-orm";
+
+const CHUNK_SIZE = 500;
+
+async function backfillVideoOrgIds() {
+ console.log("🎬 Starting video orgId backfill...");
+
+ let updated = 0;
+
+ while (true) {
+ // Find videos that need orgId backfilled
+ const videosToUpdate = await db()
+ .select({
+ id: videos.id,
+ ownerId: videos.ownerId,
+ orgId: videos.orgId,
+ })
+ .from(videos)
+ .innerJoin(users, eq(videos.ownerId, users.id))
+ .where(and(isNull(videos.orgId), isNotNull(users.activeOrganizationId)))
+ .limit(CHUNK_SIZE);
+
+ if (videosToUpdate.length === 0) break;
+
+ // Update videos in batch using subquery
+ const videoIds = videosToUpdate.map((v) => v.id);
+
+ const updateResult = await db()
+ .update(videos)
+ .set({
+ orgId: sql`(
+ SELECT u.activeOrganizationId
+ FROM users u
+ WHERE u.id = videos.ownerId
+ AND u.activeOrganizationId IS NOT NULL
+ )`,
+ })
+ .where(
+ and(
+ sql`videos.id IN (${sql.join(
+ videoIds.map((id) => sql`${id}`),
+ sql`, `,
+ )})`,
+ isNull(videos.orgId),
+ ),
+ );
+
+ const rowsUpdated = updateResult.rowsAffected || 0;
+ updated += rowsUpdated;
+
+ console.log(`πŸ“Ή Assigned orgId to ${updated} videos`);
+ }
+}
+
+async function backfillUserDefaultOrgIds() {
+ console.log("πŸ‘€ Starting user defaultOrgId backfill...");
+
+ let updated = 0;
+
+ const updateResult = await db()
+ .update(users)
+ .set({
+ defaultOrgId: users.activeOrganizationId,
+ })
+ .where(
+ and(isNull(users.defaultOrgId), isNotNull(users.activeOrganizationId)),
+ );
+ const rowsUpdated = updateResult.rowsAffected || 0;
+ updated += rowsUpdated;
+
+ console.log(`πŸ‘₯ Assigned defaultOrgId to ${updated} users`);
+}
+
+async function validateBackfill(): Promise<void> {
+ console.log("πŸ” Validating backfill results...");
+
+ // Count videos still missing orgId where owner has activeOrganizationId
+ const videosWithoutOrgId = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(videos)
+ .innerJoin(users, eq(videos.ownerId, users.id))
+ .where(and(isNull(videos.orgId), isNotNull(users.activeOrganizationId)));
+
+ // Count users still missing defaultOrgId where they have activeOrganizationId
+ const usersWithoutDefaultOrgId = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(users)
+ .where(
+ and(isNull(users.defaultOrgId), isNotNull(users.activeOrganizationId)),
+ );
+
+ // Count videos with mismatched orgId (different from owner's activeOrganizationId)
+ const videosWithMismatchedOrgId = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(videos)
+ .innerJoin(users, eq(videos.ownerId, users.id))
+ .where(
+ and(
+ isNotNull(videos.orgId),
+ isNotNull(users.activeOrganizationId),
+ sql`videos.orgId != users.activeOrganizationId`,
+ ),
+ );
+
+ // Count users with mismatched defaultOrgId (different from activeOrganizationId)
+ const usersWithMismatchedDefaultOrgId = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(users)
+ .where(
+ and(
+ isNotNull(users.defaultOrgId),
+ isNotNull(users.activeOrganizationId),
+ sql`users.defaultOrgId != users.activeOrganizationId`,
+ ),
+ );
+
+ console.log("πŸ“Š Validation results:");
+ console.log(
+ ` Videos still missing orgId: ${videosWithoutOrgId[0]?.count || 0}`,
+ );
+ console.log(
+ ` Users still missing defaultOrgId: ${usersWithoutDefaultOrgId[0]?.count || 0}`,
+ );
+ console.log(
+ ` Videos with mismatched orgId: ${videosWithMismatchedOrgId[0]?.count || 0}`,
+ );
+ console.log(
+ ` Users with mismatched defaultOrgId: ${usersWithMismatchedDefaultOrgId[0]?.count || 0}`,
+ );
+}
+
+async function getInitialStats(): Promise<void> {
+ console.log("πŸ“ˆ Getting initial stats...");
+
+ const totalVideos = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(videos);
+
+ const videosWithOrgId = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(videos)
+ .where(isNotNull(videos.orgId));
+
+ const videosNeedingOrgId = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(videos)
+ .innerJoin(users, eq(videos.ownerId, users.id))
+ .where(and(isNull(videos.orgId), isNotNull(users.activeOrganizationId)));
+
+ const totalUsers = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(users);
+
+ const usersWithDefaultOrgId = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(users)
+ .where(isNotNull(users.defaultOrgId));
+
+ const usersNeedingDefaultOrgId = await db()
+ .select({ count: sql<number>`count(*)` })
+ .from(users)
+ .where(
+ and(isNull(users.defaultOrgId), isNotNull(users.activeOrganizationId)),
+ );
+
+ console.log("πŸ“Š Initial stats:");
+ console.log(` Total videos: ${totalVideos[0]?.count || 0}`);
+ console.log(` Videos with orgId: ${videosWithOrgId[0]?.count || 0}`);
+ console.log(` Videos needing orgId: ${videosNeedingOrgId[0]?.count || 0}`);
+ console.log(` Total users: ${totalUsers[0]?.count || 0}`);
+ console.log(
+ ` Users with defaultOrgId: ${usersWithDefaultOrgId[0]?.count || 0}`,
+ );
+ console.log(
+ ` Users needing defaultOrgId: ${usersNeedingDefaultOrgId[0]?.count || 0}`,
+ );
+ console.log("");
+}
+
+async function main(): Promise<void> {
+ console.log("πŸš€ Starting orgId backfill script");
+ console.log(`πŸ“¦ Processing in chunks of ${CHUNK_SIZE} rows\n`);
+
+ try {
+ await getInitialStats();
+
+ await backfillVideoOrgIds();
+ console.log(`βœ… Video backfill complete\n`);
+
+ await backfillUserDefaultOrgIds();
+ console.log(`βœ… User backfill complete\n`);
+
+ await validateBackfill();
+ process.exit(0);
+ } catch (error) {
+ console.error("❌ Error during backfill:", error);
+ process.exit(1);
+ }
+}
+
+// Run the script
+main().catch((error) => {
+ console.error("❌ Unhandled error:", error);
+ process.exit(1);
+});
diff --git a/scripts/orgid_backfill/package.json b/scripts/orgid_backfill/package.json
new file mode 100644
index 000000000..26e987c5a
--- /dev/null
+++ b/scripts/orgid_backfill/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "@cap/orgid_backfill",
+ "private": true,
+ "scripts": {
+ "backfill": "npx dotenv -e ../../.env -- npx tsx index.ts"
+ },
+ "dependencies": {
+ "@cap/database": "workspace:^",
+ "dotenv": "^17.2.3",
+ "drizzle-orm": "0.44.5",
+ "tsx": "^4.20.6"
+ }
+}