Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

feat(app): add dashboard and overview components for enhanced user experience

Lewis Carhart181bd28b016c
diff --git a/.claude/settings.json b/.claude/settings.json
index 4bfc5569..97251ad9 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -1,3 +1,8 @@
{
- "worktree": { "bgIsolation": "none" }
+ "worktree": {
+ "bgIsolation": "none"
+ },
+ "enabledPlugins": {
+ "paper-desktop@paper": true
+ }
}
diff --git a/apps/agent/test/model.integration.spec.ts b/apps/agent/test/model.integration.spec.ts
index f4cc839b..13f5e17c 100644
--- a/apps/agent/test/model.integration.spec.ts
+++ b/apps/agent/test/model.integration.spec.ts
@@ -1,5 +1,13 @@
-import { afterEach, beforeEach, describe, expect, it } from "bun:test";
-import { db } from "@crm/db";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+} from "bun:test";
+import { db, type Prisma } from "@crm/db";
import {
DEFAULT_AGENT_MODEL,
readAgentModel,
@@ -12,9 +20,24 @@ async function clear() {
await db.appSetting.deleteMany({ where: { id: SETTINGS_ID } });
}
+/**
+ * The row holds the Context key a rep typed and the model they chose, and
+ * DATABASE_URL is somebody's working database. Deleting it and not putting it
+ * back sends them through the research-key gate again with nothing saying why.
+ */
+let saved: Prisma.AppSettingUncheckedCreateInput | null = null;
+
+beforeAll(async () => {
+ saved = await db.appSetting.findUnique({ where: { id: SETTINGS_ID } });
+});
+
beforeEach(clear);
afterEach(clear);
+afterAll(async () => {
+ if (saved) await db.appSetting.create({ data: saved });
+});
+
describe("the configured model", () => {
it("falls back when nothing has ever been chosen", async () => {
const setting = await readAgentModel(db);
diff --git a/apps/api/src/workspace/workspace.service.ts b/apps/api/src/workspace/workspace.service.ts
index 1f776036..bce1d687 100644
--- a/apps/api/src/workspace/workspace.service.ts
+++ b/apps/api/src/workspace/workspace.service.ts
@@ -7,7 +7,7 @@ import {
type WorkspaceRole,
} from "@crm/auth";
import type { Db, Prisma } from "@crm/db";
-import { isOnboarded, markOnboarded } from "@crm/db/workspace";
+import { isOnboarded, markOnboarded, workspaceSlug } from "@crm/db/workspace";
import {
BadRequestException,
ForbiddenException,
@@ -34,6 +34,7 @@ import type {
export interface Workspace {
id: string;
+ slug: string;
name: string;
website: string | null;
onboarded: boolean;
@@ -104,6 +105,7 @@ export class WorkspaceService {
return {
id: row.id,
+ slug: row.slug,
name: row.name,
website: row.website,
onboarded: isOnboarded(row.metadata),
@@ -142,6 +144,7 @@ export class WorkspaceService {
where: { id: WORKSPACE_ID },
data: {
name: input.name,
+ slug: workspaceSlug(input.name),
website,
metadata: markOnboarded(before?.metadata ?? null, new Date()),
},
@@ -286,7 +289,13 @@ export class WorkspaceService {
private async readWorkspace() {
return this.db.organization.findUnique({
where: { id: WORKSPACE_ID },
- select: { id: true, name: true, website: true, metadata: true },
+ select: {
+ id: true,
+ slug: true,
+ name: true,
+ website: true,
+ metadata: true,
+ },
});
}
diff --git a/apps/app/app/(app)/[slug]/companies/[companyId]/page.tsx b/apps/app/app/(app)/[slug]/companies/[companyId]/page.tsx
new file mode 100644
index 00000000..bba9b2d4
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/companies/[companyId]/page.tsx
@@ -0,0 +1,11 @@
+import { redirect } from "next/navigation";
+import { recordHref } from "@/lib/record-href";
+
+export default async function RecordRedirect({
+ params,
+}: {
+ params: Promise<{ slug: string; companyId: string }>;
+}) {
+ const { slug, companyId } = await params;
+ redirect(recordHref(slug, "/companies", "company", companyId));
+}
diff --git a/apps/app/app/(app)/companies/companies-search-params.ts b/apps/app/app/(app)/[slug]/companies/companies-search-params.ts
similarity index 100%
rename from apps/app/app/(app)/companies/companies-search-params.ts
rename to apps/app/app/(app)/[slug]/companies/companies-search-params.ts
diff --git a/apps/app/app/(app)/companies/companies-table.tsx b/apps/app/app/(app)/[slug]/companies/companies-table.tsx
similarity index 100%
rename from apps/app/app/(app)/companies/companies-table.tsx
rename to apps/app/app/(app)/[slug]/companies/companies-table.tsx
diff --git a/apps/app/app/(app)/companies/create-company-sheet.tsx b/apps/app/app/(app)/[slug]/companies/create-company-sheet.tsx
similarity index 100%
rename from apps/app/app/(app)/companies/create-company-sheet.tsx
rename to apps/app/app/(app)/[slug]/companies/create-company-sheet.tsx
diff --git a/apps/app/app/(app)/companies/page.tsx b/apps/app/app/(app)/[slug]/companies/page.tsx
similarity index 100%
rename from apps/app/app/(app)/companies/page.tsx
rename to apps/app/app/(app)/[slug]/companies/page.tsx
diff --git a/apps/app/app/(app)/[slug]/contacts/[contactId]/page.tsx b/apps/app/app/(app)/[slug]/contacts/[contactId]/page.tsx
new file mode 100644
index 00000000..42cd6d80
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/contacts/[contactId]/page.tsx
@@ -0,0 +1,11 @@
+import { redirect } from "next/navigation";
+import { recordHref } from "@/lib/record-href";
+
+export default async function RecordRedirect({
+ params,
+}: {
+ params: Promise<{ slug: string; contactId: string }>;
+}) {
+ const { slug, contactId } = await params;
+ redirect(recordHref(slug, "/contacts", "contact", contactId));
+}
diff --git a/apps/app/app/(app)/contacts/contacts-search-params.ts b/apps/app/app/(app)/[slug]/contacts/contacts-search-params.ts
similarity index 100%
rename from apps/app/app/(app)/contacts/contacts-search-params.ts
rename to apps/app/app/(app)/[slug]/contacts/contacts-search-params.ts
diff --git a/apps/app/app/(app)/contacts/contacts-table.tsx b/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx
similarity index 100%
rename from apps/app/app/(app)/contacts/contacts-table.tsx
rename to apps/app/app/(app)/[slug]/contacts/contacts-table.tsx
diff --git a/apps/app/app/(app)/contacts/create-contact-sheet.tsx b/apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsx
similarity index 100%
rename from apps/app/app/(app)/contacts/create-contact-sheet.tsx
rename to apps/app/app/(app)/[slug]/contacts/create-contact-sheet.tsx
diff --git a/apps/app/app/(app)/contacts/page.tsx b/apps/app/app/(app)/[slug]/contacts/page.tsx
similarity index 100%
rename from apps/app/app/(app)/contacts/page.tsx
rename to apps/app/app/(app)/[slug]/contacts/page.tsx
diff --git a/apps/app/app/(app)/dashboard-summary.tsx b/apps/app/app/(app)/[slug]/dashboard-summary.tsx
similarity index 97%
rename from apps/app/app/(app)/dashboard-summary.tsx
rename to apps/app/app/(app)/[slug]/dashboard-summary.tsx
index 7f5a4581..2ea1128d 100644
--- a/apps/app/app/(app)/dashboard-summary.tsx
+++ b/apps/app/app/(app)/[slug]/dashboard-summary.tsx
@@ -44,6 +44,7 @@ import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
import { activityLabel } from "@/components/crm/timeline/activity-icon";
import { useCrmCache } from "@/lib/trpc/cache";
import { useTRPC } from "@/lib/trpc/client";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
import { overviewParsers } from "./overview-search-params";
import { SalesDashboard } from "./sales-dashboard";
@@ -53,6 +54,7 @@ export function DashboardSummary() {
const trpc = useTRPC();
const cache = useCrmCache();
const openRecord = useOpenRecord();
+ const workspaceUrl = useWorkspaceUrl();
const [scope] = useQueryState("scope", overviewParsers.scope);
@@ -121,7 +123,7 @@ export function DashboardSummary() {
</CardDescription>
<CardAction>
<Button asChild variant="contrast" size="sm">
- <Link href="/deals">Open deals</Link>
+ <Link href={workspaceUrl("/deals")}>Open deals</Link>
</Button>
</CardAction>
</CardHeader>
@@ -240,7 +242,7 @@ export function DashboardSummary() {
</CardDescription>
<CardAction>
<Button asChild variant="contrast" size="sm">
- <Link href="/companies">All companies</Link>
+ <Link href={workspaceUrl("/companies")}>All companies</Link>
</Button>
</CardAction>
</CardHeader>
diff --git a/apps/app/app/(app)/[slug]/deals/[dealId]/page.tsx b/apps/app/app/(app)/[slug]/deals/[dealId]/page.tsx
new file mode 100644
index 00000000..edb3fcec
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/deals/[dealId]/page.tsx
@@ -0,0 +1,11 @@
+import { redirect } from "next/navigation";
+import { recordHref } from "@/lib/record-href";
+
+export default async function RecordRedirect({
+ params,
+}: {
+ params: Promise<{ slug: string; dealId: string }>;
+}) {
+ const { slug, dealId } = await params;
+ redirect(recordHref(slug, "/deals", "deal", dealId));
+}
diff --git a/apps/app/app/(app)/deals/create-deal-sheet.tsx b/apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
similarity index 100%
rename from apps/app/app/(app)/deals/create-deal-sheet.tsx
rename to apps/app/app/(app)/[slug]/deals/create-deal-sheet.tsx
diff --git a/apps/app/app/(app)/deals/deals-search-params.ts b/apps/app/app/(app)/[slug]/deals/deals-search-params.ts
similarity index 100%
rename from apps/app/app/(app)/deals/deals-search-params.ts
rename to apps/app/app/(app)/[slug]/deals/deals-search-params.ts
diff --git a/apps/app/app/(app)/deals/deals-table.tsx b/apps/app/app/(app)/[slug]/deals/deals-table.tsx
similarity index 100%
rename from apps/app/app/(app)/deals/deals-table.tsx
rename to apps/app/app/(app)/[slug]/deals/deals-table.tsx
diff --git a/apps/app/app/(app)/deals/page.tsx b/apps/app/app/(app)/[slug]/deals/page.tsx
similarity index 100%
rename from apps/app/app/(app)/deals/page.tsx
rename to apps/app/app/(app)/[slug]/deals/page.tsx
diff --git a/apps/app/app/(app)/layout.tsx b/apps/app/app/(app)/[slug]/layout.tsx
similarity index 68%
rename from apps/app/app/(app)/layout.tsx
rename to apps/app/app/(app)/[slug]/layout.tsx
index 9b3af361..750312fd 100644
--- a/apps/app/app/(app)/layout.tsx
+++ b/apps/app/app/(app)/[slug]/layout.tsx
@@ -1,3 +1,4 @@
+import { notFound } from "next/navigation";
import { AppHeader } from "@/components/app-header";
import { AppIconRail } from "@/components/app-icon-rail";
import { QuickSwitcher } from "@/components/crm/quick-switcher";
@@ -5,13 +6,25 @@ import { RecordSheetHost } from "@/components/crm/record-sheet/record-sheet-host
import { MobileNavProvider } from "@/components/mobile-nav";
import { requireGoogleAccess } from "@/lib/session";
import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
export default async function AppLayout({
children,
+ params,
}: Readonly<{
children: React.ReactNode;
+ params: Promise<{ slug: string }>;
}>) {
- const { user } = await requireGoogleAccess();
+ const [{ user }, { slug }] = await Promise.all([
+ requireGoogleAccess(),
+ params,
+ ]);
+
+ const workspace = await getServerQueryClient()
+ .fetchQuery(getServerTrpc().workspace.get.queryOptions())
+ .catch(() => null);
+
+ if (workspace && workspace.slug !== slug) notFound();
return (
<MobileNavProvider>
diff --git a/apps/app/app/(app)/overview-greeting.tsx b/apps/app/app/(app)/[slug]/overview-greeting.tsx
similarity index 100%
rename from apps/app/app/(app)/overview-greeting.tsx
rename to apps/app/app/(app)/[slug]/overview-greeting.tsx
diff --git a/apps/app/app/(app)/overview-scope.tsx b/apps/app/app/(app)/[slug]/overview-scope.tsx
similarity index 100%
rename from apps/app/app/(app)/overview-scope.tsx
rename to apps/app/app/(app)/[slug]/overview-scope.tsx
diff --git a/apps/app/app/(app)/overview-search-params.ts b/apps/app/app/(app)/[slug]/overview-search-params.ts
similarity index 100%
rename from apps/app/app/(app)/overview-search-params.ts
rename to apps/app/app/(app)/[slug]/overview-search-params.ts
diff --git a/apps/app/app/(app)/page.tsx b/apps/app/app/(app)/[slug]/page.tsx
similarity index 100%
rename from apps/app/app/(app)/page.tsx
rename to apps/app/app/(app)/[slug]/page.tsx
diff --git a/apps/app/app/(app)/sales-dashboard.tsx b/apps/app/app/(app)/[slug]/sales-dashboard.tsx
similarity index 97%
rename from apps/app/app/(app)/sales-dashboard.tsx
rename to apps/app/app/(app)/[slug]/sales-dashboard.tsx
index e18c6f75..721d72a0 100644
--- a/apps/app/app/(app)/sales-dashboard.tsx
+++ b/apps/app/app/(app)/[slug]/sales-dashboard.tsx
@@ -20,6 +20,7 @@ import type { ReactNode } from "react";
import { dealStageColor, dealStageLabel } from "@/components/crm/deal-stage";
import { AreaTrend, DonutStat } from "@/components/dashboard-charts";
import type { RouterOutputs } from "@/lib/trpc/types";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
type Summary = RouterOutputs["dashboard"]["summary"];
@@ -43,6 +44,8 @@ function changeDelta(
}
export function SalesDashboard({ summary }: { summary: Summary }) {
+ const workspaceUrl = useWorkspaceUrl();
+
const {
pipeline,
wonThisMonth,
@@ -154,7 +157,7 @@ export function SalesDashboard({ summary }: { summary: Summary }) {
{stageSlices.map((slice) => (
<li key={slice.key} className="border-t first:border-t-0">
<Link
- href={`/deals?stage=${slice.key}`}
+ href={`${workspaceUrl("/deals")}?stage=${slice.key}`}
className="flex items-center gap-2.5 py-2 text-xs hover:underline"
>
<span
diff --git a/apps/app/app/(app)/settings/agent-model.tsx b/apps/app/app/(app)/[slug]/settings/agent-model.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/agent-model.tsx
rename to apps/app/app/(app)/[slug]/settings/agent-model.tsx
diff --git a/apps/app/app/(app)/settings/connections/google-connection.tsx b/apps/app/app/(app)/[slug]/settings/connections/google-connection.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/connections/google-connection.tsx
rename to apps/app/app/(app)/[slug]/settings/connections/google-connection.tsx
diff --git a/apps/app/app/(app)/settings/connections/page.tsx b/apps/app/app/(app)/[slug]/settings/connections/page.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/connections/page.tsx
rename to apps/app/app/(app)/[slug]/settings/connections/page.tsx
diff --git a/apps/app/app/(app)/settings/layout.tsx b/apps/app/app/(app)/[slug]/settings/layout.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/layout.tsx
rename to apps/app/app/(app)/[slug]/settings/layout.tsx
diff --git a/apps/app/app/(app)/settings/members/members-search-params.ts b/apps/app/app/(app)/[slug]/settings/members/members-search-params.ts
similarity index 100%
rename from apps/app/app/(app)/settings/members/members-search-params.ts
rename to apps/app/app/(app)/[slug]/settings/members/members-search-params.ts
diff --git a/apps/app/app/(app)/settings/members/members-table.tsx b/apps/app/app/(app)/[slug]/settings/members/members-table.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/members/members-table.tsx
rename to apps/app/app/(app)/[slug]/settings/members/members-table.tsx
diff --git a/apps/app/app/(app)/settings/members/page.tsx b/apps/app/app/(app)/[slug]/settings/members/page.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/members/page.tsx
rename to apps/app/app/(app)/[slug]/settings/members/page.tsx
diff --git a/apps/app/app/(app)/settings/page.tsx b/apps/app/app/(app)/[slug]/settings/page.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/page.tsx
rename to apps/app/app/(app)/[slug]/settings/page.tsx
diff --git a/apps/app/app/(app)/settings/research-key.tsx b/apps/app/app/(app)/[slug]/settings/research-key.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/research-key.tsx
rename to apps/app/app/(app)/[slug]/settings/research-key.tsx
diff --git a/apps/app/app/(app)/settings/settings-sidebar.tsx b/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx
similarity index 74%
rename from apps/app/app/(app)/settings/settings-sidebar.tsx
rename to apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx
index a3558774..1a2a4192 100644
--- a/apps/app/app/(app)/settings/settings-sidebar.tsx
+++ b/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx
@@ -4,6 +4,8 @@ import { Button } from "@crm/ui/components/button";
import { cn } from "@crm/ui/lib/utils";
import Link from "next/link";
import { usePathname } from "next/navigation";
+import { useMemo } from "react";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
type SettingsNavItem = {
title: string;
@@ -19,8 +21,8 @@ const ITEMS: SettingsNavItem[] = [
{ title: "Connections", href: `${ROOT}/connections` },
];
-function isActive(href: string, pathname: string): boolean {
- return href === ROOT ? pathname === href : pathname.startsWith(href);
+function isActive(href: string, root: string, pathname: string): boolean {
+ return href === root ? pathname === href : pathname.startsWith(href);
}
function NavLink({
@@ -56,6 +58,13 @@ function NavLink({
export function SettingsSidebar() {
const pathname = usePathname();
+ const workspaceUrl = useWorkspaceUrl();
+
+ const root = workspaceUrl(ROOT);
+ const items = useMemo(
+ () => ITEMS.map((item) => ({ ...item, href: workspaceUrl(item.href) })),
+ [workspaceUrl],
+ );
return (
<>
@@ -64,11 +73,11 @@ export function SettingsSidebar() {
aria-label="Workspace settings"
className="flex flex-col gap-0.5 p-3"
>
- {ITEMS.map((item) => (
+ {items.map((item) => (
<NavLink
key={item.href}
item={item}
- active={isActive(item.href, pathname)}
+ active={isActive(item.href, root, pathname)}
className="w-full px-3"
/>
))}
@@ -79,11 +88,11 @@ export function SettingsSidebar() {
aria-label="Workspace settings"
className="flex gap-1 overflow-x-auto border-b p-2 md:hidden [view-transition-name:settings-sidebar]"
>
- {ITEMS.map((item) => (
+ {items.map((item) => (
<NavLink
key={item.href}
item={item}
- active={isActive(item.href, pathname)}
+ active={isActive(item.href, root, pathname)}
className="shrink-0 px-3"
/>
))}
diff --git a/apps/app/app/(app)/settings/sso/add-sso-provider-sheet.tsx b/apps/app/app/(app)/[slug]/settings/sso/add-sso-provider-sheet.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/sso/add-sso-provider-sheet.tsx
rename to apps/app/app/(app)/[slug]/settings/sso/add-sso-provider-sheet.tsx
diff --git a/apps/app/app/(app)/settings/sso/copy-value.tsx b/apps/app/app/(app)/[slug]/settings/sso/copy-value.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/sso/copy-value.tsx
rename to apps/app/app/(app)/[slug]/settings/sso/copy-value.tsx
diff --git a/apps/app/app/(app)/settings/sso/page.tsx b/apps/app/app/(app)/[slug]/settings/sso/page.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/sso/page.tsx
rename to apps/app/app/(app)/[slug]/settings/sso/page.tsx
diff --git a/apps/app/app/(app)/settings/sso/sso-search-params.ts b/apps/app/app/(app)/[slug]/settings/sso/sso-search-params.ts
similarity index 100%
rename from apps/app/app/(app)/settings/sso/sso-search-params.ts
rename to apps/app/app/(app)/[slug]/settings/sso/sso-search-params.ts
diff --git a/apps/app/app/(app)/settings/sso/sso-table.tsx b/apps/app/app/(app)/[slug]/settings/sso/sso-table.tsx
similarity index 100%
rename from apps/app/app/(app)/settings/sso/sso-table.tsx
rename to apps/app/app/(app)/[slug]/settings/sso/sso-table.tsx
diff --git a/apps/app/app/(app)/settings/workspace-form.tsx b/apps/app/app/(app)/[slug]/settings/workspace-form.tsx
similarity index 91%
rename from apps/app/app/(app)/settings/workspace-form.tsx
rename to apps/app/app/(app)/[slug]/settings/workspace-form.tsx
index 737105e5..9ced0371 100644
--- a/apps/app/app/(app)/settings/workspace-form.tsx
+++ b/apps/app/app/(app)/[slug]/settings/workspace-form.tsx
@@ -24,14 +24,19 @@ import {
} from "@crm/ui/components/input-group";
import { Spinner } from "@crm/ui/components/spinner";
import { useMutation, useQuery } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
import { useId, useState } from "react";
import { toast } from "sonner";
import { useCrmCache } from "@/lib/trpc/cache";
import { useTRPC } from "@/lib/trpc/client";
+import { useWorkspaceSlug } from "@/lib/use-workspace-url";
+import { workspaceUrl } from "@/lib/workspace-url";
export function WorkspaceForm() {
const trpc = useTRPC();
const cache = useCrmCache();
+ const router = useRouter();
+ const slug = useWorkspaceSlug();
const nameId = useId();
const websiteId = useId();
@@ -44,10 +49,14 @@ export function WorkspaceForm() {
const save = useMutation(
trpc.workspace.update.mutationOptions({
- onSuccess: async () => {
+ onSuccess: async (saved) => {
await cache.workspace();
setDraft(null);
toast.success("Workspace saved.");
+
+ if (saved.slug !== slug) {
+ router.replace(workspaceUrl(saved.slug, "/settings"));
+ }
},
onError: (error) => toast.error(error.message),
}),
diff --git a/apps/app/app/(app)/companies/[companyId]/page.tsx b/apps/app/app/(app)/companies/[companyId]/page.tsx
deleted file mode 100644
index d6f6e3ea..00000000
--- a/apps/app/app/(app)/companies/[companyId]/page.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { redirect } from "next/navigation";
-import { recordHref } from "@/lib/record-href";
-
-export default async function CompanyRedirect({
- params,
-}: {
- params: Promise<{ companyId: string }>;
-}) {
- const { companyId } = await params;
- redirect(recordHref("/companies", "company", companyId));
-}
diff --git a/apps/app/app/(app)/contacts/[contactId]/page.tsx b/apps/app/app/(app)/contacts/[contactId]/page.tsx
deleted file mode 100644
index ed76688c..00000000
--- a/apps/app/app/(app)/contacts/[contactId]/page.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { redirect } from "next/navigation";
-import { recordHref } from "@/lib/record-href";
-
-export default async function ContactRedirect({
- params,
-}: {
- params: Promise<{ contactId: string }>;
-}) {
- const { contactId } = await params;
- redirect(recordHref("/contacts", "contact", contactId));
-}
diff --git a/apps/app/app/(app)/deals/[dealId]/page.tsx b/apps/app/app/(app)/deals/[dealId]/page.tsx
deleted file mode 100644
index 5481fcc5..00000000
--- a/apps/app/app/(app)/deals/[dealId]/page.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { redirect } from "next/navigation";
-import { recordHref } from "@/lib/record-href";
-
-export default async function DealRedirect({
- params,
-}: {
- params: Promise<{ dealId: string }>;
-}) {
- const { dealId } = await params;
- redirect(recordHref("/deals", "deal", dealId));
-}
diff --git a/apps/app/app/(auth)/grant-access/grant-access.tsx b/apps/app/app/(landing)/grant-access/grant-access.tsx
similarity index 100%
rename from apps/app/app/(auth)/grant-access/grant-access.tsx
rename to apps/app/app/(landing)/grant-access/grant-access.tsx
diff --git a/apps/app/app/(auth)/grant-access/page.tsx b/apps/app/app/(landing)/grant-access/page.tsx
similarity index 100%
rename from apps/app/app/(auth)/grant-access/page.tsx
rename to apps/app/app/(landing)/grant-access/page.tsx
diff --git a/apps/app/app/(auth)/onboarding/onboarding-form.tsx b/apps/app/app/(landing)/onboarding/onboarding-form.tsx
similarity index 100%
rename from apps/app/app/(auth)/onboarding/onboarding-form.tsx
rename to apps/app/app/(landing)/onboarding/onboarding-form.tsx
diff --git a/apps/app/app/(auth)/onboarding/page.tsx b/apps/app/app/(landing)/onboarding/page.tsx
similarity index 100%
rename from apps/app/app/(auth)/onboarding/page.tsx
rename to apps/app/app/(landing)/onboarding/page.tsx
diff --git a/apps/app/app/(auth)/onboarding/research/page.tsx b/apps/app/app/(landing)/onboarding/research/page.tsx
similarity index 100%
rename from apps/app/app/(auth)/onboarding/research/page.tsx
rename to apps/app/app/(landing)/onboarding/research/page.tsx
diff --git a/apps/app/app/(auth)/onboarding/research/research-form.tsx b/apps/app/app/(landing)/onboarding/research/research-form.tsx
similarity index 100%
rename from apps/app/app/(auth)/onboarding/research/research-form.tsx
rename to apps/app/app/(landing)/onboarding/research/research-form.tsx
diff --git a/apps/app/app/(landing)/page.tsx b/apps/app/app/(landing)/page.tsx
new file mode 100644
index 00000000..c5f7e540
--- /dev/null
+++ b/apps/app/app/(landing)/page.tsx
@@ -0,0 +1,61 @@
+import { Button } from "@crm/ui/components/button";
+import Logo from "@crm/ui/components/logo";
+import Link from "next/link";
+import { AuthShader } from "@/components/auth-shader";
+
+export default function Home() {
+ return (
+ <main className="dark relative flex min-h-svh flex-col overflow-hidden bg-background text-foreground">
+ <AuthShader />
+
+ <header className="relative flex h-12 shrink-0 items-center gap-2 px-6 sm:px-10">
+ <Link href="/" aria-label="Homepage" className="flex">
+ <Logo className="size-5 shrink-0" />
+ </Link>
+
+ <div className="ml-auto">
+ <Button asChild variant="outline" size="sm">
+ <Link href="/sign-in">Sign in</Link>
+ </Button>
+ </div>
+ </header>
+
+ <div className="relative flex flex-1 items-center px-6 py-16 sm:px-10">
+ <div className="flex max-w-lg flex-col gap-8">
+ <div className="flex flex-col gap-4">
+ <p className="font-mono text-muted-foreground text-xs/4 uppercase">
+ CRM
+ </p>
+ <h1 className="max-w-[14ch] text-balance font-semibold text-5xl/14">
+ Every customer, one place.
+ </h1>
+ <p className="max-w-[46ch] text-pretty text-muted-foreground text-sm/6">
+ Your inbox and calendar become the record. A research agent works
+ out who everybody is, and what each account is worth.
+ </p>
+ </div>
+
+ <div className="flex gap-2">
+ <Button asChild>
+ <Link href="/sign-in">Get started</Link>
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ <footer className="relative px-6 py-8 sm:px-10">
+ <p className="font-mono text-muted-foreground text-xs/4">
+ Made with love by{" "}
+ <a
+ href="https://trycomp.ai"
+ target="_blank"
+ rel="noreferrer"
+ className="underline underline-offset-4 hover:text-foreground"
+ >
+ Comp AI
+ </a>
+ </p>
+ </footer>
+ </main>
+ );
+}
diff --git a/apps/app/app/(auth)/sign-in/google-sign-in.tsx b/apps/app/app/(landing)/sign-in/google-sign-in.tsx
similarity index 100%
rename from apps/app/app/(auth)/sign-in/google-sign-in.tsx
rename to apps/app/app/(landing)/sign-in/google-sign-in.tsx
diff --git a/apps/app/app/(auth)/sign-in/page.tsx b/apps/app/app/(landing)/sign-in/page.tsx
similarity index 100%
rename from apps/app/app/(auth)/sign-in/page.tsx
rename to apps/app/app/(landing)/sign-in/page.tsx
diff --git a/apps/app/app/(auth)/sign-in/sso-sign-in.tsx b/apps/app/app/(landing)/sign-in/sso-sign-in.tsx
similarity index 100%
rename from apps/app/app/(auth)/sign-in/sso-sign-in.tsx
rename to apps/app/app/(landing)/sign-in/sso-sign-in.tsx
diff --git a/apps/app/components/app-header.tsx b/apps/app/components/app-header.tsx
index 0a402240..318034f2 100644
--- a/apps/app/components/app-header.tsx
+++ b/apps/app/components/app-header.tsx
@@ -24,6 +24,7 @@ import { useTheme } from "next-themes";
import { toast } from "sonner";
import { useMobileNav } from "@/components/mobile-nav";
import { useTRPC } from "@/lib/trpc/client";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
type User = { name: string; email: string; image: string | null };
@@ -44,6 +45,7 @@ export function workspaceLabel(name: string | undefined): string {
export function AppHeader({ user }: { user: User }) {
const { setOpen: setMobileNavOpen } = useMobileNav();
const trpc = useTRPC();
+ const workspaceUrl = useWorkspaceUrl();
const workspace = useQuery(trpc.workspace.get.queryOptions());
const label = workspaceLabel(workspace.data?.name);
@@ -71,7 +73,7 @@ export function AppHeader({ user }: { user: User }) {
<Menu />
</Button>
<Link
- href="/"
+ href={workspaceUrl()}
aria-label="Homepage"
className="hidden size-8 items-center justify-center text-foreground md:flex"
>
diff --git a/apps/app/components/app-icon-rail.tsx b/apps/app/components/app-icon-rail.tsx
index 659ae1df..ba09f274 100644
--- a/apps/app/components/app-icon-rail.tsx
+++ b/apps/app/components/app-icon-rail.tsx
@@ -22,7 +22,9 @@ import {
import { cn } from "@crm/ui/lib/utils";
import Link from "next/link";
import { usePathname } from "next/navigation";
+import { useMemo } from "react";
import { useMobileNav } from "@/components/mobile-nav";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
type RailItem = {
title: string;
@@ -113,15 +115,21 @@ function MobileRailLink({
export function AppIconRail() {
const pathname = usePathname();
+ const workspaceUrl = useWorkspaceUrl();
const { open, setOpen } = useMobileNav();
+ const items = useMemo(
+ () => ITEMS.map((item) => ({ ...item, href: workspaceUrl(item.href) })),
+ [workspaceUrl],
+ );
+
return (
<>
<nav
aria-label="Primary"
className="hidden w-14 shrink-0 flex-col items-center gap-1 border-r py-3 md:flex [view-transition-name:app-rail]"
>
- {ITEMS.map((item) => (
+ {items.map((item) => (
<RailLink
key={item.href}
item={item}
@@ -136,7 +144,7 @@ export function AppIconRail() {
<SheetTitle>Navigation</SheetTitle>
</SheetHeader>
<nav aria-label="Primary" className="flex flex-1 flex-col gap-1 p-2">
- {ITEMS.map((item) => (
+ {items.map((item) => (
<MobileRailLink
key={item.href}
item={item}
diff --git a/apps/app/lib/onboarding.ts b/apps/app/lib/onboarding.ts
index e9b57f77..fd4c184c 100644
--- a/apps/app/lib/onboarding.ts
+++ b/apps/app/lib/onboarding.ts
@@ -34,15 +34,27 @@ async function read<T>(
}
}
-export async function readOnboardingGate(request: NextRequest): Promise<Gate> {
- const workspace = await read<{ onboarded?: boolean; canRename?: boolean }>(
- request,
- "workspace.get",
- );
+export type WorkspaceGate = { gate: Gate; slug: string | null };
+
+export async function readWorkspaceGate(
+ request: NextRequest,
+): Promise<WorkspaceGate> {
+ const workspace = await read<{
+ onboarded?: boolean;
+ canRename?: boolean;
+ slug?: string;
+ }>(request, "workspace.get");
+
+ const slug = workspace?.slug ? workspace.slug : null;
- if (typeof workspace?.onboarded !== "boolean") return "unknown";
+ if (typeof workspace?.onboarded !== "boolean") {
+ return { gate: "unknown", slug };
+ }
- return workspace.onboarded || !workspace.canRename ? "settled" : "required";
+ return {
+ gate: workspace.onboarded || !workspace.canRename ? "settled" : "required",
+ slug,
+ };
}
export async function readResearchGate(request: NextRequest): Promise<Gate> {
diff --git a/apps/app/lib/record-href.ts b/apps/app/lib/record-href.ts
index 1616f99e..01a1f95b 100644
--- a/apps/app/lib/record-href.ts
+++ b/apps/app/lib/record-href.ts
@@ -1,7 +1,12 @@
+import { workspaceUrl } from "@/lib/workspace-url";
+
export function recordHref(
+ slug: string,
list: "/companies" | "/contacts" | "/deals",
kind: "company" | "contact" | "deal",
id: string,
): string {
- return `${list}?${new URLSearchParams({ record: `${kind}:${id}` })}`;
+ const query = new URLSearchParams({ record: `${kind}:${id}` });
+
+ return `${workspaceUrl(slug, list)}?${query}`;
}
diff --git a/apps/app/lib/use-workspace-url.ts b/apps/app/lib/use-workspace-url.ts
new file mode 100644
index 00000000..384158dd
--- /dev/null
+++ b/apps/app/lib/use-workspace-url.ts
@@ -0,0 +1,17 @@
+"use client";
+
+import { useParams } from "next/navigation";
+import { useCallback } from "react";
+import { workspaceUrl } from "@/lib/workspace-url";
+
+export function useWorkspaceSlug(): string {
+ const { slug } = useParams<{ slug: string }>();
+
+ return slug;
+}
+
+export function useWorkspaceUrl(): (path?: string) => string {
+ const slug = useWorkspaceSlug();
+
+ return useCallback((path = "/") => workspaceUrl(slug, path), [slug]);
+}
diff --git a/apps/app/lib/workspace-url.ts b/apps/app/lib/workspace-url.ts
new file mode 100644
index 00000000..26f93a28
--- /dev/null
+++ b/apps/app/lib/workspace-url.ts
@@ -0,0 +1,5 @@
+export function workspaceUrl(slug: string, path = "/"): string {
+ const suffix = path === "/" ? "" : path.startsWith("/") ? path : `/${path}`;
+
+ return `/${slug}${suffix}`;
+}
diff --git a/apps/app/proxy.ts b/apps/app/proxy.ts
index 374f7fad..79dff2d8 100644
--- a/apps/app/proxy.ts
+++ b/apps/app/proxy.ts
@@ -4,21 +4,28 @@ import { type NextRequest, NextResponse } from "next/server";
import {
ONBOARDING_PATH,
RESEARCH_PATH,
- readOnboardingGate,
readResearchGate,
+ readWorkspaceGate,
} from "@/lib/onboarding";
+import { workspaceUrl } from "@/lib/workspace-url";
+
+const LANDING_PATH = "/";
const SIGN_IN_PATH = "/sign-in";
+const PUBLIC = [LANDING_PATH, SIGN_IN_PATH];
+
const UNGATED = [SIGN_IN_PATH, "/grant-access", "/eve"];
+const SECTIONS = ["/companies", "/contacts", "/deals", "/settings"];
+
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
if (
getSessionCookie(request, { cookiePrefix: AUTH_COOKIE_PREFIX }) === null
) {
- return pathname === SIGN_IN_PATH
+ return isPublic(pathname)
? NextResponse.next()
: NextResponse.redirect(new URL(SIGN_IN_PATH, request.nextUrl));
}
@@ -27,25 +34,47 @@ export async function proxy(request: NextRequest) {
// Both answers, every time, and concurrently — so the gate costs one round
// trip rather than two, and neither answer can be stale.
- const [onboarding, research] = await Promise.all([
- readOnboardingGate(request),
+ const [workspace, research] = await Promise.all([
+ readWorkspaceGate(request),
readResearchGate(request),
]);
- if (onboarding === "required") return sendTo(ONBOARDING_PATH, request);
+ if (workspace.gate === "required") return sendTo(ONBOARDING_PATH, request);
if (research === "required") return sendTo(RESEARCH_PATH, request);
- const settled = onboarding === "settled" && research === "settled";
+ const settled = workspace.gate === "settled" && research === "settled";
+
+ if (!settled || !workspace.slug) return NextResponse.next();
+
+ return sendTo(appPath(pathname, workspace.slug), request);
+}
+
+function appPath(pathname: string, slug: string): string {
+ if (pathname === LANDING_PATH || isSetup(pathname)) {
+ return workspaceUrl(slug);
+ }
+
+ if (SECTIONS.some((section) => isUnder(pathname, section))) {
+ return workspaceUrl(slug, pathname);
+ }
+
+ const [first, ...rest] = pathname.slice(1).split("/");
+
+ if (first === slug) return pathname;
+
+ return workspaceUrl(slug, rest.length ? `/${rest.join("/")}` : "/");
+}
- return settled && isSetup(pathname)
- ? NextResponse.redirect(new URL("/", request.nextUrl))
- : NextResponse.next();
+function isUnder(pathname: string, prefix: string): boolean {
+ return pathname === prefix || pathname.startsWith(`${prefix}/`);
+}
+
+function isPublic(pathname: string): boolean {
+ return PUBLIC.some((prefix) => isUnder(pathname, prefix));
}
function isUngated(pathname: string): boolean {
- return UNGATED.some(
- (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`),
- );
+ return UNGATED.some((prefix) => isUnder(pathname, prefix));
}
function isSetup(pathname: string): boolean {
@@ -53,9 +82,12 @@ function isSetup(pathname: string): boolean {
}
function sendTo(path: string, request: NextRequest): NextResponse {
- return request.nextUrl.pathname === path
- ? NextResponse.next()
- : NextResponse.redirect(new URL(path, request.nextUrl));
+ if (request.nextUrl.pathname === path) return NextResponse.next();
+
+ const url = new URL(path, request.nextUrl);
+ url.search = request.nextUrl.search;
+
+ return NextResponse.redirect(url);
}
export const config = {
diff --git a/apps/app/test/onboarding-gate.spec.ts b/apps/app/test/onboarding-gate.spec.ts
index 07320140..72f1b7d8 100644
--- a/apps/app/test/onboarding-gate.spec.ts
+++ b/apps/app/test/onboarding-gate.spec.ts
@@ -1,11 +1,13 @@
import { afterEach, describe, expect, it } from "bun:test";
import { AUTH_COOKIE_PREFIX } from "@crm/auth/cookies";
import { NextRequest } from "next/server";
-import { readOnboardingGate, readResearchGate } from "../lib/onboarding";
+import { readResearchGate, readWorkspaceGate } from "../lib/onboarding";
import { proxy } from "../proxy";
const SESSION_COOKIE = `${AUTH_COOKIE_PREFIX}.session_token=abc.def`;
+const SLUG = "comp-ai";
+
const realFetch = globalThis.fetch;
afterEach(() => {
@@ -28,9 +30,11 @@ function answerWith(body: unknown, status = 200) {
stub(async () => json(body, status));
}
-const workspace = (data: { onboarded: boolean; canRename: boolean }) => ({
- result: { data },
-});
+const workspace = (data: {
+ onboarded: boolean;
+ canRename: boolean;
+ slug?: string;
+}) => ({ result: { data: { slug: SLUG, ...data } } });
const researchKey = (configured: boolean) => ({
result: { data: { configured, hint: configured ? "••••9876" : null } },
@@ -41,17 +45,19 @@ function setup({
onboarded = true,
canRename = true,
configured = true,
+ slug = SLUG,
}: {
onboarded?: boolean;
canRename?: boolean;
configured?: boolean;
+ slug?: string;
} = {}) {
const calls = { workspace: 0, research: 0 };
stub(async (url) => {
if (url.includes("workspace.get")) {
calls.workspace += 1;
- return json(workspace({ onboarded, canRename }));
+ return json(workspace({ onboarded, canRename, slug }));
}
calls.research += 1;
@@ -73,40 +79,43 @@ function redirectedTo(response: Response): string | null {
return location ? new URL(location).pathname : null;
}
-describe("readOnboardingGate", () => {
+async function gateOf(pathname: string) {
+ return (await readWorkspaceGate(request(pathname, [SESSION_COOKIE]))).gate;
+}
+
+describe("readWorkspaceGate", () => {
it("reads the answer out of a plain tRPC envelope", async () => {
answerWith(workspace({ onboarded: false, canRename: true }));
- expect(await readOnboardingGate(request("/", [SESSION_COOKIE]))).toBe(
- "required",
- );
+ expect(await gateOf("/")).toBe("required");
});
it("settles for someone who could not answer the form anyway", async () => {
answerWith(workspace({ onboarded: false, canRename: false }));
- expect(await readOnboardingGate(request("/", [SESSION_COOKIE]))).toBe(
- "settled",
- );
+ expect(await gateOf("/")).toBe("settled");
+ });
+
+ it("carries the slug the app is served under", async () => {
+ answerWith(workspace({ onboarded: true, canRename: true }));
+
+ expect(await readWorkspaceGate(request("/", [SESSION_COOKIE]))).toEqual({
+ gate: "settled",
+ slug: SLUG,
+ });
});
it("is unknown rather than required when the API cannot be read", async () => {
answerWith({ error: { message: "UNAUTHORIZED" } }, 401);
- expect(await readOnboardingGate(request("/", [SESSION_COOKIE]))).toBe(
- "unknown",
- );
+ expect(await gateOf("/")).toBe("unknown");
stub(async () => {
throw new Error("connect ECONNREFUSED");
});
- expect(await readOnboardingGate(request("/", [SESSION_COOKIE]))).toBe(
- "unknown",
- );
+ expect(await gateOf("/")).toBe("unknown");
answerWith({ result: { data: { nothing: "useful" } } });
- expect(await readOnboardingGate(request("/", [SESSION_COOKIE]))).toBe(
- "unknown",
- );
+ expect(await gateOf("/")).toBe("unknown");
});
});
@@ -135,9 +144,13 @@ describe("readResearchGate", () => {
});
describe("proxy", () => {
- it("sends a stranger to sign in, and leaves them there", async () => {
- expect(redirectedTo(await proxy(request("/companies")))).toBe("/sign-in");
+ it("shows a stranger the landing page and nothing behind it", async () => {
+ expect(redirectedTo(await proxy(request("/")))).toBeNull();
expect(redirectedTo(await proxy(request("/sign-in")))).toBeNull();
+ expect(redirectedTo(await proxy(request(`/${SLUG}`)))).toBe("/sign-in");
+ expect(redirectedTo(await proxy(request(`/${SLUG}/companies`)))).toBe(
+ "/sign-in",
+ );
});
it("ignores a neighbour's cookie from the parent domain", async () => {
@@ -147,7 +160,9 @@ describe("proxy", () => {
expect(
redirectedTo(
await proxy(
- request("/companies", ["better-auth.session_token=someone.else"]),
+ request(`/${SLUG}/companies`, [
+ "better-auth.session_token=someone.else",
+ ]),
),
),
).toBe("/sign-in");
@@ -157,7 +172,9 @@ describe("proxy", () => {
setup({ onboarded: false });
expect(
- redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),
+ redirectedTo(
+ await proxy(request(`/${SLUG}/companies`, [SESSION_COOKIE])),
+ ),
).toBe("/onboarding");
});
@@ -172,12 +189,12 @@ describe("proxy", () => {
it("asks again on every request, and remembers nothing", async () => {
const calls = setup();
- const first = await proxy(request("/companies", [SESSION_COOKIE]));
+ const first = await proxy(request(`/${SLUG}/companies`, [SESSION_COOKIE]));
expect([...first.cookies.getAll()]).toHaveLength(0);
expect(calls).toEqual({ workspace: 1, research: 1 });
- await proxy(request("/companies", [SESSION_COOKIE]));
+ await proxy(request(`/${SLUG}/companies`, [SESSION_COOKIE]));
expect(calls).toEqual({ workspace: 2, research: 2 });
});
@@ -185,29 +202,33 @@ describe("proxy", () => {
it("notices when the answer changes underneath it", async () => {
setup();
expect(
- redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),
+ redirectedTo(
+ await proxy(request(`/${SLUG}/companies`, [SESSION_COOKIE])),
+ ),
).toBeNull();
// A reset database, a removed key: the browser is carrying nothing that
// could keep saying the gate was satisfied.
setup({ onboarded: false });
expect(
- redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),
+ redirectedTo(
+ await proxy(request(`/${SLUG}/companies`, [SESSION_COOKIE])),
+ ),
).toBe("/onboarding");
});
- it("takes a settled rep off both setup pages", async () => {
+ it("takes a settled rep off both setup pages and into the workspace", async () => {
setup();
expect(
redirectedTo(await proxy(request("/onboarding", [SESSION_COOKIE]))),
- ).toBe("/");
+ ).toBe(`/${SLUG}`);
expect(
redirectedTo(
await proxy(request("/onboarding/research", [SESSION_COOKIE])),
),
- ).toBe("/");
+ ).toBe(`/${SLUG}`);
});
it("never fights /grant-access, which would ping-pong forever", async () => {
@@ -231,18 +252,72 @@ describe("proxy", () => {
throw new Error("connect ECONNREFUSED");
});
- const response = await proxy(request("/companies", [SESSION_COOKIE]));
+ const response = await proxy(
+ request(`/${SLUG}/companies`, [SESSION_COOKIE]),
+ );
expect(redirectedTo(response)).toBeNull();
});
});
+describe("the slug the app is served under", () => {
+ it("sends a signed-in rep off the landing page and into the workspace", async () => {
+ setup();
+
+ expect(redirectedTo(await proxy(request("/", [SESSION_COOKIE])))).toBe(
+ `/${SLUG}`,
+ );
+ });
+
+ it("puts the slug on a link that predates it, keeping the query", async () => {
+ setup();
+
+ const response = await proxy(
+ request("/companies?record=contact:abc", [SESSION_COOKIE]),
+ );
+
+ expect(response.headers.get("location")).toBe(
+ `http://localhost:3000/${SLUG}/companies?record=contact:abc`,
+ );
+ });
+
+ it("moves a stale slug onto the current one, keeping the rest", async () => {
+ setup();
+
+ expect(
+ redirectedTo(
+ await proxy(request("/old-name/settings/members", [SESSION_COOKIE])),
+ ),
+ ).toBe(`/${SLUG}/settings/members`);
+ });
+
+ it("leaves a request that already carries the slug alone", async () => {
+ setup();
+
+ expect(
+ redirectedTo(
+ await proxy(request(`/${SLUG}/settings/sso`, [SESSION_COOKIE])),
+ ),
+ ).toBeNull();
+ });
+
+ it("rewrites nothing when the API could not say what the slug is", async () => {
+ setup({ slug: "" });
+
+ expect(
+ redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),
+ ).toBeNull();
+ });
+});
+
describe("the research key gate", () => {
it("sends an onboarded rep with no key to the key form", async () => {
setup({ configured: false });
expect(
- redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),
+ redirectedTo(
+ await proxy(request(`/${SLUG}/companies`, [SESSION_COOKIE])),
+ ),
).toBe("/onboarding/research");
});
@@ -260,7 +335,9 @@ describe("the research key gate", () => {
setup({ onboarded: false, configured: false });
expect(
- redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),
+ redirectedTo(
+ await proxy(request(`/${SLUG}/companies`, [SESSION_COOKIE])),
+ ),
).toBe("/onboarding");
});
diff --git a/docs/api.md b/docs/api.md
index 7a9a78a8..16870831 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -167,6 +167,10 @@ called, who works here, and what do we sell — and for nothing else.
`requireGoogleAccess()` redirects to `/grant-access`, so gating it would
ping-pong against the onboarding redirect for anyone who signed in without
both scopes.
+ - **`/` and `/sign-in` are the only two paths a stranger may read**, and they
+ are a different list from the ungated one. `/` is the landing page in
+ `app/(landing)` — the marketing front of a clone, served to somebody who has
+ no account yet. Everything else still goes to `/sign-in`.
- **An unreachable API fails open.** Each read returns `unknown` on a
non-200, a timeout or a parse failure, and an unknown gate lets the request
through. The alternative is an install that cannot reach its own API
@@ -211,6 +215,53 @@ called, who works here, and what do we sell — and for nothing else.
`components/app-header.tsx` tests the name rather than comparing it to the
default, because a workspace genuinely called `Acme CRM` has the same
problem and no comparison to `DEFAULT_WORKSPACE_NAME` would catch it.
+- **The name is also the URL, and `workspaceSlug` is the one thing that says
+ so.** The CRM is served under the workspace's slug — `/comp-ai/companies`,
+ never `/companies` — which is what leaves `/` free for the landing page in
+ `app/(landing)`. It is a **cosmetic** prefix and it is emphatically not the
+ tenancy this file spends its first paragraphs refusing: no read takes it, no
+ record carries it, and the app resolves every query through `WORKSPACE_ID`
+ exactly as before. It exists so a rep reads their own company's name in the
+ address bar instead of somebody's route table.
+ - **The slug is the plugin's column, derived from the name.** Better Auth's
+ organization plugin owns `organization.slug` and enforces its uniqueness, so
+ that column is the answer and `workspace.get` returns it verbatim. What is
+ derived is what gets *written*: `workspaceSlug(name)` in
+ [`@crm/db/workspace`](../packages/db/src/workspace.ts) is the single rule,
+ applied by `WorkspaceService.update` on a rename and at create. Deriving on
+ *read* instead was the tempting shortcut and it is wrong the moment anything
+ else — the plugin, a script, a future admin UI — writes the column: two
+ answers to one question, and the URL a rep bookmarked disagreeing with the
+ row.
+ - **`ensureWorkspaceMembership` reconciles it**, in the same
+ `databaseHooks.session.create.before` hook that already guarantees the
+ workspace row and the caller's membership exist. That is what backfills an
+ install created before the slug meant anything — its row says `workspace`
+ and its name says `Comp AI` — without a migration that would restate the
+ slug rule in SQL. It writes only when the two disagree, and it degrades like
+ everything else in that hook.
+ - **A slug never collides with a route the app serves.** `RESERVED_SLUGS`
+ holds them — `sign-in`, `onboarding`, `settings`, `companies`, and the rest
+ — and a name that slugifies onto one gets `-crm` appended. Without it a
+ company called Settings has a CRM it cannot reach, and a static route in
+ `(landing)` wins over `[slug]` silently.
+ - **The proxy puts the slug on, and it is the only thing that does.** A path
+ with no slug is a link that predates the move (`/companies`); a path with
+ the wrong one is a stale bookmark from before a rename. Both are the same
+ request with the wrong front on it, so both are redirected onto the current
+ slug with the query string intact, rather than 404ing at somebody who did
+ nothing wrong. `app/(app)/[slug]/layout.tsx` is the backstop and
+ `notFound()`s on a mismatch the proxy could not read the slug to correct.
+ - **A signed-in rep does not see the landing page.** `/` resolves to their
+ workspace, which is what keeps every `callbackURL` and post-onboarding
+ `redirect("/")` in the codebase correct without any of them learning what a
+ slug is. There is one place to change that if the landing page should ever
+ outrank the CRM: `appPath` in `proxy.ts`.
+ - **Renaming moves the URL, so the form moves with it.** `workspace.update`
+ returns the new slug and `workspace-form.tsx` replaces the current location
+ onto it. Without that, saving a rename leaves the browser sitting on a slug
+ that no longer resolves, and the next navigation 404s at the person who just
+ renamed their own company.
- **The website is the field with a consequence.** Saving it queues the agent's
`workspace-profile` task, and what comes back is read into the opening context
of every session the agent runs — see
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index 19f9426e..4fed1a17 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -10,7 +10,6 @@ export {
isWorkspaceRole,
WORKSPACE_ID,
WORKSPACE_ROLES,
- WORKSPACE_SLUG,
type WorkspaceRole,
} from "./organization";
export {
diff --git a/packages/auth/src/organization.ts b/packages/auth/src/organization.ts
index 18ab8e7b..35397ec5 100644
--- a/packages/auth/src/organization.ts
+++ b/packages/auth/src/organization.ts
@@ -1,10 +1,8 @@
import { db } from "@crm/db";
-import { WORKSPACE_ID } from "@crm/db/workspace";
+import { WORKSPACE_ID, workspaceSlug } from "@crm/db/workspace";
export { WORKSPACE_ID };
-export const WORKSPACE_SLUG = "workspace";
-
export const DEFAULT_WORKSPACE_NAME = "CRM";
export const WORKSPACE_ROLES = ["owner", "admin", "member"] as const;
@@ -37,13 +35,22 @@ export async function ensureWorkspaceMembership(
create: {
id: WORKSPACE_ID,
name: DEFAULT_WORKSPACE_NAME,
- slug: WORKSPACE_SLUG,
+ slug: workspaceSlug(DEFAULT_WORKSPACE_NAME),
createdAt: new Date(),
},
update: {},
- select: { id: true },
+ select: { id: true, name: true, slug: true },
});
+ const slug = workspaceSlug(workspace.name);
+
+ if (workspace.slug !== slug) {
+ await tx.organization.update({
+ where: { id: workspace.id },
+ data: { slug },
+ });
+ }
+
const enrolled = await tx.member.count({
where: { organizationId: workspace.id },
});
diff --git a/packages/auth/test/organization.integration.spec.ts b/packages/auth/test/organization.integration.spec.ts
index 3d685f56..7b568949 100644
--- a/packages/auth/test/organization.integration.spec.ts
+++ b/packages/auth/test/organization.integration.spec.ts
@@ -14,7 +14,12 @@ const suffix = process.env.TEST_RUN_ID ?? "organization-spec";
const emailOf = (label: string) => `${label}.${suffix}@example.test`;
type Snapshot = {
- organization: { name: string; slug: string; website: string | null } | null;
+ organization: {
+ name: string;
+ slug: string;
+ website: string | null;
+ metadata: string | null;
+ } | null;
members: { id: string; userId: string; role: string; createdAt: Date }[];
};
@@ -57,7 +62,7 @@ const clear = async () => {
beforeAll(async () => {
const organization = await db.organization.findUnique({
where: { id: WORKSPACE_ID },
- select: { name: true, slug: true, website: true },
+ select: { name: true, slug: true, website: true, metadata: true },
});
snapshot = {
diff --git a/packages/db/src/workspace.ts b/packages/db/src/workspace.ts
index 8d35a736..c7053329 100644
--- a/packages/db/src/workspace.ts
+++ b/packages/db/src/workspace.ts
@@ -3,6 +3,37 @@ import type { WorkspaceProfileSections } from "./json";
export const WORKSPACE_ID = "workspace";
+export const DEFAULT_WORKSPACE_SLUG = "workspace";
+
+export const MAX_SLUG = 48;
+
+export const RESERVED_SLUGS: readonly string[] = [
+ "_next",
+ "api",
+ "companies",
+ "contacts",
+ "deals",
+ "eve",
+ "grant-access",
+ "onboarding",
+ "settings",
+ "sign-in",
+];
+
+export function workspaceSlug(name: string): string {
+ const base = name
+ .normalize("NFKD")
+ .replace(/\p{M}/gu, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .slice(0, MAX_SLUG)
+ .replace(/^-+|-+$/g, "");
+
+ if (!base) return DEFAULT_WORKSPACE_SLUG;
+
+ return RESERVED_SLUGS.includes(base) ? `${base}-crm` : base;
+}
+
export const MAX_NARRATIVE = 320;
export const MAX_LINE = 140;
diff --git a/packages/db/test/workspace-slug.spec.ts b/packages/db/test/workspace-slug.spec.ts
new file mode 100644
index 00000000..941e1040
--- /dev/null
+++ b/packages/db/test/workspace-slug.spec.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "bun:test";
+import {
+ DEFAULT_WORKSPACE_SLUG,
+ MAX_SLUG,
+ RESERVED_SLUGS,
+ workspaceSlug,
+} from "../src/workspace";
+
+describe("workspaceSlug", () => {
+ it("is the company name a rep can read in the address bar", () => {
+ expect(workspaceSlug("Comp AI")).toBe("comp-ai");
+ expect(workspaceSlug("Acme")).toBe("acme");
+ expect(workspaceSlug("Northwind Savings Group")).toBe(
+ "northwind-savings-group",
+ );
+ });
+
+ it("keeps the punctuation out of the URL rather than escaping it", () => {
+ expect(workspaceSlug(" Fernhill & Co. ")).toBe("fernhill-co");
+ expect(workspaceSlug("Reply.io")).toBe("reply-io");
+ expect(workspaceSlug("Zoë Söderberg AB")).toBe("zoe-soderberg-ab");
+ });
+
+ it("never collides with a route the app already serves", () => {
+ for (const reserved of RESERVED_SLUGS) {
+ expect(workspaceSlug(reserved)).not.toBe(reserved);
+ }
+
+ expect(workspaceSlug("Settings")).toBe("settings-crm");
+ expect(workspaceSlug("Sign In")).toBe("sign-in-crm");
+ });
+
+ it("falls back rather than producing an empty segment", () => {
+ expect(workspaceSlug("")).toBe(DEFAULT_WORKSPACE_SLUG);
+ expect(workspaceSlug(" ")).toBe(DEFAULT_WORKSPACE_SLUG);
+ expect(workspaceSlug("——")).toBe(DEFAULT_WORKSPACE_SLUG);
+ expect(workspaceSlug("株式会社")).toBe(DEFAULT_WORKSPACE_SLUG);
+ });
+
+ it("is bounded, and never ends on the dash the cut left behind", () => {
+ const slug = workspaceSlug(`${"a".repeat(MAX_SLUG)} Holdings`);
+
+ expect(slug).toHaveLength(MAX_SLUG);
+ expect(slug.endsWith("-")).toBe(false);
+ });
+
+ it("gives one name one answer, whoever asks", () => {
+ expect(workspaceSlug("Comp AI")).toBe(workspaceSlug("comp ai"));
+ });
+});