Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
feat(organisation): unify project workspace and onboarding (#1285)
Aman Agarwal532be8b42740
diff --git a/.claude/commands/project-hierarchy-check.md b/.claude/commands/project-hierarchy-check.mdindex 6b353d67..f2b1bbb1 100644--- a/.claude/commands/project-hierarchy-check.md+++ b/.claude/commands/project-hierarchy-check.md@@ -4,15 +4,19 @@ Use this command before changing organisation, project, or database config behav1. Confirm this is shared CE behavior. Enterprise-only implementation must stay in `openlit-enterprise/src/client/src/ee/`.2. Confirm any enterprise extension point has only an OSS-safe no-op fallback in CE.-3. Confirm CE strings go in `src/client/src/constants/messages/en.ts`; enterprise-only strings stay in the private EE message file.-4. Confirm the code follows `Organisation -> Project -> Database configuration`.-5. Check that database config reads and writes are scoped by current project.-6. Check that project list and switch routes validate organisation membership.-7. Check that switching organisation refreshes projects and database config state.-8. Add or update tests for membership denial, selected project, cross-project denial, and invalid JSON.-9. Run:+3. Confirm shared imports use neutral extension paths, not `@/ee/**`.+4. Confirm CE fallback hooks do not expose RBAC permission literals or enterprise entitlement maps.+5. Confirm CE strings go in `src/client/src/constants/messages/en.ts`; enterprise-only strings stay in the private EE message file.+6. Confirm the code follows `Organisation -> Project -> Database configuration`.+7. Check that database config reads and writes are scoped by current project.+8. Check that project list and switch routes validate organisation membership.+9. Check that switching organisation refreshes projects and database config state.+10. Add or update tests for membership denial, selected project, cross-project denial, and invalid JSON.+11. Run:```bashcd src/clientnpm test -- --runInBand src/__tests__/lib/db-config.test.ts src/__tests__/lib/organisation.test.ts src/__tests__/app/api/organisation/projects-route.test.ts+rg -n "@/ee/" src+rg -n '"[a-z_]+:[a-z_]+"' src```diff --git a/.claude/commands/security-validation.md b/.claude/commands/security-validation.mdindex cfc600f4..02821264 100644--- a/.claude/commands/security-validation.md+++ b/.claude/commands/security-validation.md@@ -7,11 +7,14 @@ Use this command before handing off security-sensitive OpenLIT changes.3. Confirm malformed JSON returns `400`, not `500`.4. Confirm secrets, tokens, cookies, passwords, API keys, and license keys are redacted from logs and audit metadata.5. Confirm user-facing strings come from `src/client/src/constants/messages/en.ts`.-6. Run:+6. Confirm CE/shared files do not import `@/ee/**` and do not contain RBAC permission literals.+7. Run:```bashcd src/clientnpm test -- --runInBandnpm run lintnpx prisma validate --schema prisma/schema.prisma+rg -n "@/ee/" src+rg -n '"[a-z_]+:[a-z_]+"' src```diff --git a/.cursor-rules/README.md b/.cursor-rules/README.mdindex 4f09b165..df012962 100644--- a/.cursor-rules/README.md+++ b/.cursor-rules/README.md@@ -34,6 +34,8 @@ This directory contains organized cursor rules for different aspects of the Open- Compact operational UI guidance- CE/EE boundary expectations- OSS-safe fallback guidance+- Neutral extension hook guidance+- No enterprise permission literals or `@/ee/**` imports in CE- Project hierarchy UI expectations- Message key requirements@@ -49,6 +51,8 @@ This directory contains organized cursor rules for different aspects of the Open- Server-side authorization requirements- Invalid JSON handling- OSS-safe extension fallback requirements+- Neutral shared import requirements+- CE leakage scans for `@/ee/**` imports and RBAC permission literals- Secret redaction requirements- Project-scoped DB config test expectationsdiff --git a/.cursor-rules/frontend.md b/.cursor-rules/frontend.mdindex 802ac06d..f7bc2914 100644--- a/.cursor-rules/frontend.md+++ b/.cursor-rules/frontend.md@@ -22,8 +22,12 @@ Use these rules for OpenLIT client UI work in `src/client/src`.## Enterprise Boundary- Do not add enterprise implementation to CE.+- Common/shared behavior belongs in CE first, then should be synced into `openlit-enterprise`.- CE may include OSS-safe no-op extension fallbacks used by shared code.+- CE fallbacks must stay neutral: no RBAC permission literals, no entitlement feature maps, no paid-plan decisions, and no `@/ee/**` imports.+- Shared UI should import neutral extension points such as `@/components/rbac/feature-access`, `@/components/rbac/otter-page-access`, and `@/components/enterprise-feature-access-provider`.- Enterprise-only UI, providers, stores, selectors, types, and feature pages belong under `src/client/src/ee/` in `openlit-enterprise`.+- RBAC UI must stay out of CE and live under `openlit-enterprise/src/client/src/ee/**`; enterprise `app/**` pages should be thin wrappers only.## Project Hierarchy UI@@ -38,3 +42,4 @@ Use these rules for OpenLIT client UI work in `src/client/src`.- [ ] Text uses CE `messages/en.ts`, with no enterprise-only copy added to CE.- [ ] Project-scoped UI refreshes after organisation or project changes.- [ ] Loading, empty, disabled, and error states are covered.+- [ ] CE has no `@/ee/**` imports and no RBAC permission literals.diff --git a/.cursor-rules/security-testing.md b/.cursor-rules/security-testing.mdindex 3c6f6d20..b746c06e 100644--- a/.cursor-rules/security-testing.md+++ b/.cursor-rules/security-testing.md@@ -9,8 +9,10 @@ Use these rules for API routes, auth checks, project hierarchy, billing, licensi- Server routes must enforce authorization. UI checks are not authorization.- Project routes must validate organisation membership.- Enterprise routes in the private repo must enforce entitlement or billing-admin checks on the server.+- RBAC, audit, billing, licensing, seats, and entitlement route implementations must stay out of CE and live under `openlit-enterprise/src/client/src/ee/**`; enterprise `app/api/**` files should be thin Next.js wrappers only.- Database config selection must be scoped to the current project.- CE must not contain enterprise audit, billing, licensing, or entitlement implementation beyond OSS-safe contracts and disabled/no-op fallbacks.+- CE must not contain RBAC permission literals such as `dashboard:read`; shared route wrappers should accept neutral access keys such as `dashboard.read`.## Input Handling@@ -28,8 +30,10 @@ Use these rules for API routes, auth checks, project hierarchy, billing, licensi## Extension Points- Shared code may import stable extension hooks only when CE provides an OSS-safe no-op fallback.+- Common/shared behavior belongs in CE first, then should be synced into `openlit-enterprise`.- Enterprise implementations for those hooks must live under `src/client/src/ee/**` in `openlit-enterprise`.- Keep tests covering the CE fallback behavior when a shared hook is added.+- Use neutral import paths in shared files. Do not import `@/ee/**` outside `src/client/src/ee/**` and EE-only tests.## Tests@@ -43,4 +47,8 @@ cd src/clientnpm test -- --runInBandnpm run lintnpx prisma validate --schema prisma/schema.prisma+rg -n "@/ee/" src+rg -n '"[a-z_]+:[a-z_]+"' src```++Review colon-string matches manually. CSS variants, cache keys, and encrypted-value prefixes are acceptable; RBAC permission literals are not.diff --git a/.cursorrules b/.cursorrulesindex f5a7dbcf..ca6ec3a8 100644--- a/.cursorrules+++ b/.cursorrules@@ -14,13 +14,13 @@ For all documentation work including MDX files, guides, and API documentation.For OpenLIT client UI work.- **File**: `.cursor-rules/frontend.md`- **Applies to**: `src/client/src/**/*.tsx`, settings pages, telemetry-style pages, stores, selectors, helpers, and OSS-safe extension fallbacks-- **Purpose**: Keeps light/dark styling, compact page layout, project hierarchy UI, CE message usage, and CE/EE boundary placement consistent+- **Purpose**: Keeps light/dark styling, compact page layout, project hierarchy UI, CE message usage, neutral extension hooks, and CE/EE boundary placement consistent### Security And Testing RulesFor API routes, project hierarchy, auth, audit, billing, licensing, and tests.- **File**: `.cursor-rules/security-testing.md`- **Applies to**: `src/client/src/app/api/**`, `src/client/src/lib/**`, `src/client/src/ee/**`, `src/client/src/__tests__/**`-- **Purpose**: Ensures server-side authorization, invalid JSON handling, project scoping, OSS-safe fallback boundaries, redaction, and validation coverage+- **Purpose**: Ensures server-side authorization, invalid JSON handling, project scoping, OSS-safe fallback boundaries, no enterprise leakage into CE, redaction, and validation coverage## Usagediff --git a/AGENTS.md b/AGENTS.mdindex c7a80cc3..a68289ab 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -4,12 +4,18 @@- This repository is the open-source CE/OSS codebase.- Do not add enterprise implementation here.-- CE may contain shared contracts, empty feature lists, disabled feature placeholders, upgrade-required responses, and OSS-safe no-op extension fallbacks.+- CE may contain shared contracts, neutral extension hook types, empty feature lists, disabled feature placeholders, upgrade-required responses, and OSS-safe no-op extension fallbacks.+- CE must not contain enterprise permission names, RBAC policy maps, entitlement feature maps, paid-plan branching, enterprise imports, or private implementation details.- Enterprise implementation belongs in `openlit-enterprise/src/client/src/ee/`.+- RBAC, audit log, billing, licensing, seats, entitlements, enterprise stores/selectors, enterprise route handlers, and enterprise UI must stay out of CE and live under `openlit-enterprise/src/client/src/ee/**`.+- Common/shared behavior must be implemented here in CE first, then synced into `openlit-enterprise`; enterprise `app/**` route/page files should be thin wrappers only when they need Next.js filesystem routing.## Extension Points- Shared code may import a stable extension hook only when CE provides a no-op fallback.+- Shared imports must use neutral paths such as `@/lib/access/route-access`, `@/components/rbac/feature-access`, or `@/store/enterprise`. Enterprise implementations are selected by the enterprise repo's path aliases or thin wrappers.+- Never import `@/ee/**` from CE or from shared/common files. `@/ee/**` imports are allowed only inside `src/client/src/ee/**` and EE-only tests.+- CE fallback APIs should expose feature-agnostic keys such as `dashboard.read`, not permission literals such as `dashboard:read`.- Do not import private enterprise modules from CE.- Keep CE messages in `src/client/src/constants/messages/en.ts`; enterprise-only messages belong in `src/client/src/ee/constants/messages/en.ts` in the private repo.@@ -23,3 +29,11 @@- Add tests for changed security boundaries.- Run focused tests and `npm run lint` from `src/client` before handoff.+- Before handoff, scan CE for accidental enterprise leakage:++```bash+rg -n "@/ee/" src/client/src+rg -n '"[a-z_]+:[a-z_]+"' src/client/src+```++The second scan may find non-RBAC strings such as CSS variants, cache keys, or encrypted-value prefixes. Review every match and keep RBAC permission literals out of CE.diff --git a/CLAUDE.md b/CLAUDE.mdindex 05746ec1..793f91a7 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4,9 +4,14 @@- This repository is the open-source CE/OSS codebase.- Do not add enterprise implementation files here.-- CE may contain shared contracts, feature IDs, empty feature lists, disabled feature placeholders, upgrade-required responses, and OSS-safe no-op extension fallbacks.+- CE may contain shared contracts, neutral extension hook types, empty feature lists, disabled feature placeholders, upgrade-required responses, and OSS-safe no-op extension fallbacks.+- CE must not contain enterprise permission names, RBAC policy maps, entitlement feature maps, paid-plan branching, enterprise imports, or private implementation details.- Enterprise-only implementation belongs in the private `openlit-enterprise` repository under `src/client/src/ee/`.+- RBAC, audit log, billing, licensing, seats, entitlements, enterprise stores/selectors, enterprise route handlers, and enterprise UI must stay out of CE and live under `openlit-enterprise/src/client/src/ee/**`.+- Common/shared behavior must be implemented here in CE first, then synced into `openlit-enterprise`; enterprise `app/**` route/page files should be thin wrappers only when they need Next.js filesystem routing.- If shared code needs an enterprise extension point, add a stable shared import with a CE no-op fallback here, then let `openlit-enterprise` override it from `src/client/src/ee/**`.+- Shared imports must use neutral paths such as `@/lib/access/route-access`, `@/components/rbac/feature-access`, `@/components/enterprise-feature-access-provider`, or `@/store/enterprise`; never import `@/ee/**` from CE or shared/common files.+- CE fallback APIs should expose feature-agnostic keys such as `dashboard.read`, not permission literals such as `dashboard:read`. The enterprise repo maps neutral keys to actual permissions under `src/client/src/ee/**`.- Do not add enterprise-only libraries, stores, selectors, middleware behavior, feature rules, billing logic, license logic, audit implementation, or UI here.## Project Hierarchy@@ -44,8 +49,12 @@ cd src/clientnpm test -- --runInBandnpm run lintnpx prisma validate --schema prisma/schema.prisma+rg -n "@/ee/" src+rg -n '"[a-z_]+:[a-z_]+"' src```+Review the colon-string scan manually. CSS variants, cache keys, and encrypted-value prefixes are fine; RBAC permission literals are not.+## Security Rules- UI feature checks are presentation only. Server routes must enforce authorization.diff --git a/docs/docs.json b/docs/docs.jsonindex ab2be952..c93087a4 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -56,7 +56,15 @@},"latest/openlit/configuration","latest/openlit/oauth",- "latest/openlit/organisation"+ {+ "group": "Organisation",+ "icon": "building",+ "pages": [+ "latest/openlit/organisation/overview",+ "latest/openlit/organisation/projects",+ "latest/openlit/organisation/database-config"+ ]+ }]},{@@ -441,4 +449,4 @@"contextual": {"options": ["copy", "chatgpt", "claude"]}-}\ No newline at end of file+}diff --git a/docs/latest/openlit/organisation/database-config.mdx b/docs/latest/openlit/organisation/database-config.mdxnew file mode 100644index 00000000..3ffd27b8--- /dev/null+++ b/docs/latest/openlit/organisation/database-config.mdx@@ -0,0 +1,39 @@+---+title: 'Database Config'+description: 'Add and manage ClickHouse database configurations for an OpenLIT project'+icon: 'database'+---++Database configurations connect OpenLIT to ClickHouse. They are scoped to the active project, so each project can use its own database connection.++## Add a database configuration++<Steps>+ <Step title="Open Organisation">+ Select **Organisation** from the sidebar.+ </Step>+ <Step title="Open a project">+ Choose the project that should own the database configuration.+ </Step>+ <Step title="Add config">+ Click **Add database config** and enter the ClickHouse connection details.+ </Step>+ <Step title="Test and save">+ Test the connection, then save the configuration.+ </Step>+ <Step title="Select config">+ Select the database configuration from the project page or the top navigation selector.+ </Step>+</Steps>++## Selection behavior++The active database configuration is scoped to the current user and project. Switching projects updates the available database configurations. If a project does not have a database configuration, OpenLIT guides you through onboarding before showing data pages.++## Multiple databases++A project can have multiple database configurations. Use multiple configurations when you need to switch between environments or ClickHouse clusters without changing the organisation.++<Card title="Multiple database guide" href="/latest/openlit/developer-resources/multiple-db" icon="database">+ Learn more about using multiple ClickHouse database configurations in OpenLIT.+</Card>diff --git a/docs/latest/openlit/organisation/overview.mdx b/docs/latest/openlit/organisation/overview.mdxnew file mode 100644index 00000000..fc7e76d7--- /dev/null+++ b/docs/latest/openlit/organisation/overview.mdx@@ -0,0 +1,40 @@+---+title: 'Organisation Overview'+description: 'Understand how organisations, projects, and database configurations fit together in OpenLIT'+icon: 'building'+---++Organisations in OpenLIT are shared workspaces for teams and environments. An organisation contains projects, and each project contains one or more ClickHouse database configurations.++```text+Organisation+ Project+ Database configuration+```++Use organisations for workspace and membership boundaries. Use projects when you need separate database boundaries inside the same organisation, such as production, staging, customer-specific environments, or different teams.++## What belongs to an organisation++- Organisation identity, such as the workspace name.+- Members and pending invitations.+- Projects owned by the organisation.+- Billing and licensing state where applicable.++Every organisation has a default project. Existing installations are mapped to a default project so existing database configurations continue to work after upgrading.++## Common tasks++<CardGroup cols={2}>+ <Card title="Manage projects" href="/latest/openlit/organisation/projects" icon="folder">+ Create projects, switch project context, and review project-level structure.+ </Card>+ <Card title="Configure databases" href="/latest/openlit/organisation/database-config" icon="database">+ Add, select, and update ClickHouse database configurations inside a project.+ </Card>+</CardGroup>++## Workspace switching++If you belong to multiple organisations, use the organisation selector in the top navigation to change the active workspace. Project and database configuration selectors update based on the selected organisation.+diff --git a/docs/latest/openlit/organisation/projects.mdx b/docs/latest/openlit/organisation/projects.mdxnew file mode 100644index 00000000..edc59fc5--- /dev/null+++ b/docs/latest/openlit/organisation/projects.mdx@@ -0,0 +1,42 @@+---+title: 'Projects'+description: 'Create and manage project boundaries inside an OpenLIT organisation'+icon: 'folder'+---++Projects group database configurations and resources inside an organisation. They are useful when one organisation needs multiple isolated environments without creating separate workspaces.++## When to create a project++Create a project for:++- Production, staging, and development environments.+- Separate teams that share the same organisation.+- Customer-specific deployments.+- Workloads that should use different ClickHouse database configurations.++## Create a project++<Steps>+ <Step title="Open Organisation">+ Select **Organisation** from the sidebar.+ </Step>+ <Step title="Review existing projects">+ Use the projects list to see the projects already available in the organisation.+ </Step>+ <Step title="Create project">+ Click **Create project**, enter a project name, and submit the form.+ </Step>+ <Step title="Select project">+ Use the project selector in the top navigation to make the project active.+ </Step>+</Steps>++## Project details++Project details show the project name, status, and database configurations attached to that project. Open a project from the Organisation page to review or update its configuration.++## Member access++Project access controls which organisation members can use a project. Existing organisation members are assigned to existing projects during migration so current installations continue to work. New members can be invited to the organisation first and then granted access to specific projects as needed.+diff --git a/src/client/prisma/migrations/20260617000000_db_config_project_cascade/migration.sql b/src/client/prisma/migrations/20260617000000_db_config_project_cascade/migration.sqlnew file mode 100644index 00000000..7bd61ed5--- /dev/null+++ b/src/client/prisma/migrations/20260617000000_db_config_project_cascade/migration.sql@@ -0,0 +1,102 @@+PRAGMA defer_foreign_keys=ON;+PRAGMA foreign_keys=OFF;++CREATE TABLE "new_databaseconfig" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "name" TEXT NOT NULL,+ "environment" TEXT NOT NULL DEFAULT 'production',+ "username" TEXT NOT NULL DEFAULT 'admin',+ "password" TEXT,+ "host" TEXT NOT NULL DEFAULT '127.0.0.1',+ "port" TEXT NOT NULL DEFAULT '8123',+ "database" TEXT NOT NULL DEFAULT 'openlit',+ "query" TEXT,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" DATETIME NOT NULL,+ "user_id" TEXT NOT NULL,+ "project_id" TEXT,+ CONSTRAINT "databaseconfig_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "databaseconfig_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects" ("id") ON DELETE CASCADE ON UPDATE CASCADE+);++INSERT INTO "new_databaseconfig" ("createdAt", "database", "environment", "host", "id", "name", "password", "port", "project_id", "query", "updatedAt", "user_id", "username")+SELECT "createdAt", "database", "environment", "host", "id", "name", "password", "port", "project_id", "query", "updatedAt", "user_id", "username"+FROM "databaseconfig";++DROP TABLE "databaseconfig";+ALTER TABLE "new_databaseconfig" RENAME TO "databaseconfig";++CREATE UNIQUE INDEX "databaseconfig_name_project_id_key" ON "databaseconfig"("name", "project_id");++CREATE TABLE "new_databaseconfiguser" (+ "databaseConfigId" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "isCurrent" BOOLEAN NOT NULL DEFAULT false,+ "canEdit" BOOLEAN NOT NULL DEFAULT false,+ "canShare" BOOLEAN NOT NULL DEFAULT false,+ "canDelete" BOOLEAN NOT NULL DEFAULT false,+ "createdAt" DATETIME DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" DATETIME,+ CONSTRAINT "databaseconfiguser_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "databaseconfiguser_databaseConfigId_fkey" FOREIGN KEY ("databaseConfigId") REFERENCES "databaseconfig" ("id") ON DELETE CASCADE ON UPDATE CASCADE+);++INSERT INTO "new_databaseconfiguser" ("canDelete", "canEdit", "canShare", "createdAt", "databaseConfigId", "isCurrent", "updatedAt", "user_id")+SELECT "canDelete", "canEdit", "canShare", "createdAt", "databaseConfigId", "isCurrent", "updatedAt", "user_id"+FROM "databaseconfiguser"+WHERE "databaseConfigId" IN (SELECT "id" FROM "databaseconfig");++DROP TABLE "databaseconfiguser";+ALTER TABLE "new_databaseconfiguser" RENAME TO "databaseconfiguser";++CREATE UNIQUE INDEX "databaseconfiguser_databaseConfigId_user_id_key" ON "databaseconfiguser"("databaseConfigId", "user_id");++-- Preserve existing organisation-level access after introducing the project+-- layer. Any user who was already a member of an organisation gets access to+-- all DB configs attached to projects in that organisation. Config creators+-- retain owner-level DB-config actions; other members get read/select access.+INSERT OR IGNORE INTO "databaseconfiguser" (+ "databaseConfigId",+ "user_id",+ "isCurrent",+ "canEdit",+ "canShare",+ "canDelete",+ "createdAt",+ "updatedAt"+)+SELECT+ dc."id",+ ou."user_id",+ CASE+ WHEN ou."current_project_id" = dc."project_id"+ AND dc."id" = (+ SELECT first_dc."id"+ FROM "databaseconfig" first_dc+ WHERE first_dc."project_id" = dc."project_id"+ ORDER BY first_dc."createdAt" ASC, first_dc."id" ASC+ LIMIT 1+ )+ AND NOT EXISTS (+ SELECT 1+ FROM "databaseconfiguser" existing_current+ JOIN "databaseconfig" existing_dc ON existing_dc."id" = existing_current."databaseConfigId"+ JOIN "projects" existing_project ON existing_project."id" = existing_dc."project_id"+ WHERE existing_current."user_id" = ou."user_id"+ AND existing_current."isCurrent" = true+ AND existing_project."organisation_id" = p."organisation_id"+ )+ THEN true+ ELSE false+ END,+ CASE WHEN dc."user_id" = ou."user_id" THEN true ELSE false END,+ CASE WHEN dc."user_id" = ou."user_id" THEN true ELSE false END,+ CASE WHEN dc."user_id" = ou."user_id" THEN true ELSE false END,+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP+FROM "organisation_users" ou+JOIN "projects" p ON p."organisation_id" = ou."organisation_id"+JOIN "databaseconfig" dc ON dc."project_id" = p."id";++PRAGMA foreign_keys=ON;+PRAGMA defer_foreign_keys=OFF;diff --git a/src/client/prisma/migrations/20260618000000_project_membership/migration.sql b/src/client/prisma/migrations/20260618000000_project_membership/migration.sqlnew file mode 100644index 00000000..1666e9b5--- /dev/null+++ b/src/client/prisma/migrations/20260618000000_project_membership/migration.sql@@ -0,0 +1,22 @@+-- Shared project membership table for OSS project sharing.+-- CE stores the membership relation but does not enforce enterprise RBAC+-- permission checks. Existing organisation members retain access to every+-- existing project in their organisations.+CREATE TABLE "project_users" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "project_id" TEXT NOT NULL,+ "organisation_user_id" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ CONSTRAINT "project_users_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "project_users_organisation_user_id_fkey" FOREIGN KEY ("organisation_user_id") REFERENCES "organisation_users" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "project_users_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE+);++CREATE UNIQUE INDEX "project_users_project_id_organisation_user_id_key" ON "project_users"("project_id", "organisation_user_id");+CREATE INDEX "project_users_user_id_idx" ON "project_users"("user_id");++INSERT OR IGNORE INTO "project_users" ("id", "project_id", "organisation_user_id", "user_id", "createdAt")+SELECT lower(hex(randomblob(12))), p."id", ou."id", ou."user_id", CURRENT_TIMESTAMP+FROM "organisation_users" ou+JOIN "projects" p ON p."organisation_id" = ou."organisation_id";diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prismaindex 341937f6..ff1d74bd 100644--- a/src/client/prisma/schema.prisma+++ b/src/client/prisma/schema.prisma@@ -59,6 +59,7 @@ model User {deletedApiKeys APIKeys[] @relation("deletedByUser")opengrounds OpenGround[]organisations OrganisationUser[]+ projectMemberships ProjectUser[]@@map("users")}@@ -101,6 +102,7 @@ model Project {updatedAt DateTime @updatedAtdatabaseConfigs DatabaseConfig[]currentForUsers OrganisationUser[] @relation("CurrentOrganisationProject")+ members ProjectUser[]@@unique([organisationId, slug])@@map("projects")@@ -116,6 +118,7 @@ model OrganisationUser {isCurrent Boolean @default(false)currentProjectId String? @map("current_project_id")currentProject Project? @relation("CurrentOrganisationProject", fields: [currentProjectId], references: [id], onDelete: SetNull)+ projects ProjectUser[]createdAt DateTime @default(now())updatedAt DateTime @updatedAt@@ -123,6 +126,21 @@ model OrganisationUser {@@map("organisation_users")}+model ProjectUser {+ id String @id @default(cuid())+ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ organisationUserId String @map("organisation_user_id")+ organisationUser OrganisationUser @relation(fields: [organisationUserId], references: [id], onDelete: Cascade)+ userId String @map("user_id")+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ createdAt DateTime @default(now())++ @@unique([projectId, organisationUserId])+ @@index([userId])+ @@map("project_users")+}+model OrganisationInvitedUser {id String @id @default(cuid())organisationId String @map("organisation_id")@@ -152,7 +170,7 @@ model DatabaseConfig {createdByUserId String @map("user_id")createdByUser User @relation(fields: [createdByUserId], references: [id])projectId String? @map("project_id")- project Project? @relation(fields: [projectId], references: [id])+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)dbInvitedUsers DatabaseConfigInvitedUser[]apiKeys APIKeys[]opengrounds OpenGround[]@@ -165,7 +183,7 @@ model DatabaseConfigUser {databaseConfigId StringuserId String @map("user_id")user User @relation(fields: [userId], references: [id])- databaseConfig DatabaseConfig? @relation(fields: [databaseConfigId], references: [id])+ databaseConfig DatabaseConfig? @relation(fields: [databaseConfigId], references: [id], onDelete: Cascade)isCurrent Boolean @default(false)canEdit Boolean @default(false)canShare Boolean @default(false)diff --git a/src/client/src/__tests__/app/api/organisation/projects-route.test.ts b/src/client/src/__tests__/app/api/organisation/projects-route.test.tsindex 69b44a22..618eadd5 100644--- a/src/client/src/__tests__/app/api/organisation/projects-route.test.ts+++ b/src/client/src/__tests__/app/api/organisation/projects-route.test.ts@@ -72,6 +72,27 @@ describe("organisation projects route", () => {expect(prisma.project.findMany).not.toHaveBeenCalled();});+ it("requires authentication before creating projects", async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);++ const response = await POST(jsonRequest({ name: "Production" }), params);++ expect(response.status).toBe(401);+ expect(await response.json()).toBe("Unauthorized user!");+ expect(prisma.organisationUser.findUnique).not.toHaveBeenCalled();+ expect(createOrganisationProject).not.toHaveBeenCalled();+ });++ it("requires organisation membership before creating projects", async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue(null);++ const response = await POST(jsonRequest({ name: "Production" }), params);++ expect(response.status).toBe(404);+ expect(await response.json()).toBe("Organisation not found");+ expect(createOrganisationProject).not.toHaveBeenCalled();+ });+it("marks the selected project in the list", async () => {(prisma.project.findMany as jest.Mock).mockResolvedValue([{ id: "project1", name: "Default", isDefault: true },diff --git a/src/client/src/__tests__/components/database-config-tabs.test.tsx b/src/client/src/__tests__/components/database-config-tabs.test.tsxnew file mode 100644index 00000000..c8c46486--- /dev/null+++ b/src/client/src/__tests__/components/database-config-tabs.test.tsx@@ -0,0 +1,54 @@+import { fireEvent, render, screen } from "@testing-library/react";+import DatabaseConfigTabs from "@/components/(playground)/database-config/database-config-tabs";+import { TooltipProvider } from "@/components/ui/tooltip";++describe("DatabaseConfigTabs", () => {+ it("renders localized actions and database config items", () => {+ const onClickTab = jest.fn();+ const onClickItemChangeActive = jest.fn();++ render(+ <TooltipProvider>+ <DatabaseConfigTabs+ addButton+ items={[+ {+ id: "db-1",+ name: "Default DB",+ badge: "production",+ isCurrent: true,+ canSelect: false,+ },+ ]}+ onClickItemChangeActive={onClickItemChangeActive}+ onClickTab={onClickTab}+ selectedTabId="db-1"+ />+ </TooltipProvider>+ );++ expect(screen.getByText("Add New Config")).toBeInTheDocument();+ expect(screen.getByText("Default DB")).toBeInTheDocument();+ expect(screen.getByText("production")).toBeInTheDocument();+ expect(screen.getByRole("checkbox")).toBeDisabled();++ fireEvent.click(screen.getByText("Add New Config"));+ expect(onClickTab).toHaveBeenCalledTimes(1);+ });++ it("hides the create action when creation is unavailable", () => {+ render(+ <TooltipProvider>+ <DatabaseConfigTabs+ items={[]}+ onClickItemChangeActive={jest.fn()}+ onClickTab={jest.fn()}+ selectedTabId=""+ addButton={false}+ />+ </TooltipProvider>+ );++ expect(screen.queryByText("Add New Config")).not.toBeInTheDocument();+ });+});diff --git a/src/client/src/__tests__/helpers/client/organisation.test.ts b/src/client/src/__tests__/helpers/client/organisation.test.tsindex 78367863..528d7909 100644--- a/src/client/src/__tests__/helpers/client/organisation.test.ts+++ b/src/client/src/__tests__/helpers/client/organisation.test.ts@@ -46,6 +46,9 @@ jest.mock('@/helpers/client/database-config', () => ({fetchDatabaseConfigList: jest.fn().mockResolvedValue(undefined),pingActiveDatabaseConfig: jest.fn().mockResolvedValue(undefined),}));+jest.mock('@/features/organisation', () => ({+ onOrganisationChanged: jest.fn().mockResolvedValue(undefined),+}));import {fetchOrganisationList,@@ -65,6 +68,7 @@ import { useRootStore } from '@/store';import { getData, postData, deleteData } from '@/utils/api';import asaw from '@/utils/asaw';import { toast } from 'sonner';+import { onOrganisationChanged } from '@/features/organisation';const mockSetIsLoading = jest.fn();const mockSetList = jest.fn();@@ -73,6 +77,8 @@ const mockSetPendingInvitations = jest.fn();const mockProjectSetIsLoading = jest.fn();const mockProjectSetList = jest.fn();const mockProjectSetCurrent = jest.fn();+const mockProjectReset = jest.fn();+const mockDatabaseConfigReset = jest.fn();const makeGetState = (list: any[] = []) => ({organisation: {@@ -86,12 +92,14 @@ const makeGetState = (list: any[] = []) => ({setIsLoading: jest.fn(),setList: jest.fn(),setPing: jest.fn(),+ reset: mockDatabaseConfigReset,list: [],},project: {setIsLoading: mockProjectSetIsLoading,setList: mockProjectSetList,setCurrent: mockProjectSetCurrent,+ reset: mockProjectReset,list: [],},});@@ -151,6 +159,9 @@ describe('changeActiveOrganisation', () => {await changeActiveOrganisation('org-1', successCb);expect(mockSetCurrent).toHaveBeenCalledWith(orgList[0]);+ expect(mockProjectReset).toHaveBeenCalled();+ expect(mockDatabaseConfigReset).toHaveBeenCalled();+ expect(onOrganisationChanged).toHaveBeenCalledWith('org-1');expect(toast.success).toHaveBeenCalled();expect(successCb).toHaveBeenCalled();});diff --git a/src/client/src/__tests__/lib/db-config.test.ts b/src/client/src/__tests__/lib/db-config.test.tsindex fcd1ea79..c79c2ad5 100644--- a/src/client/src/__tests__/lib/db-config.test.ts+++ b/src/client/src/__tests__/lib/db-config.test.ts@@ -38,6 +38,10 @@ jest.mock('@/lib/organisation', () => ({getCurrentOrganisation: jest.fn(),getCurrentProjectForOrganisation: jest.fn(),}));+jest.mock('../../lib/organisation', () => ({+ getCurrentOrganisation: jest.fn(),+ getCurrentProjectForOrganisation: jest.fn(),+}));jest.mock('@/utils/asaw', () => jest.fn());jest.mock('@/constants/messages', () => ({__esModule: true,@@ -71,7 +75,7 @@ import {} from '@/lib/db-config';import prisma from '@/lib/prisma';import { getCurrentUser } from '@/lib/session';-import { getCurrentOrganisation, getCurrentProjectForOrganisation } from '@/lib/organisation';+import { getCurrentOrganisation, getCurrentProjectForOrganisation } from '../../lib/organisation';import asaw from '@/utils/asaw';const mockUser = { id: 'u1', email: '[email protected]' };diff --git a/src/client/src/__tests__/lib/organisation.test.ts b/src/client/src/__tests__/lib/organisation.test.tsindex 24dde7a8..d76a9906 100644--- a/src/client/src/__tests__/lib/organisation.test.ts+++ b/src/client/src/__tests__/lib/organisation.test.ts@@ -12,6 +12,9 @@ jest.mock('@/lib/prisma', () => ({findUnique: jest.fn(),create: jest.fn(),},+ projectUser: {+ create: jest.fn(),+ },organisationUser: {findFirst: jest.fn(),findMany: jest.fn(),@@ -62,6 +65,8 @@ jest.mock('@/constants/messages', () => ({ONLY_ADMIN_CAN_UPDATE_ORGANISATION: 'Only admin can update',ORGANISATION_NOTHING_TO_UPDATE: 'Nothing to update',PROJECT_NAME_LENGTH_RANGE_ERROR: 'Project name must be between 1 and 120 characters',+ EMAIL_REQUIRED: 'Email cannot be empty',+ INVALID_EMAIL_FORMAT: 'Invalid email format',ONLY_ADMIN_CAN_INVITE: 'Only admin can invite',USER_ALREADY_ORGANISATION_MEMBER: 'Already a member',USER_ALREADY_INVITED: 'Already invited',@@ -142,6 +147,8 @@ beforeEach(() => {ONLY_ADMIN_CAN_UPDATE_ORGANISATION: 'Only admin can update',ORGANISATION_NOTHING_TO_UPDATE: 'Nothing to update',PROJECT_NAME_LENGTH_RANGE_ERROR: 'Project name must be between 1 and 120 characters',+ EMAIL_REQUIRED: 'Email cannot be empty',+ INVALID_EMAIL_FORMAT: 'Invalid email format',ONLY_ADMIN_CAN_INVITE: 'Only admin can invite',USER_ALREADY_ORGANISATION_MEMBER: 'Already a member',USER_ALREADY_INVITED: 'Already invited',diff --git a/src/client/src/__tests__/lib/user.test.ts b/src/client/src/__tests__/lib/user.test.tsindex d95f4262..556398de 100644--- a/src/client/src/__tests__/lib/user.test.ts+++ b/src/client/src/__tests__/lib/user.test.ts@@ -15,9 +15,15 @@ jest.mock('@/utils/asaw', () => jest.fn());jest.mock('@/lib/db-config', () => ({moveSharedDBConfigToDBUser: jest.fn().mockResolvedValue(undefined),}));+jest.mock('../../lib/db-config', () => ({+ moveSharedDBConfigToDBUser: jest.fn().mockResolvedValue(undefined),+}));jest.mock('@/lib/organisation', () => ({moveInvitationsToMembership: jest.fn().mockResolvedValue(undefined),}));+jest.mock('../../lib/organisation', () => ({+ moveInvitationsToMembership: jest.fn().mockResolvedValue(undefined),+}));jest.mock('@/constants/messages', () => ({__esModule: true,default: jest.fn(() => ({diff --git a/src/client/src/__tests__/middleware/check-auth.test.ts b/src/client/src/__tests__/middleware/check-auth.test.tsindex 33ccdec3..1dc92099 100644--- a/src/client/src/__tests__/middleware/check-auth.test.ts+++ b/src/client/src/__tests__/middleware/check-auth.test.ts@@ -139,6 +139,14 @@ describe('checkAuth', () => {const redirectCall = (NextResponse.redirect as jest.Mock).mock.calls[0][0];expect(redirectCall.toString()).toContain('/onboarding');});++ it('allows organisation setup pages before project setup is complete', async () => {+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: false });+ const req = makeRequest('GET', '/organisation');+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.next).toHaveBeenCalled();+ expect(NextResponse.redirect).not.toHaveBeenCalled();+ });});describe('error handling', () => {@@ -192,6 +200,14 @@ describe('checkAuth', () => {});describe('onboarding-whitelisted API routes (prefix match)', () => {+ it('allows organisation management APIs without onboarding completion', async () => {+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: false });+ const req = makeRequest('GET', '/api/organisation/org-1/projects');+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.next).toHaveBeenCalled();+ expect(NextResponse.json).not.toHaveBeenCalled();+ });+it('allows POST to /api/organisation/current/123 without onboarding', async () => {(getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: false });const req = makeRequest('POST', '/api/organisation/current/123');diff --git a/src/client/src/__tests__/store/database-config.test.ts b/src/client/src/__tests__/store/database-config.test.tsindex 158ad012..02f8edb9 100644--- a/src/client/src/__tests__/store/database-config.test.ts+++ b/src/client/src/__tests__/store/database-config.test.ts@@ -73,4 +73,22 @@ describe('databaseConfigStoreSlice', () => {expect(store.getState().databaseConfig.isLoading).toBe(false);});});++ describe('reset', () => {+ it('restores the initial state', () => {+ const list = [{ id: 'db1', name: 'Primary', isCurrent: true }];++ store.getState().databaseConfig.setList(list);+ store+ .getState()+ .databaseConfig.setPing({ status: 'failure', error: 'Connection refused' });+ store.getState().databaseConfig.setIsLoading(true);++ store.getState().databaseConfig.reset();++ expect(store.getState().databaseConfig.list).toBeUndefined();+ expect(store.getState().databaseConfig.isLoading).toBe(false);+ expect(store.getState().databaseConfig.ping).toEqual({ status: 'pending' });+ });+ });});diff --git a/src/client/src/app/(playground)/chat/page.tsx b/src/client/src/app/(playground)/chat/page.tsxindex a891c32d..1db17d28 100644--- a/src/client/src/app/(playground)/chat/page.tsx+++ b/src/client/src/app/(playground)/chat/page.tsx@@ -1,12 +1,63 @@"use client";-import { useSearchParams } from "next/navigation";+import { useEffect } from "react";+import { useRouter, useSearchParams } from "next/navigation";import ChatLayout from "@/components/(playground)/chat/chat-layout";import { RequestProvider } from "@/components/(playground)/request/request-context";+import { useRootStore } from "@/store";+import { getCurrentOrganisation } from "@/selectors/organisation";+import {+ getCurrentProject,+ getProjectIsLoading,+ getProjectList,+} from "@/selectors/project";+import {+ getDatabaseConfigList,+ getDatabaseConfigListIsLoading,+} from "@/selectors/database-config";+import { fetchProjectList } from "@/helpers/client/project";+import { fetchDatabaseConfigList } from "@/helpers/client/database-config";+import Loader from "@/components/common/loader";export default function ChatPage() {+ const router = useRouter();const searchParams = useSearchParams();const conversationId = searchParams.get("id");+ const currentOrg = useRootStore(getCurrentOrganisation);+ const projects = useRootStore(getProjectList);+ const currentProject = useRootStore(getCurrentProject);+ const isProjectLoading = useRootStore(getProjectIsLoading);+ const databaseConfigs = useRootStore(getDatabaseConfigList);+ const isDatabaseConfigLoading = useRootStore(getDatabaseConfigListIsLoading);+ const hasProject = Boolean(currentProject?.id && (projects?.length || 0) > 0);+ const hasDbConfig = Boolean(databaseConfigs?.length);+ const isSetupLoading =+ isProjectLoading ||+ isDatabaseConfigLoading ||+ projects === undefined ||+ (hasProject && databaseConfigs === undefined);++ useEffect(() => {+ if (currentOrg?.id) fetchProjectList(currentOrg.id);+ }, [currentOrg?.id]);++ useEffect(() => {+ if (currentProject?.id) fetchDatabaseConfigList(() => {});+ }, [currentProject?.id]);++ useEffect(() => {+ if (!isSetupLoading && (!currentOrg?.id || !hasProject || !hasDbConfig)) {+ router.replace("/onboarding");+ }+ }, [currentOrg?.id, hasDbConfig, hasProject, isSetupLoading, router]);++ if (isSetupLoading || !hasProject || !hasDbConfig) {+ return (+ <div className="flex h-full w-full items-center justify-center">+ <Loader />+ </div>+ );+ }return (<RequestProvider>diff --git a/src/client/src/app/(playground)/home/page.tsx b/src/client/src/app/(playground)/home/page.tsxindex 1f51be2f..42f7d083 100644--- a/src/client/src/app/(playground)/home/page.tsx+++ b/src/client/src/app/(playground)/home/page.tsx@@ -1,12 +1,27 @@"use client";+import Filter from "@/components/(playground)/filter";import { useEffect, useMemo, useState } from "react";import useFetchWrapper from "@/utils/hooks/useFetchWrapper";-import { useSearchParams } from "next/navigation";-import Dashboard, { DashboardConfig } from "../../../components/(playground)/manage-dashboard/board-creator";+import { useRouter, useSearchParams } from "next/navigation";+import Dashboard, {+ DashboardConfig,+} from "../../../components/(playground)/manage-dashboard/board-creator";import { useRootStore } from "@/store";import { getFilterDetails } from "@/selectors/filter";+import { getCurrentOrganisation } from "@/selectors/organisation";+import {+ getCurrentProject,+ getProjectIsLoading,+ getProjectList,+} from "@/selectors/project";+import {+ getDatabaseConfigList,+ getDatabaseConfigListIsLoading,+} from "@/selectors/database-config";import { getFilterParamsForDashboard } from "@/helpers/client/filter";+import { fetchProjectList } from "@/helpers/client/project";+import { fetchDatabaseConfigList } from "@/helpers/client/database-config";import Loader from "@/components/common/loader";import { usePageHeader } from "@/selectors/page";import { usePostHog } from "posthog-js/react";@@ -17,7 +32,14 @@ import DescriptionTooltip from "@/components/common/description-tooltip";import { BookText } from "lucide-react";export default function DashboardPage() {+ const router = useRouter();const filter = useRootStore(getFilterDetails);+ const currentOrg = useRootStore(getCurrentOrganisation);+ const projects = useRootStore(getProjectList);+ const currentProject = useRootStore(getCurrentProject);+ const isProjectLoading = useRootStore(getProjectIsLoading);+ const databaseConfigs = useRootStore(getDatabaseConfigList);+ const isDatabaseConfigLoading = useRootStore(getDatabaseConfigListIsLoading);const { fireRequest, isLoading } = useFetchWrapper();const { fireRequest: fireRunQuery } = useFetchWrapper();const [initialConfig, setInitialConfig] = useState<@@ -27,8 +49,34 @@ export default function DashboardPage() {const dashboardId = searchParams.get("dashboardId");const { setHeader } = usePageHeader();const posthog = usePostHog();+ const hasProject = Boolean(currentProject?.id && (projects?.length || 0) > 0);+ const hasDbConfig = Boolean(databaseConfigs?.length);+ const isSetupLoading =+ isProjectLoading ||+ isDatabaseConfigLoading ||+ projects === undefined ||+ (hasProject && databaseConfigs === undefined);++ useEffect(() => {+ if (currentOrg?.id) {+ fetchProjectList(currentOrg.id);+ }+ }, [currentOrg?.id]);useEffect(() => {+ if (currentProject?.id) {+ fetchDatabaseConfigList(() => {});+ }+ }, [currentProject?.id]);++ useEffect(() => {+ if (!isSetupLoading && (!currentOrg?.id || !hasProject || !hasDbConfig)) {+ router.replace("/onboarding");+ }+ }, [currentOrg?.id, hasDbConfig, hasProject, isSetupLoading, router]);++ useEffect(() => {+ if (isSetupLoading || !hasProject || !hasDbConfig) return;const fetchBoardLayout = async () => {try {setInitialConfig(undefined);@@ -67,7 +115,7 @@ export default function DashboardPage() {};fetchBoardLayout();- }, [dashboardId, fireRequest]);+ }, [dashboardId, fireRequest, hasDbConfig, hasProject, isSetupLoading]);const runFilters = useMemo(() => {return getFilterParamsForDashboard({@@ -82,7 +130,6 @@ export default function DashboardPage() {const data = await fireRunQuery({requestType: "POST",url: "/api/manage-dashboard/query/run",- // Add params of the dashboard & add a check for edit mode to send query or not through bodybody: JSON.stringify({widgetId,filter: runFilters,@@ -93,22 +140,32 @@ export default function DashboardPage() {return data.response;};+ if (isSetupLoading || !hasProject || !hasDbConfig) {+ return (+ <div className="flex h-full w-full items-center justify-center">+ <Loader />+ </div>+ );+ }+return (<><div className="flex w-full items-center justify-between mb-4 gap-4">{initialConfig?.description && (- <DescriptionTooltip description={initialConfig.description} className="ml-2 h-4 w-4" icon={<BookText className="text-stone-500 cursor-pointer" />} />+ <DescriptionTooltip+ description={initialConfig.description}+ className="ml-2 h-4 w-4"+ icon={<BookText className="text-stone-500 cursor-pointer" />}+ />)}<Filter /><BoardList dashboardId={dashboardId} /></div>- {- isLoading ? (- <div className="flex items-center justify-center h-full w-full">- <Loader />- </div>- ) : null- }+ {isLoading ? (+ <div className="flex items-center justify-center h-full w-full">+ <Loader />+ </div>+ ) : null}{initialConfig ? (<DashboardclassName="h-100 overflow-y-auto"diff --git a/src/client/src/app/(playground)/layout.tsx b/src/client/src/app/(playground)/layout.tsxindex 26e13cd0..fcb02fec 100644--- a/src/client/src/app/(playground)/layout.tsx+++ b/src/client/src/app/(playground)/layout.tsx@@ -8,6 +8,11 @@ import NavigationEvents from "@/components/common/navigation-events";import AppInit from "@/components/common/app-init";import { PortalProvider } from "@/components/(playground)/header-portal";import ChatFloatingButton from "@/components/(playground)/chat/chat-floating-button";+import {+ EnterpriseFeatureAccessProvider,+ EnterpriseFeatureRouteGate,+} from "@/components/enterprise-feature-access-provider";+import { getEnterpriseFeatureAccessSnapshot } from "@/lib/enterprise-feature-access";export default async function PlaygroundLayout({children,@@ -15,24 +20,29 @@ export default async function PlaygroundLayout({children: React.ReactNode;}) {const telemetryEnabled = process.env.TELEMETRY_ENABLED !== "false";+ const enterpriseFeatureAccess = await getEnterpriseFeatureAccessSnapshot();return (<CustomPostHogProvider telemetryEnabled={telemetryEnabled}><TooltipProvider>- <PortalProvider>- <div className="flex h-screen w-full gap-4 overflow-hidden p-2">- <Sidebar />- <div className="flex flex-col grow w-full">- <Header />- <main className="flex flex-col grow flex-1 items-start p-0 overflow-hidden">- <ClickhouseConnectivityWrapper>- {children}- </ClickhouseConnectivityWrapper>- </main>+ <EnterpriseFeatureAccessProvider snapshot={enterpriseFeatureAccess}>+ <PortalProvider>+ <div className="flex h-screen w-full gap-4 overflow-hidden p-2">+ <Sidebar />+ <div className="flex flex-col grow w-full">+ <Header />+ <main className="flex flex-col grow flex-1 items-start p-0 overflow-hidden">+ <ClickhouseConnectivityWrapper>+ <EnterpriseFeatureRouteGate>+ {children}+ </EnterpriseFeatureRouteGate>+ </ClickhouseConnectivityWrapper>+ </main>+ </div></div>- </div>- <ChatFloatingButton />- </PortalProvider>+ <ChatFloatingButton />+ </PortalProvider>+ </EnterpriseFeatureAccessProvider></TooltipProvider><Suspense fallback={null}><NavigationEvents />diff --git a/src/client/src/app/(playground)/onboarding/page.tsx b/src/client/src/app/(playground)/onboarding/page.tsxindex 47a2d318..1b985e22 100644--- a/src/client/src/app/(playground)/onboarding/page.tsx+++ b/src/client/src/app/(playground)/onboarding/page.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect } from "react";+import { useState, useEffect, type ReactNode } from "react";import { useSession } from "next-auth/react";import { usePostHog } from "posthog-js/react";import { CLIENT_EVENTS } from "@/constants/events";@@ -14,22 +14,126 @@ import {CardHeader,CardTitle,} from "@/components/ui/card";-import { Building2, Mail, Check, X, ArrowRight, Users } from "lucide-react";+import {+ Building2,+ Mail,+ Check,+ X,+ ArrowRight,+ Users,+ FolderKanban,+ Database,+ Plus,+ Sparkles,+} from "lucide-react";import { useRootStore } from "@/store";import {getOrganisationPendingInvitations,getOrganisationList,+ getCurrentOrganisation,+ getOrganisationIsLoading,} from "@/selectors/organisation";+import {+ getCurrentProject,+ getProjectIsLoading,+ getProjectList,+} from "@/selectors/project";+import {+ getDatabaseConfigList,+ getDatabaseConfigListIsLoading,+} from "@/selectors/database-config";import {acceptInvitation,declineInvitation,fetchOrganisationList,fetchPendingInvitations,} from "@/helpers/client/organisation";+import { fetchProjectList } from "@/helpers/client/project";+import { fetchDatabaseConfigList } from "@/helpers/client/database-config";import { postData } from "@/utils/api";import asaw from "@/utils/asaw";import getMessage from "@/constants/messages";import { DEFAULT_LOGGED_IN_ROUTE } from "@/constants/route";+import Link from "next/link";+import Loader from "@/components/common/loader";+import FeaturePageHeader from "@/components/(playground)/feature-page-header";++function TimelineStep({+ active,+ complete,+ description,+ icon,+ isLast,+ stepNumber,+ title,+ children,+}: {+ active?: boolean;+ complete?: boolean;+ description: string;+ icon: ReactNode;+ isLast?: boolean;+ stepNumber: number;+ title: string;+ children?: ReactNode;+}) {+ return (+ <div className="relative flex gap-4">+ <div className="relative flex w-9 shrink-0 justify-center">+ {!isLast ? (+ <div+ className={`absolute bottom-[-1rem] top-10 w-px ${+ complete+ ? "bg-primary/70"+ : "bg-stone-200 dark:bg-stone-800"+ }`}+ />+ ) : null}+ <div+ className={`z-10 flex h-9 w-9 items-center justify-center rounded-full border text-xs font-semibold shadow-sm transition-colors ${+ complete+ ? "border-primary bg-primary text-primary-foreground"+ : active+ ? "border-primary bg-primary/10 text-primary dark:bg-primary/15"+ : "border-stone-300 bg-white text-stone-500 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-400"+ }`}+ >+ {complete ? <Check className="h-4 w-4" /> : stepNumber}+ </div>+ </div>+ <div+ className={`min-w-0 flex-1 rounded-xl border p-4 shadow-sm transition-colors ${+ active+ ? "border-primary/50 bg-primary/5 dark:border-primary/60 dark:bg-primary/10"+ : complete+ ? "border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950"+ : "border-stone-200 bg-stone-50/80 dark:border-stone-800 dark:bg-stone-900/40"+ }`}+ >+ <div className="flex items-start gap-3">+ <div+ className={`rounded-lg border p-2 ${+ active || complete+ ? "border-primary/20 bg-primary/10 text-primary dark:border-primary/30"+ : "border-stone-200 bg-white text-stone-500 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-400"+ }`}+ >+ {icon}+ </div>+ <div className="min-w-0 flex-1">+ <h3 className="text-sm font-semibold text-stone-950 dark:text-stone-50">+ {title}+ </h3>+ <p className="mt-1 text-sm leading-6 text-stone-600 dark:text-stone-300">+ {description}+ </p>+ {children ? <div className="mt-3">{children}</div> : null}+ </div>+ </div>+ </div>+ </div>+ );+}export default function OnboardingPage() {const posthog = usePostHog();@@ -40,19 +144,67 @@ export default function OnboardingPage() {const [isSkipping, setIsSkipping] = useState(false);const [isSelectingOrg, setIsSelectingOrg] = useState<string | null>(null);const [isCompleting, setIsCompleting] = useState(false);+ const [hasLoadedOrganisations, setHasLoadedOrganisations] = useState(false);+ const [projectName, setProjectName] = useState("");+ const [isCreatingProject, setIsCreatingProject] = useState(false);const pendingInvitations = useRootStore(getOrganisationPendingInvitations);const organisationList = useRootStore(getOrganisationList);+ const currentOrg = useRootStore(getCurrentOrganisation);+ const isOrganisationLoading = useRootStore(getOrganisationIsLoading);+ const projects = useRootStore(getProjectList);+ const currentProject = useRootStore(getCurrentProject);+ const isProjectLoading = useRootStore(getProjectIsLoading);+ const databaseConfigs = useRootStore(getDatabaseConfigList);+ const isDatabaseConfigLoading = useRootStore(getDatabaseConfigListIsLoading);+ const hasProject = Boolean(currentProject?.id && (projects?.length || 0) > 0);+ const hasDbConfig = Boolean(databaseConfigs?.length);+ const isSetupComplete = Boolean(currentOrg?.id && hasProject && hasDbConfig);+ const isInitialising =+ !currentOrg?.id &&+ (!hasLoadedOrganisations || isOrganisationLoading || organisationList === undefined);// Filter out orgs that are already current (shouldn't happen, but just in case)const existingMemberships = organisationList?.filter((org) => !org.isCurrent) || [];useEffect(() => {posthog?.capture(CLIENT_EVENTS.ONBOARDING_PAGE_VISITED);- // Fetch organisations and invitations on mount- fetchOrganisationList();- fetchPendingInvitations();+ let isMounted = true;+ Promise.all([fetchOrganisationList(), fetchPendingInvitations()]).finally(() => {+ if (isMounted) setHasLoadedOrganisations(true);+ });+ return () => {+ isMounted = false;+ };}, []);+ useEffect(() => {+ if (currentOrg?.id) {+ fetchProjectList(currentOrg.id);+ }+ }, [currentOrg?.id]);++ useEffect(() => {+ if (currentProject?.id) {+ fetchDatabaseConfigList(() => {});+ }+ }, [currentProject?.id]);++ const handleCreateProject = async () => {+ if (!currentOrg?.id || !projectName.trim()) return;+ setIsCreatingProject(true);+ const [err, data] = await asaw(+ postData({+ url: `/api/organisation/${currentOrg.id}/projects`,+ data: { name: projectName.trim() },+ })+ );+ setIsCreatingProject(false);++ if (err || data?.err) return;+ setProjectName("");+ await fetchProjectList(currentOrg.id);+ };+const setCurrentOrgAndComplete = async (orgId: string) => {// Prevent multiple callsif (isCompleting) return false;@@ -134,23 +286,129 @@ export default function OnboardingPage() {}};- const handleAcceptInvitation = async (invitationId: string) => {- await acceptInvitation(invitationId);+ const handleAcceptInvitation = async (invitation: {+ id: string;+ organisationId: string;+ }) => {+ if (isCompleting) return;++ setIsSelectingOrg(invitation.organisationId);+ try {+ const accepted = await acceptInvitation(invitation.id);+ if (accepted) {+ await setCurrentOrgAndComplete(invitation.organisationId);+ }+ } finally {+ setIsSelectingOrg(null);+ }};const handleDeclineInvitation = async (invitationId: string) => {await declineInvitation(invitationId);};+ if (isInitialising) {+ return (+ <div className="flex min-h-screen w-full items-center justify-center bg-background">+ <Loader />+ </div>+ );+ }+return (- <div className="min-h-screen w-full flex items-center justify-center bg-background p-4">- <div className="w-full max-w-2xl space-y-6">- <div className="text-center space-y-2">- <h1 className="text-3xl font-bold">{messages.ONBOARDING_WELCOME}</h1>- <p className="text-muted-foreground">{messages.ONBOARDING_SUBTITLE}</p>- </div>+ <div className="h-full w-full overflow-y-auto bg-stone-50 p-2 text-stone-950 dark:bg-stone-950 dark:text-stone-50 md:p-3">+ <div className="w-full space-y-3">+ <FeaturePageHeader+ eyebrow={messages.ONBOARDING}+ title={messages.ONBOARDING_WELCOME}+ description={messages.ONBOARDING_SUBTITLE}+ icon={<Sparkles className="h-4 w-4" />}+ tone="border-primary/20 bg-primary/10 text-primary dark:border-primary/30"+ />- {existingMemberships.length > 0 && (+ {currentOrg?.id && (+ <Card className="overflow-hidden border-stone-200 bg-white shadow-sm dark:border-stone-800 dark:bg-stone-900">+ <CardHeader className="border-b border-stone-100 bg-stone-50/80 dark:border-stone-800 dark:bg-stone-950/60">+ <CardTitle className="text-stone-950 dark:text-stone-50">+ {messages.HOME_SETUP_TITLE}+ </CardTitle>+ <CardDescription className="text-stone-600 dark:text-stone-300">+ {messages.HOME_SETUP_DESCRIPTION}+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4 p-5">+ <TimelineStep+ complete+ description={currentOrg.name}+ icon={<Building2 className="h-4 w-4" />}+ stepNumber={1}+ title={messages.HOME_SETUP_ORGANISATION_STEP}+ />+ <TimelineStep+ active={!hasProject}+ complete={hasProject}+ description={messages.HOME_SETUP_PROJECT_DESCRIPTION}+ icon={<FolderKanban className="h-4 w-4" />}+ stepNumber={2}+ title={messages.HOME_SETUP_PROJECT_STEP}+ >+ {!hasProject ? (+ <div className="flex gap-2">+ <Input+ value={projectName}+ onChange={(event) => setProjectName(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") handleCreateProject();+ }}+ placeholder={messages.PROJECT_NAME_PLACEHOLDER}+ className="h-9"+ disabled={isProjectLoading}+ />+ <Button+ onClick={handleCreateProject}+ disabled={isCreatingProject || !projectName.trim()}+ size="sm"+ className="h-9 shrink-0"+ >+ <Plus className="mr-1.5 h-3.5 w-3.5" />+ {messages.CREATE_ORGANISATION_PROJECT}+ </Button>+ </div>+ ) : null}+ </TimelineStep>+ <TimelineStep+ active={hasProject && !hasDbConfig}+ complete={hasDbConfig}+ description={messages.HOME_SETUP_DB_CONFIG_DESCRIPTION}+ icon={<Database className="h-4 w-4" />}+ stepNumber={3}+ title={messages.HOME_SETUP_DB_CONFIG_STEP}+ >+ {hasProject && !hasDbConfig && currentProject?.id ? (+ <Button asChild size="sm" className="h-9">+ <Link href={`/organisation/project/${currentProject.id}?tab=database`}>+ <Database className="mr-1.5 h-3.5 w-3.5" />+ {isDatabaseConfigLoading+ ? messages.LOADING+ : messages.ADD_NEW_CONFIG}+ </Link>+ </Button>+ ) : null}+ </TimelineStep>+ <TimelineStep+ active={isSetupComplete}+ complete={isSetupComplete}+ description={messages.HOME_SETUP_READY_DESCRIPTION}+ icon={<Sparkles className="h-4 w-4" />}+ isLast+ stepNumber={4}+ title={messages.HOME_SETUP_READY_STEP}+ />+ </CardContent>+ </Card>+ )}++ {!currentOrg?.id && existingMemberships.length > 0 && (<Card><CardHeader><CardTitle className="flex items-center gap-2">@@ -193,7 +451,7 @@ export default function OnboardingPage() {</Card>)}- {pendingInvitations.length > 0 && (+ {!currentOrg?.id && pendingInvitations.length > 0 && (<Card><CardHeader><CardTitle className="flex items-center gap-2">@@ -223,10 +481,17 @@ export default function OnboardingPage() {</Button><Buttonsize="sm"- onClick={() => handleAcceptInvitation(invitation.id)}+ onClick={() => handleAcceptInvitation(invitation)}+ disabled={isCompleting || isSelectingOrg === invitation.organisationId}>- <Check className="h-4 w-4 mr-1" />- {messages.JOIN}+ {isSelectingOrg === invitation.organisationId ? (+ messages.LOADING+ ) : (+ <>+ <Check className="h-4 w-4 mr-1" />+ {messages.JOIN}+ </>+ )}</Button></div></div>@@ -235,6 +500,7 @@ export default function OnboardingPage() {</Card>)}+ {!currentOrg?.id && (<Card><CardHeader><CardTitle className="flex items-center gap-2">@@ -272,7 +538,9 @@ export default function OnboardingPage() {</div></CardContent></Card>+ )}+ {!currentOrg?.id && (<div className="text-center"><Buttonvariant="ghost"@@ -283,6 +551,7 @@ export default function OnboardingPage() {{isSkipping ? messages.SETTING_UP : messages.ONBOARDING_SKIP}</Button></div>+ )}</div></div>);diff --git a/src/client/src/app/(playground)/organisation/page.tsx b/src/client/src/app/(playground)/organisation/page.tsxnew file mode 100644index 00000000..89f63108--- /dev/null+++ b/src/client/src/app/(playground)/organisation/page.tsx@@ -0,0 +1,5 @@+import OrganisationPage from "@/components/(playground)/organisation/organisation-page";++export default function OrganisationRoutePage() {+ return <OrganisationPage />;+}diff --git a/src/client/src/app/(playground)/organisation/project/[projectId]/page.tsx b/src/client/src/app/(playground)/organisation/project/[projectId]/page.tsxnew file mode 100644index 00000000..dd9e6de2--- /dev/null+++ b/src/client/src/app/(playground)/organisation/project/[projectId]/page.tsx@@ -0,0 +1,9 @@+import OrganisationProjectPage from "@/components/(playground)/organisation/project-page";++export default function ProjectRoutePage({+ params,+}: {+ params: { projectId: string };+}) {+ return <OrganisationProjectPage projectId={params.projectId} />;+}diff --git a/src/client/src/app/(playground)/settings/database-config/page.tsx b/src/client/src/app/(playground)/settings/database-config/page.tsxindex 5d82587e..6ccaf55d 100644--- a/src/client/src/app/(playground)/settings/database-config/page.tsx+++ b/src/client/src/app/(playground)/settings/database-config/page.tsx@@ -1,345 +1,5 @@-"use client";+import { redirect } from "next/navigation";-import FormBuilder from "@/components/common/form-builder";-import DatabaseConfigTabs from "@/app/(playground)/settings/database-config/database-config-tabs";-import { Button } from "@/components/ui/button";-import { DatabaseConfig, DatabaseConfigWithActive } from "@/constants/dbConfig";-import {- changeActiveDatabaseConfig,- deleteDatabaseConfig,- fetchDatabaseConfigList,-} from "@/helpers/client/database-config";-import {- getDatabaseConfigList,- getDatabaseConfigListIsLoading,-} from "@/selectors/database-config";-import { useRootStore } from "@/store";-import useFetchWrapper from "@/utils/hooks/useFetchWrapper";-import { isNil, keyBy } from "lodash";-import { MouseEventHandler, useCallback, useState } from "react";-import { toast } from "sonner";-import { usePostHog } from "posthog-js/react";-import { CLIENT_EVENTS } from "@/constants/events";-import { DatabaseConfigTabItemProps } from "@/types/database-config";-import { FormBuilderEvent } from "@/types/form";-import { PRIMARY_BACKGROUND } from "@/constants/common-classes";--function ModifyDatabaseConfig({- dbConfig,-}: {- dbConfig?: DatabaseConfigWithActive;-}) {- const posthog = usePostHog();- const { fireRequest, isLoading } = useFetchWrapper();-- const modifyDetails: FormBuilderEvent = useCallback(- (event) => {- event.preventDefault();- const formElement = event.target as HTMLFormElement;-- toast.loading("Modifying db config...", {- id: "db-config-details",- });-- const payload: DatabaseConfig = {- id: dbConfig?.id || "",- name: (formElement.name as any).value,- environment: formElement.environment.value,- username: formElement.username.value,- host: formElement.host.value,- port: formElement.port.value,- database: formElement.database.value,- query: formElement.query.value,- };-- if (formElement.password.value) {- payload.password = formElement.password.value;- }-- fireRequest({- body: JSON.stringify(payload),- requestType: "POST",- url: "/api/db-config",- responseDataKey: "data",- successCb: () => {- fetchDatabaseConfigList((data: any[]) => {- posthog?.capture(CLIENT_EVENTS.DB_CONFIG_LIST, {- count: data.length,- });- });- toast.success("Db config updated!", {- id: "db-config-details",- });- if (!dbConfig?.id) formElement.reset();- posthog?.capture(- payload.id- ? CLIENT_EVENTS.DB_CONFIG_UPDATE_SUCCESS- : CLIENT_EVENTS.DB_CONFIG_ADD_SUCCESS- );- },- failureCb: (err?: string) => {- toast.error(err || "Db config updation failed!", {- id: "db-config-details",- });- posthog?.capture(- payload.id- ? CLIENT_EVENTS.DB_CONFIG_UPDATE_FAILURE- : CLIENT_EVENTS.DB_CONFIG_ADD_FAILURE- );- },- });- },- [dbConfig?.id]- );-- const formFieldsDisabled =- dbConfig?.id && !dbConfig?.permissions?.canEdit ? true : false;-- return (- <FormBuilder- cardClassName={`${PRIMARY_BACKGROUND} py-4 px-6 rounded-none`}- fields={[- {- label: "Config Name",- inputKey: `${dbConfig?.id}-name`,- fieldType: "INPUT",- fieldTypeProps: {- type: "text",- name: "name",- placeholder: "db-config",- defaultValue: dbConfig?.name,- disabled: formFieldsDisabled,- },- },- {- label: "Environment",- inputKey: `${dbConfig?.id}-environment`,- fieldType: "INPUT",- fieldTypeProps: {- type: "text",- name: "environment",- placeholder: "production",- defaultValue: dbConfig?.environment,- disabled: formFieldsDisabled,- },- },- {- label: "Username",- fieldType: "INPUT",- inputKey: `${dbConfig?.id}-username`,- fieldTypeProps: {- type: "text",- name: "username",- placeholder: "username",- defaultValue: dbConfig?.username,- disabled: formFieldsDisabled,- },- },- {- label: "Password",- inputKey: `${dbConfig?.id}-password`,- fieldType: "INPUT",- fieldTypeProps: {- type: "password",- name: "password",- placeholder: "*******",- disabled: formFieldsDisabled,- },- },- {- label: "Host",- inputKey: `${dbConfig?.id}-host`,- fieldType: "INPUT",- fieldTypeProps: {- type: "text",- name: "host",- placeholder: "127.0.0.1",- defaultValue: dbConfig?.host,- disabled: formFieldsDisabled,- },- },- {- label: "Port",- inputKey: `${dbConfig?.id}-port`,- fieldType: "INPUT",- fieldTypeProps: {- type: "number",- name: "port",- placeholder: "8123",- defaultValue: dbConfig?.port,- disabled: formFieldsDisabled,- },- },- {- label: "Database",- inputKey: `${dbConfig?.id}-database`,- fieldType: "INPUT",- fieldTypeProps: {- type: "text",- name: "database",- placeholder: "default",- defaultValue: dbConfig?.database,- disabled: formFieldsDisabled,- },- },- {- label: "Query params",- inputKey: `${dbConfig?.id}-query`,- fieldType: "INPUT",- fieldTypeProps: {- type: "text",- name: "query",- placeholder: "a=b&c=d",- defaultValue: dbConfig?.query,- disabled: formFieldsDisabled,- },- },- ]}- heading={`${- dbConfig?.id- ? !dbConfig?.permissions?.canEdit- ? ""- : "Update "- : "Add "- }Database config`}- subHeading={- !dbConfig?.id || dbConfig?.permissions?.canEdit- ? ""- : "You don't have enough permissions to edit this database config"- }- subHeadingClass="text-error"- isLoading={isLoading}- onSubmit={modifyDetails}- isAllowedToSubmit={!dbConfig?.id || !!dbConfig?.permissions?.canEdit}- submitButtonText={dbConfig?.id ? "Update" : "Save"}- />- );-}-function DatabaseList({- dbConfigs,- isLoadingList,-}: {- dbConfigs: DatabaseConfigWithActive[];- isLoadingList: boolean;-}) {- const posthog = usePostHog();- const [selectedDBConfigId, setSelectedDBConfigId] = useState<- string | undefined- >();-- const dbConfigByKey = keyBy(dbConfigs, "id");-- const onClickDB: MouseEventHandler<HTMLDivElement | HTMLButtonElement> = (- event- ) => {- const parent = (event.target as HTMLElement).closest(- ".item-element-card"- ) as HTMLElement;- if (!parent) return null;- const { itemId = "" } = parent.dataset;- setSelectedDBConfigId(itemId);- };-- const onClickDelete: MouseEventHandler<SVGSVGElement> = (event) => {- event.stopPropagation();- const parent = (event.target as HTMLElement).closest(- ".item-element-card"- ) as HTMLElement;- if (!parent) return null;- const { itemId = "" } = parent.dataset;-- if (itemId) deleteDatabaseConfig(itemId);- };-- const onClickSetCurrent: MouseEventHandler<HTMLDivElement> = (event) => {- event.stopPropagation();- const parent = (event.target as HTMLElement).closest(- ".item-element-card"- ) as HTMLElement;- if (!parent) return null;- const { itemId = "" } = parent.dataset;-- if (itemId) {- toast.loading(- `Db config: ${dbConfigByKey[itemId].name} setting active!`,- {- id: "db-config-current",- }- );- changeActiveDatabaseConfig(itemId, () => {- posthog?.capture(CLIENT_EVENTS.DB_CONFIG_ACTION_CHANGE);- });- }- };-- const items: DatabaseConfigTabItemProps[] = dbConfigs.map((dbConfig) => ({- id: dbConfig.id,- name: dbConfig.name,- badge: dbConfig.environment,- isCurrent: !!dbConfig.isCurrent,- canDelete: !!dbConfig.permissions?.canDelete,- canEdit: !!dbConfig.permissions?.canEdit,- canShare: !!dbConfig.permissions?.canShare,- }));-- return (- <div className="flex w-full flex-1 relative">- <DatabaseConfigTabs- addButton- items={items}- onClickTab={onClickDB}- selectedTabId={selectedDBConfigId || ""}- onClickItemChangeActive={onClickSetCurrent}- onClickItemDelete={onClickDelete}- />- <div className="flex flex-1 w-full h-full overflow-hidden">- {selectedDBConfigId ? (- <ModifyDatabaseConfig dbConfig={dbConfigByKey[selectedDBConfigId]} />- ) : (- <div className="flex flex-1 items-center justify-center">- <div className="flex flex-col items-center gap-1 text-center">- <h3 className="text-2xl font-bold tracking-tight text-stone-900 dark:text-stone-100">- {dbConfigs.length === 0- ? "You have not created any database config"- : "You have not selected any database config"}- </h3>- <p className="text-sm text-stone-700 dark:text-stone-300">- {dbConfigs.length === 0- ? "You can have multiple database config to manage your different environments"- : "You can have multiple database config to manage your different environments. Select database config to update the details"}- </p>- {dbConfigs.length !== 0 && (- <Button- className="mt-4 item-element-card"- data-item-id={"ADD_NEW_ID"}- onClick={onClickDB}- >- Add database config- </Button>- )}- </div>- </div>- )}- </div>- {isLoadingList && (- <div className="flex absolute w-full left-0 top-0 h-full animate-pulse z-10" />- )}- </div>- );-}--export default function Database() {- const databaseList = useRootStore(getDatabaseConfigList);- const databaseListIsLoading = useRootStore(getDatabaseConfigListIsLoading);-- return isNil(databaseList) ? (- <div className="flex items-center justify-center w-full h-full animate-pulse dark:text-white">- Loading...- </div>- ) : (- <DatabaseList- dbConfigs={(databaseList as DatabaseConfigWithActive[]) || []}- isLoadingList={databaseListIsLoading}- />- );+export default function DatabaseConfigSettingsRedirect() {+ redirect("/organisation");}diff --git a/src/client/src/app/(playground)/settings/layout.tsx b/src/client/src/app/(playground)/settings/layout.tsxindex 6e9099b8..87a90467 100644--- a/src/client/src/app/(playground)/settings/layout.tsx+++ b/src/client/src/app/(playground)/settings/layout.tsx@@ -4,6 +4,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";import type React from "react";import ThemeToggleSwitch from "@/components/(playground)/sidebar/theme-switch";import { PRIMARY_BACKGROUND } from "@/constants/common-classes";+import { getSettingsTabs } from "@/constants/settings";export default function SettingsLayout({children,@@ -12,21 +13,7 @@ export default function SettingsLayout({}) {const router = useRouter();const pathname = usePathname();-- const tabs = [- {- value: "organisation",- label: "Organisation",- path: "/settings/organisation",- },- { value: "profile", label: "User Profile", path: "/settings/profile" },- {- value: "database",- label: "Database Config",- path: "/settings/database-config",- },- { value: "api-keys", label: "API Keys", path: "/settings/api-keys" },- ];+ const tabs = getSettingsTabs();const currentTab =tabs.find((tab) => pathname.startsWith(tab.path))?.value || "profile";@@ -46,7 +33,7 @@ export default function SettingsLayout({className="w-full flex flex-col h-full"><div className="flex items-center justify-between gap-4 mb-4">- <TabsList className="p-0 h-[30px] grid grid-cols-4 self-start border border-stone-200 dark:border-stone-800">+ <TabsList className="p-0 h-[30px] flex self-start border border-stone-200 dark:border-stone-800">{tabs.map((tab) => (<TabsTrigger key={tab.value} value={tab.value} className="py-1.5 text-xs rounded-md">{tab.label}diff --git a/src/client/src/app/(playground)/settings/organisation/page.tsx b/src/client/src/app/(playground)/settings/organisation/page.tsxindex b8a5860e..4198a74e 100644--- a/src/client/src/app/(playground)/settings/organisation/page.tsx+++ b/src/client/src/app/(playground)/settings/organisation/page.tsx@@ -1,891 +1,5 @@-"use client";+import { redirect } from "next/navigation";-import { useState, useEffect } from "react";-import { usePostHog } from "posthog-js/react";-import { CLIENT_EVENTS } from "@/constants/events";-import { useRouter, useSearchParams } from "next/navigation";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@/components/ui/card";-import {- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,-} from "@/components/ui/table";-import { Badge } from "@/components/ui/badge";-import {- Tabs,- TabsContent,- TabsList,- TabsTrigger,-} from "@/components/ui/tabs";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import {- Building2,- Mail,- Check,- X,- Trash2,- UserPlus,- Crown,- LogOut,- Loader2,- Save,- Users,- Settings,- Clock,- FolderKanban,- Database,-} from "lucide-react";-import { useRootStore } from "@/store";-import {- getCurrentOrganisation,- getOrganisationList,- getOrganisationPendingInvitations,- getOrganisationIsLoading,-} from "@/selectors/organisation";-import { getCurrentUserId } from "@/selectors/user";-import {- updateOrganisation,- deleteOrganisation,- inviteToOrganisation,- acceptInvitation,- declineInvitation,- removeOrganisationMember,- cancelOrganisationInvitation,- fetchOrganisationList,- fetchPendingInvitations,- changeActiveOrganisation,- updateMemberRole,-} from "@/helpers/client/organisation";-import {- changeActiveProject,- fetchProjectList,-} from "@/helpers/client/project";-import { getData, postData } from "@/utils/api";-import asaw from "@/utils/asaw";-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,- AlertDialogTrigger,-} from "@/components/ui/alert-dialog";-import CreateOrganisationDialog from "@/components/(playground)/sidebar/create-organisation-dialog";-import getMessage from "@/constants/messages";-import { escapeEmailForDisplay } from "@/utils/string";-import { toast } from "sonner";--interface Member {- id: string;- email: string;- name: string | null;- image: string | null;- isCreator: boolean;- role: "owner" | "admin" | "member";- joinedAt: string;-}--interface PendingInvite {- id: string;- email: string;- invitedAt: string;-}--interface Project {- id: string;- name: string;- slug: string;- isDefault: boolean;- isCurrent: boolean;- createdAt: string;-}--export default function OrganisationSettingsPage() {- const posthog = usePostHog();- const router = useRouter();- const searchParams = useSearchParams();- const messages = getMessage();- const currentOrg = useRootStore(getCurrentOrganisation);- const organisations = useRootStore(getOrganisationList) || [];- const pendingInvitations = useRootStore(getOrganisationPendingInvitations);- const currentUserId = useRootStore(getCurrentUserId);- const isOrgLoading = useRootStore(getOrganisationIsLoading);-- const [orgName, setOrgName] = useState("");- const [inviteEmail, setInviteEmail] = useState("");- const [members, setMembers] = useState<Member[]>([]);- const [orgPendingInvites, setOrgPendingInvites] = useState<PendingInvite[]>(- []- );- const [isLoading, setIsLoading] = useState(false);- const [isSaving, setIsSaving] = useState(false);- const [isInviting, setIsInviting] = useState(false);- const [createDialogOpen, setCreateDialogOpen] = useState(false);- const [hasFetchedOrgs, setHasFetchedOrgs] = useState(false);- const [projects, setProjects] = useState<Project[]>([]);- const [projectName, setProjectName] = useState("");- const [isProjectsLoading, setIsProjectsLoading] = useState(false);- const [isCreatingProject, setIsCreatingProject] = useState(false);-- const isCreator = currentOrg?.createdByUserId === currentUserId;-- // Get current user's role and permissions- const currentUserMember = members.find(m => m.id === currentUserId);- const currentUserRole = currentUserMember?.role;- const hasAdminPermissions = currentUserRole === 'owner' || currentUserRole === 'admin';- const displayEmail = (email: string) => escapeEmailForDisplay(email);-- useEffect(() => {- posthog?.capture(CLIENT_EVENTS.SETTINGS_ORGANISATION_PAGE_VISITED);- }, []);-- // Fetch organisations on mount- useEffect(() => {- const fetchData = async () => {- await fetchOrganisationList();- await fetchPendingInvitations();- setHasFetchedOrgs(true);- };- fetchData();- }, []);-- // Redirect to onboarding if user has no organisations after fetch completes- useEffect(() => {- if (hasFetchedOrgs && !isOrgLoading && organisations.length === 0) {- router.push("/onboarding");- }- }, [hasFetchedOrgs, isOrgLoading, organisations.length, router]);-- useEffect(() => {- if (currentOrg) {- setOrgName(currentOrg.name);- fetchMembers();- fetchProjects();- }- }, [currentOrg?.id]);-- const fetchMembers = async () => {- if (!currentOrg) return;-- setIsLoading(true);- const [err, data] = await asaw(- getData({- url: `/api/organisation/${currentOrg.id}/members`,- method: "GET",- })- );- setIsLoading(false);-- if (!err && data) {- setMembers(data.members || []);- setOrgPendingInvites(data.pendingInvites || []);- }- };-- const fetchProjects = async () => {- if (!currentOrg) return;-- setIsProjectsLoading(true);- const data = await fetchProjectList(currentOrg.id);- setIsProjectsLoading(false);-- if (Array.isArray(data)) {- setProjects(data);- }- };-- const handleCreateProject = async () => {- if (!currentOrg || !projectName.trim()) return;-- setIsCreatingProject(true);- const [err, data] = await asaw(- postData({- url: `/api/organisation/${currentOrg.id}/projects`,- data: { name: projectName.trim() },- })- );- setIsCreatingProject(false);-- if (err || data?.err) {- toast.error(err || data?.err || messages.ORGANISATION_PROJECT_CREATE_FAILED, {- id: "project-create",- });- return;- }-- toast.success(messages.ORGANISATION_PROJECT_CREATED, {- id: "project-create",- });- setProjectName("");- await fetchProjects();- };-- const handleUseProject = async (projectId: string) => {- await changeActiveProject(projectId, fetchProjects);- };-- const handleSaveName = async () => {- if (!currentOrg || !orgName.trim() || orgName === currentOrg.name) return;-- setIsSaving(true);- await updateOrganisation(currentOrg.id, orgName.trim());- setIsSaving(false);- };-- const handleInvite = async () => {- if (!currentOrg || !inviteEmail.trim()) return;-- setIsInviting(true);- await inviteToOrganisation(currentOrg.id, [inviteEmail.trim()], () => {- setInviteEmail("");- fetchMembers();- });- setIsInviting(false);- };-- const handleRemoveMember = async (userId: string) => {- if (!currentOrg) return;- await removeOrganisationMember(currentOrg.id, userId, fetchMembers);- };-- const handleCancelInvite = async (inviteId: string) => {- await cancelOrganisationInvitation(inviteId, fetchMembers);- };-- const handleUpdateRole = async (userId: string, role: string) => {- if (!currentOrg) return;- await updateMemberRole(currentOrg.id, userId, role, fetchMembers);- };-- const handleLeaveOrg = async () => {- if (!currentOrg || !currentUserId) return;-- await removeOrganisationMember(currentOrg.id, currentUserId, async () => {- await fetchOrganisationList();- // The server already sets the correct current org based on organisationUser.createdAt- // Only switch if no current org was set (edge case)- const state = useRootStore.getState().organisation;- const newCurrent = state.current;- if (!newCurrent && state.list && state.list.length > 0) {- // Fallback: use the org marked as current by the server, or first one if none marked- const serverSelected = state.list.find((org) => org.isCurrent) || state.list[0];- if (serverSelected) {- await changeActiveOrganisation(serverSelected.id);- }- }- });- };-- const handleDeleteOrg = async () => {- if (!currentOrg) return;-- await deleteOrganisation(currentOrg.id, async () => {- // The server already sets the correct current org based on organisationUser.createdAt- // Only switch if no current org was set (edge case)- const state = useRootStore.getState().organisation;- const newCurrent = state.current;- if (!newCurrent && state.list && state.list.length > 0) {- // Fallback: use the org marked as current by the server, or first one if none marked- const serverSelected = state.list.find((org) => org.isCurrent) || state.list[0];- if (serverSelected) {- await changeActiveOrganisation(serverSelected.id);- }- }- });- };-- const handleAcceptInvitation = async (invitationId: string) => {- await acceptInvitation(invitationId);- };-- const handleDeclineInvitation = async (invitationId: string) => {- await declineInvitation(invitationId);- };-- return (- <div className="p-4 space-y-4 overflow-auto w-full text-stone-700 dark:text-stone-300">- <div className="flex items-center justify-between">- <div>- <h1 className="text-xl font-bold">{messages.ORGANISATION_SETTINGS}</h1>- <p className="text-sm text-muted-foreground">- {messages.ORGANISATION_SETTINGS_DESCRIPTION}- </p>- </div>- <Button onClick={() => setCreateDialogOpen(true)} size="sm">- <Building2 className="h-3.5 w-3.5 mr-1.5" />- {messages.NEW_ORGANISATION}- </Button>- </div>-- {pendingInvitations.length > 0 && (- <Card className="border-primary/20 bg-primary/5 dark:border-primary/30 dark:bg-primary/10">- <CardHeader className="pb-3">- <CardTitle className="text-base flex items-center gap-2">- <Mail className="h-4 w-4" />- {messages.PENDING_INVITATIONS}- </CardTitle>- </CardHeader>- <CardContent className="space-y-2">- {pendingInvitations.map((invitation) => (- <div- key={invitation.id}- className="flex items-center justify-between p-2 border border-stone-200 dark:border-stone-800 rounded-md bg-background"- >- <p className="text-sm font-medium">{invitation.organisationName}</p>- <div className="flex gap-1">- <Button- size="sm"- variant="ghost"- className="h-7 w-7 p-0"- onClick={() => handleDeclineInvitation(invitation.id)}- >- <X className="h-3.5 w-3.5" />- </Button>- <Button- size="sm"- className="h-7"- onClick={() => handleAcceptInvitation(invitation.id)}- >- <Check className="h-3.5 w-3.5 mr-1" />- {messages.JOIN}- </Button>- </div>- </div>- ))}- </CardContent>- </Card>- )}-- {currentOrg && (- <Tabs defaultValue={searchParams.get("tab") === "projects" ? "projects" : "details"} className="w-auto">- <TabsList className="w-auto justify-start p-0 h-auto">- <TabsTrigger value="details" className="text-xs text-stone-700 dark:text-stone-300">- <Settings className="h-3.5 w-3.5 mr-1.5" />- {messages.DETAILS}- </TabsTrigger>- <TabsTrigger value="projects" className="text-xs text-stone-700 dark:text-stone-300">- <FolderKanban className="h-3.5 w-3.5 mr-1.5" />- {messages.PROJECTS} ({projects.length})- </TabsTrigger>- <TabsTrigger value="members" className="text-xs text-stone-700 dark:text-stone-300">- <Users className="h-3.5 w-3.5 mr-1.5" />- {messages.MEMBERS} ({members.length})- </TabsTrigger>- {orgPendingInvites.length > 0 && (- <TabsTrigger value="pending" className="text-xs text-stone-700 dark:text-stone-300">- <Clock className="h-3.5 w-3.5 mr-1.5" />- {messages.PENDING} ({orgPendingInvites.length})- </TabsTrigger>- )}- <TabsTrigger value="all" className="text-xs text-stone-700 dark:text-stone-300">- <Building2 className="h-3.5 w-3.5 mr-1.5" />- {messages.ORGANISATIONS}- </TabsTrigger>- </TabsList>-- <TabsContent value="details" className="space-y-4 mt-0">- {hasAdminPermissions ? (- <div className="space-y-3 py-4">- <div className="space-y-1.5">- <Label htmlFor="org-name" className="text-sm">- {messages.ORGANISATION_NAME}- </Label>- <div className="flex gap-2">- <Input- id="org-name"- value={orgName}- onChange={(e) => setOrgName(e.target.value)}- className="h-9"- />- <Button- onClick={handleSaveName}- disabled={- isSaving ||- !orgName.trim() ||- orgName === currentOrg.name- }- size="sm"- className="h-9"- >- <Save className="h-3.5 w-3.5 mr-1.5" />- {isSaving ? messages.SAVING : messages.SAVE}- </Button>- </div>- </div>- </div>- ) : (- <div className="py-4">- <Card className="border-stone-200 dark:border-stone-800">- <CardContent className="pt-6">- <p className="text-sm text-muted-foreground">- {messages.INSUFFICIENT_PERMISSIONS}- </p>- </CardContent>- </Card>- </div>- )}-- {isCreator && (- <div className="border-t border-stone-200 dark:border-stone-800 pt-4 px-4 pb-4">- <div className="space-y-2">- <h4 className="text-sm font-medium text-destructive">- {messages.DANGER_ZONE}- </h4>- <p className="text-xs text-muted-foreground">- {messages.DANGER_ZONE_DESCRIPTION}- </p>- <AlertDialog>- <AlertDialogTrigger asChild>- <Button- variant="destructive"- size="sm"- className="h-8"- disabled={members.length > 1}- >- <Trash2 className="h-3.5 w-3.5 mr-1.5" />- {messages.DELETE_ORGANISATION}- </Button>- </AlertDialogTrigger>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>- {messages.DELETE_ORGANISATION}- </AlertDialogTitle>- <AlertDialogDescription>- {messages.DELETE_ORGANISATION_CONFIRMATION}- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>- {messages.CANCEL}- </AlertDialogCancel>- <AlertDialogAction onClick={handleDeleteOrg}>- {messages.DELETE}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- {members.length > 1 && (- <p className="text-xs text-stone-600 dark:text-stone-400">- {messages.ORGANISATION_DELETE_DESCRIPTION}- </p>- )}- </div>- </div>- )}- </TabsContent>-- <TabsContent value="projects" className="mt-0 p-0 pt-2">- <div className="mb-3 rounded-md border border-stone-200 bg-stone-50/60 p-3 dark:border-stone-800 dark:bg-stone-900/40">- <div className="mb-3 flex items-start justify-between gap-3">- <div>- <h3 className="text-sm font-medium text-stone-900 dark:text-stone-100">- {messages.ORGANISATION} / {messages.PROJECTS} / {messages.DB_CONFIG}- </h3>- <p className="text-xs text-muted-foreground">- {messages.PROJECT_DB_CONFIG_DESCRIPTION}- </p>- </div>- <Button- variant="outline"- size="sm"- className="h-8"- onClick={() => router.push("/settings/database-config")}- >- <Database className="mr-1.5 h-3.5 w-3.5" />- {messages.MANAGE_DB_CONFIG}- </Button>- </div>- {hasAdminPermissions ? (- <div className="flex gap-2">- <Input- id="project-name"- placeholder={messages.PROJECT_NAME_PLACEHOLDER}- value={projectName}- onChange={(event) => setProjectName(event.target.value)}- onKeyDown={(event) => {- if (event.key === "Enter") {- handleCreateProject();- }- }}- className="h-9"- />- <Button- onClick={handleCreateProject}- disabled={isCreatingProject || !projectName.trim()}- size="sm"- className="h-9 shrink-0"- >- <FolderKanban className="h-3.5 w-3.5 mr-1.5" />- {isCreatingProject ? messages.CREATING : messages.CREATE_ORGANISATION_PROJECT}- </Button>- </div>- ) : null}- </div>- {isProjectsLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 className="h-5 w-5 animate-spin" />- </div>- ) : projects.length === 0 ? (- <div className="py-4 text-sm text-muted-foreground">- {messages.NO_ORGANISATION_PROJECTS}- </div>- ) : (- <Table>- <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">- <TableRow className="text-xs">- <TableHead className="h-8 pl-2">{messages.PROJECT_NAME}</TableHead>- <TableHead className="h-8">{messages.SLUG}</TableHead>- <TableHead className="h-8">{messages.STATUS}</TableHead>- <TableHead className="h-8 text-right">{messages.DB_CONFIG}</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {projects.map((project) => (- <TableRow key={project.id} className="text-sm">- <TableCell className="py-2 pl-2 font-medium">- {project.name}- </TableCell>- <TableCell className="py-2 text-xs text-muted-foreground">- {project.slug}- </TableCell>- <TableCell className="py-2">- <div className="flex gap-1.5">- {project.isCurrent ? (- <Badge className="text-xs h-5 px-2">- {messages.CURRENT}- </Badge>- ) : null}- {project.isDefault ? (- <Badge variant="outline" className="text-xs h-5 px-2">- {messages.DEFAULT_PROJECT}- </Badge>- ) : null}- </div>- </TableCell>- <TableCell className="py-2 text-right">- <div className="flex justify-end gap-1.5">- {!project.isCurrent ? (- <Button- variant="outline"- size="sm"- className="h-7 px-2 text-xs"- onClick={() => handleUseProject(project.id)}- >- {messages.USE_PROJECT}- </Button>- ) : null}- <Button- variant="outline"- size="sm"- className="h-7 px-2 text-xs"- onClick={async () => {- if (!project.isCurrent) {- await handleUseProject(project.id);- }- router.push("/settings/database-config");- }}- >- {messages.MANAGE_DB_CONFIG}- </Button>- </div>- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- )}- </TabsContent>-- <TabsContent value="members" className="mt-0 p-0 pt-2">- {hasAdminPermissions ? (- <div className="space-y-1.5 mb-3">- <Label htmlFor="invite-email" className="text-sm">- {messages.INVITE_NEW_MEMBER}- </Label>- <div className="flex gap-2">- <Input- id="invite-email"- placeholder="[email protected]"- type="email"- value={inviteEmail}- onChange={(e) => setInviteEmail(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") {- handleInvite();- }- }}- className="h-9"- />- <Button- onClick={handleInvite}- disabled={isInviting || !inviteEmail.trim()}- size="sm"- className="h-9"- >- <UserPlus className="h-3.5 w-3.5 mr-1.5" />- {isInviting ? messages.INVITING : messages.INVITE}- </Button>- </div>- </div>- ) : null}- {isLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 className="h-5 w-5 animate-spin" />- </div>- ) : (- <Table>- <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">- <TableRow className="text-xs">- <TableHead className="h-8 pl-2">{messages.MEMBER}</TableHead>- <TableHead className="h-8">{messages.ROLE}</TableHead>- <TableHead className="h-8 text-right">- {messages.ACTIONS}- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {members.map((member) => (- <TableRow key={member.id} className="text-sm">- <TableCell className="py-2 pl-2">- <div>- <p className="font-medium">- {member.name || displayEmail(member.email)}- </p>- {member.name && (- <p className="text-xs text-muted-foreground">- {displayEmail(member.email)}- </p>- )}- </div>- </TableCell>- <TableCell className="py-2">- {member.isCreator ? (- <Badge- variant="secondary"- className="text-xs h-5 px-2"- >- <Crown className="h-3 w-3 mr-1" />- {messages.OWNER}- </Badge>- ) : hasAdminPermissions ? (- <Select- value={member.role}- onValueChange={(value) =>- handleUpdateRole(member.id, value)- }- >- <SelectTrigger className="h-7 w-auto text-xs">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="admin" className="text-xs">- {messages.ADMIN}- </SelectItem>- <SelectItem value="member" className="text-xs">- {messages.MEMBER}- </SelectItem>- </SelectContent>- </Select>- ) : (- <Badge variant="outline" className="text-xs h-5 px-2">- {member.role === "admin"- ? messages.ADMIN- : messages.MEMBER}- </Badge>- )}- </TableCell>- <TableCell className="py-2 text-right">- <div className="flex justify-end gap-1">- {!member.isCreator && hasAdminPermissions && (- <AlertDialog>- <AlertDialogTrigger asChild>- <Button- variant="ghost"- size="sm"- className="h-7 w-7 p-0 text-destructive"- >- <Trash2 className="h-3.5 w-3.5" />- </Button>- </AlertDialogTrigger>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>- {messages.REMOVE_MEMBER}- </AlertDialogTitle>- <AlertDialogDescription>- {messages.REMOVE_MEMBER_CONFIRMATION}- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>- {messages.CANCEL}- </AlertDialogCancel>- <AlertDialogAction- onClick={() =>- handleRemoveMember(member.id)- }- >- {messages.DELETE}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- )}- {member.id === currentUserId && !member.isCreator && (- <AlertDialog>- <AlertDialogTrigger asChild>- <Button- variant="ghost"- size="sm"- className="h-7 w-7 p-0 text-destructive"- >- <LogOut className="h-3.5 w-3.5" />- </Button>- </AlertDialogTrigger>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>- {messages.LEAVE_ORGANISATION}- </AlertDialogTitle>- <AlertDialogDescription>- {messages.LEAVE_ORGANISATION_CONFIRMATION}- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>- {messages.CANCEL}- </AlertDialogCancel>- <AlertDialogAction onClick={handleLeaveOrg}>- {messages.LEAVE}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- )}- </div>- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- )}- </TabsContent>-- {orgPendingInvites.length > 0 && (- <TabsContent value="pending" className="mt-0 p-4">- <Table>- <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">- <TableRow className="text-xs">- <TableHead className="h-8 pl-2">{messages.EMAIL}</TableHead>- <TableHead className="h-8">{messages.INVITED}</TableHead>- <TableHead className="h-8 text-right">- {messages.ACTIONS}- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {orgPendingInvites.map((invite) => (- <TableRow key={invite.id} className="text-sm">- <TableCell className="py-2 pl-2">- {displayEmail(invite.email)}- </TableCell>- <TableCell className="py-2 text-xs text-muted-foreground">- {new Date(invite.invitedAt).toLocaleDateString()}- </TableCell>- <TableCell className="py-2 text-right">- <Button- variant="ghost"- size="sm"- className="h-7 w-7 p-0 text-destructive"- onClick={() => handleCancelInvite(invite.id)}- >- <X className="h-3.5 w-3.5" />- </Button>- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </TabsContent>- )}-- <TabsContent value="all" className="mt-0 p-0 pt-2">- <Table>- <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">- <TableRow className="text-xs">- <TableHead className="h-8 pl-2">{messages.NAME}</TableHead>- <TableHead className="h-8">{messages.MEMBERS}</TableHead>- <TableHead className="h-8">{messages.STATUS}</TableHead>- <TableHead className="h-8 text-right">- {messages.ACTIONS}- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {organisations.map((org) => (- <TableRow key={org.id} className="text-sm">- <TableCell className="py-2 font-medium pl-2">- {org.name}- </TableCell>- <TableCell className="py-2 text-xs text-muted-foreground">- {org.memberCount} {messages.MEMBER}- {org.memberCount !== 1 ? "s" : ""}- </TableCell>- <TableCell className="py-2">- {org.isCurrent ? (- <Badge className="text-xs h-5 px-2">- {messages.ACTIVE}- </Badge>- ) : (- <span className="text-xs text-muted-foreground">-</span>- )}- </TableCell>- <TableCell className="py-2 text-right">- {!org.isCurrent && (- <Button- variant="outline"- size="sm"- className="h-7 text-xs"- onClick={() => changeActiveOrganisation(org.id)}- >- {messages.SWITCH_ORGANISATION}- </Button>- )}- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </TabsContent>- </Tabs>- )}-- <CreateOrganisationDialog- open={createDialogOpen}- onOpenChange={setCreateDialogOpen}- />- </div>- );+export default function OrganisationSettingsRedirect() {+ redirect("/organisation");}diff --git a/src/client/src/app/api/evaluation/offline/types/route.ts b/src/client/src/app/api/evaluation/offline/types/route.tsindex c9a5da9f..19d7153d 100644--- a/src/client/src/app/api/evaluation/offline/types/route.ts+++ b/src/client/src/app/api/evaluation/offline/types/route.ts@@ -4,34 +4,32 @@ import { getEvaluationConfigByDbConfigId } from "@/lib/platform/evaluation/confiimport getMessage from "@/constants/messages";import PostHogServer from "@/lib/posthog";import asaw from "@/utils/asaw";+import { errorResponse } from "@/helpers/server/response";export async function GET(request: Request) {const startTimestamp = Date.now();const authorizationHeader = request.headers.get("Authorization") || "";if (!authorizationHeader.startsWith("Bearer ")) {- return Response.json({ err: getMessage().NO_API_KEY }, { status: 401 });+ return errorResponse(getMessage().NO_API_KEY, 401);}const apiKey = authorizationHeader.replace(/^Bearer /, "").trim();if (!apiKey) {- return Response.json({ err: getMessage().NO_API_KEY }, { status: 401 });+ return errorResponse(getMessage().NO_API_KEY, 401);}const [keyErr, apiInfo] = await getAPIKeyInfo({ apiKey });if (keyErr || !apiInfo?.databaseConfigId) {- return Response.json({ err: getMessage().NO_API_KEY }, { status: 401 });+ return errorResponse(getMessage().NO_API_KEY, 401);}const [configErr, config] = await asaw(getEvaluationConfigByDbConfigId(apiInfo.databaseConfigId, true));if (configErr || !config?.id) {- return Response.json(- {- err: "Evaluation not configured. Set up evaluation in the OpenLIT dashboard first.",- eval_types: [],- configured: false,- },- { status: 200 }+ return errorResponse(+ "Evaluation not configured. Set up evaluation in the OpenLIT dashboard first.",+ 200,+ { eval_types: [], configured: false });}diff --git a/src/client/src/app/api/organisation/[id]/projects/route.ts b/src/client/src/app/api/organisation/[id]/projects/route.tsindex fec81ae5..cbe6af90 100644--- a/src/client/src/app/api/organisation/[id]/projects/route.ts+++ b/src/client/src/app/api/organisation/[id]/projects/route.ts@@ -57,9 +57,24 @@ export async function POST(request: Request,{ params }: { params: { id: string } }) {+ const messages = getMessage();+ const user = await getCurrentUser();+ if (!user) return Response.json(messages.UNAUTHORIZED_USER, { status: 401 });++ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId: params.id,+ userId: user.id,+ },+ },+ select: { id: true },+ });++ if (!membership) return Response.json(messages.ORGANISATION_NOT_FOUND, { status: 404 });+const formData = await readJson(request);const name = formData?.name?.trim();- const messages = getMessage();if (!name) return Response.json(messages.PROJECT_NAME_REQUIRED, { status: 400 });if (name.length > 120) {diff --git a/src/client/src/app/api/organisation/route.ts b/src/client/src/app/api/organisation/route.tsindex cb90b24e..91da2f24 100644--- a/src/client/src/app/api/organisation/route.ts+++ b/src/client/src/app/api/organisation/route.ts@@ -3,13 +3,12 @@ import {getOrganisationsByUser,} from "@/lib/organisation";import asaw from "@/utils/asaw";+import { errorResponse } from "@/helpers/server/response";export async function GET() {const [err, res] = await asaw(getOrganisationsByUser());if (err)- return Response.json(err, {- status: 400,- });+ return errorResponse(err);return Response.json(res);}@@ -19,17 +18,13 @@ export async function POST(request: Request) {const { name } = formData;if (!name) {- return Response.json("Name is required", {- status: 400,- });+ return errorResponse("Name is required");}const [err, res] = await asaw(createOrganisation(name));if (err)- return Response.json(err, {- status: 400,- });+ return errorResponse(err);return Response.json(res);}diff --git a/src/client/src/app/api/prompt/get/[id]/route.ts b/src/client/src/app/api/prompt/get/[id]/route.tsindex 1267b362..b5a4e04c 100644--- a/src/client/src/app/api/prompt/get/[id]/route.ts+++ b/src/client/src/app/api/prompt/get/[id]/route.ts@@ -1,4 +1,5 @@import { getPromptDetails } from "@/lib/platform/prompt";+import { errorResponse } from "@/helpers/server/response";import { NextRequest } from "next/server";export async function GET(request: NextRequest, context: any) {@@ -7,5 +8,7 @@ export async function GET(request: NextRequest, context: any) {const { id } = context.params || {};const res: any = await getPromptDetails(id, { version });+ if (res?.err) return errorResponse(res.err, 404);+return Response.json(res);}diff --git a/src/client/src/app/api/prompt/get/route.ts b/src/client/src/app/api/prompt/get/route.tsindex 07b43a60..c3dad098 100644--- a/src/client/src/app/api/prompt/get/route.ts+++ b/src/client/src/app/api/prompt/get/route.ts@@ -1,11 +1,10 @@import { getPrompts } from "@/lib/platform/prompt";+import { errorResponse } from "@/helpers/server/response";export async function POST() {const { err, data }: any = await getPrompts();if (err) {- return Response.json(err, {- status: 400,- });+ return errorResponse(err);}return Response.json(data);diff --git a/src/client/src/app/api/vault/get/route.ts b/src/client/src/app/api/vault/get/route.tsindex 16078e7a..3b1b4ae4 100644--- a/src/client/src/app/api/vault/get/route.ts+++ b/src/client/src/app/api/vault/get/route.ts@@ -1,5 +1,6 @@import { SecretGetFilters } from "@/types/vault";import { getSecrets } from "@/lib/platform/vault";+import { errorResponse } from "@/helpers/server/response";export async function POST(request: Request) {const formData = await request.json();@@ -11,9 +12,7 @@ export async function POST(request: Request) {const { err, data }: any = await getSecrets(filters);if (err) {- return Response.json(err, {- status: 400,- });+ return errorResponse(err);}return Response.json(data);diff --git a/src/client/src/components/(playground)/clickhouse-connectivity-wrapper.tsx b/src/client/src/components/(playground)/clickhouse-connectivity-wrapper.tsxindex c3d075e5..812ae059 100644--- a/src/client/src/components/(playground)/clickhouse-connectivity-wrapper.tsx+++ b/src/client/src/components/(playground)/clickhouse-connectivity-wrapper.tsx@@ -38,7 +38,7 @@ export default function ClickhouseConnectivityWrapper({ children }: { children:{pingDetails.error}</div><Link- href="/settings/database-config"+ href="/organisation"className="inline-flex my-2 border rounded md py-2 px-4 text-center bg-primary cursor-pointer text-white hover:bg-stone-950 outline-none self-start text-sm">Take me there!diff --git a/src/client/src/components/(playground)/database-config/database-config-page.tsx b/src/client/src/components/(playground)/database-config/database-config-page.tsxnew file mode 100644index 00000000..1912a0d8--- /dev/null+++ b/src/client/src/components/(playground)/database-config/database-config-page.tsx@@ -0,0 +1,390 @@+"use client";++import FormBuilder from "@/components/common/form-builder";+import DatabaseConfigTabs from "@/components/(playground)/database-config/database-config-tabs";+import { Button } from "@/components/ui/button";+import { DatabaseConfig, DatabaseConfigWithActive } from "@/constants/dbConfig";+import {+ changeActiveDatabaseConfig,+ deleteDatabaseConfig,+ fetchDatabaseConfigList,+} from "@/helpers/client/database-config";+import {+ getDatabaseConfigList,+ getDatabaseConfigListIsLoading,+} from "@/selectors/database-config";+import { useRootStore } from "@/store";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import { isNil, keyBy } from "lodash";+import { MouseEventHandler, useCallback, useState } from "react";+import { toast } from "sonner";+import { usePostHog } from "posthog-js/react";+import { CLIENT_EVENTS } from "@/constants/events";+import { DatabaseConfigTabItemProps } from "@/types/database-config";+import { FormBuilderEvent } from "@/types/form";+import { PRIMARY_BACKGROUND } from "@/constants/common-classes";+import getMessage from "@/constants/messages";++function ModifyDatabaseConfig({+ dbConfig,+ canCreate = true,+ canUpdate = true,+}: {+ dbConfig?: DatabaseConfigWithActive;+ canCreate?: boolean;+ canUpdate?: boolean;+}) {+ const posthog = usePostHog();+ const { fireRequest, isLoading } = useFetchWrapper();+ const messages = getMessage();++ const modifyDetails: FormBuilderEvent = useCallback(+ (event) => {+ event.preventDefault();+ const formElement = event.target as HTMLFormElement;++ toast.loading(messages.MODIFYING_DB_CONFIG, {+ id: "db-config-details",+ });++ const payload: DatabaseConfig = {+ id: dbConfig?.id || "",+ name: (formElement.name as any).value,+ environment: formElement.environment.value,+ username: formElement.username.value,+ host: formElement.host.value,+ port: formElement.port.value,+ database: formElement.database.value,+ query: formElement.query.value,+ };++ if (formElement.password.value) {+ payload.password = formElement.password.value;+ }++ fireRequest({+ body: JSON.stringify(payload),+ requestType: "POST",+ url: "/api/db-config",+ responseDataKey: "data",+ successCb: () => {+ fetchDatabaseConfigList((data: any[]) => {+ posthog?.capture(CLIENT_EVENTS.DB_CONFIG_LIST, {+ count: data.length,+ });+ });+ toast.success(messages.DB_CONFIG_UPDATED, {+ id: "db-config-details",+ });+ if (!dbConfig?.id) formElement.reset();+ posthog?.capture(+ payload.id+ ? CLIENT_EVENTS.DB_CONFIG_UPDATE_SUCCESS+ : CLIENT_EVENTS.DB_CONFIG_ADD_SUCCESS+ );+ },+ failureCb: (err?: string) => {+ toast.error(err || messages.DB_CONFIG_UPDATE_FAILED, {+ id: "db-config-details",+ });+ posthog?.capture(+ payload.id+ ? CLIENT_EVENTS.DB_CONFIG_UPDATE_FAILURE+ : CLIENT_EVENTS.DB_CONFIG_ADD_FAILURE+ );+ },+ });+ },+ [dbConfig?.id]+ );++ const formFieldsDisabled = dbConfig?.id+ ? !canUpdate || !dbConfig.permissions?.canEdit+ : !canCreate;++ return (+ <FormBuilder+ cardClassName={`${PRIMARY_BACKGROUND} py-4 px-6 rounded-none`}+ fields={[+ {+ label: messages.DB_CONFIG_FIELD_CONFIG_NAME,+ inputKey: `${dbConfig?.id}-name`,+ fieldType: "INPUT",+ fieldTypeProps: {+ type: "text",+ name: "name",+ placeholder: "db-config",+ defaultValue: dbConfig?.name,+ disabled: formFieldsDisabled,+ },+ },+ {+ label: messages.DB_CONFIG_FIELD_ENVIRONMENT,+ inputKey: `${dbConfig?.id}-environment`,+ fieldType: "INPUT",+ fieldTypeProps: {+ type: "text",+ name: "environment",+ placeholder: "production",+ defaultValue: dbConfig?.environment,+ disabled: formFieldsDisabled,+ },+ },+ {+ label: messages.DB_CONFIG_FIELD_USERNAME,+ fieldType: "INPUT",+ inputKey: `${dbConfig?.id}-username`,+ fieldTypeProps: {+ type: "text",+ name: "username",+ placeholder: "username",+ defaultValue: dbConfig?.username,+ disabled: formFieldsDisabled,+ },+ },+ {+ label: messages.DB_CONFIG_FIELD_PASSWORD,+ inputKey: `${dbConfig?.id}-password`,+ fieldType: "INPUT",+ fieldTypeProps: {+ type: "password",+ name: "password",+ placeholder: "*******",+ disabled: formFieldsDisabled,+ },+ },+ {+ label: messages.DB_CONFIG_FIELD_HOST,+ inputKey: `${dbConfig?.id}-host`,+ fieldType: "INPUT",+ fieldTypeProps: {+ type: "text",+ name: "host",+ placeholder: "127.0.0.1",+ defaultValue: dbConfig?.host,+ disabled: formFieldsDisabled,+ },+ },+ {+ label: messages.DB_CONFIG_FIELD_PORT,+ inputKey: `${dbConfig?.id}-port`,+ fieldType: "INPUT",+ fieldTypeProps: {+ type: "number",+ name: "port",+ placeholder: "8123",+ defaultValue: dbConfig?.port,+ disabled: formFieldsDisabled,+ },+ },+ {+ label: messages.DB_CONFIG_FIELD_DATABASE,+ inputKey: `${dbConfig?.id}-database`,+ fieldType: "INPUT",+ fieldTypeProps: {+ type: "text",+ name: "database",+ placeholder: "default",+ defaultValue: dbConfig?.database,+ disabled: formFieldsDisabled,+ },+ },+ {+ label: messages.DB_CONFIG_FIELD_QUERY_PARAMS,+ inputKey: `${dbConfig?.id}-query`,+ fieldType: "INPUT",+ fieldTypeProps: {+ type: "text",+ name: "query",+ placeholder: "a=b&c=d",+ defaultValue: dbConfig?.query,+ disabled: formFieldsDisabled,+ },+ },+ ]}+ heading={+ dbConfig?.id+ ? !dbConfig?.permissions?.canEdit+ ? messages.DATABASE_CONFIG+ : messages.UPDATE_DB_CONFIG+ : messages.ADD_DB_CONFIG+ }+ subHeading={+ !dbConfig?.id || dbConfig?.permissions?.canEdit+ ? ""+ : messages.DB_CONFIG_EDIT_PERMISSION_REQUIRED+ }+ subHeadingClass="text-error"+ isLoading={isLoading}+ onSubmit={modifyDetails}+ isAllowedToSubmit={+ dbConfig?.id+ ? canUpdate && !!dbConfig.permissions?.canEdit+ : canCreate+ }+ submitButtonText={dbConfig?.id ? messages.UPDATE : messages.SAVE}+ />+ );+}+function DatabaseList({+ dbConfigs,+ isLoadingList,+ canCreate,+ canSelect,+ canUpdate,+ canDelete,+ canShare,+}: {+ dbConfigs: DatabaseConfigWithActive[];+ isLoadingList: boolean;+ canCreate: boolean;+ canSelect: boolean;+ canUpdate: boolean;+ canDelete: boolean;+ canShare: boolean;+}) {+ const posthog = usePostHog();+ const messages = getMessage();+ const [selectedDBConfigId, setSelectedDBConfigId] = useState<+ string | undefined+ >();++ const dbConfigByKey = keyBy(dbConfigs, "id");++ const onClickDB: MouseEventHandler<HTMLDivElement | HTMLButtonElement> = (+ event+ ) => {+ const parent = (event.target as HTMLElement).closest(+ ".item-element-card"+ ) as HTMLElement;+ if (!parent) return null;+ const { itemId = "" } = parent.dataset;+ setSelectedDBConfigId(itemId);+ };++ const onClickDelete: MouseEventHandler<SVGSVGElement> = (event) => {+ event.stopPropagation();+ const parent = (event.target as HTMLElement).closest(+ ".item-element-card"+ ) as HTMLElement;+ if (!parent) return null;+ const { itemId = "" } = parent.dataset;++ if (itemId) deleteDatabaseConfig(itemId);+ };++ const onClickSetCurrent: MouseEventHandler<HTMLDivElement> = (event) => {+ event.stopPropagation();+ const parent = (event.target as HTMLElement).closest(+ ".item-element-card"+ ) as HTMLElement;+ if (!parent) return null;+ const { itemId = "" } = parent.dataset;++ if (itemId) {+ toast.loading(+ messages.DB_CONFIG_SET_ACTIVE(dbConfigByKey[itemId].name),+ {+ id: "db-config-current",+ }+ );+ changeActiveDatabaseConfig(itemId, () => {+ posthog?.capture(CLIENT_EVENTS.DB_CONFIG_ACTION_CHANGE);+ });+ }+ };++ const items: DatabaseConfigTabItemProps[] = dbConfigs.map((dbConfig) => ({+ id: dbConfig.id,+ name: dbConfig.name,+ badge: dbConfig.environment,+ isCurrent: !!dbConfig.isCurrent,+ canDelete: canDelete && !!dbConfig.permissions?.canDelete,+ canEdit: canUpdate && !!dbConfig.permissions?.canEdit,+ canShare: canShare && !!dbConfig.permissions?.canShare,+ canSelect,+ }));++ return (+ <div className="flex w-full flex-1 relative">+ <DatabaseConfigTabs+ addButton={canCreate}+ items={items}+ onClickTab={onClickDB}+ selectedTabId={selectedDBConfigId || ""}+ onClickItemChangeActive={onClickSetCurrent}+ onClickItemDelete={onClickDelete}+ />+ <div className="flex flex-1 w-full h-full overflow-hidden">+ {selectedDBConfigId ? (+ <ModifyDatabaseConfig+ dbConfig={dbConfigByKey[selectedDBConfigId]}+ canCreate={canCreate}+ canUpdate={canUpdate}+ />+ ) : (+ <div className="flex flex-1 items-center justify-center">+ <div className="flex flex-col items-center gap-1 text-center">+ <h3 className="text-2xl font-bold tracking-tight text-stone-900 dark:text-stone-100">+ {dbConfigs.length === 0+ ? messages.DB_CONFIG_EMPTY_TITLE+ : messages.DB_CONFIG_NOT_SELECTED_TITLE}+ </h3>+ <p className="text-sm text-stone-700 dark:text-stone-300">+ {dbConfigs.length === 0+ ? messages.DB_CONFIG_EMPTY_DESCRIPTION+ : messages.DB_CONFIG_NOT_SELECTED_DESCRIPTION}+ </p>+ {dbConfigs.length !== 0 && canCreate && (+ <Button+ className="mt-4 item-element-card"+ data-item-id={"ADD_NEW_ID"}+ onClick={onClickDB}+ >+ {messages.ADD_DATABASE_CONFIG}+ </Button>+ )}+ </div>+ </div>+ )}+ </div>+ {isLoadingList && (+ <div className="flex absolute w-full left-0 top-0 h-full animate-pulse z-10" />+ )}+ </div>+ );+}++export default function Database({+ canCreate = true,+ canSelect = true,+ canUpdate = true,+ canDelete = true,+ canShare = true,+}: {+ canCreate?: boolean;+ canSelect?: boolean;+ canUpdate?: boolean;+ canDelete?: boolean;+ canShare?: boolean;+}) {+ const messages = getMessage();+ const databaseList = useRootStore(getDatabaseConfigList);+ const databaseListIsLoading = useRootStore(getDatabaseConfigListIsLoading);++ return isNil(databaseList) ? (+ <div className="flex items-center justify-center w-full h-full animate-pulse dark:text-white">+ {messages.OBSERVABILITY_LOADING}+ </div>+ ) : (+ <DatabaseList+ dbConfigs={(databaseList as DatabaseConfigWithActive[]) || []}+ isLoadingList={databaseListIsLoading}+ canCreate={canCreate}+ canSelect={canSelect}+ canUpdate={canUpdate}+ canDelete={canDelete}+ canShare={canShare}+ />+ );+}diff --git a/src/client/src/app/(playground)/settings/database-config/database-config-tabs.tsx b/src/client/src/components/(playground)/database-config/database-config-tabs.tsxsimilarity index 81%rename from src/client/src/app/(playground)/settings/database-config/database-config-tabs.tsxrename to src/client/src/components/(playground)/database-config/database-config-tabs.tsxindex 1d3d4946..b833caf4 100644--- a/src/client/src/app/(playground)/settings/database-config/database-config-tabs.tsx+++ b/src/client/src/components/(playground)/database-config/database-config-tabs.tsx@@ -9,12 +9,13 @@ import { Trash2 } from "lucide-react";import ShareDialog from "./share-dialog";import { Checkbox } from "@/components/ui/checkbox";import { DatabaseConfigTabsProps } from "@/types/database-config";+import getMessage from "@/constants/messages";const ADD_NEW_ID = "ADD_NEW_ID";const getCommonCardClasses = (isActive: boolean) =>- `item-element-card flex flex-col p-4 text-sm cursor-pointer relative group w-64 hover:bg-primary/30 dark:hover:bg-primary/30 ${- isActive ? "bg-primary/30 dark:bg-primary/40 text-stone-700 dark:text-stone-200" : "text-stone-700 dark:text-stone-300"+ `item-element-card flex flex-col p-4 text-sm cursor-pointer relative group w-64 hover:bg-primary/10 dark:hover:bg-primary/20 ${+ isActive ? "bg-primary/15 dark:bg-primary/25 text-stone-900 dark:text-stone-100" : "text-stone-700 dark:text-stone-300"}`;export default function DatabaseConfigTabs({@@ -25,8 +26,10 @@ export default function DatabaseConfigTabs({onClickItemChangeActive,addButton,}: DatabaseConfigTabsProps) {+ const messages = getMessage();+return (- <div className="flex flex-col overflow-hidden border-r dark:border-stone-800">+ <div className="flex max-h-full shrink-0 flex-col overflow-hidden border-r border-stone-200 dark:border-stone-800">{addButton && (<><div@@ -36,7 +39,7 @@ export default function DatabaseConfigTabs({data-item-id={ADD_NEW_ID}onClick={onClickTab}>- Add New Config+ {messages.ADD_NEW_CONFIG}</div><hr className="dark:border-stone-800" /></>@@ -70,15 +73,22 @@ export default function DatabaseConfigTabs({<div className="flex flex-col h-full space-y-1 items-end"><Tooltip><TooltipTrigger asChild>- <div onClick={onClickItemChangeActive}>+ <div+ onClick={+ item.canSelect === false+ ? undefined+ : onClickItemChangeActive+ }+ ><Checkboxchecked={!!item.isCurrent}+ disabled={item.canSelect === false}className="data-[state=checked]:bg-primary dark:data-[state=checked]:bg-primary text-white data-[state=checked]:border-primary dark:data-[state=checked]:border-primary data-[state=checked]:ring-offset-primary dark:text-white data-[state=checked]:text-white dark:data-[state=checked]:text-white"/></div></TooltipTrigger><TooltipContent side="bottom" sideOffset={5}>- Mark {item.name} as the active database config+ {messages.MARK_DB_CONFIG_ACTIVE(item.name)}</TooltipContent></Tooltip>{item.canDelete && onClickItemDelete && (diff --git a/src/client/src/app/(playground)/settings/database-config/share-dialog.tsx b/src/client/src/components/(playground)/database-config/share-dialog.tsxsimilarity index 87%rename from src/client/src/app/(playground)/settings/database-config/share-dialog.tsxrename to src/client/src/components/(playground)/database-config/share-dialog.tsxindex 8a692499..c200c230 100644--- a/src/client/src/app/(playground)/settings/database-config/share-dialog.tsx+++ b/src/client/src/components/(playground)/database-config/share-dialog.tsx@@ -27,6 +27,7 @@ import { set } from "lodash";import useFetchWrapper from "@/utils/hooks/useFetchWrapper";import { DatabaseConfigPermissions } from "@/constants/dbConfig";import { escapeEmailForDisplay } from "@/utils/string";+import getMessage from "@/constants/messages";const validateEmail = (email: string) => {return String(email)@@ -50,6 +51,7 @@ export default function ShareDialog({}[]>([]);const { fireRequest, isLoading } = useFetchWrapper();+ const messages = getMessage();const emailRef = useRef<HTMLInputElement>(null);@@ -71,7 +73,7 @@ export default function ShareDialog({return;}- toast.error("Email invalid!", {+ toast.error(messages.EMAIL_INVALID, {id: "share-db-config",});};@@ -91,14 +93,14 @@ export default function ShareDialog({requestType: "POST",url: "/api/db-config/share",responseDataKey: "data",- successCb: (res) => {- toast.success("Db config shared!", {+ successCb: () => {+ toast.success(messages.DB_CONFIG_SHARED, {id: "share-db-config",});resetData();},failureCb: (err?: string) => {- toast.error(err || "Db config shared failed!", {+ toast.error(err || messages.DB_CONFIG_SHARE_FAILED, {id: "db-config-details",});},@@ -122,10 +124,9 @@ export default function ShareDialog({</DialogTrigger><DialogContent className=""><DialogHeader>- <DialogTitle>Share Database config</DialogTitle>+ <DialogTitle>{messages.SHARE_DATABASE_CONFIG}</DialogTitle><DialogDescription>- You can share the selected database config to multiple users with- different permissions.+ {messages.SHARE_DATABASE_CONFIG_DESCRIPTION}</DialogDescription></DialogHeader><div className="flex items-center space-x-2">@@ -133,7 +134,7 @@ export default function ShareDialog({id="email"name="email"className="dark:text-stone-200"- placeholder="Add an email..."+ placeholder={messages.ADD_EMAIL_PLACEHOLDER}ref={emailRef}/><Button@@ -142,17 +143,17 @@ export default function ShareDialog({className="px-3"onClick={onEnterEmail}>- <span className="sr-only">Enter</span>+ <span className="sr-only">{messages.ENTER}</span><CornerDownLeft className="h-4 w-4" /></Button></div><Table><TableHeader><TableRow>- <TableHead>Email</TableHead>- <TableHead className="text-center">Edit</TableHead>- <TableHead className="text-center">Delete</TableHead>- <TableHead className="text-center">Share</TableHead>+ <TableHead>{messages.EMAIL}</TableHead>+ <TableHead className="text-center">{messages.EDIT}</TableHead>+ <TableHead className="text-center">{messages.DELETE}</TableHead>+ <TableHead className="text-center">{messages.SHARE}</TableHead></TableRow></TableHeader><TableBody>@@ -206,11 +207,11 @@ export default function ShareDialog({</Table><DialogFooter className="justify-end"><Button type="button" variant="default" onClick={shareRequest}>- Share+ {messages.SHARE}</Button><DialogClose asChild><Button type="button" variant="secondary">- Close+ {messages.CLOSE}</Button></DialogClose></DialogFooter>diff --git a/src/client/src/components/(playground)/feature-page-header.tsx b/src/client/src/components/(playground)/feature-page-header.tsxnew file mode 100644index 00000000..15ec6125--- /dev/null+++ b/src/client/src/components/(playground)/feature-page-header.tsx@@ -0,0 +1,47 @@+import type { ReactNode } from "react";++type FeaturePageHeaderProps = {+ eyebrow: string;+ title: string;+ description?: string;+ icon: ReactNode;+ tone?: string;+ actions?: ReactNode;+};++export default function FeaturePageHeader({+ eyebrow,+ title,+ description,+ icon,+ tone = "border-stone-200 bg-stone-50 text-stone-700 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-200",+ actions,+}: FeaturePageHeaderProps) {+ return (+ <section className="rounded-md border border-stone-200 bg-white px-3 py-2 dark:border-stone-800 dark:bg-stone-950">+ <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span className={`rounded-md border p-1.5 ${tone}`}>+ {icon}+ </span>+ <div>+ <p className="text-[11px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {eyebrow}+ </p>+ <h1 className="text-base font-semibold text-stone-950 dark:text-stone-50">+ {title}+ </h1>+ {description ? (+ <p className="mt-0.5 text-xs text-stone-600 dark:text-stone-300">+ {description}+ </p>+ ) : null}+ </div>+ </div>+ </div>+ {actions ? <div className="shrink-0">{actions}</div> : null}+ </div>+ </section>+ );+}diff --git a/src/client/src/components/(playground)/header-project-switch.tsx b/src/client/src/components/(playground)/header-project-switch.tsxindex 9ecb2c58..08a1072f 100644--- a/src/client/src/components/(playground)/header-project-switch.tsx+++ b/src/client/src/components/(playground)/header-project-switch.tsx@@ -74,7 +74,7 @@ export default function HeaderProjectSwitch() {<DropdownMenuSeparator /><DropdownMenuItemonSelect={() => {- router.push("/settings/organisation?tab=projects");+ router.push("/organisation");}}>{messages.MANAGE_PROJECTS}diff --git a/src/client/src/components/(playground)/organisation/organisation-page.tsx b/src/client/src/components/(playground)/organisation/organisation-page.tsxnew file mode 100644index 00000000..8420ef62--- /dev/null+++ b/src/client/src/components/(playground)/organisation/organisation-page.tsx@@ -0,0 +1,896 @@+"use client";++import { useState, useEffect } from "react";+import { usePostHog } from "posthog-js/react";+import { CLIENT_EVENTS } from "@/constants/events";+import { useRouter, useSearchParams } from "next/navigation";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import { Badge } from "@/components/ui/badge";+import {+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from "@/components/ui/tabs";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ Building2,+ Mail,+ Check,+ X,+ Trash2,+ UserPlus,+ Crown,+ LogOut,+ Loader2,+ Save,+ Users,+ Settings,+ Clock,+ FolderKanban,+ Database,+} from "lucide-react";+import { useRootStore } from "@/store";+import {+ getCurrentOrganisation,+ getOrganisationList,+ getOrganisationPendingInvitations,+ getOrganisationIsLoading,+} from "@/selectors/organisation";+import { getCurrentUserId } from "@/selectors/user";+import {+ updateOrganisation,+ deleteOrganisation,+ inviteToOrganisation,+ acceptInvitation,+ declineInvitation,+ removeOrganisationMember,+ cancelOrganisationInvitation,+ fetchOrganisationList,+ fetchPendingInvitations,+ changeActiveOrganisation,+ updateMemberRole,+} from "@/helpers/client/organisation";+import {+ changeActiveProject,+ fetchProjectList,+} from "@/helpers/client/project";+import { getData, postData } from "@/utils/api";+import asaw from "@/utils/asaw";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";+import CreateOrganisationDialog from "@/components/(playground)/sidebar/create-organisation-dialog";+import getMessage from "@/constants/messages";+import { escapeEmailForDisplay } from "@/utils/string";+import { toast } from "sonner";++interface Member {+ id: string;+ email: string;+ name: string | null;+ image: string | null;+ isCreator: boolean;+ role: "owner" | "admin" | "member";+ joinedAt: string;+}++interface PendingInvite {+ id: string;+ email: string;+ invitedAt: string;+}++interface Project {+ id: string;+ name: string;+ slug: string;+ isDefault: boolean;+ isCurrent: boolean;+ createdAt: string;+}++export default function OrganisationSettingsPage() {+ const posthog = usePostHog();+ const router = useRouter();+ const searchParams = useSearchParams();+ const messages = getMessage();+ const currentOrg = useRootStore(getCurrentOrganisation);+ const organisations = useRootStore(getOrganisationList) || [];+ const pendingInvitations = useRootStore(getOrganisationPendingInvitations);+ const currentUserId = useRootStore(getCurrentUserId);+ const isOrgLoading = useRootStore(getOrganisationIsLoading);++ const [orgName, setOrgName] = useState("");+ const [inviteEmail, setInviteEmail] = useState("");+ const [members, setMembers] = useState<Member[]>([]);+ const [orgPendingInvites, setOrgPendingInvites] = useState<PendingInvite[]>(+ []+ );+ const [isLoading, setIsLoading] = useState(false);+ const [isSaving, setIsSaving] = useState(false);+ const [isInviting, setIsInviting] = useState(false);+ const [createDialogOpen, setCreateDialogOpen] = useState(false);+ const [hasFetchedOrgs, setHasFetchedOrgs] = useState(false);+ const [projects, setProjects] = useState<Project[]>([]);+ const [projectName, setProjectName] = useState("");+ const [isProjectsLoading, setIsProjectsLoading] = useState(false);+ const [isCreatingProject, setIsCreatingProject] = useState(false);++ const isCreator = currentOrg?.createdByUserId === currentUserId;++ // Get current user's role and permissions+ const currentUserMember = members.find(m => m.id === currentUserId);+ const currentUserRole = currentUserMember?.role;+ const hasAdminPermissions = currentUserRole === 'owner' || currentUserRole === 'admin';+ const displayEmail = (email: string) => escapeEmailForDisplay(email);++ useEffect(() => {+ posthog?.capture(CLIENT_EVENTS.SETTINGS_ORGANISATION_PAGE_VISITED);+ }, []);++ // Fetch organisations on mount+ useEffect(() => {+ const fetchData = async () => {+ await fetchOrganisationList();+ await fetchPendingInvitations();+ setHasFetchedOrgs(true);+ };+ fetchData();+ }, []);++ // Redirect to onboarding if user has no organisations after fetch completes+ useEffect(() => {+ if (hasFetchedOrgs && !isOrgLoading && organisations.length === 0) {+ router.push("/onboarding");+ }+ }, [hasFetchedOrgs, isOrgLoading, organisations.length, router]);++ useEffect(() => {+ if (currentOrg) {+ setOrgName(currentOrg.name);+ fetchMembers();+ fetchProjects();+ }+ }, [currentOrg?.id]);++ const fetchMembers = async () => {+ if (!currentOrg) return;++ setIsLoading(true);+ const [err, data] = await asaw(+ getData({+ url: `/api/organisation/${currentOrg.id}/members`,+ method: "GET",+ })+ );+ setIsLoading(false);++ if (!err && data) {+ setMembers(data.members || []);+ setOrgPendingInvites(data.pendingInvites || []);+ }+ };++ const fetchProjects = async () => {+ if (!currentOrg) return;++ setIsProjectsLoading(true);+ const data = await fetchProjectList(currentOrg.id);+ setIsProjectsLoading(false);++ if (Array.isArray(data)) {+ setProjects(data);+ }+ };++ const handleCreateProject = async () => {+ if (!currentOrg || !projectName.trim()) return;++ setIsCreatingProject(true);+ const [err, data] = await asaw(+ postData({+ url: `/api/organisation/${currentOrg.id}/projects`,+ data: { name: projectName.trim() },+ })+ );+ setIsCreatingProject(false);++ if (err || data?.err) {+ toast.error(err || data?.err || messages.ORGANISATION_PROJECT_CREATE_FAILED, {+ id: "project-create",+ });+ return;+ }++ toast.success(messages.ORGANISATION_PROJECT_CREATED, {+ id: "project-create",+ });+ setProjectName("");+ await fetchProjects();+ };++ const handleUseProject = async (projectId: string) => {+ await changeActiveProject(projectId, fetchProjects);+ };++ const handleSaveName = async () => {+ if (!currentOrg || !orgName.trim() || orgName === currentOrg.name) return;++ setIsSaving(true);+ await updateOrganisation(currentOrg.id, orgName.trim());+ setIsSaving(false);+ };++ const handleInvite = async () => {+ if (!currentOrg || !inviteEmail.trim()) return;++ setIsInviting(true);+ await inviteToOrganisation(currentOrg.id, [inviteEmail.trim()], () => {+ setInviteEmail("");+ fetchMembers();+ });+ setIsInviting(false);+ };++ const handleRemoveMember = async (userId: string) => {+ if (!currentOrg) return;+ await removeOrganisationMember(currentOrg.id, userId, fetchMembers);+ };++ const handleCancelInvite = async (inviteId: string) => {+ await cancelOrganisationInvitation(inviteId, fetchMembers);+ };++ const handleUpdateRole = async (userId: string, role: string) => {+ if (!currentOrg) return;+ await updateMemberRole(currentOrg.id, userId, role, fetchMembers);+ };++ const handleLeaveOrg = async () => {+ if (!currentOrg || !currentUserId) return;++ await removeOrganisationMember(currentOrg.id, currentUserId, async () => {+ await fetchOrganisationList();+ // The server already sets the correct current org based on organisationUser.createdAt+ // Only switch if no current org was set (edge case)+ const state = useRootStore.getState().organisation;+ const newCurrent = state.current;+ if (!newCurrent && state.list && state.list.length > 0) {+ // Fallback: use the org marked as current by the server, or first one if none marked+ const serverSelected = state.list.find((org) => org.isCurrent) || state.list[0];+ if (serverSelected) {+ await changeActiveOrganisation(serverSelected.id);+ }+ }+ });+ };++ const handleDeleteOrg = async () => {+ if (!currentOrg) return;++ await deleteOrganisation(currentOrg.id, async () => {+ // The server already sets the correct current org based on organisationUser.createdAt+ // Only switch if no current org was set (edge case)+ const state = useRootStore.getState().organisation;+ const newCurrent = state.current;+ if (!newCurrent && state.list && state.list.length > 0) {+ // Fallback: use the org marked as current by the server, or first one if none marked+ const serverSelected = state.list.find((org) => org.isCurrent) || state.list[0];+ if (serverSelected) {+ await changeActiveOrganisation(serverSelected.id);+ }+ }+ });+ };++ const handleAcceptInvitation = async (invitationId: string) => {+ await acceptInvitation(invitationId);+ };++ const handleDeclineInvitation = async (invitationId: string) => {+ await declineInvitation(invitationId);+ };++ return (+ <div className="p-4 space-y-4 overflow-auto w-full text-stone-700 dark:text-stone-300">+ <div className="flex items-center justify-between">+ <div>+ <h1 className="text-xl font-bold">{messages.ORGANISATION_SETTINGS}</h1>+ <p className="text-sm text-muted-foreground">+ {messages.ORGANISATION_SETTINGS_DESCRIPTION}+ </p>+ </div>+ <Button onClick={() => setCreateDialogOpen(true)} size="sm">+ <Building2 className="h-3.5 w-3.5 mr-1.5" />+ {messages.NEW_ORGANISATION}+ </Button>+ </div>++ {pendingInvitations.length > 0 && (+ <Card className="border-primary/20 bg-primary/5 dark:border-primary/30 dark:bg-primary/10">+ <CardHeader className="pb-3">+ <CardTitle className="text-base flex items-center gap-2">+ <Mail className="h-4 w-4" />+ {messages.PENDING_INVITATIONS}+ </CardTitle>+ </CardHeader>+ <CardContent className="space-y-2">+ {pendingInvitations.map((invitation) => (+ <div+ key={invitation.id}+ className="flex items-center justify-between p-2 border border-stone-200 dark:border-stone-800 rounded-md bg-background"+ >+ <p className="text-sm font-medium">{invitation.organisationName}</p>+ <div className="flex gap-1">+ <Button+ size="sm"+ variant="ghost"+ className="h-7 w-7 p-0"+ onClick={() => handleDeclineInvitation(invitation.id)}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ <Button+ size="sm"+ className="h-7"+ onClick={() => handleAcceptInvitation(invitation.id)}+ >+ <Check className="h-3.5 w-3.5 mr-1" />+ {messages.JOIN}+ </Button>+ </div>+ </div>+ ))}+ </CardContent>+ </Card>+ )}++ {currentOrg && (+ <Tabs defaultValue={searchParams.get("tab") === "projects" ? "projects" : "details"} className="w-auto">+ <TabsList className="w-auto justify-start p-0 h-auto">+ <TabsTrigger value="details" className="text-xs text-stone-700 dark:text-stone-300">+ <Settings className="h-3.5 w-3.5 mr-1.5" />+ {messages.DETAILS}+ </TabsTrigger>+ <TabsTrigger value="projects" className="text-xs text-stone-700 dark:text-stone-300">+ <FolderKanban className="h-3.5 w-3.5 mr-1.5" />+ {messages.PROJECTS} ({projects.length})+ </TabsTrigger>+ <TabsTrigger value="members" className="text-xs text-stone-700 dark:text-stone-300">+ <Users className="h-3.5 w-3.5 mr-1.5" />+ {messages.MEMBERS} ({members.length})+ </TabsTrigger>+ {orgPendingInvites.length > 0 && (+ <TabsTrigger value="pending" className="text-xs text-stone-700 dark:text-stone-300">+ <Clock className="h-3.5 w-3.5 mr-1.5" />+ {messages.PENDING} ({orgPendingInvites.length})+ </TabsTrigger>+ )}+ <TabsTrigger value="all" className="text-xs text-stone-700 dark:text-stone-300">+ <Building2 className="h-3.5 w-3.5 mr-1.5" />+ {messages.ORGANISATIONS}+ </TabsTrigger>+ </TabsList>++ <TabsContent value="details" className="space-y-4 mt-0">+ {hasAdminPermissions ? (+ <div className="space-y-3 py-4">+ <div className="space-y-1.5">+ <Label htmlFor="org-name" className="text-sm">+ {messages.ORGANISATION_NAME}+ </Label>+ <div className="flex gap-2">+ <Input+ id="org-name"+ value={orgName}+ onChange={(e) => setOrgName(e.target.value)}+ className="h-9"+ />+ <Button+ onClick={handleSaveName}+ disabled={+ isSaving ||+ !orgName.trim() ||+ orgName === currentOrg.name+ }+ size="sm"+ className="h-9"+ >+ <Save className="h-3.5 w-3.5 mr-1.5" />+ {isSaving ? messages.SAVING : messages.SAVE}+ </Button>+ </div>+ </div>+ </div>+ ) : (+ <div className="py-4">+ <Card className="border-stone-200 dark:border-stone-800">+ <CardContent className="pt-6">+ <p className="text-sm text-muted-foreground">+ {messages.INSUFFICIENT_PERMISSIONS}+ </p>+ </CardContent>+ </Card>+ </div>+ )}++ {isCreator && (+ <div className="border-t border-stone-200 dark:border-stone-800 pt-4 px-4 pb-4">+ <div className="space-y-2">+ <h4 className="text-sm font-medium text-destructive">+ {messages.DANGER_ZONE}+ </h4>+ <p className="text-xs text-muted-foreground">+ {messages.DANGER_ZONE_DESCRIPTION}+ </p>+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button+ variant="destructive"+ size="sm"+ className="h-8"+ disabled={members.length > 1}+ >+ <Trash2 className="h-3.5 w-3.5 mr-1.5" />+ {messages.DELETE_ORGANISATION}+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {messages.DELETE_ORGANISATION}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {messages.DELETE_ORGANISATION_CONFIRMATION}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>+ {messages.CANCEL}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleDeleteOrg}>+ {messages.DELETE}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ {members.length > 1 && (+ <p className="text-xs text-stone-600 dark:text-stone-400">+ {messages.ORGANISATION_DELETE_DESCRIPTION}+ </p>+ )}+ </div>+ </div>+ )}+ </TabsContent>++ <TabsContent value="projects" className="mt-0 p-0 pt-2">+ <div className="mb-3 rounded-md border border-stone-200 bg-stone-50/60 p-3 dark:border-stone-800 dark:bg-stone-900/40">+ <div className="mb-3 flex items-start justify-between gap-3">+ <div>+ <h3 className="text-sm font-medium text-stone-900 dark:text-stone-100">+ {messages.ORGANISATION} / {messages.PROJECTS} / {messages.DB_CONFIG}+ </h3>+ <p className="text-xs text-muted-foreground">+ {messages.PROJECT_DB_CONFIG_DESCRIPTION}+ </p>+ </div>+ <Button+ variant="outline"+ size="sm"+ className="h-8"+ onClick={() => {+ const currentProject = projects.find((project) => project.isCurrent) || projects[0];+ router.push(+ currentProject ? `/organisation/project/${currentProject.id}` : "/organisation"+ );+ }}+ >+ <Database className="mr-1.5 h-3.5 w-3.5" />+ {messages.MANAGE_DB_CONFIG}+ </Button>+ </div>+ {hasAdminPermissions ? (+ <div className="flex gap-2">+ <Input+ id="project-name"+ placeholder={messages.PROJECT_NAME_PLACEHOLDER}+ value={projectName}+ onChange={(event) => setProjectName(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ handleCreateProject();+ }+ }}+ className="h-9"+ />+ <Button+ onClick={handleCreateProject}+ disabled={isCreatingProject || !projectName.trim()}+ size="sm"+ className="h-9 shrink-0"+ >+ <FolderKanban className="h-3.5 w-3.5 mr-1.5" />+ {isCreatingProject ? messages.CREATING : messages.CREATE_ORGANISATION_PROJECT}+ </Button>+ </div>+ ) : null}+ </div>+ {isProjectsLoading ? (+ <div className="flex items-center justify-center py-8">+ <Loader2 className="h-5 w-5 animate-spin" />+ </div>+ ) : projects.length === 0 ? (+ <div className="py-4 text-sm text-muted-foreground">+ {messages.NO_ORGANISATION_PROJECTS}+ </div>+ ) : (+ <Table>+ <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">+ <TableRow className="text-xs">+ <TableHead className="h-8 pl-2">{messages.PROJECT_NAME}</TableHead>+ <TableHead className="h-8">{messages.SLUG}</TableHead>+ <TableHead className="h-8">{messages.STATUS}</TableHead>+ <TableHead className="h-8 text-right">{messages.DB_CONFIG}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {projects.map((project) => (+ <TableRow key={project.id} className="text-sm">+ <TableCell className="py-2 pl-2 font-medium">+ {project.name}+ </TableCell>+ <TableCell className="py-2 text-xs text-muted-foreground">+ {project.slug}+ </TableCell>+ <TableCell className="py-2">+ <div className="flex gap-1.5">+ {project.isCurrent ? (+ <Badge className="text-xs h-5 px-2">+ {messages.CURRENT}+ </Badge>+ ) : null}+ {project.isDefault ? (+ <Badge variant="outline" className="text-xs h-5 px-2">+ {messages.DEFAULT_PROJECT}+ </Badge>+ ) : null}+ </div>+ </TableCell>+ <TableCell className="py-2 text-right">+ <div className="flex justify-end gap-1.5">+ {!project.isCurrent ? (+ <Button+ variant="outline"+ size="sm"+ className="h-7 px-2 text-xs"+ onClick={() => handleUseProject(project.id)}+ >+ {messages.USE_PROJECT}+ </Button>+ ) : null}+ <Button+ variant="outline"+ size="sm"+ className="h-7 px-2 text-xs"+ onClick={async () => {+ if (!project.isCurrent) {+ await handleUseProject(project.id);+ }+ router.push(`/organisation/project/${project.id}`);+ }}+ >+ {messages.MANAGE_DB_CONFIG}+ </Button>+ </div>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}+ </TabsContent>++ <TabsContent value="members" className="mt-0 p-0 pt-2">+ {hasAdminPermissions ? (+ <div className="space-y-1.5 mb-3">+ <Label htmlFor="invite-email" className="text-sm">+ {messages.INVITE_NEW_MEMBER}+ </Label>+ <div className="flex gap-2">+ <Input+ id="invite-email"+ placeholder="[email protected]"+ type="email"+ value={inviteEmail}+ onChange={(e) => setInviteEmail(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ handleInvite();+ }+ }}+ className="h-9"+ />+ <Button+ onClick={handleInvite}+ disabled={isInviting || !inviteEmail.trim()}+ size="sm"+ className="h-9"+ >+ <UserPlus className="h-3.5 w-3.5 mr-1.5" />+ {isInviting ? messages.INVITING : messages.INVITE}+ </Button>+ </div>+ </div>+ ) : null}+ {isLoading ? (+ <div className="flex items-center justify-center py-8">+ <Loader2 className="h-5 w-5 animate-spin" />+ </div>+ ) : (+ <Table>+ <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">+ <TableRow className="text-xs">+ <TableHead className="h-8 pl-2">{messages.MEMBER}</TableHead>+ <TableHead className="h-8">{messages.ROLE}</TableHead>+ <TableHead className="h-8 text-right">+ {messages.ACTIONS}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {members.map((member) => (+ <TableRow key={member.id} className="text-sm">+ <TableCell className="py-2 pl-2">+ <div>+ <p className="font-medium">+ {member.name || displayEmail(member.email)}+ </p>+ {member.name && (+ <p className="text-xs text-muted-foreground">+ {displayEmail(member.email)}+ </p>+ )}+ </div>+ </TableCell>+ <TableCell className="py-2">+ {member.isCreator ? (+ <Badge+ variant="secondary"+ className="text-xs h-5 px-2"+ >+ <Crown className="h-3 w-3 mr-1" />+ {messages.OWNER}+ </Badge>+ ) : hasAdminPermissions ? (+ <Select+ value={member.role}+ onValueChange={(value) =>+ handleUpdateRole(member.id, value)+ }+ >+ <SelectTrigger className="h-7 w-auto text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="admin" className="text-xs">+ {messages.ADMIN}+ </SelectItem>+ <SelectItem value="member" className="text-xs">+ {messages.MEMBER}+ </SelectItem>+ </SelectContent>+ </Select>+ ) : (+ <Badge variant="outline" className="text-xs h-5 px-2">+ {member.role === "admin"+ ? messages.ADMIN+ : messages.MEMBER}+ </Badge>+ )}+ </TableCell>+ <TableCell className="py-2 text-right">+ <div className="flex justify-end gap-1">+ {!member.isCreator && hasAdminPermissions && (+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="h-7 w-7 p-0 text-destructive"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {messages.REMOVE_MEMBER}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {messages.REMOVE_MEMBER_CONFIRMATION}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>+ {messages.CANCEL}+ </AlertDialogCancel>+ <AlertDialogAction+ onClick={() =>+ handleRemoveMember(member.id)+ }+ >+ {messages.DELETE}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )}+ {member.id === currentUserId && !member.isCreator && (+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="h-7 w-7 p-0 text-destructive"+ >+ <LogOut className="h-3.5 w-3.5" />+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {messages.LEAVE_ORGANISATION}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {messages.LEAVE_ORGANISATION_CONFIRMATION}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>+ {messages.CANCEL}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleLeaveOrg}>+ {messages.LEAVE}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )}+ </div>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}+ </TabsContent>++ {orgPendingInvites.length > 0 && (+ <TabsContent value="pending" className="mt-0 p-4">+ <Table>+ <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">+ <TableRow className="text-xs">+ <TableHead className="h-8 pl-2">{messages.EMAIL}</TableHead>+ <TableHead className="h-8">{messages.INVITED}</TableHead>+ <TableHead className="h-8 text-right">+ {messages.ACTIONS}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {orgPendingInvites.map((invite) => (+ <TableRow key={invite.id} className="text-sm">+ <TableCell className="py-2 pl-2">+ {displayEmail(invite.email)}+ </TableCell>+ <TableCell className="py-2 text-xs text-muted-foreground">+ {new Date(invite.invitedAt).toLocaleDateString()}+ </TableCell>+ <TableCell className="py-2 text-right">+ <Button+ variant="ghost"+ size="sm"+ className="h-7 w-7 p-0 text-destructive"+ onClick={() => handleCancelInvite(invite.id)}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </TabsContent>+ )}++ <TabsContent value="all" className="mt-0 p-0 pt-2">+ <Table>+ <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">+ <TableRow className="text-xs">+ <TableHead className="h-8 pl-2">{messages.NAME}</TableHead>+ <TableHead className="h-8">{messages.MEMBERS}</TableHead>+ <TableHead className="h-8">{messages.STATUS}</TableHead>+ <TableHead className="h-8 text-right">+ {messages.ACTIONS}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {organisations.map((org) => (+ <TableRow key={org.id} className="text-sm">+ <TableCell className="py-2 font-medium pl-2">+ {org.name}+ </TableCell>+ <TableCell className="py-2 text-xs text-muted-foreground">+ {org.memberCount} {messages.MEMBER}+ {org.memberCount !== 1 ? "s" : ""}+ </TableCell>+ <TableCell className="py-2">+ {org.isCurrent ? (+ <Badge className="text-xs h-5 px-2">+ {messages.ACTIVE}+ </Badge>+ ) : (+ <span className="text-xs text-muted-foreground">-</span>+ )}+ </TableCell>+ <TableCell className="py-2 text-right">+ {!org.isCurrent && (+ <Button+ variant="outline"+ size="sm"+ className="h-7 text-xs"+ onClick={() => changeActiveOrganisation(org.id)}+ >+ {messages.SWITCH_ORGANISATION}+ </Button>+ )}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </TabsContent>+ </Tabs>+ )}++ <CreateOrganisationDialog+ open={createDialogOpen}+ onOpenChange={setCreateDialogOpen}+ />+ </div>+ );+}diff --git a/src/client/src/components/(playground)/organisation/project-page-header.tsx b/src/client/src/components/(playground)/organisation/project-page-header.tsxnew file mode 100644index 00000000..b236f3d6--- /dev/null+++ b/src/client/src/components/(playground)/organisation/project-page-header.tsx@@ -0,0 +1,13 @@+"use client";++import Link from "next/link";+import { ArrowLeft, FolderKanban } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import FeaturePageHeader from "@/components/(playground)/feature-page-header";+import getMessage from "@/constants/messages";++export default function ProjectPageHeader({ project }: { project?: { name?: string; isCurrent?: boolean; isDefault?: boolean } }) {+ const messages = getMessage();+ return <FeaturePageHeader eyebrow={messages.ORGANISATION} title={project?.name || messages.LOADING_PROJECT} description={messages.PROJECT_DETAILS_DESCRIPTION} icon={<FolderKanban className="h-4 w-4" />} tone="border-primary/20 bg-primary/10 text-primary dark:border-primary/30" actions={<div className="flex flex-wrap items-center gap-2"><Button asChild variant="outline" size="sm" className="h-8"><Link href="/organisation"><ArrowLeft className="mr-1.5 h-3.5 w-3.5" />{messages.BACK_TO_ORGANISATION}</Link></Button>{project?.isCurrent ? <Badge className="h-6">{messages.CURRENT}</Badge> : null}{project?.isDefault ? <Badge variant="outline" className="h-6">{messages.DEFAULT_PROJECT}</Badge> : null}</div>} />;+}diff --git a/src/client/src/components/(playground)/organisation/project-page.tsx b/src/client/src/components/(playground)/organisation/project-page.tsxnew file mode 100644index 00000000..7932d783--- /dev/null+++ b/src/client/src/components/(playground)/organisation/project-page.tsx@@ -0,0 +1,108 @@+"use client";++import { useEffect, useMemo } from "react";+import { usePathname, useRouter, useSearchParams } from "next/navigation";+import { Database, FolderKanban } from "lucide-react";+import DatabaseConfigPage from "@/components/(playground)/database-config/database-config-page";+import ProjectPageHeader from "./project-page-header";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { getCurrentOrganisation } from "@/selectors/organisation";+import { getCurrentProject, getProjectList } from "@/selectors/project";+import { changeActiveProject, fetchProjectList } from "@/helpers/client/project";+import { useRootStore } from "@/store";+import getMessage from "@/constants/messages";++export default function OrganisationProjectPage({+ projectId,+}: {+ projectId: string;+}) {+ const messages = getMessage();+ const currentOrg = useRootStore(getCurrentOrganisation);+ const router = useRouter();+ const pathname = usePathname();+ const searchParams = useSearchParams();+ const projects = useRootStore(getProjectList) || [];+ const currentProject = useRootStore(getCurrentProject);+ const project = useMemo(+ () => projects.find((item) => item.id === projectId),+ [projectId, projects]+ );+ const selectedTab = searchParams.get("tab") === "database" ? "database" : "overview";+ const setSelectedTab = (tab: string) => {+ const params = new URLSearchParams(searchParams.toString());+ if (tab === "overview") params.delete("tab");+ else params.set("tab", tab);+ router.replace(`${pathname}${params.size ? `?${params}` : ""}`);+ };++ useEffect(() => {+ if (currentOrg?.id) fetchProjectList(currentOrg.id);+ }, [currentOrg?.id]);++ useEffect(() => {+ if (project?.id && currentProject?.id !== project.id) {+ changeActiveProject(project.id);+ }+ }, [currentProject?.id, project?.id]);++ return (+ <div className="flex h-full w-full flex-col gap-4 overflow-auto p-3 text-stone-700 dark:text-stone-300">+ <ProjectPageHeader project={project} />++ <Tabs value={selectedTab} onValueChange={setSelectedTab} className="flex min-h-0 w-full flex-1 flex-col">+ <TabsList className="h-auto w-full justify-start rounded-md border border-stone-200 bg-white p-1 dark:border-stone-800 dark:bg-stone-950 md:w-auto">+ <TabsTrigger value="overview" className="gap-1.5 text-xs"><FolderKanban className="h-3.5 w-3.5" />{messages.PROJECT_OVERVIEW}</TabsTrigger>+ <TabsTrigger value="database" className="gap-1.5 text-xs"><Database className="h-3.5 w-3.5" />{messages.PROJECT_DATABASE_CONFIGS}</TabsTrigger>+ </TabsList>+ <TabsContent value="overview" className="mt-0 data-[state=active]:mt-3">+ <section className="rounded-md border border-stone-200 bg-white p-4 dark:border-stone-800 dark:bg-stone-950">+ <div className="mb-4 flex items-center gap-2">+ <FolderKanban className="h-4 w-4 text-primary" />+ <h2 className="text-sm font-semibold text-stone-950 dark:text-stone-50">+ {messages.PROJECT_DETAILS}+ </h2>+ </div>+ <div className="space-y-3 text-sm">+ <div>+ <p className="text-xs uppercase text-muted-foreground">+ {messages.PROJECT_NAME}+ </p>+ <p className="font-medium text-stone-950 dark:text-stone-50">+ {project?.name || "-"}+ </p>+ </div>+ <div>+ <p className="text-xs uppercase text-muted-foreground">+ {messages.SLUG}+ </p>+ <p className="font-mono text-xs text-stone-700 dark:text-stone-300">+ {project?.slug || "-"}+ </p>+ </div>+ </div>+ </section>+ </TabsContent>++ <TabsContent value="database" className="mt-0 data-[state=active]:mt-3">+ <section className="min-h-[520px] overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950">+ <div className="border-b border-stone-200 p-4 dark:border-stone-800">+ <div className="flex items-center gap-2">+ <Database className="h-4 w-4 text-primary" />+ <h2 className="text-sm font-semibold text-stone-950 dark:text-stone-50">+ {messages.PROJECT_DATABASE_CONFIGS}+ </h2>+ </div>+ <p className="mt-1 text-xs text-muted-foreground">+ {messages.PROJECT_DATABASE_CONFIGS_DESCRIPTION}+ </p>+ </div>+ <div className="flex h-[clamp(360px,calc(100dvh-320px),620px)] min-h-0 overflow-hidden">+ <DatabaseConfigPage />+ </div>+ </section>+ </TabsContent>+ </Tabs>+ </div>+ );+}diff --git a/src/client/src/components/(playground)/sidebar/database-config-switch.tsx b/src/client/src/components/(playground)/sidebar/database-config-switch.tsxindex f28fd777..e2372226 100644--- a/src/client/src/components/(playground)/sidebar/database-config-switch.tsx+++ b/src/client/src/components/(playground)/sidebar/database-config-switch.tsx@@ -1,4 +1,5 @@import { getDatabaseConfigList } from "@/selectors/database-config";+import { getCurrentProject } from "@/selectors/project";import { useRootStore } from "@/store";import { useEffect } from "react";import {@@ -31,7 +32,11 @@ export default function DatabaseConfigSwitch({const router = useRouter();const messages = getMessage();const list = useRootStore(getDatabaseConfigList) || [];+ const currentProject = useRootStore(getCurrentProject);const activeDatabase = list.find((item) => !!item.isCurrent);+ const manageDbConfigHref = currentProject?.id+ ? `/organisation/project/${currentProject.id}`+ : "/organisation";const onClickItem = (id: string) => {changeActiveDatabaseConfig(id, () => {posthog?.capture(CLIENT_EVENTS.DB_CONFIG_ACTION_CHANGE);@@ -52,7 +57,7 @@ export default function DatabaseConfigSwitch({<Buttonvariant="outline"className={cn(triggerClasses, className)}- onClick={() => router.push("/settings/database-config")}+ onClick={() => router.push(manageDbConfigHref)}><span className="min-w-0 truncate text-xs font-medium">{messages.MANAGE_DB_CONFIG}@@ -96,7 +101,7 @@ export default function DatabaseConfigSwitch({))}<DropdownMenuSeparator /><DropdownMenuItem className="py-1.5 pl-8 pr-2">- <Link href="/settings/database-config" className=" flex items-center">+ <Link href={manageDbConfigHref} className=" flex items-center">{messages.ADD_NEW_CONFIG}</Link></DropdownMenuItem>diff --git a/src/client/src/components/(playground)/sidebar/index.tsx b/src/client/src/components/(playground)/sidebar/index.tsxindex 035d4b1f..4c2a8b1b 100644--- a/src/client/src/components/(playground)/sidebar/index.tsx+++ b/src/client/src/components/(playground)/sidebar/index.tsx@@ -1,6 +1,6 @@"use client";import Image from "next/image";-import { usePathname } from "next/navigation";+import { usePathname, useSearchParams } from "next/navigation";import Link from "next/link";import {Tooltip,@@ -18,7 +18,11 @@ import { Accordion, AccordionTrigger, AccordionItem, AccordionContent } from "@/import { PRIMARY_BACKGROUND } from "@/constants/common-classes";import getMessage from "@/constants/messages";-const getIfSidebarItemClasses = (pathname: string, item: SidebarItemProps) => {+const getIfSidebarItemClasses = (+ pathname: string,+ item: SidebarItemProps,+ currentUrl = pathname+) => {const commonClasses = "flex gap-2 group-data-[state=open]:w-auto group-data-[state=open]:justify-start p-2.5 font-normal ";const activeClasses = "text-white bg-primary dark:bg-primary dark:text-white [&]:hover:bg-primary [&]:dark:hover:bg-primary hover:text-white [&>.external-icon-svg]:fill-white [&>.external-icon-svg]:dark:fill-white ";const inactiveClasses = "text-stone-500 dark:text-stone-300 hover:bg-stone-700 dark:hover:bg-stone-600 hover:text-white [&>.external-icon-svg]:fill-stone-500 [&>.external-icon-svg]:dark:fill-stone-300 [&>.external-icon-svg]:hover:fill-white ";@@ -27,7 +31,11 @@ const getIfSidebarItemClasses = (pathname: string, item: SidebarItemProps) => {return `${inactiveClasses}${commonClasses}`;if(item.link) {- if (["/home", "/dashboard", "/telemetry", "/requests", "/exceptions", "/prompt-hub", "/vault", "/openground", "/settings"].includes(item.link)) {+ if (item.link.includes("?")) {+ return currentUrl.startsWith(item.link) ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;+ }++ if (["/home", "/dashboard", "/telemetry", "/requests", "/exceptions", "/prompt-hub", "/vault", "/openground", "/organisation", "/settings"].includes(item.link)) {return pathname.startsWith(item.link) ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;}@@ -61,6 +69,8 @@ const getIfSidebarItemClasses = (pathname: string, item: SidebarItemProps) => {return pathname.startsWith("/vault") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;case "/openground":return pathname.startsWith("/openground") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;+ case "/organisation":+ return pathname.startsWith("/organisation") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;case "/settings":return pathname.startsWith("/settings") ? `${activeClasses}${commonClasses}` : `${inactiveClasses}${commonClasses}`;default:@@ -109,7 +119,17 @@ const SidebarActionItemComponent = ({ item, className }: { item: SidebarActionIt);}-const SidebarItem = ({ item, className, pathname }: { item: SidebarItemProps, className?: string, pathname: string }) => {+const SidebarItem = ({+ item,+ className,+ pathname,+ currentUrl,+}: {+ item: SidebarItemProps;+ className?: string;+ pathname: string;+ currentUrl: string;+}) => {if (item.type === "section") {return (<Accordion@@ -135,7 +155,7 @@ const SidebarItem = ({ item, className, pathname }: { item: SidebarItemProps, cl</AccordionTrigger><AccordionContent className="flex flex-col pb-0">{item.children?.map((child, index) => (- <SidebarActionItemComponent key={`sidebar-${item.title}-${index}`} item={child} className={getIfSidebarItemClasses(pathname, child)} />+ <SidebarActionItemComponent key={`sidebar-${item.title}-${index}`} item={child} className={getIfSidebarItemClasses(pathname, child, currentUrl)} />))}</AccordionContent></AccordionItem>@@ -148,8 +168,11 @@ const SidebarItem = ({ item, className, pathname }: { item: SidebarItemProps, clexport default function Sidebar() {const pathname = usePathname();+ const searchParams = useSearchParams();const messages = getMessage();const [isExpanded, setIsExpanded] = useState<boolean>(true);+ const queryString = searchParams.toString();+ const currentUrl = queryString ? `${pathname}?${queryString}` : pathname;const toggleExpansion = () => setIsExpanded(e => !e);@@ -180,9 +203,10 @@ export default function Sidebar() {{SIDEBAR_ITEMS.map((item, index) => (<SidebarItemkey={`sidebar-top-${index}`}- className={getIfSidebarItemClasses(pathname, item)}+ className={getIfSidebarItemClasses(pathname, item, currentUrl)}item={item}pathname={pathname}+ currentUrl={currentUrl}/>))}</nav>diff --git a/src/client/src/components/(playground)/sidebar/organisation-switch.tsx b/src/client/src/components/(playground)/sidebar/organisation-switch.tsxindex 5b8af40a..23a6a216 100644--- a/src/client/src/components/(playground)/sidebar/organisation-switch.tsx+++ b/src/client/src/components/(playground)/sidebar/organisation-switch.tsx@@ -104,7 +104,7 @@ export default function OrganisationSwitch({<><DropdownMenuItem className="py-1.5 pl-8 pr-2"><Link- href="/settings/organisation"+ href="/organisation"className="flex items-center gap-2"><Mail className="size-4" />@@ -126,7 +126,7 @@ export default function OrganisationSwitch({</DropdownMenuItem><DropdownMenuItem className="py-1.5 pl-8 pr-2"><Link- href="/settings/organisation"+ href="/organisation"className="flex items-center w-full">{messages.MANAGE_ORGANISATIONS}diff --git a/src/client/src/components/common/app-init.tsx b/src/client/src/components/common/app-init.tsxindex a116548c..64fdaa0a 100644--- a/src/client/src/components/common/app-init.tsx+++ b/src/client/src/components/common/app-init.tsx@@ -8,12 +8,17 @@ import {fetchPendingInvitations,} from "@/helpers/client/organisation";import { getIsUserFetched } from "@/selectors/user";-import { getOrganisationList } from "@/selectors/organisation";+import {+ getCurrentOrganisation,+ getOrganisationList,+} from "@/selectors/organisation";import { useRootStore } from "@/store";+import { onOrganisationChanged } from "@/features/organisation";export default function AppInit() {const isFetched = useRootStore(getIsUserFetched);const organisationList = useRootStore(getOrganisationList);+ const currentOrg = useRootStore(getCurrentOrganisation);const isOrgLoading = useRootStore((state) => state.organisation.isLoading);@@ -27,6 +32,12 @@ export default function AppInit() {}}, [isFetched]);+ useEffect(() => {+ if (currentOrg?.id) {+ onOrganisationChanged(currentOrg.id);+ }+ }, [currentOrg?.id]);+// Redirect to onboarding if user has no organisationsuseEffect(() => {if (diff --git a/src/client/src/components/enterprise-feature-access-provider.tsx b/src/client/src/components/enterprise-feature-access-provider.tsxnew file mode 100644index 00000000..c9aae561--- /dev/null+++ b/src/client/src/components/enterprise-feature-access-provider.tsx@@ -0,0 +1,28 @@+"use client";++import type { ReactNode } from "react";+import type { EnterpriseFeatureAccessSnapshot } from "@/lib/enterprise-feature-access";++export function EnterpriseFeatureAccessProvider({+ children,+}: {+ children: ReactNode;+ snapshot: EnterpriseFeatureAccessSnapshot;+}) {+ return <>{children}</>;+}++export function EnterpriseFeatureRouteGate({ children }: { children: ReactNode }) {+ return <>{children}</>;+}++export function useEnterpriseFeatureAccess() {+ return {+ accounts: [],+ selectedAccountId: "",+ selectedAccount: null,+ accessByAccountId: {},+ setSelectedAccountId: () => {},+ hasFeatureAccess: () => true,+ };+}diff --git a/src/client/src/components/rbac/feature-access.tsx b/src/client/src/components/rbac/feature-access.tsxnew file mode 100644index 00000000..232c8c3f--- /dev/null+++ b/src/client/src/components/rbac/feature-access.tsx@@ -0,0 +1,16 @@+"use client";++import type { ReactNode } from "react";++export type FeatureAccessKey = string;++type FeatureAccessProps = {+ access: FeatureAccessKey;+ children: ReactNode;+ requireProject?: boolean;+ hideWhenDenied?: boolean;+};++export default function FeatureAccess({ children }: FeatureAccessProps) {+ return <>{children}</>;+}diff --git a/src/client/src/components/rbac/otter-page-access.tsx b/src/client/src/components/rbac/otter-page-access.tsxnew file mode 100644index 00000000..8324100e--- /dev/null+++ b/src/client/src/components/rbac/otter-page-access.tsx@@ -0,0 +1,11 @@+"use client";++import type { ReactNode } from "react";++type OtterPageAccessProps = {+ children: ReactNode;+};++export default function OtterPageAccess({ children }: OtterPageAccessProps) {+ return <>{children}</>;+}diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.tsindex 999b29c5..d835eead 100644--- a/src/client/src/constants/messages/en.ts+++ b/src/client/src/constants/messages/en.ts@@ -2,6 +2,7 @@ export const DATABASE_CONFIG_NOT_FOUND = "No database config present!";export const UNAUTHORIZED_USER = "Unauthorized user!";export const FORBIDDEN_ACTION = "You do not have permission to perform this action.";export const NO_ORGANISATION_SELECTED = "No active organisation. Switch organisations to continue.";+export const ORGANISATION_CONTEXT_REQUIRED = "Organisation context required";export const MALFORMED_INPUTS = "Malformed input! Please check the docs";export const OPERATION_FAILED = "Operation failed!";@@ -1000,9 +1001,50 @@ export const LOG_OUT = "Log out";export const EXPAND = "Expand";export const DATABASES = "Databases";export const DATABASE_CONFIG = "Database Config";+export const API_KEYS = "API Keys";+export const USER_PROFILE = "User Profile";export const DB_CONFIG = "DB Config";export const ADD_NEW_CONFIG = "Add New Config";export const MANAGE_DB_CONFIG = "Manage DB Config";+export const MODIFYING_DB_CONFIG = "Modifying database config...";+export const DB_CONFIG_UPDATED = "Database config updated";+export const DB_CONFIG_UPDATE_FAILED = "Database config update failed";+export const DB_CONFIG_SET_ACTIVE = (name: string) =>+ `Database config: ${name} is being set active`;+export const DB_CONFIG_FIELD_CONFIG_NAME = "Config Name";+export const DB_CONFIG_FIELD_ENVIRONMENT = "Environment";+export const DB_CONFIG_FIELD_USERNAME = "Username";+export const DB_CONFIG_FIELD_PASSWORD = "Password";+export const DB_CONFIG_FIELD_HOST = "Host";+export const DB_CONFIG_FIELD_PORT = "Port";+export const DB_CONFIG_FIELD_DATABASE = "Database";+export const DB_CONFIG_FIELD_QUERY_PARAMS = "Query params";+export const UPDATE_DB_CONFIG = "Update Database config";+export const ADD_DB_CONFIG = "Add Database config";+export const DB_CONFIG_EDIT_PERMISSION_REQUIRED =+ "You don't have enough permissions to edit this database config";+export const UPDATE = "Update";+export const DB_CONFIG_EMPTY_TITLE = "You have not created any database config";+export const DB_CONFIG_NOT_SELECTED_TITLE =+ "You have not selected any database config";+export const DB_CONFIG_EMPTY_DESCRIPTION =+ "You can have multiple database configs to manage different environments.";+export const DB_CONFIG_NOT_SELECTED_DESCRIPTION =+ "Select a database config to update its details.";+export const ADD_DATABASE_CONFIG = "Add database config";+export const MARK_DB_CONFIG_ACTIVE = (name: string) =>+ `Mark ${name} as the active database config`;+export const SHARE_DATABASE_CONFIG = "Share Database config";+export const SHARE_DATABASE_CONFIG_DESCRIPTION =+ "You can share the selected database config with multiple users and permissions.";+export const ADD_EMAIL_PLACEHOLDER = "Add an email...";+export const ENTER = "Enter";+export const SHARE = "Share";+export const EMAIL_INVALID = "Email invalid";+export const EMAIL_REQUIRED = "Email is required";+export const INVALID_EMAIL_FORMAT = "Invalid email format";+export const DB_CONFIG_SHARED = "Database config shared";+export const DB_CONFIG_SHARE_FAILED = "Database config share failed";export const PENDING_INVITATION = "Pending Invitation";// Organisation@@ -1029,6 +1071,16 @@ export const CURRENT_DB_CONFIG_SET_SUCCESS ="Current DB config set successfully!";export const PROJECT_DB_CONFIG_DESCRIPTION ="Projects group database configs inside an organisation. Select a project before managing its database config.";+export const BACK_TO_ORGANISATION = "Back to Organisation";+export const PROJECT_DETAILS = "Project details";+export const PROJECT_DETAILS_DESCRIPTION =+ "Review project identity, current status, and database configuration.";+export const PROJECT_DATABASE_CONFIGS = "Database configurations";+export const PROJECT_DATABASE_CONFIGS_DESCRIPTION =+ "Create, select, and update database configs scoped to this project.";+export const PROJECT_MEMBER_ACCESS = "Project member access";+export const PROJECT_MEMBER_ACCESS_DESCRIPTION =+ "Control which organisation members can access this project.";export const USE_PROJECT = "Use project";export const ORGANISATION_NAME = "Organisation Name";export const ORGANISATION_NAME_PLACEHOLDER = "My Company";@@ -1036,8 +1088,8 @@ export const CREATE_ORGANISATION = "Create Organisation";export const NEW_ORGANISATION = "New Organisation";export const MANAGE_ORGANISATIONS = "Manage Organisations";export const SWITCH_ORGANISATION = "Switch Organisation";-export const ORGANISATION_SETTINGS = "Organisation Settings";-export const ORGANISATION_SETTINGS_DESCRIPTION = "Manage your organisations and team members";+export const ORGANISATION_SETTINGS = "Organisation";+export const ORGANISATION_SETTINGS_DESCRIPTION = "Manage organisation details, projects, database configs, and members";export const CURRENT_ORGANISATION = "Current Organisation";export const UPDATE_ORGANISATION_DETAILS = "Update your organisation details";export const YOUR_ORGANISATIONS = "Your Organisations";@@ -1091,6 +1143,7 @@ export const INACTIVE = "Inactive";export const STATUS = "Status";// Organisation Errors+export const PROJECT_OVERVIEW = "Overview";export const NOT_ORGANISATION_MEMBER = "You are not a member of this organisation";export const ORGANISATION_NOT_FOUND = "Organisation not found";export const ORGANISATION_NOTHING_TO_UPDATE = "Nothing to update";@@ -1102,6 +1155,19 @@ export const ORGANISATION_PROJECT_CREATED = "Project created";export const ORGANISATION_PROJECT_CREATE_FAILED ="Unable to create project";export const NO_ORGANISATION_PROJECTS = "No projects yet. Create one above.";+export const HOME_SETUP_TITLE = "Set up your workspace";+export const HOME_SETUP_DESCRIPTION =+ "Create a project, connect a database config, then OpenLIT will show dashboards for that project.";+export const HOME_SETUP_ORGANISATION_STEP = "Organisation selected";+export const HOME_SETUP_PROJECT_STEP = "Create a project";+export const HOME_SETUP_PROJECT_DESCRIPTION =+ "Projects group telemetry, dashboards, members, and database configs.";+export const HOME_SETUP_DB_CONFIG_STEP = "Add database config";+export const HOME_SETUP_DB_CONFIG_DESCRIPTION =+ "Connect the ClickHouse database config that stores this project's data.";+export const HOME_SETUP_READY_STEP = "Devtool unlocked";+export const HOME_SETUP_READY_DESCRIPTION =+ "Your AI devtool is ready. Explore traces, prompts, evals, and the rest of the workspace.";export const SLUG = "Slug";export const USER_ALREADY_INVITED = "User has already been invited to this organisation";export const INVITATION_NOT_FOR_YOU = "This invitation is not for you";@@ -1261,6 +1327,7 @@ export const CONTEXT_NAME_REQUIRED = "Context name is required!";export const CONTEXT_CONTENT_REQUIRED = "Context content is required!";// Onboarding+export const ONBOARDING = "Onboarding";export const ONBOARDING_WELCOME = "Welcome to OpenLIT";export const ONBOARDING_SUBTITLE = "Let's get you set up with an organisation";export const ONBOARDING_CREATE_DESCRIPTION = "Create a new organisation to get started";diff --git a/src/client/src/constants/route.ts b/src/client/src/constants/route.tsindex 4cb94734..6d33fb01 100644--- a/src/client/src/constants/route.ts+++ b/src/client/src/constants/route.ts@@ -21,6 +21,9 @@ export const CRON_JOB_ROUTES = [// Non-API routes that are accessible without completing onboardingexport const ONBOARDING_WHITELIST_ROUTES = ["/onboarding"];+export const ONBOARDING_WHITELIST_ROUTE_PREFIXES = [+ "/organisation",+];// API routes that are accessible without completing onboarding.// Prefix entries must include a trailing slash to avoid overmatching sibling routes.@@ -30,8 +33,11 @@ export const ONBOARDING_WHITELIST_API_ROUTES = {POST: ["/api/organisation", "/api/user/complete-onboarding", "/api/auth/session"],},prefix: {- POST: ["/api/organisation/current/", "/api/organisation/invitation/"],- DELETE: ["/api/organisation/invitation/"],+ GET: ["/api/organisation/"],+ POST: ["/api/organisation/current/", "/api/organisation/invitation/", "/api/organisation/"],+ PUT: ["/api/organisation/"],+ PATCH: ["/api/organisation/"],+ DELETE: ["/api/organisation/invitation/", "/api/organisation/"],},} as const;diff --git a/src/client/src/constants/settings.ts b/src/client/src/constants/settings.tsnew file mode 100644index 00000000..7646202d--- /dev/null+++ b/src/client/src/constants/settings.ts@@ -0,0 +1,18 @@+import getMessage from "@/constants/messages";++export type SettingsTab = {+ value: string;+ label: string;+ path: string;+};++export function getSettingsTabs(): SettingsTab[] {+ const messages = getMessage();++ return [+ { value: "profile", label: messages.USER_PROFILE, path: "/settings/profile" },+ { value: "api-keys", label: messages.API_KEYS, path: "/settings/api-keys" },+ { value: "organisation", label: messages.ORGANISATION_SETTINGS, path: "/organisation" },+ { value: "pricing", label: messages.PRICING_TITLE, path: "/pricing" },+ ];+}diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsxindex 7cc2a1a2..abdb1c8d 100644--- a/src/client/src/constants/sidebar.tsx+++ b/src/client/src/constants/sidebar.tsx@@ -1,22 +1,24 @@+import OpenTelemetrySvg from "@/components/svg/opentelemetry";+import Otter from "@/components/svg/otter";+import { getEnterpriseSidebarItems } from "@/features/sidebar";import { SidebarItemProps } from "@/types/sidebar";import {+ Activity,BookKey,BookOpen,BookText,+ Bot,+ Building2,CircleDollarSign,Component,- Activity,Home,Key,- Bot,LayoutDashboard,MonitorCog,MonitorPlay,SettingsIcon,SlidersHorizontal,} from "lucide-react";-import OpenTelemetrySvg from "@/components/svg/opentelemetry";-import Otter from "@/components/svg/otter";export const ICON_CLASSES = "flex-shrink-0 size-5";@@ -42,83 +44,94 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [{title: "Monitoring",type: "section",- children: [{- icon: <Activity className={ICON_CLASSES} />,- text: "Telemetry",- link: "/telemetry",- type: "action",- },- {- icon: <Bot className={ICON_CLASSES} />,- text: "Agents",- link: "/agents",- type: "action",- },- {- icon: <OpenTelemetrySvg className={ICON_CLASSES} />,- text: "Fleet Hub",- link: "/fleet-hub",- type: "action",- },- ]+ children: [+ {+ icon: <Activity className={ICON_CLASSES} />,+ text: "Telemetry",+ link: "/telemetry",+ type: "action",+ },+ ...getEnterpriseSidebarItems("monitoring", ICON_CLASSES),+ {+ icon: <Bot className={ICON_CLASSES} />,+ text: "Agents",+ link: "/agents",+ type: "action",+ },+ {+ icon: <OpenTelemetrySvg className={ICON_CLASSES} />,+ text: "Fleet Hub",+ link: "/fleet-hub",+ type: "action",+ },+ ],},{title: "Resources",type: "section",- children: [{- icon: <Component className={ICON_CLASSES} />,- text: "Prompt Hub",- link: "/prompt-hub",- type: "action",- },- {- icon: <BookKey className={ICON_CLASSES} />,- text: "Vault",- link: "/vault",- type: "action",- },- {- icon: <BookOpen className={ICON_CLASSES} />,- text: "Contexts",- link: "/context",- type: "action",- },- {- icon: <SlidersHorizontal className={ICON_CLASSES} />,- text: "Rule Engine",- link: "/rule-engine",- type: "action",- },- {- icon: <MonitorPlay className={ICON_CLASSES} />,- text: "Openground",- link: "/openground",- type: "action",- },- ]+ children: [+ {+ icon: <Component className={ICON_CLASSES} />,+ text: "Prompt Hub",+ link: "/prompt-hub",+ type: "action",+ },+ {+ icon: <BookKey className={ICON_CLASSES} />,+ text: "Vault",+ link: "/vault",+ type: "action",+ },+ {+ icon: <BookOpen className={ICON_CLASSES} />,+ text: "Contexts",+ link: "/context",+ type: "action",+ },+ {+ icon: <SlidersHorizontal className={ICON_CLASSES} />,+ text: "Rule Engine",+ link: "/rule-engine",+ type: "action",+ },+ {+ icon: <MonitorPlay className={ICON_CLASSES} />,+ text: "Openground",+ link: "/openground",+ type: "action",+ },+ ],},{title: "Configuration",type: "section",- children: [{- icon: <MonitorCog className={ICON_CLASSES} />,- text: "Evaluations",- link: "/evaluations",- type: "action",- },- {- icon: <SettingsIcon className={ICON_CLASSES} />,- text: "Manage Models",- link: "/manage-models",- type: "action",- },- {- icon: <CircleDollarSign className={ICON_CLASSES} />,- text: "Pricing",- link: "/pricing",- type: "action",- },- ]+ children: [+ {+ icon: <MonitorCog className={ICON_CLASSES} />,+ text: "Evaluations",+ link: "/evaluations",+ type: "action",+ },+ {+ icon: <SettingsIcon className={ICON_CLASSES} />,+ text: "Manage Models",+ link: "/manage-models",+ type: "action",+ },+ {+ icon: <CircleDollarSign className={ICON_CLASSES} />,+ text: "Pricing",+ link: "/pricing",+ type: "action",+ },+ {+ icon: <Building2 className={ICON_CLASSES} />,+ text: "Organisation",+ link: "/organisation",+ type: "action",+ },+ ...getEnterpriseSidebarItems("configuration", ICON_CLASSES),+ ],},{title: "Settings",@@ -131,7 +144,7 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [link: "/settings/api-keys",type: "action",},- ]+ ],},{text: "Documentation",@@ -139,5 +152,5 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [target: "_blank",icon: <BookText className={ICON_CLASSES} />,type: "action",- }+ },];diff --git a/src/client/src/features/organisation-access.ts b/src/client/src/features/organisation-access.tsnew file mode 100644index 00000000..40c07e29--- /dev/null+++ b/src/client/src/features/organisation-access.ts@@ -0,0 +1,17 @@+export type OrganisationAccessAction =+ | "organisation.update"+ | "members.invite"+ | "members.remove"+ | "members.role_change";++type OrganisationAccessContext = {+ organisationId: string;+ userId: string;+ action: OrganisationAccessAction;+};++export async function canManageOrganisation(+ _context: OrganisationAccessContext+): Promise<boolean | undefined> {+ return undefined;+}diff --git a/src/client/src/features/organisation.ts b/src/client/src/features/organisation.tsnew file mode 100644index 00000000..9cf29178--- /dev/null+++ b/src/client/src/features/organisation.ts@@ -0,0 +1,3 @@+export async function onOrganisationChanged(_organisationId: string) {+ return;+}diff --git a/src/client/src/features/sidebar.ts b/src/client/src/features/sidebar.tsnew file mode 100644index 00000000..4d27ef4f--- /dev/null+++ b/src/client/src/features/sidebar.ts@@ -0,0 +1,10 @@+import { SidebarActionItem } from "@/types/sidebar";++export type EnterpriseSidebarSection = "monitoring" | "configuration";++export function getEnterpriseSidebarItems(+ _section: EnterpriseSidebarSection,+ _iconClasses: string+): SidebarActionItem[] {+ return [];+}diff --git a/src/client/src/helpers/client/organisation.ts b/src/client/src/helpers/client/organisation.tsindex be9b3de6..6891ae9c 100644--- a/src/client/src/helpers/client/organisation.ts+++ b/src/client/src/helpers/client/organisation.ts@@ -8,6 +8,7 @@ import { OrganisationWithMeta } from "@/types/store/organisation";import getMessage from "@/constants/messages";import { CLIENT_EVENTS } from "@/constants/events";import posthog from "posthog-js";+import { onOrganisationChanged } from "@/features/organisation";export const fetchOrganisationList = async () => {useRootStore.getState().organisation.setIsLoading(true);@@ -59,6 +60,8 @@ export const changeActiveOrganisation = async (}// Update the current organisation in store+ useRootStore.getState().project.reset();+ useRootStore.getState().databaseConfig.reset();const list = useRootStore.getState().organisation.list || [];const newCurrent = list.find((org) => org.id === organisationId);if (newCurrent) {@@ -73,6 +76,7 @@ export const changeActiveOrganisation = async (await fetchProjectList(organisationId);await fetchDatabaseConfigList(() => {});await pingActiveDatabaseConfig();+ await onOrganisationChanged(organisationId);successCb?.();};@@ -243,7 +247,7 @@ export const inviteToOrganisation = async (export const acceptInvitation = async (invitationId: string,successCb?: () => void-) => {+): Promise<boolean> => {const messages = getMessage();const [err, data] = await asaw(postData({@@ -256,7 +260,7 @@ export const acceptInvitation = async (toast.error(err || data?.err || messages.INVITATION_ACCEPT_FAILED, {id: "organisation-invitation",});- return;+ return false;}toast.success(messages.INVITATION_ACCEPTED, {@@ -270,6 +274,7 @@ export const acceptInvitation = async (await fetchOrganisationList();await fetchPendingInvitations();successCb?.();+ return true;};export const declineInvitation = async (diff --git a/src/client/src/helpers/client/project.ts b/src/client/src/helpers/client/project.tsindex 4a5b631b..c3d9eeff 100644--- a/src/client/src/helpers/client/project.ts+++ b/src/client/src/helpers/client/project.ts@@ -6,6 +6,8 @@ import { toast } from "sonner";import getMessage from "@/constants/messages";import { fetchDatabaseConfigList, pingActiveDatabaseConfig } from "./database-config";+const inFlightProjectListRequests = new Map<string, Promise<ProjectWithMeta[]>>();+export const fetchProjectList = async (organisationId?: string) => {const currentOrgId =organisationId || useRootStore.getState().organisation.current?.id;@@ -15,22 +17,34 @@ export const fetchProjectList = async (organisationId?: string) => {return [];}+ const inFlight = inFlightProjectListRequests.get(currentOrgId);+ if (inFlight) return inFlight;+useRootStore.getState().project.setIsLoading(true);- const [err, data] = await asaw(- getData({- url: `/api/organisation/${currentOrgId}/projects`,- method: "GET",- })- );+ const request = (async () => {+ const [err, data] = await asaw(+ getData({+ url: `/api/organisation/${currentOrgId}/projects`,+ method: "GET",+ })+ );- if (err || !Array.isArray(data)) {- useRootStore.getState().project.setIsLoading(false);- useRootStore.getState().project.setList([]);- return [];- }+ if (err || !Array.isArray(data)) {+ useRootStore.getState().project.setIsLoading(false);+ useRootStore.getState().project.setList([]);+ return [];+ }- useRootStore.getState().project.setList(data);- return data as ProjectWithMeta[];+ useRootStore.getState().project.setList(data);+ return data as ProjectWithMeta[];+ })();++ inFlightProjectListRequests.set(currentOrgId, request);+ try {+ return await request;+ } finally {+ inFlightProjectListRequests.delete(currentOrgId);+ }};export const changeActiveProject = async (diff --git a/src/client/src/helpers/server/response.ts b/src/client/src/helpers/server/response.tsnew file mode 100644index 00000000..6c123616--- /dev/null+++ b/src/client/src/helpers/server/response.ts@@ -0,0 +1,22 @@+export function getErrorMessage(error: unknown, fallback = "Request failed") {+ if (error instanceof Error) return error.message;+ if (typeof error === "string") return error;+ if (+ error &&+ typeof error === "object" &&+ "message" in error &&+ typeof error.message === "string"+ ) {+ return error.message;+ }+ return fallback;+}++export function errorResponse(+ error: unknown,+ status = 400,+ extra: Record<string, unknown> = {}+) {+ const message = getErrorMessage(error);+ return Response.json({ error: message, err: message, ...extra }, { status });+}diff --git a/src/client/src/lib/access/route-access.ts b/src/client/src/lib/access/route-access.tsnew file mode 100644index 00000000..39c7464f--- /dev/null+++ b/src/client/src/lib/access/route-access.ts@@ -0,0 +1,18 @@+type RouteHandler = (+ request: any,+ context: any+) => Promise<Response> | Response;++export type RouteAccessKey = string;++export async function requireRouteAccess(_access: RouteAccessKey) {+ return null;+}++export function withRouteAccess<THandler extends RouteHandler>(+ _access: RouteAccessKey,+ handler: THandler,+ _options: { requireDbConfig?: boolean } = {}+): THandler {+ return handler;+}diff --git a/src/client/src/lib/chat/access.ts b/src/client/src/lib/chat/access.tsnew file mode 100644index 00000000..0c0cd9e7--- /dev/null+++ b/src/client/src/lib/chat/access.ts@@ -0,0 +1,14 @@+type RouteHandler = (+ request: any,+ context: any+) => Promise<Response> | Response;++function passthrough<THandler extends RouteHandler>(handler: THandler): THandler {+ return handler;+}++export const withOtterReadAccess = passthrough;+export const withOtterChatAccess = passthrough;+export const withOtterConfigureAccess = passthrough;+export const withOtterDbReadAccess = passthrough;+export const withOtterDbChatAccess = passthrough;diff --git a/src/client/src/lib/enterprise-feature-access.ts b/src/client/src/lib/enterprise-feature-access.tsnew file mode 100644index 00000000..82d53fe1--- /dev/null+++ b/src/client/src/lib/enterprise-feature-access.ts@@ -0,0 +1,24 @@+export type EnterpriseFeatureOrganisation = {+ id: string;+ name: string;+ role: string;+ plan?: string;+ status?: string;+ isCurrent?: boolean;+};++export type EnterpriseFeatureAccount = EnterpriseFeatureOrganisation;++export type EnterpriseFeatureAccessSnapshot = {+ accounts: EnterpriseFeatureOrganisation[];+ selectedAccountId: string;+ accessByAccountId: Record<string, Record<string, boolean | undefined>>;+};++export async function getEnterpriseFeatureAccessSnapshot(): Promise<EnterpriseFeatureAccessSnapshot> {+ return {+ accounts: [],+ selectedAccountId: "",+ accessByAccountId: {},+ };+}diff --git a/src/client/src/lib/organisation.ts b/src/client/src/lib/organisation.tsindex 640482eb..a98ecb88 100644--- a/src/client/src/lib/organisation.ts+++ b/src/client/src/lib/organisation.ts@@ -2,6 +2,10 @@ import prisma from "./prisma";import { getCurrentUser } from "./session";import getMessage from "@/constants/messages";import { throwIfError } from "@/utils/error";+import {+ OrganisationAccessAction,+ canManageOrganisation,+} from "@/features/organisation-access";/*** Generate a URL-safe slug from a name@@ -49,8 +53,16 @@ async function generateUniqueOrganisationSlug(*/async function hasAdminOrOwnerRole(organisationId: string,- userId: string+ userId: string,+ action: OrganisationAccessAction): Promise<boolean> {+ const extensionDecision = await canManageOrganisation({+ organisationId,+ userId,+ action,+ });+ if (typeof extensionDecision === "boolean") return extensionDecision;+const membership = await prisma.organisationUser.findUnique({where: {organisationId_userId: {@@ -115,6 +127,82 @@ async function setMembershipCurrentProjectId(`;}+async function assignUserToAllOrganisationProjects(+ organisationId: string,+ userId: string+) {+ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId,+ userId,+ },+ },+ select: { id: true },+ });+ if (!membership) return;++ const projects = await prisma.project.findMany({+ where: { organisationId },+ select: { id: true },+ orderBy: [{ isDefault: "desc" }, { createdAt: "asc" }],+ });++ for (const project of projects) {+ await prisma.projectUser.upsert({+ where: {+ projectId_organisationUserId: {+ projectId: project.id,+ organisationUserId: membership.id,+ },+ },+ create: {+ projectId: project.id,+ organisationUserId: membership.id,+ userId,+ },+ update: {},+ });+ }++ if (projects[0]?.id) {+ const currentProjectId = await getMembershipCurrentProjectId(+ organisationId,+ userId+ );+ if (!currentProjectId) {+ await setMembershipCurrentProjectId(organisationId, userId, projects[0].id);+ }+ }+}++async function assignAllOrganisationMembersToProject(+ organisationId: string,+ projectId: string+) {+ const memberships = await prisma.organisationUser.findMany({+ where: { organisationId },+ select: { id: true, userId: true },+ });++ for (const membership of memberships) {+ await prisma.projectUser.upsert({+ where: {+ projectId_organisationUserId: {+ projectId,+ organisationUserId: membership.id,+ },+ },+ create: {+ projectId,+ organisationUserId: membership.id,+ userId: membership.userId,+ },+ update: {},+ });+ }+}+export async function getDefaultProjectForOrganisation(organisationId: string) {const existingProject = await prisma.project.findFirst({where: { organisationId, isDefault: true },@@ -223,7 +311,11 @@ export async function createOrganisationProject(getMessage().PROJECT_NAME_LENGTH_RANGE_ERROR);- const isAdmin = await hasAdminOrOwnerRole(organisationId, user!.id);+ const isAdmin = await hasAdminOrOwnerRole(+ organisationId,+ user!.id,+ "organisation.update"+ );throwIfError(!isAdmin, getMessage().ONLY_ADMIN_CAN_UPDATE_ORGANISATION);const baseSlug = slugify(trimmedName) || "project";@@ -241,13 +333,15 @@ export async function createOrganisationProject(});if (!existing) {- return prisma.project.create({+ const project = await prisma.project.create({data: {organisationId,name: trimmedName,slug,},});+ await assignAllOrganisationMembersToProject(organisationId, project.id);+ return project;}}@@ -282,7 +376,7 @@ export async function createOrganisation(name: string) {});// Add creator as a member with owner role- await prisma.organisationUser.create({+ const creatorMembership = await prisma.organisationUser.create({data: {organisationId: organisation.id,userId: user!.id,@@ -291,6 +385,13 @@ export async function createOrganisation(name: string) {},});if (organisation.projects?.[0]?.id) {+ await prisma.projectUser.create({+ data: {+ projectId: organisation.projects[0].id,+ organisationUserId: creatorMembership.id,+ userId: user!.id,+ },+ });await setMembershipCurrentProjectId(organisation.id,user!.id,@@ -445,7 +546,11 @@ export async function updateOrganisation(throwIfError(!user, getMessage().UNAUTHORIZED_USER);// Verify user has admin or owner role- const hasPermission = await hasAdminOrOwnerRole(id, user!.id);+ const hasPermission = await hasAdminOrOwnerRole(+ id,+ user!.id,+ "organisation.update"+ );throwIfError(!hasPermission, getMessage().ONLY_ADMIN_CAN_UPDATE_ORGANISATION);const updateData: { name?: string } = {};@@ -543,7 +648,11 @@ export async function inviteUserToOrganisation(throwIfError(!user, getMessage().UNAUTHORIZED_USER);// Verify inviter has admin or owner role- const hasPermission = await hasAdminOrOwnerRole(organisationId, user!.id);+ const hasPermission = await hasAdminOrOwnerRole(+ organisationId,+ user!.id,+ "members.invite"+ );throwIfError(!hasPermission, getMessage().ONLY_ADMIN_CAN_INVITE);// Validate and normalize email@@ -551,14 +660,14 @@ export async function inviteUserToOrganisation(// Validate email is not emptyif (!normalizedEmail) {- throw new Error("Email cannot be empty");+ throw new Error(getMessage().EMAIL_REQUIRED);}// Validate email format - using a safer regex pattern that avoids ReDoS// This pattern is more restrictive but safe from catastrophic backtrackingconst EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;if (!EMAIL_REGEX.test(normalizedEmail)) {- throw new Error("Invalid email format");+ throw new Error(getMessage().INVALID_EMAIL_FORMAT);}// Check if user already exists@@ -591,6 +700,8 @@ export async function inviteUserToOrganisation(},});+ await assignUserToAllOrganisationProjects(organisationId, existingUser.id);+// Share all organisation database configs with the new memberawait shareOrganisationDatabaseConfigs(organisationId, existingUser.id);@@ -683,6 +794,8 @@ export async function acceptInvitation(invitationId: string) {},});+ await assignUserToAllOrganisationProjects(invitation!.organisationId, user!.id);+// Share all organisation database configs with the new memberawait shareOrganisationDatabaseConfigs(invitation!.organisationId, user!.id);@@ -807,9 +920,17 @@ export async function removeUserFromOrganisation(userId);- // Only admins and owners can remove other members+ // Only admins and owners can remove other members by default. Enterprise can+ // override this through the organisation access extension hook.+ const extensionDecision = await canManageOrganisation({+ organisationId,+ userId: user!.id,+ action: "members.remove",+ });const hasPermission =- currentUserRole === "owner" || currentUserRole === "admin";+ typeof extensionDecision === "boolean"+ ? extensionDecision+ : currentUserRole === "owner" || currentUserRole === "admin";throwIfError(!hasPermission,getMessage().ONLY_ADMIN_CAN_REMOVE_MEMBERS@@ -983,9 +1104,17 @@ export async function updateMemberRole();throwIfError(!targetUserRole, getMessage().NOT_ORGANISATION_MEMBER);- // Only admins and owners can update roles+ // Only admins and owners can update roles by default. Enterprise can override+ // this through the organisation access extension hook.+ const extensionDecision = await canManageOrganisation({+ organisationId,+ userId: user!.id,+ action: "members.role_change",+ });const hasPermission =- currentUserRole === "owner" || currentUserRole === "admin";+ typeof extensionDecision === "boolean"+ ? extensionDecision+ : currentUserRole === "owner" || currentUserRole === "admin";throwIfError(!hasPermission, getMessage().ONLY_ADMIN_OR_OWNER_CAN_UPDATE_ROLES);// Only owner can change admin roles (demote admin to member)@@ -1062,7 +1191,8 @@ export async function cancelInvitation(invitationId: string) {// Verify user has admin or owner roleconst hasPermission = await hasAdminOrOwnerRole(invitation!.organisationId,- user!.id+ user!.id,+ "members.invite");throwIfError(!hasPermission, getMessage().ONLY_ADMIN_CAN_CANCEL_INVITATION);@@ -1188,6 +1318,7 @@ async function migrateUserConfigsToOrganisation(sharedUserId,project.id);+ await assignUserToAllOrganisationProjects(organisationId, sharedUserId);} else if (!hasCurrentOrg) {// Existing membership but no current org — fix itawait prisma.organisationUser.update({@@ -1204,6 +1335,9 @@ async function migrateUserConfigsToOrganisation(sharedUserId,project.id);+ await assignUserToAllOrganisationProjects(organisationId, sharedUserId);+ } else {+ await assignUserToAllOrganisationProjects(organisationId, sharedUserId);}// Share org DB configs with the new memberdiff --git a/src/client/src/middleware/check-auth.ts b/src/client/src/middleware/check-auth.tsindex f9f941d1..1678208d 100644--- a/src/client/src/middleware/check-auth.ts+++ b/src/client/src/middleware/check-auth.ts@@ -12,6 +12,7 @@ import {ALLOWED_OPENLIT_ROUTE_PREFIXES_WITHOUT_TOKEN,CRON_JOB_ROUTES,ONBOARDING_WHITELIST_ROUTES,+ ONBOARDING_WHITELIST_ROUTE_PREFIXES,ONBOARDING_WHITELIST_API_ROUTES,} from "@/constants/route";@@ -42,6 +43,8 @@ export default function checkAuth(next: NextMiddleware) {const method = request.method.toUpperCase();const isOnboardingWhitelistedPage = ONBOARDING_WHITELIST_ROUTES.includes(pathname+ ) || ONBOARDING_WHITELIST_ROUTE_PREFIXES.some(+ (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));const exactApiRoutes: readonly string[] =method in ONBOARDING_WHITELIST_API_ROUTES.exactdiff --git a/src/client/src/store/database-config.ts b/src/client/src/store/database-config.tsindex 1272915f..4fa8439f 100644--- a/src/client/src/store/database-config.ts+++ b/src/client/src/store/database-config.ts@@ -2,11 +2,15 @@import { DatabaseConfigStore } from "@/types/store/database-config";import { lens } from "@dhmk/zustand-lens";+const initialState = {+ ping: { status: "pending" as const },+ isLoading: false,+ list: undefined,+};export const databaseConfigStoreSlice: DatabaseConfigStore = lens((setStore, getStore) => ({- ping: { status: "pending" },- isLoading: false,+ ...initialState,setPing: ({ error, status }) =>setStore(() => ({...getStore(),@@ -26,5 +30,9 @@ export const databaseConfigStoreSlice: DatabaseConfigStore = lens(...getStore(),isLoading: !!isLoading,})),+ reset: () =>+ setStore(() => ({+ ...initialState,+ })),}));diff --git a/src/client/src/store/enterprise.ts b/src/client/src/store/enterprise.tsnew file mode 100644index 00000000..53d20530--- /dev/null+++ b/src/client/src/store/enterprise.ts@@ -0,0 +1 @@+export const enterpriseStoreSlices = {};diff --git a/src/client/src/store/index.ts b/src/client/src/store/index.tsindex ab3d8808..0ae06ab5 100644--- a/src/client/src/store/index.ts+++ b/src/client/src/store/index.ts@@ -13,6 +13,7 @@ import { projectStoreSlice } from "./project";import { ruleEngineStoreSlice } from "./rule-engine";import { chatStoreSlice } from "./chat";import { agentsInstrumentationStoreSlice } from "./agents-instrumentation";+import { enterpriseStoreSlices } from "@/store/enterprise";export const useRootStore = create<RootStore>()(devtools(@@ -28,6 +29,7 @@ export const useRootStore = create<RootStore>()(ruleEngine: ruleEngineStoreSlice,chat: chatStoreSlice,agentsInstrumentation: agentsInstrumentationStoreSlice,+ ...enterpriseStoreSlices,})));diff --git a/src/client/src/types/database-config.ts b/src/client/src/types/database-config.tsindex fb842d83..86483ffb 100644--- a/src/client/src/types/database-config.ts+++ b/src/client/src/types/database-config.ts@@ -11,6 +11,7 @@ export type DatabaseConfigTabItemProps = {canDelete?: boolean;canShare?: boolean;canEdit?: boolean;+ canSelect?: boolean;};export type DatabaseConfigTabsProps = {diff --git a/src/client/src/types/store/database-config.ts b/src/client/src/types/store/database-config.tsindex 3f1df871..a821deb4 100644--- a/src/client/src/types/store/database-config.ts+++ b/src/client/src/types/store/database-config.ts@@ -15,4 +15,5 @@ export type DatabaseConfigStore = {}) => void;setList: (u: DatabaseConfigWithActive[]) => void;setIsLoading: (f?: boolean) => void;+ reset: () => void;};diff --git a/src/client/src/types/store/enterprise.ts b/src/client/src/types/store/enterprise.tsnew file mode 100644index 00000000..1a5c8cd3--- /dev/null+++ b/src/client/src/types/store/enterprise.ts@@ -0,0 +1 @@+export type EnterpriseRootStore = {};diff --git a/src/client/src/types/store/root.ts b/src/client/src/types/store/root.tsindex fc752350..888c6dd9 100644--- a/src/client/src/types/store/root.ts+++ b/src/client/src/types/store/root.ts@@ -9,6 +9,7 @@ import { ProjectStore } from "./project";import { RuleEngineStore } from "./rule-engine";import { ChatStore } from "./chat";import { AgentInstrumentationStore } from "./agents-instrumentation";+import { EnterpriseRootStore } from "@/types/store/enterprise";export type RootStore = {user: UserStore;@@ -22,4 +23,4 @@ export type RootStore = {ruleEngine: RuleEngineStore;chat: ChatStore;agentsInstrumentation: AgentInstrumentationStore;-};+} & EnterpriseRootStore;