Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: add enterprise support foundation (#1226)

Aman Agarwal290e8ee94e20
diff --git a/.claude/commands/project-hierarchy-check.md b/.claude/commands/project-hierarchy-check.md
new file mode 100644
index 00000000..cec24f06
--- /dev/null
+++ b/.claude/commands/project-hierarchy-check.md
@@ -0,0 +1,15 @@
+# Project Hierarchy Check
+
+Use this command before changing organisation, project, or database config behavior.
+
+1. Confirm the code follows `Organisation -> Project -> Database configuration`.
+2. Check that database config reads and writes are scoped by current project.
+3. Check that project list and switch routes validate organisation membership.
+4. Check that switching organisation refreshes projects and database config state.
+5. Add or update tests for membership denial, selected project, cross-project denial, and invalid JSON.
+6. Run:
+
+```bash
+cd src/client
+npm test -- --runInBand src/__tests__/lib/db-config.test.ts src/__tests__/lib/organisation.test.ts src/__tests__/app/api/organisation/projects-route.test.ts
+```
diff --git a/.claude/commands/security-validation.md b/.claude/commands/security-validation.md
new file mode 100644
index 00000000..cfc600f4
--- /dev/null
+++ b/.claude/commands/security-validation.md
@@ -0,0 +1,17 @@
+# Security Validation
+
+Use this command before handing off security-sensitive OpenLIT changes.
+
+1. Identify every route touched by the change.
+2. Confirm server-side authorization is enforced in each route.
+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:
+
+```bash
+cd src/client
+npm test -- --runInBand
+npm run lint
+npx prisma validate --schema prisma/schema.prisma
+```
diff --git a/.cursor-rules/README.md b/.cursor-rules/README.md
new file mode 100644
index 00000000..520a7632
--- /dev/null
+++ b/.cursor-rules/README.md
@@ -0,0 +1,100 @@
+# Cursor Rules Organization
+
+This directory contains organized cursor rules for different aspects of the OpenLIT project.
+
+## Current Rule Files
+
+### `documentation.md`
+**Purpose**: Guidelines for creating and maintaining OpenLIT documentation
+**Applies to**:
+- All files in `/docs/` directory
+- MDX files (`.mdx`)
+- README files
+- API documentation
+- Integration guides
+- Quickstart tutorials
+
+**Key Features**:
+- File organization and naming conventions
+- MDX component usage guidelines
+- Content structure templates
+- Brand and voice guidelines
+- Quality checklists
+
+### `frontend.md`
+**Purpose**: Guidelines for OpenLIT client UI work
+**Applies to**:
+- Settings pages
+- Telemetry-style pages
+- Header switchers and breadcrumbs
+- Client stores, selectors, and helpers
+
+**Key Features**:
+- Light and dark mode styling standards
+- Compact operational UI guidance
+- Project hierarchy UI expectations
+- Message key requirements
+
+### `security-testing.md`
+**Purpose**: Security and testing standards for API, auth, project hierarchy, and paid-feature boundaries
+**Applies to**:
+- API routes
+- Library mutations
+- Audit, billing, licensing, and entitlement checks
+- Tests under `src/client/src/__tests__`
+
+**Key Features**:
+- Server-side authorization requirements
+- Invalid JSON handling
+- Secret redaction requirements
+- Project-scoped DB config test expectations
+
+## File Naming Convention
+
+Use descriptive names that clearly indicate the purpose and scope:
+- `documentation.md` - Documentation writing and structure
+- `frontend.md` - Frontend development (React, TypeScript, UI components)
+- `backend.md` - Backend development (Go, Python, APIs)
+- `testing.md` - Testing standards and practices
+- `deployment.md` - Deployment and infrastructure
+- `security.md` - Security guidelines and best practices
+
+## Rule File Structure
+
+Each rule file should follow this structure:
+
+```markdown
+# [Category] Cursor Rules
+
+## Overview
+Brief description of what this rule file covers
+
+## [Section 1]
+### Subsection
+Guidelines and examples
+
+## [Section 2]
+### Subsection
+More guidelines
+
+## Quality Checklist
+- [ ] Checklist items for quality assurance
+
+## Quick Reference
+Summary of key points
+```
+
+## Adding New Rules
+
+1. Create a new `.md` file in this directory
+2. Follow the established structure and format
+3. Update the main `.cursorrules` file to reference the new category
+4. Update this README to document the new rule file
+
+## Best Practices
+
+- Keep rules specific and actionable
+- Include code examples where helpful
+- Provide templates for common patterns
+- Include quality checklists
+- Regular review and updates as the project evolves
diff --git a/.cursor-rules/documentation.md b/.cursor-rules/documentation.md
new file mode 100644
index 00000000..0df04d56
--- /dev/null
+++ b/.cursor-rules/documentation.md
@@ -0,0 +1,309 @@
+# OpenLIT Documentation Cursor Rules
+
+## Overview
+These rules guide the creation and maintenance of documentation for OpenLIT, an open-source AI observability platform. Follow these standards to ensure consistency, clarity, and user-friendliness across all documentation.
+
+## Documentation Structure
+
+### File Organization
+- Use `.mdx` format for all documentation files
+- Organize files in logical hierarchies under `/docs/latest/`
+- Main sections: `openlit/`, `sdk/`, `operator/`
+- Use descriptive, kebab-case filenames (e.g., `quickstart-ai-observability.mdx`)
+- Place reusable content in `/docs/snippets/` for import across multiple files
+
+### Navigation Structure
+- Update `docs.json` when adding new pages
+- Organize content in logical groups with clear hierarchies
+- Use descriptive titles and appropriate icons
+- Maintain consistent navigation patterns across sections
+
+## Content Standards
+
+### Front Matter
+Every documentation file must start with YAML front matter:
+```yaml
+---
+title: "Clear, Descriptive Title"
+sidebarTitle: "Short Title" # Optional, for sidebar display
+description: "Brief description of the content (1-2 sentences)"
+---
+```
+
+### Writing Style
+- **Tone**: Professional, helpful, and accessible
+- **Voice**: Active voice preferred, direct and clear
+- **Audience**: Developers and technical users with varying experience levels
+- **Language**: Use simple, clear language; avoid unnecessary jargon
+- **Structure**: Start with overview, then step-by-step instructions
+
+### Content Organization
+1. **Introduction**: Brief overview of what the page covers
+2. **Prerequisites**: List any requirements (if applicable)
+3. **Main Content**: Step-by-step instructions or detailed explanations
+4. **Examples**: Practical code examples and use cases
+5. **Next Steps**: Links to related content or logical next actions
+
+## Formatting Guidelines
+
+### Headers
+- Use descriptive, action-oriented headers
+- Follow logical hierarchy (H1 → H2 → H3)
+- Use sentence case for headers
+- Examples: "Get started", "Configure authentication", "Monitor your application"
+
+### Code Blocks
+- Always specify language for syntax highlighting
+- Use realistic, working examples
+- Include necessary imports and setup
+- Provide context for code snippets
+- Use `bash` for shell commands, `python`/`typescript` for code
+
+```python
+import openlit
+
+openlit.init(otlp_endpoint="http://127.0.0.1:4318")
+```
+
+### Links and References
+- Use descriptive link text (avoid "click here")
+- Link to relevant internal pages using relative paths
+- Include external links where helpful
+- Format: `[descriptive text](/path/to/page)` or `[external site](https://example.com)`
+
+### Lists and Steps
+- Use numbered lists for sequential steps
+- Use bullet points for non-sequential items
+- Keep list items parallel in structure
+- Use the `<Steps>` component for multi-step processes
+
+### Images and Media
+- Store images in `/docs/images/`
+- Use descriptive filenames
+- Include alt text for accessibility
+- Optimize file sizes
+- Use videos for complex workflows when helpful
+
+## Component Usage
+
+### MDX Components
+Use OpenLIT's custom MDX components consistently:
+
+#### Steps Component
+```mdx
+<Steps>
+ <Step title="Install OpenLIT">
+ Content for step 1
+ </Step>
+ <Step title="Configure your application">
+ Content for step 2
+ </Step>
+</Steps>
+```
+
+#### Tabs Component
+```mdx
+<Tabs>
+ <Tab title="Python">
+ Python-specific content
+ </Tab>
+ <Tab title="TypeScript">
+ TypeScript-specific content
+ </Tab>
+</Tabs>
+```
+
+#### Cards and Card Groups
+```mdx
+<CardGroup cols={2}>
+ <Card title="Feature Name" href="/path/to/page" icon="icon-name">
+ Brief description of the feature
+ </Card>
+</CardGroup>
+```
+
+#### Info Boxes
+```mdx
+<Info>
+Important information that helps users understand context
+</Info>
+
+<Tip>
+Helpful tips and best practices
+</Tip>
+
+<Warning>
+Important warnings about potential issues
+</Warning>
+```
+
+#### Code Groups
+```mdx
+<CodeGroup>
+```python OpenAI
+# OpenAI example
+```
+
+```python Anthropic
+# Anthropic example
+```
+</CodeGroup>
+```
+
+## Integration Documentation Patterns
+
+### LLM/Framework Integration Pages
+Follow this structure for integration documentation:
+
+1. **Introduction**: Brief description of the integration
+2. **Compatibility**: Supported versions and requirements
+3. **Get started**: Installation and basic setup
+4. **Configuration**: Advanced configuration options
+5. **Examples**: Working code examples
+6. **Related links**: Cards linking to quickstarts, configuration, destinations
+
+### Standard Integration Template
+```mdx
+---
+title: 'Monitor [Service] using OpenTelemetry'
+sidebarTitle: '[Service Name]'
+---
+
+import IntegrationMethods from '/snippets/integration-methods.mdx';
+
+Brief description of what this integration provides and its benefits.
+
+Auto-instrumentation means you don't have to set up monitoring manually...
+
+The integration is compatible with:
+- [Service] version requirements
+
+## Get started
+
+<Steps>
+ <Step title="Install OpenLIT">
+ Installation instructions with tabs for Python/TypeScript
+ </Step>
+ <IntegrationMethods />
+</Steps>
+
+---
+
+<CardGroup cols={3}>
+ <Card title="Quickstart: LLM Observability" href="/latest/sdk/quickstart-ai-observability" icon='bolt'>
+ Production-ready AI monitoring setup in 2 simple steps with zero code changes
+ </Card>
+ <Card title="Configuration" href="/latest/sdk/configuration" icon='bolt'>
+ Configure the OpenLIT SDK according to you requirements.
+ </Card>
+ <Card title="Destinations" href="/latest/sdk/destinations/overview" icon='link'>
+ Send telemetry to Datadog, Grafana, New Relic, and other observability stacks
+ </Card>
+</CardGroup>
+```
+
+## Quickstart Documentation
+
+### Structure for Quickstart Guides
+1. **Mermaid diagram**: Show the architecture/flow
+2. **Prerequisites**: What users need before starting
+3. **Step-by-step instructions**: Clear, numbered steps
+4. **Verification**: How to confirm everything works
+5. **Next steps**: Where to go from here
+
+### Standard Quickstart Elements
+- Use `<Steps>` component for main workflow
+- Include both Python and TypeScript examples where applicable
+- Provide realistic, working code examples
+- Include screenshots or videos for UI interactions
+- End with verification steps and next actions
+
+## Content Reuse and Snippets
+
+### Snippet Usage
+- Create reusable content in `/docs/snippets/`
+- Import snippets using: `import SnippetName from '/snippets/snippet-name.mdx';`
+- Use snippets for commonly repeated content like installation steps
+- Keep snippets focused and modular
+
+### Common Snippets
+- Integration methods (`integration-methods.mdx`)
+- Installation instructions
+- Configuration patterns
+- Kubernetes operator promotion cards
+
+## Quality Checklist
+
+Before publishing documentation:
+
+### Content Quality
+- [ ] Clear, descriptive title and description
+- [ ] Logical flow from introduction to conclusion
+- [ ] All code examples are tested and working
+- [ ] Links are functional and point to correct destinations
+- [ ] Grammar and spelling are correct
+- [ ] Technical accuracy is verified
+
+### Structure and Formatting
+- [ ] Proper front matter included
+- [ ] Headers follow logical hierarchy
+- [ ] Code blocks have appropriate language tags
+- [ ] Components are used correctly
+- [ ] Images have alt text and are optimized
+
+### User Experience
+- [ ] Content is accessible to target audience
+- [ ] Prerequisites are clearly stated
+- [ ] Examples are realistic and helpful
+- [ ] Next steps are provided
+- [ ] Related content is linked appropriately
+
+### Navigation and Discovery
+- [ ] Page is added to `docs.json` navigation
+- [ ] Appropriate cross-links are included
+- [ ] Cards link to relevant related content
+- [ ] Search-friendly titles and descriptions
+
+## Brand and Voice Guidelines
+
+### OpenLIT Brand Elements
+- Use official OpenLIT orange color (#FFA500) in examples
+- Include Kubernetes operator promotion cards where relevant
+- Link to community resources (Slack, GitHub) appropriately
+- Maintain consistent terminology across all documentation
+
+### Technical Terminology
+- "OpenLIT" (not "openlit" or "OpenLit")
+- "AI observability" (preferred over "LLM monitoring")
+- "OpenTelemetry" (not "OpenTel" or "OTEL" in user-facing content)
+- "Zero-code instrumentation" (for automatic instrumentation)
+- Use consistent service names (e.g., "OpenAI", "Anthropic", "LangChain")
+
+## Maintenance and Updates
+
+### Regular Review
+- Update version compatibility information
+- Verify all links and examples remain functional
+- Update screenshots and videos as UI changes
+- Review and update outdated information
+
+### Version Management
+- Keep compatibility matrices current
+- Update installation instructions for new versions
+- Maintain backward compatibility information where relevant
+- Archive or redirect outdated content
+
+---
+
+## Quick Reference
+
+When creating new documentation:
+
+1. **Start with the template** appropriate for your content type
+2. **Follow the structure** outlined in these rules
+3. **Use components consistently** as shown in examples
+4. **Test all code examples** before publishing
+5. **Update navigation** in `docs.json`
+6. **Review against checklist** before finalizing
+
+Remember: Great documentation helps users succeed quickly and confidently with OpenLIT. Focus on clarity, accuracy, and user success.
diff --git a/.cursor-rules/frontend.md b/.cursor-rules/frontend.md
new file mode 100644
index 00000000..543bb68f
--- /dev/null
+++ b/.cursor-rules/frontend.md
@@ -0,0 +1,33 @@
+# Frontend Cursor Rules
+
+## Overview
+
+Use these rules for OpenLIT client UI work in `src/client/src`.
+
+## Styling
+
+- Match the existing settings and telemetry page classes for light and dark mode.
+- Avoid one-off palettes and hard-coded colors unless the surrounding component already uses them.
+- Keep filter and pagination controls compact on data-heavy pages.
+- Do not place cards inside cards.
+- Keep headers, toolbars, tables, and empty states readable in both themes.
+
+## Text
+
+- Do not hard-code user-facing strings.
+- Add strings to `src/client/src/constants/messages/en.ts`.
+- Use existing message keys before adding new ones.
+
+## Project Hierarchy UI
+
+- Header should show organisation and project switching.
+- Breadcrumbs belong below the header.
+- Settings should present `Organisation -> Project -> Database configuration` in that order.
+- Project switching must refresh database config list and active ping state.
+
+## Quality Checklist
+
+- [ ] Light and dark mode are both checked.
+- [ ] Text uses `messages/en.ts`.
+- [ ] Project-scoped UI refreshes after organisation or project changes.
+- [ ] Loading, empty, disabled, and error states are covered.
diff --git a/.cursor-rules/security-testing.md b/.cursor-rules/security-testing.md
new file mode 100644
index 00000000..34e75ec5
--- /dev/null
+++ b/.cursor-rules/security-testing.md
@@ -0,0 +1,38 @@
+# Security And Testing Cursor Rules
+
+## Overview
+
+Use these rules for API routes, auth checks, project hierarchy, billing, licensing, audit logs, and tests.
+
+## Authorization
+
+- Server routes must enforce authorization. UI checks are not authorization.
+- Project routes must validate organisation membership.
+- Enterprise routes must enforce entitlement or billing-admin checks on the server.
+- Database config selection must be scoped to the current project.
+
+## Input Handling
+
+- Parse JSON with a helper or try/catch.
+- Malformed JSON should return `400`.
+- Validate names and identifiers before calling library mutation functions.
+- Use messages from `src/client/src/constants/messages/en.ts` for user-facing validation errors.
+
+## Audit And Secrets
+
+- Do not persist raw passwords, tokens, cookies, API keys, license keys, authorization headers, or session values.
+- Audit metadata must redact sensitive request fields.
+
+## Tests
+
+- Add focused tests for every security boundary changed.
+- Include invalid JSON tests for new mutation routes.
+- Include cross-project denial tests for project-scoped DB config behavior.
+- Run full local validation before handoff:
+
+```bash
+cd src/client
+npm test -- --runInBand
+npm run lint
+npx prisma validate --schema prisma/schema.prisma
+```
diff --git a/.cursorrules b/.cursorrules
new file mode 100644
index 00000000..dd952c7f
--- /dev/null
+++ b/.cursorrules
@@ -0,0 +1,44 @@
+# OpenLIT Cursor Rules
+
+This project uses organized cursor rules to maintain consistency across different types of development work.
+
+## Rule Categories
+
+### Documentation Rules
+For all documentation work including MDX files, guides, and API documentation.
+- **File**: `.cursor-rules/documentation.md`
+- **Applies to**: `/docs/**`, `*.mdx`, `README.md`, documentation-related files
+- **Purpose**: Ensures consistent documentation structure, formatting, and OpenLIT brand guidelines
+
+### Frontend Rules
+For OpenLIT client UI work.
+- **File**: `.cursor-rules/frontend.md`
+- **Applies to**: `src/client/src/**/*.tsx`, settings pages, telemetry-style pages, stores, selectors, and helpers
+- **Purpose**: Keeps light/dark styling, compact page layout, project hierarchy UI, and message usage consistent
+
+### Security And Testing Rules
+For 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, redaction, and validation coverage
+
+## Usage
+
+Cursor will automatically apply the appropriate rules based on the files you're working with. The rules are organized by category to make them easier to maintain and update.
+
+## Adding New Rule Categories
+
+When adding new types of cursor rules:
+
+1. Create a new file in `.cursor-rules/` with a descriptive name (e.g., `frontend.md`, `backend.md`, `testing.md`)
+2. Update this main `.cursorrules` file to reference the new category
+3. Follow the same structure and format as existing rule files
+
+## Rule Structure
+
+Each rule file should include:
+- Clear overview and purpose
+- Specific guidelines and standards
+- Code examples and templates
+- Quality checklists
+- Quick reference sections
diff --git a/.github/workflows/oss-leak-check.yml b/.github/workflows/oss-leak-check.yml
new file mode 100644
index 00000000..a59b0c88
--- /dev/null
+++ b/.github/workflows/oss-leak-check.yml
@@ -0,0 +1,43 @@
+name: OSS Leak Check
+
+on:
+ pull_request:
+ branches: [main]
+ push:
+ branches: [main]
+
+permissions:
+ contents: read
+
+jobs:
+ leak-check:
+ if: github.repository == 'openlit/openlit'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+
+ - name: Check for enterprise-only files
+ shell: bash
+ run: |
+ set -euo pipefail
+
+ if [[ "${{ github.event_name }}" == "pull_request" ]]; then
+ BASE_SHA="${{ github.event.pull_request.base.sha }}"
+ HEAD_SHA="${{ github.event.pull_request.head.sha }}"
+ else
+ BASE_SHA="${{ github.event.before }}"
+ HEAD_SHA="${{ github.sha }}"
+ fi
+
+ changed_files="$(git diff --name-only "$BASE_SHA" "$HEAD_SHA")"
+
+ forbidden_paths='^(src/client/src/ee/|deploy/enterprise/|deploy/cloud/)'
+ if echo "$changed_files" | grep -E "$forbidden_paths"; then
+ echo "Enterprise-only files cannot be added to the OSS repository."
+ exit 1
+ fi
+
+ scripts/check-oss-boundary.sh
diff --git a/.github/workflows/trigger-enterprise-sync.yml b/.github/workflows/trigger-enterprise-sync.yml
new file mode 100644
index 00000000..1553e606
--- /dev/null
+++ b/.github/workflows/trigger-enterprise-sync.yml
@@ -0,0 +1,33 @@
+name: Trigger Enterprise Sync
+
+on:
+ push:
+ branches:
+ - main
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ trigger:
+ if: github.repository == 'openlit/openlit'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Dispatch enterprise OSS sync
+ uses: actions/github-script@v9
+ with:
+ github-token: ${{ secrets.ENTERPRISE_SYNC_TOKEN }}
+ script: |
+ await github.rest.repos.createDispatchEvent({
+ owner: 'openlit',
+ repo: 'openlit-enterprise',
+ event_type: 'oss-main-updated',
+ client_payload: {
+ source_repository: context.repo.repo,
+ source_owner: context.repo.owner,
+ source_ref: context.ref,
+ source_sha: context.sha,
+ source_run_id: context.runId,
+ },
+ });
diff --git a/.github/workflows/ui-test.yml b/.github/workflows/ui-test.yml
index aa3ddb21..d0756953 100644
--- a/.github/workflows/ui-test.yml
+++ b/.github/workflows/ui-test.yml
@@ -18,6 +18,8 @@ jobs:
jest:
name: Jest Unit Tests
runs-on: ubuntu-latest
+ env:
+ SQLITE_DATABASE_URL: file:./test.db
defaults:
run:
working-directory: src/client
diff --git a/.gitignore b/.gitignore
index 449fef74..6331bbc9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,9 +12,7 @@ logs/
**.env
.vscode/
.idea/
-.cursor-rules/
-.cursorrules
**.pem
**certs/index.txt
**.csr
-sdk/typescript-test/
\ No newline at end of file
+sdk/typescript-test/
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..1c072232
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,53 @@
+# OpenLIT Contributor Rules
+
+## Repository Scope
+
+- This repository is the open-source CE/OSS codebase.
+- Do not add enterprise implementation files here.
+- CE may contain shared contracts, feature IDs, disabled feature placeholders, and upgrade-required responses.
+- Enterprise-only implementation belongs in the private `openlit-enterprise` repository under `src/client/src/ee/`.
+
+## Project Hierarchy
+
+OpenLIT uses this hierarchy:
+
+```text
+Organisation
+ Project
+ Database configuration
+```
+
+- Organisation is the account and membership boundary.
+- Project is the workspace boundary for database configurations.
+- Database configs must be read, created, selected, and shared through the current project.
+- New organisation flows must ensure a default project exists.
+- Switching organisation must refresh projects, database configs, and the active DB ping state.
+
+## UI Rules
+
+- Follow the existing settings-page classes for light and dark mode.
+- Do not hard-code user-facing strings in React, route handlers, or library errors. Add them to `src/client/src/constants/messages/en.ts`.
+- Use compact controls in settings and telemetry-style data pages.
+- Keep project and organisation switchers in the header; breadcrumbs belong below the header.
+
+## Testing Rules
+
+- Add tests with the change, not afterwards.
+- For project hierarchy changes, cover membership denial, current project selection, cross-project DB config denial, and default project fallback.
+- For route handlers, test invalid JSON and authorization boundaries.
+- Before handing off, run:
+
+```bash
+cd src/client
+npm test -- --runInBand
+npm run lint
+npx prisma validate --schema prisma/schema.prisma
+```
+
+## Security Rules
+
+- UI feature checks are presentation only. Server routes must enforce authorization.
+- Do not log raw secrets, tokens, passwords, cookies, license keys, or authorization headers.
+- Audit metadata must be redacted before persistence.
+- Internal APIs must use constant-time key comparisons.
+- Stripe webhooks must verify signatures before processing payloads.
diff --git a/docs/latest/openlit/organisation.mdx b/docs/latest/openlit/organisation.mdx
index 26a14be9..bb7a923f 100644
--- a/docs/latest/openlit/organisation.mdx
+++ b/docs/latest/openlit/organisation.mdx
@@ -4,11 +4,12 @@ description: 'Manage multi-tenant workspaces, invite team members, and control a
icon: 'building'
---
-Organisations in OpenLIT let you group team members under a shared workspace, each connected to its own ClickHouse database configuration. All resources — dashboards, prompts, rules, contexts, and secrets — are scoped per organisation, giving teams full isolation and control.
+Organisations in OpenLIT let you group team members under a shared workspace. Each organisation contains one or more projects, and each project owns its own ClickHouse database configuration. Resources such as dashboards, prompts, rules, contexts, and secrets are scoped through the selected organisation and project, giving teams isolation without forcing every workspace to become a separate organisation.
## Key features
- **Workspace isolation**: Each organisation maintains its own database configuration and resource space.
+- **Project hierarchy**: Projects sit inside organisations and group database configurations for different environments, teams, or workloads.
- **Role-based access control**: Assign **Admin** or **Member** roles to control who can manage settings and invite others.
- **Email invitations**: Invite teammates by email. Invitations can be accepted or declined from the notification panel.
- **Multiple organisations**: A single user can belong to multiple organisations and switch between them at any time.
@@ -34,6 +35,22 @@ Organisations in OpenLIT let you group team members under a shared workspace, ea
Invited users receive an email with a link to accept and join the organisation.
</Step>
+ <Step title="Create a project">
+ Add a project when an organisation needs separate database configuration boundaries.
+ 1. Navigate to **Settings → Organisation → Projects**.
+ 2. Enter a project name.
+ 3. Click **Create project**.
+
+ New projects appear in the project dropdown in the top navigation bar.
+ </Step>
+ <Step title="Switch projects">
+ Projects control which database configuration is active.
+ 1. Use the project dropdown in the top navigation bar.
+ 2. Select the project you want to work in.
+ 3. Open **Settings → Organisation** to manage the project's database configuration.
+
+ Database configuration lists update to match the selected project.
+ </Step>
<Step title="Accept an invitation">
When you receive an invitation:
1. Open the link in the invitation email or log in to OpenLIT.
@@ -70,6 +87,21 @@ Organisations in OpenLIT let you group team members under a shared workspace, ea
| Remove members | ✅ | ❌ |
| Delete organisation | ✅ | ❌ |
| Manage database configuration | ✅ | ❌ |
+| Create and switch projects | ✅ | ✅ |
+
+## Project hierarchy
+
+OpenLIT uses the following hierarchy:
+
+```text
+Organisation
+ Project
+ Database configuration
+```
+
+Use organisations for account and membership boundaries. Use projects for separate database configuration boundaries inside the same organisation, such as production, staging, customer-specific workspaces, or different teams sharing the same membership model.
+
+Every organisation has a default project. Existing organisations are mapped to a default project so database configurations continue to work after upgrading.
---
diff --git a/env.example b/env.example
index 7466b84d..83828e86 100644
--- a/env.example
+++ b/env.example
@@ -14,6 +14,11 @@ OPENLIT_DB_PASSWORD=OPENLIT
PORT=3000
DOCKER_PORT=3000
+# Edition mode for shared OSS/Enterprise contracts.
+# OSS contains feature metadata and disabled-feature responses only.
+# Paid implementations live in the private Enterprise repository.
+OPENLIT_EDITION=oss
+
# =============================================================================
# OAuth Configuration (Optional)
# =============================================================================
diff --git a/scripts/check-oss-boundary.sh b/scripts/check-oss-boundary.sh
new file mode 100755
index 00000000..12a8b6a4
--- /dev/null
+++ b/scripts/check-oss-boundary.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$ROOT_DIR"
+
+if find src/client/src/ee deploy/enterprise deploy/cloud -mindepth 0 -maxdepth 0 -print -quit 2>/dev/null | grep -q .; then
+ echo "Enterprise-only paths cannot exist in the OSS repository."
+ exit 1
+fi
+
+if rg -n 'src/client/src/ee|@/ee' src --glob '!*.md'; then
+ echo "Enterprise-only imports cannot be referenced by OSS code."
+ exit 1
+fi
diff --git a/src/client/prisma/migrations/20260528000000_organisation_projects/migration.sql b/src/client/prisma/migrations/20260528000000_organisation_projects/migration.sql
new file mode 100644
index 00000000..da8b721b
--- /dev/null
+++ b/src/client/prisma/migrations/20260528000000_organisation_projects/migration.sql
@@ -0,0 +1,75 @@
+-- Add projects between organisations and database configs.
+CREATE TABLE "projects" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "organisation_id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "slug" TEXT NOT NULL,
+ "is_default" BOOLEAN NOT NULL DEFAULT false,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ CONSTRAINT "projects_organisation_id_fkey" FOREIGN KEY ("organisation_id") REFERENCES "organisations" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+ALTER TABLE "organisation_users" ADD COLUMN "current_project_id" TEXT;
+ALTER TABLE "databaseconfig" ADD COLUMN "project_id" TEXT;
+
+INSERT INTO "projects" ("id", "organisation_id", "name", "slug", "is_default", "createdAt", "updatedAt")
+SELECT
+ 'prj_' || lower(hex(randomblob(16))),
+ "id",
+ 'Default Project',
+ 'default',
+ true,
+ CURRENT_TIMESTAMP,
+ CURRENT_TIMESTAMP
+FROM "organisations";
+
+UPDATE "databaseconfig"
+SET "project_id" = (
+ SELECT "projects"."id"
+ FROM "projects"
+ WHERE "projects"."organisation_id" = "databaseconfig"."organisation_id"
+ AND "projects"."is_default" = true
+ LIMIT 1
+)
+WHERE "organisation_id" IS NOT NULL;
+
+UPDATE "organisation_users"
+SET "current_project_id" = (
+ SELECT "projects"."id"
+ FROM "projects"
+ WHERE "projects"."organisation_id" = "organisation_users"."organisation_id"
+ AND "projects"."is_default" = true
+ LIMIT 1
+)
+WHERE "current_project_id" IS NULL;
+
+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 SET NULL 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";
+PRAGMA foreign_keys=ON;
+PRAGMA defer_foreign_keys=OFF;
+
+CREATE UNIQUE INDEX "projects_organisation_id_slug_key" ON "projects"("organisation_id", "slug");
+CREATE UNIQUE INDEX "databaseconfig_name_project_id_key" ON "databaseconfig"("name", "project_id");
diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prisma
index 700f280f..341937f6 100644
--- a/src/client/prisma/schema.prisma
+++ b/src/client/prisma/schema.prisma
@@ -85,11 +85,27 @@ model Organisation {
createdByUserId String @map("created_by_user_id")
members OrganisationUser[]
invitedUsers OrganisationInvitedUser[]
- databaseConfigs DatabaseConfig[]
+ projects Project[]
@@map("organisations")
}
+model Project {
+ id String @id @default(cuid())
+ organisationId String @map("organisation_id")
+ organisation Organisation @relation(fields: [organisationId], references: [id], onDelete: Cascade)
+ name String
+ slug String
+ isDefault Boolean @default(false) @map("is_default")
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ databaseConfigs DatabaseConfig[]
+ currentForUsers OrganisationUser[] @relation("CurrentOrganisationProject")
+
+ @@unique([organisationId, slug])
+ @@map("projects")
+}
+
model OrganisationUser {
id String @id @default(cuid())
organisationId String @map("organisation_id")
@@ -98,6 +114,8 @@ model OrganisationUser {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
role String @default("member")
isCurrent Boolean @default(false)
+ currentProjectId String? @map("current_project_id")
+ currentProject Project? @relation("CurrentOrganisationProject", fields: [currentProjectId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -133,13 +151,13 @@ model DatabaseConfig {
updatedAt DateTime @updatedAt
createdByUserId String @map("user_id")
createdByUser User @relation(fields: [createdByUserId], references: [id])
- organisationId String? @map("organisation_id")
- organisation Organisation? @relation(fields: [organisationId], references: [id])
+ projectId String? @map("project_id")
+ project Project? @relation(fields: [projectId], references: [id])
dbInvitedUsers DatabaseConfigInvitedUser[]
apiKeys APIKeys[]
opengrounds OpenGround[]
- @@unique([name, organisationId])
+ @@unique([name, projectId])
@@map("databaseconfig")
}
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.ts
new file mode 100644
index 00000000..69b44a22
--- /dev/null
+++ b/src/client/src/__tests__/app/api/organisation/projects-route.test.ts
@@ -0,0 +1,118 @@
+jest.mock("@/lib/prisma", () => ({
+ __esModule: true,
+ default: {
+ organisationUser: {
+ findUnique: jest.fn(),
+ },
+ project: {
+ findMany: jest.fn(),
+ },
+ },
+}));
+jest.mock("@/lib/session", () => ({
+ getCurrentUser: jest.fn(),
+}));
+jest.mock("@/lib/organisation", () => ({
+ createOrganisationProject: jest.fn(),
+ getCurrentProjectForOrganisation: jest.fn(),
+}));
+jest.mock("@/utils/asaw", () => jest.fn());
+
+import { GET, POST } from "@/app/api/organisation/[id]/projects/route";
+import prisma from "@/lib/prisma";
+import { getCurrentUser } from "@/lib/session";
+import {
+ createOrganisationProject,
+ getCurrentProjectForOrganisation,
+} from "@/lib/organisation";
+import asaw from "@/utils/asaw";
+
+const params = { params: { id: "org1" } };
+
+(globalThis as unknown as { Response: { json: unknown } }).Response = {
+ json: (body: unknown, init?: ResponseInit) => ({
+ status: init?.status ?? 200,
+ json: async () => body,
+ }),
+};
+
+function jsonRequest(body: unknown) {
+ return {
+ json: jest.fn().mockResolvedValue(body),
+ } as unknown as Request;
+}
+
+function invalidJsonRequest() {
+ return {
+ json: jest.fn().mockRejectedValue(new Error("Invalid JSON")),
+ } as unknown as Request;
+}
+
+describe("organisation projects route", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "user1" });
+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({
+ id: "membership1",
+ });
+ (prisma.project.findMany as jest.Mock).mockResolvedValue([]);
+ (asaw as jest.Mock).mockImplementation(async (promise) => [null, await promise]);
+ (getCurrentProjectForOrganisation as jest.Mock).mockResolvedValue({
+ id: "project1",
+ });
+ });
+
+ it("requires organisation membership before listing projects", async () => {
+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue(null);
+
+ const response = await GET({} as Request, params);
+
+ expect(response.status).toBe(404);
+ expect(await response.json()).toBe("Organisation not found");
+ expect(prisma.project.findMany).not.toHaveBeenCalled();
+ });
+
+ it("marks the selected project in the list", async () => {
+ (prisma.project.findMany as jest.Mock).mockResolvedValue([
+ { id: "project1", name: "Default", isDefault: true },
+ { id: "project2", name: "Production", isDefault: false },
+ ]);
+
+ const response = await GET({} as Request, params);
+ const body = await response.json();
+
+ expect(response.status).toBe(200);
+ expect(body).toEqual([
+ expect.objectContaining({ id: "project1", isCurrent: true }),
+ expect.objectContaining({ id: "project2", isCurrent: false }),
+ ]);
+ });
+
+ it("returns a validation error for invalid JSON", async () => {
+ const response = await POST(invalidJsonRequest(), params);
+
+ expect(response.status).toBe(400);
+ expect(await response.json()).toBe("Project name is required");
+ expect(createOrganisationProject).not.toHaveBeenCalled();
+ });
+
+ it("returns a validation error for long project names", async () => {
+ const response = await POST(jsonRequest({ name: "a".repeat(121) }), params);
+
+ expect(response.status).toBe(400);
+ expect(await response.json()).toBe("Project name must be 120 characters or less");
+ expect(createOrganisationProject).not.toHaveBeenCalled();
+ });
+
+ it("trims and creates valid project names", async () => {
+ (asaw as jest.Mock).mockResolvedValueOnce([
+ null,
+ { id: "project2", name: "Production" },
+ ]);
+
+ const response = await POST(jsonRequest({ name: " Production " }), params);
+
+ expect(response.status).toBe(200);
+ expect(createOrganisationProject).toHaveBeenCalledWith("org1", "Production");
+ });
+});
diff --git a/src/client/src/__tests__/helpers/client/organisation.test.ts b/src/client/src/__tests__/helpers/client/organisation.test.ts
index 1f1141f0..78367863 100644
--- a/src/client/src/__tests__/helpers/client/organisation.test.ts
+++ b/src/client/src/__tests__/helpers/client/organisation.test.ts
@@ -70,6 +70,9 @@ const mockSetIsLoading = jest.fn();
const mockSetList = jest.fn();
const mockSetCurrent = jest.fn();
const mockSetPendingInvitations = jest.fn();
+const mockProjectSetIsLoading = jest.fn();
+const mockProjectSetList = jest.fn();
+const mockProjectSetCurrent = jest.fn();
const makeGetState = (list: any[] = []) => ({
organisation: {
@@ -85,6 +88,12 @@ const makeGetState = (list: any[] = []) => ({
setPing: jest.fn(),
list: [],
},
+ project: {
+ setIsLoading: mockProjectSetIsLoading,
+ setList: mockProjectSetList,
+ setCurrent: mockProjectSetCurrent,
+ list: [],
+ },
});
beforeEach(() => {
diff --git a/src/client/src/__tests__/lib/db-config.test.ts b/src/client/src/__tests__/lib/db-config.test.ts
index 6fff6eb3..fcd1ea79 100644
--- a/src/client/src/__tests__/lib/db-config.test.ts
+++ b/src/client/src/__tests__/lib/db-config.test.ts
@@ -23,6 +23,9 @@ jest.mock('@/lib/prisma', () => ({
findMany: jest.fn(),
create: jest.fn(),
},
+ project: {
+ findFirst: jest.fn(),
+ },
user: {
findUnique: jest.fn(),
},
@@ -33,12 +36,15 @@ jest.mock('@/lib/session', () => ({
}));
jest.mock('@/lib/organisation', () => ({
getCurrentOrganisation: jest.fn(),
+ getCurrentProjectForOrganisation: jest.fn(),
}));
jest.mock('@/utils/asaw', () => jest.fn());
jest.mock('@/constants/messages', () => ({
__esModule: true,
default: jest.fn(() => ({
UNAUTHORIZED_USER: 'Unauthorized',
+ DB_CONFIG_NOT_IN_CURRENT_PROJECT: "Database config doesn't exist in current project",
+ CURRENT_DB_CONFIG_SET_SUCCESS: 'Current DB config set successfully!',
})),
}));
jest.mock('@/utils/error', () => ({
@@ -65,11 +71,12 @@ import {
} from '@/lib/db-config';
import prisma from '@/lib/prisma';
import { getCurrentUser } from '@/lib/session';
-import { getCurrentOrganisation } from '@/lib/organisation';
+import { getCurrentOrganisation, getCurrentProjectForOrganisation } from '@/lib/organisation';
import asaw from '@/utils/asaw';
const mockUser = { id: 'u1', email: '[email protected]' };
const mockOrg = { id: 'org1', name: 'Test Org' };
+const mockProject = { id: 'project1', organisationId: 'org1', name: 'Default Project' };
const mockDbConfig = {
id: 'db1',
name: 'Test DB',
@@ -78,7 +85,7 @@ const mockDbConfig = {
username: 'admin',
password: 'pass',
database: 'default',
- organisationId: 'org1',
+ projectId: 'project1',
createdByUserId: 'u1',
createdAt: new Date(),
};
@@ -87,6 +94,7 @@ beforeEach(() => {
jest.clearAllMocks();
(getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
(getCurrentOrganisation as jest.Mock).mockResolvedValue(mockOrg);
+ (getCurrentProjectForOrganisation as jest.Mock).mockResolvedValue(mockProject);
(prisma.databaseConfigUser.findMany as jest.Mock).mockResolvedValue([]);
(prisma.databaseConfigUser.findFirst as jest.Mock).mockResolvedValue(null);
(prisma.databaseConfig.findFirst as jest.Mock).mockResolvedValue(null);
@@ -137,14 +145,14 @@ describe('getDBConfigByUser', () => {
expect(result).toBeUndefined();
});
- it('auto-migrates orphaned configs when org exists', async () => {
+ it('auto-migrates orphaned configs when project exists', async () => {
(prisma.databaseConfigUser.findMany as jest.Mock)
.mockResolvedValueOnce([{ databaseConfigId: 'db-orphan' }]) // orphaned
.mockResolvedValueOnce([]); // user configs
(prisma.databaseConfig.updateMany as jest.Mock).mockResolvedValue({ count: 1 });
await getDBConfigByUser();
expect(prisma.databaseConfig.updateMany).toHaveBeenCalledWith(
- expect.objectContaining({ data: { organisationId: 'org1' } })
+ expect.objectContaining({ data: { projectId: 'project1' } })
);
});
@@ -218,22 +226,23 @@ describe('upsertDBConfig', () => {
await expect(upsertDBConfig(validConfig)).rejects.toThrow('DB config Name already exists');
});
- it('creates new config with org (org upsert path)', async () => {
- (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'new-db', organisationId: 'org1' }]);
- (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ organisationId: 'org1' });
+ it('creates new config with project (project upsert path)', async () => {
+ (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'new-db', projectId: 'project1' }]);
+ (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ projectId: 'project1' });
(prisma.databaseConfigUser.create as jest.Mock).mockResolvedValue({});
const result = await upsertDBConfig(validConfig);
expect(result).toBe('Added db details successfully');
});
- it('creates config without org (no-org create path)', async () => {
+ it('creates config without project (no-project create path)', async () => {
(getCurrentOrganisation as jest.Mock).mockResolvedValue(null);
+ (getCurrentProjectForOrganisation as jest.Mock).mockResolvedValue(null);
(prisma.databaseConfig.findFirst as jest.Mock)
.mockResolvedValueOnce(null) // name uniqueness check
- .mockResolvedValueOnce(null); // check if existing (no-org path)
+ .mockResolvedValueOnce(null); // check if existing (no-project path)
(prisma.databaseConfig.create as jest.Mock).mockResolvedValue({ id: 'new-db' });
- (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ organisationId: null });
+ (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ projectId: null });
(prisma.databaseConfigUser.create as jest.Mock).mockResolvedValue({});
const result = await upsertDBConfig(validConfig);
@@ -241,13 +250,14 @@ describe('upsertDBConfig', () => {
expect(prisma.databaseConfig.create).toHaveBeenCalled();
});
- it('updates existing config without org (no-org update path)', async () => {
+ it('updates existing config without project (no-project update path)', async () => {
(getCurrentOrganisation as jest.Mock).mockResolvedValue(null);
+ (getCurrentProjectForOrganisation as jest.Mock).mockResolvedValue(null);
(prisma.databaseConfig.findFirst as jest.Mock)
.mockResolvedValueOnce(null) // name uniqueness check
- .mockResolvedValueOnce({ id: 'existing-db' }); // existing no-org config
+ .mockResolvedValueOnce({ id: 'existing-db' }); // existing no-project config
(prisma.databaseConfig.update as jest.Mock).mockResolvedValue({ id: 'existing-db' });
- (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ organisationId: null });
+ (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ projectId: null });
(prisma.databaseConfigUser.create as jest.Mock).mockResolvedValue({});
const result = await upsertDBConfig(validConfig);
@@ -319,6 +329,7 @@ describe('deleteDBConfig', () => {
describe('setCurrentDBConfig', () => {
it('sets a new current db config (unsets old current)', async () => {
+ (prisma.databaseConfig.findFirst as jest.Mock).mockResolvedValue({ id: 'new-db' });
(prisma.databaseConfigUser.findFirst as jest.Mock).mockResolvedValue({
databaseConfig: { id: 'old-db' },
});
@@ -330,6 +341,7 @@ describe('setCurrentDBConfig', () => {
});
it('sets current db config when no existing current', async () => {
+ (prisma.databaseConfig.findFirst as jest.Mock).mockResolvedValue({ id: 'new-db' });
(prisma.databaseConfigUser.findFirst as jest.Mock).mockResolvedValue(null);
(prisma.databaseConfigUser.update as jest.Mock).mockResolvedValue({});
@@ -342,6 +354,14 @@ describe('setCurrentDBConfig', () => {
(getCurrentUser as jest.Mock).mockResolvedValue(null);
await expect(setCurrentDBConfig('db1')).rejects.toThrow('Unauthorized');
});
+
+ it('rejects configs outside the current project', async () => {
+ (prisma.databaseConfig.findFirst as jest.Mock).mockResolvedValue(null);
+
+ await expect(setCurrentDBConfig('other-project-db')).rejects.toThrow(
+ "Database config doesn't exist in current project"
+ );
+ });
});
describe('shareDBConfig', () => {
@@ -363,7 +383,7 @@ describe('shareDBConfig', () => {
.mockResolvedValueOnce([null, { canShare: true, canEdit: true, canDelete: true }]) // checkPermissionForDbAction
.mockResolvedValueOnce([null, { id: 'u2', email: '[email protected]' }]) // user.findUnique
.mockResolvedValueOnce([null, null]); // databaseConfigUser.findFirst (no existing)
- (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ organisationId: null });
+ (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ projectId: null });
(prisma.databaseConfigUser.create as jest.Mock).mockResolvedValue({});
const result = await shareDBConfig({
diff --git a/src/client/src/__tests__/lib/organisation.test.ts b/src/client/src/__tests__/lib/organisation.test.ts
index ed30a8db..24dde7a8 100644
--- a/src/client/src/__tests__/lib/organisation.test.ts
+++ b/src/client/src/__tests__/lib/organisation.test.ts
@@ -7,6 +7,11 @@ jest.mock('@/lib/prisma', () => ({
update: jest.fn(),
delete: jest.fn(),
},
+ project: {
+ findFirst: jest.fn(),
+ findUnique: jest.fn(),
+ create: jest.fn(),
+ },
organisationUser: {
findFirst: jest.fn(),
findMany: jest.fn(),
@@ -39,6 +44,8 @@ jest.mock('@/lib/prisma', () => ({
update: jest.fn(),
},
$transaction: jest.fn(),
+ $queryRaw: jest.fn(),
+ $executeRaw: jest.fn(),
},
}));
jest.mock('@/lib/session', () => ({
@@ -54,6 +61,7 @@ jest.mock('@/constants/messages', () => ({
ORGANISATION_CANNOT_DELETE_WITH_MEMBERS: 'Cannot delete with members',
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',
ONLY_ADMIN_CAN_INVITE: 'Only admin can invite',
USER_ALREADY_ORGANISATION_MEMBER: 'Already a member',
USER_ALREADY_INVITED: 'Already invited',
@@ -101,12 +109,20 @@ import { throwIfError } from '@/utils/error';
import getMessage from '@/constants/messages';
const mockUser = { id: 'u1', email: '[email protected]' };
+const mockProject = {
+ id: 'project1',
+ organisationId: 'org1',
+ name: 'Default Project',
+ slug: 'default',
+ isDefault: true,
+};
const mockOrg = {
id: 'org1',
name: 'Test Org',
slug: 'test-org-abc123',
createdByUserId: 'u1',
_count: { members: 1 },
+ projects: [mockProject],
};
beforeEach(() => {
@@ -125,6 +141,7 @@ beforeEach(() => {
ORGANISATION_CANNOT_DELETE_WITH_MEMBERS: 'Cannot delete with members',
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',
ONLY_ADMIN_CAN_INVITE: 'Only admin can invite',
USER_ALREADY_ORGANISATION_MEMBER: 'Already a member',
USER_ALREADY_INVITED: 'Already invited',
@@ -143,6 +160,11 @@ beforeEach(() => {
(getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
// Default: no existing slug (unique slug generation)
(prisma.organisation.findUnique as jest.Mock).mockResolvedValue(null);
+ (prisma.project.findFirst as jest.Mock).mockResolvedValue(mockProject);
+ (prisma.project.findUnique as jest.Mock).mockResolvedValue(mockProject);
+ (prisma.project.create as jest.Mock).mockResolvedValue(mockProject);
+ (prisma.$queryRaw as jest.Mock).mockResolvedValue([{ current_project_id: 'project1' }]);
+ (prisma.$executeRaw as jest.Mock).mockResolvedValue(1);
// Default: findUnique on organisationUser returns null (not a member by default)
(prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue(null);
// Default: findMany returns empty arrays
@@ -150,8 +172,10 @@ beforeEach(() => {
(prisma.databaseConfigUser.findMany as jest.Mock).mockResolvedValue([]);
// Default: databaseConfig.findMany returns [] (no org configs)
(prisma.databaseConfig.findMany as jest.Mock).mockResolvedValue([]);
- // Default: $transaction resolves
- (prisma.$transaction as jest.Mock).mockResolvedValue([]);
+ // Default: $transaction executes callback transactions and resolves batch transactions
+ (prisma.$transaction as jest.Mock).mockImplementation(async (arg) =>
+ typeof arg === 'function' ? arg(prisma) : arg
+ );
// Default: user.findUnique returns null
(prisma.user.findUnique as jest.Mock).mockResolvedValue(null);
// Default: invited user operations return null/[]
diff --git a/src/client/src/app/(playground)/settings/organisation/page.tsx b/src/client/src/app/(playground)/settings/organisation/page.tsx
index 97f13825..b8a5860e 100644
--- a/src/client/src/app/(playground)/settings/organisation/page.tsx
+++ b/src/client/src/app/(playground)/settings/organisation/page.tsx
@@ -3,7 +3,7 @@
import { useState, useEffect } from "react";
import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
-import { useRouter } from "next/navigation";
+import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -50,6 +50,8 @@ import {
Users,
Settings,
Clock,
+ FolderKanban,
+ Database,
} from "lucide-react";
import { useRootStore } from "@/store";
import {
@@ -72,7 +74,11 @@ import {
changeActiveOrganisation,
updateMemberRole,
} from "@/helpers/client/organisation";
-import { getData } from "@/utils/api";
+import {
+ changeActiveProject,
+ fetchProjectList,
+} from "@/helpers/client/project";
+import { getData, postData } from "@/utils/api";
import asaw from "@/utils/asaw";
import {
AlertDialog,
@@ -88,6 +94,7 @@ import {
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;
@@ -105,9 +112,19 @@ interface PendingInvite {
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) || [];
@@ -126,6 +143,10 @@ export default function OrganisationSettingsPage() {
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;
@@ -160,6 +181,7 @@ export default function OrganisationSettingsPage() {
if (currentOrg) {
setOrgName(currentOrg.name);
fetchMembers();
+ fetchProjects();
}
}, [currentOrg?.id]);
@@ -181,6 +203,48 @@ export default function OrganisationSettingsPage() {
}
};
+ 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;
@@ -314,12 +378,16 @@ export default function OrganisationSettingsPage() {
)}
{currentOrg && (
- <Tabs defaultValue="details" className="w-auto">
+ <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})
@@ -428,6 +496,128 @@ export default function OrganisationSettingsPage() {
)}
</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">
diff --git a/src/client/src/app/api/organisation/[id]/projects/current/[projectId]/route.ts b/src/client/src/app/api/organisation/[id]/projects/current/[projectId]/route.ts
new file mode 100644
index 00000000..46cf9a66
--- /dev/null
+++ b/src/client/src/app/api/organisation/[id]/projects/current/[projectId]/route.ts
@@ -0,0 +1,15 @@
+import { setCurrentProject } from "@/lib/organisation";
+import asaw from "@/utils/asaw";
+
+export async function POST(
+ _request: Request,
+ { params }: { params: { id: string; projectId: string } }
+) {
+ const [err, res] = await asaw(
+ setCurrentProject(params.id, params.projectId)
+ );
+
+ if (err) return Response.json(err, { status: 400 });
+
+ return Response.json(res);
+}
diff --git a/src/client/src/app/api/organisation/[id]/projects/route.ts b/src/client/src/app/api/organisation/[id]/projects/route.ts
new file mode 100644
index 00000000..fec81ae5
--- /dev/null
+++ b/src/client/src/app/api/organisation/[id]/projects/route.ts
@@ -0,0 +1,75 @@
+import {
+ createOrganisationProject,
+ getCurrentProjectForOrganisation,
+} from "@/lib/organisation";
+import prisma from "@/lib/prisma";
+import { getCurrentUser } from "@/lib/session";
+import asaw from "@/utils/asaw";
+import getMessage from "@/constants/messages";
+
+async function readJson(request: Request) {
+ try {
+ return await request.json();
+ } catch {
+ return null;
+ }
+}
+
+export async function GET(
+ _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 [currentProjectErr, currentProject] = await asaw(
+ getCurrentProjectForOrganisation(params.id)
+ );
+ if (currentProjectErr) return Response.json(currentProjectErr, { status: 400 });
+
+ const projects = await prisma.project.findMany({
+ where: { organisationId: params.id },
+ orderBy: [{ isDefault: "desc" }, { createdAt: "asc" }],
+ });
+
+ return Response.json(
+ projects.map((project) => ({
+ ...project,
+ isCurrent: project.id === currentProject?.id,
+ }))
+ );
+}
+
+export async function POST(
+ request: Request,
+ { params }: { params: { id: string } }
+) {
+ 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) {
+ return Response.json(messages.PROJECT_NAME_LENGTH_ERROR, {
+ status: 400,
+ });
+ }
+
+ const [err, project] = await asaw(createOrganisationProject(params.id, name));
+ if (err) return Response.json(err, { status: 400 });
+
+ return Response.json(project);
+}
diff --git a/src/client/src/components/(playground)/header-project-switch.tsx b/src/client/src/components/(playground)/header-project-switch.tsx
new file mode 100644
index 00000000..072d2693
--- /dev/null
+++ b/src/client/src/components/(playground)/header-project-switch.tsx
@@ -0,0 +1,90 @@
+"use client";
+
+import { useEffect } from "react";
+import { useRouter } from "next/navigation";
+import { Loader2 } from "lucide-react";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Button } from "@/components/ui/button";
+import { getCurrentOrganisation } from "@/selectors/organisation";
+import {
+ getCurrentProject,
+ getProjectIsLoading,
+ getProjectList,
+} from "@/selectors/project";
+import { useRootStore } from "@/store";
+import { cn } from "@/lib/utils";
+import getMessage from "@/constants/messages";
+import { changeActiveProject, fetchProjectList } from "@/helpers/client/project";
+
+export default function HeaderProjectSwitch() {
+ const messages = getMessage();
+ const router = useRouter();
+ const currentOrg = useRootStore(getCurrentOrganisation);
+ const projects = useRootStore(getProjectList) || [];
+ const selectedProject = useRootStore(getCurrentProject);
+ const isLoading = useRootStore(getProjectIsLoading);
+
+ useEffect(() => {
+ if (!currentOrg?.id) {
+ useRootStore.getState().project.setList([]);
+ return;
+ }
+
+ fetchProjectList(currentOrg.id);
+ }, [currentOrg?.id]);
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ className="h-9 min-w-32 max-w-56 shrink-0 justify-start overflow-hidden border-stone-200 bg-stone-100/50 px-3 py-1.5 text-left font-normal text-stone-700 hover:bg-stone-200 hover:text-stone-950 dark:border-stone-800 dark:bg-stone-900/70 dark:text-stone-200 dark:hover:bg-stone-800 dark:hover:text-white"
+ disabled={!currentOrg?.id || isLoading || projects.length === 0}
+ >
+ {isLoading ? (
+ <Loader2 className="mr-2 size-3 shrink-0 animate-spin" />
+ ) : null}
+ <span className="min-w-0 truncate text-xs font-medium">
+ {selectedProject?.name ||
+ (isLoading ? messages.LOADING_PROJECT : messages.NO_PROJECT)}
+ </span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-56" side="bottom" align="start">
+ <DropdownMenuLabel>{messages.PROJECTS}</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ {projects.map((project) => (
+ <DropdownMenuCheckboxItem
+ key={project.id}
+ checked={project.id === selectedProject?.id}
+ onCheckedChange={() => changeActiveProject(project.id)}
+ className={cn(project.isDefault && "font-medium")}
+ >
+ <span className="truncate">{project.name}</span>
+ {project.isDefault ? (
+ <span className="ml-2 text-xs text-muted-foreground">
+ {messages.DEFAULT_PROJECT}
+ </span>
+ ) : null}
+ </DropdownMenuCheckboxItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ router.push("/settings/organisation?tab=projects");
+ }}
+ >
+ {messages.MANAGE_PROJECTS}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/src/client/src/components/(playground)/header.tsx b/src/client/src/components/(playground)/header.tsx
index 37304698..d3217c46 100644
--- a/src/client/src/components/(playground)/header.tsx
+++ b/src/client/src/components/(playground)/header.tsx
@@ -2,6 +2,9 @@
import { useEffect, useRef } from "react";
import RouteBreadcrumbs from "./route-breadcrumbs";
import { usePortal } from "./header-portal";
+import OrganisationSwitch from "./sidebar/organisation-switch";
+import HeaderProjectSwitch from "./header-project-switch";
+import DatabaseConfigSwitch from "./sidebar/database-config-switch";
export default function Header() {
const { setHeaderRef } = usePortal();
@@ -14,9 +17,26 @@ export default function Header() {
}, [setHeaderRef]);
return (
- <header className="flex w-full mb-2">
- <RouteBreadcrumbs />
- <div ref={containerRef} />
+ <header className="mb-2 flex w-full flex-col gap-1.5">
+ <div className="flex min-w-0 items-center gap-2">
+ <OrganisationSwitch
+ contentAlign="start"
+ contentSide="bottom"
+ className="border-stone-200 bg-stone-100/50 text-stone-700 hover:bg-stone-200 hover:text-stone-950 dark:border-stone-800 dark:bg-stone-900/70 dark:text-stone-200 dark:hover:bg-stone-800 dark:hover:text-white"
+ />
+ <span className="text-sm text-stone-400 dark:text-stone-600">/</span>
+ <HeaderProjectSwitch />
+ <span className="text-sm text-stone-400 dark:text-stone-600">/</span>
+ <DatabaseConfigSwitch
+ contentAlign="start"
+ contentSide="bottom"
+ className="border-stone-200 bg-stone-100/50 text-stone-700 hover:bg-stone-200 hover:text-stone-950 dark:border-stone-800 dark:bg-stone-900/70 dark:text-stone-200 dark:hover:bg-stone-800 dark:hover:text-white"
+ />
+ <div ref={containerRef} className="ml-auto flex items-center" />
+ </div>
+ <div className="min-w-0">
+ <RouteBreadcrumbs />
+ </div>
</header>
);
}
diff --git a/src/client/src/components/(playground)/sidebar/database-config-switch.tsx b/src/client/src/components/(playground)/sidebar/database-config-switch.tsx
index f51fcd2a..f28fd777 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,3 @@
-import { ChevronsUpDown, Database, Plus, Settings } from "lucide-react";
import { getDatabaseConfigList } from "@/selectors/database-config";
import { useRootStore } from "@/store";
import { useEffect } from "react";
@@ -10,12 +9,24 @@ import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
-import { ICON_CLASSES } from "@/constants/sidebar";
import Link from "next/link";
import { useRouter } from "next/navigation";
import getMessage from "@/constants/messages";
+import { cn } from "@/lib/utils";
-export default function DatabaseConfigSwitch() {
+type DatabaseConfigSwitchProps = {
+ className?: string;
+ contentAlign?: "center" | "end" | "start";
+ contentSide?: "bottom" | "left" | "right" | "top";
+};
+
+const triggerClasses = "flex h-9 min-w-32 max-w-56 shrink-0 items-center justify-start overflow-hidden px-3 py-1.5 text-left font-normal";
+
+export default function DatabaseConfigSwitch({
+ className,
+ contentAlign = "start",
+ contentSide = "right",
+}: DatabaseConfigSwitchProps) {
const posthog = usePostHog();
const router = useRouter();
const messages = getMessage();
@@ -40,11 +51,10 @@ export default function DatabaseConfigSwitch() {
return (
<Button
variant="outline"
- className="flex gap-2 shrink-0 justify-start group-data-[state=close]:justify-center p-[calc(0.625rem-1px)] overflow-hidden text-stone-500 dark:text-stone-300 hover:bg-stone-700 dark:hover:bg-stone-600 hover:text-white font-normal"
+ className={cn(triggerClasses, className)}
onClick={() => router.push("/settings/database-config")}
>
- <Settings className={`${ICON_CLASSES} shrink-0`} />
- <span className="block group-data-[state=close]:hidden text-ellipsis overflow-hidden whitespace-nowrap grow text-left">
+ <span className="min-w-0 truncate text-xs font-medium">
{messages.MANAGE_DB_CONFIG}
</span>
</Button>
@@ -57,13 +67,11 @@ export default function DatabaseConfigSwitch() {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button variant="outline" className="flex gap-2 shrink-0 justify-start group-data-[state=close]:justify-center p-[calc(0.625rem-1px)] overflow-hidden text-stone-500 dark:text-stone-300 hover:bg-stone-700 dark:hover:bg-stone-600 hover:text-white font-normal">
- <Database className={`${ICON_CLASSES} shrink-0`} />
- <span className="block group-data-[state=close]:hidden text-ellipsis overflow-hidden whitespace-nowrap grow text-left">{displayDatabaseName}</span>
- <ChevronsUpDown className={`size-4 block group-data-[state=close]:hidden shrink-0`} />
+ <Button variant="outline" className={cn(triggerClasses, className)}>
+ <span className="min-w-0 truncate text-xs font-medium">{displayDatabaseName}</span>
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent className="w-56" side="right" align="start">
+ <DropdownMenuContent className="w-56" side={contentSide} align={contentAlign}>
<DropdownMenuLabel>{messages.DATABASES}</DropdownMenuLabel>
<DropdownMenuSeparator />
{list.map((item) => (
@@ -95,4 +103,4 @@ export default function DatabaseConfigSwitch() {
</DropdownMenuContent>
</DropdownMenu>
);
-}
\ No newline at end of file
+}
diff --git a/src/client/src/components/(playground)/sidebar/organisation-switch.tsx b/src/client/src/components/(playground)/sidebar/organisation-switch.tsx
index f5de7304..5b8af40a 100644
--- a/src/client/src/components/(playground)/sidebar/organisation-switch.tsx
+++ b/src/client/src/components/(playground)/sidebar/organisation-switch.tsx
@@ -1,5 +1,5 @@
"use client";
-import { Building2, ChevronsUpDown, Plus, Mail } from "lucide-react";
+import { Plus, Mail } from "lucide-react";
import {
getCurrentOrganisation,
getOrganisationList,
@@ -19,14 +19,26 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
-import { ICON_CLASSES } from "@/constants/sidebar";
import Link from "next/link";
import { Badge } from "@/components/ui/badge";
import CreateOrganisationDialog from "./create-organisation-dialog";
import getMessage from "@/constants/messages";
import { CLIENT_EVENTS } from "@/constants/events";
+import { cn } from "@/lib/utils";
-export default function OrganisationSwitch() {
+type OrganisationSwitchProps = {
+ className?: string;
+ contentAlign?: "center" | "end" | "start";
+ contentSide?: "bottom" | "left" | "right" | "top";
+};
+
+const triggerClasses = "flex h-9 min-w-36 max-w-64 shrink-0 items-center justify-start overflow-hidden px-3 py-1.5 text-left font-normal relative";
+
+export default function OrganisationSwitch({
+ className,
+ contentAlign = "start",
+ contentSide = "right",
+}: OrganisationSwitchProps) {
const posthog = usePostHog();
const messages = getMessage();
const list = useRootStore(getOrganisationList) || [];
@@ -49,26 +61,22 @@ export default function OrganisationSwitch() {
<DropdownMenuTrigger asChild>
<Button
variant="outline"
- className="flex gap-2 shrink-0 justify-start group-data-[state=close]:justify-center p-[calc(0.625rem-1px)] overflow-hidden text-stone-500 dark:text-stone-300 hover:bg-stone-700 dark:hover:bg-stone-600 hover:text-white font-normal relative"
+ className={cn(triggerClasses, className)}
>
- <Building2 className={`${ICON_CLASSES} shrink-0`} />
- <span className="block group-data-[state=close]:hidden text-ellipsis overflow-hidden whitespace-nowrap grow text-left">
+ <span className="min-w-0 grow truncate text-xs font-medium">
{currentOrg?.name}
</span>
{pendingInvitationsCount > 0 && (
<Badge
variant="destructive"
- className="h-5 w-5 p-0 flex items-center justify-center text-xs group-data-[state=close]:absolute group-data-[state=close]:-top-1 group-data-[state=close]:-right-1"
+ className="h-4 min-w-4 px-1 flex items-center justify-center text-[10px]"
>
{pendingInvitationsCount}
</Badge>
)}
- <ChevronsUpDown
- className={`size-4 block group-data-[state=close]:hidden shrink-0`}
- />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent className="w-56" side="right" align="start">
+ <DropdownMenuContent className="w-56" side={contentSide} align={contentAlign}>
<DropdownMenuLabel>{messages.ORGANISATIONS}</DropdownMenuLabel>
<DropdownMenuSeparator />
{list.map((item) => (
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index 95e669d9..559aef65 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -933,6 +933,8 @@ export const EDIT_DETAILS = "Edit details";
export const LOG_OUT = "Log out";
export const EXPAND = "Expand";
export const DATABASES = "Databases";
+export const DATABASE_CONFIG = "Database Config";
+export const DB_CONFIG = "DB Config";
export const ADD_NEW_CONFIG = "Add New Config";
export const MANAGE_DB_CONFIG = "Manage DB Config";
export const PENDING_INVITATION = "Pending Invitation";
@@ -940,6 +942,28 @@ export const PENDING_INVITATION = "Pending Invitation";
// Organisation
export const ORGANISATION = "Organisation";
export const ORGANISATIONS = "Organisations";
+export const PROJECT = "Project";
+export const PROJECTS = "Projects";
+export const PROJECT_NAME = "Project Name";
+export const PROJECT_NAME_PLACEHOLDER = "Production";
+export const MANAGE_PROJECTS = "Manage Projects";
+export const DEFAULT_PROJECT = "Default Project";
+export const PROJECT_NAME_REQUIRED = "Project name is required";
+export const PROJECT_NAME_LENGTH_ERROR = "Project name must be 120 characters or less";
+export const PROJECT_NAME_LENGTH_RANGE_ERROR =
+ "Project name must be between 1 and 120 characters";
+export const CURRENT = "Current";
+export const LOADING_PROJECT = "Loading project";
+export const NO_PROJECT = "No project";
+export const PROJECT_NOT_FOUND = "Project not found";
+export const PROJECT_SWITCH_FAILED = "Failed to switch project";
+export const DB_CONFIG_NOT_IN_CURRENT_PROJECT =
+ "Database config doesn't exist in current project";
+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 USE_PROJECT = "Use project";
export const ORGANISATION_NAME = "Organisation Name";
export const ORGANISATION_NAME_PLACEHOLDER = "My Company";
export const CREATE_ORGANISATION = "Create Organisation";
@@ -1007,6 +1031,12 @@ export const ORGANISATION_NOTHING_TO_UPDATE = "Nothing to update";
export const ORGANISATION_ONLY_CREATOR_CAN_DELETE = "Only the creator can delete the organisation";
export const ORGANISATION_CANNOT_DELETE_WITH_MEMBERS = "Cannot delete organisation with other members";
export const USER_ALREADY_ORGANISATION_MEMBER = "User is already a member of this organisation";
+export const CREATE_ORGANISATION_PROJECT = "Create project";
+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 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";
export const INVITATION_NOT_FOUND = "Invitation not found";
diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsx
index 31da1edf..046388dd 100644
--- a/src/client/src/constants/sidebar.tsx
+++ b/src/client/src/constants/sidebar.tsx
@@ -14,25 +14,12 @@ import {
SettingsIcon,
SlidersHorizontal,
} from "lucide-react";
-import DatabaseConfigSwitch from "@/components/(playground)/sidebar/database-config-switch";
import OpenTelemetrySvg from "@/components/svg/opentelemetry";
-import OrganisationSwitch from "@/components/(playground)/sidebar/organisation-switch";
import Otter from "@/components/svg/otter";
export const ICON_CLASSES = "flex-shrink-0 size-5";
export const SIDEBAR_ITEMS: SidebarItemProps[] = [
- {
- title: "Organisation",
- type: "section",
- children: [
- {
- text: "Organisation Switch",
- component: <OrganisationSwitch />,
- type: "action",
- },
- ]
- },
{
icon: <Home className={ICON_CLASSES} />,
text: "Home",
@@ -113,11 +100,6 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [
title: "Configuration",
type: "section",
children: [{
- text: "Database Switch",
- component: <DatabaseConfigSwitch />,
- type: "action",
- },
- {
icon: <MonitorCog className={ICON_CLASSES} />,
text: "Evaluations",
link: "/evaluations",
diff --git a/src/client/src/features/disabled-feature.ts b/src/client/src/features/disabled-feature.ts
new file mode 100644
index 00000000..ae16a641
--- /dev/null
+++ b/src/client/src/features/disabled-feature.ts
@@ -0,0 +1,34 @@
+import { FeatureId, getFeatureDefinition } from "@/features";
+
+export type UpgradeRequiredBody = {
+ code: "upgrade_required";
+ featureId: FeatureId;
+ featureName: string;
+ message: string;
+};
+
+export function upgradeRequiredBody(featureId: FeatureId): UpgradeRequiredBody {
+ const feature = getFeatureDefinition(featureId);
+ const planName = feature.tier === "cloud" ? "Cloud" : "Enterprise";
+
+ return {
+ code: "upgrade_required",
+ featureId,
+ featureName: feature.name,
+ message: `${feature.name} requires an active ${planName} plan.`,
+ };
+}
+
+export function upgradeRequiredResponse(featureId: FeatureId) {
+ return Response.json(upgradeRequiredBody(featureId), {
+ status: 403,
+ });
+}
+
+export function disabledFeature(featureId: FeatureId) {
+ return {
+ featureId,
+ isEnabled: false,
+ upgradeRequired: () => upgradeRequiredResponse(featureId),
+ };
+}
diff --git a/src/client/src/features/index.ts b/src/client/src/features/index.ts
new file mode 100644
index 00000000..a6fecf35
--- /dev/null
+++ b/src/client/src/features/index.ts
@@ -0,0 +1,31 @@
+export type FeatureId = string;
+export type FeatureTier = "free" | "enterprise" | "cloud";
+
+export type FeatureDefinition = {
+ id: FeatureId;
+ name: string;
+ tier: FeatureTier;
+ description: string;
+ routePrefixes?: string[];
+};
+
+export const EDITION_FEATURES: FeatureDefinition[] = [];
+
+export const FEATURES = Object.freeze(
+ Object.fromEntries(EDITION_FEATURES.map((feature) => [feature.id, feature]))
+) as Readonly<Record<FeatureId, FeatureDefinition>>;
+
+export function getFeatureDefinition(featureId: FeatureId) {
+ return (
+ FEATURES[featureId] ?? {
+ id: featureId,
+ name: featureId,
+ tier: "enterprise",
+ description: "Paid feature.",
+ }
+ );
+}
+
+export function getPaidFeatures() {
+ return EDITION_FEATURES.filter((feature) => feature.tier !== "free");
+}
diff --git a/src/client/src/features/registry.ts b/src/client/src/features/registry.ts
new file mode 100644
index 00000000..6d1e0ee8
--- /dev/null
+++ b/src/client/src/features/registry.ts
@@ -0,0 +1 @@
+export * from "./index";
diff --git a/src/client/src/helpers/client/organisation.ts b/src/client/src/helpers/client/organisation.ts
index e3c0f45e..be9b3de6 100644
--- a/src/client/src/helpers/client/organisation.ts
+++ b/src/client/src/helpers/client/organisation.ts
@@ -3,6 +3,7 @@ import { deleteData, getData, postData } from "@/utils/api";
import asaw from "@/utils/asaw";
import { toast } from "sonner";
import { fetchDatabaseConfigList, pingActiveDatabaseConfig } from "./database-config";
+import { fetchProjectList } from "./project";
import { OrganisationWithMeta } from "@/types/store/organisation";
import getMessage from "@/constants/messages";
import { CLIENT_EVENTS } from "@/constants/events";
@@ -69,6 +70,7 @@ export const changeActiveOrganisation = async (
});
// Refetch database configs for the new organisation
+ await fetchProjectList(organisationId);
await fetchDatabaseConfigList(() => {});
await pingActiveDatabaseConfig();
diff --git a/src/client/src/helpers/client/project.ts b/src/client/src/helpers/client/project.ts
new file mode 100644
index 00000000..4a5b631b
--- /dev/null
+++ b/src/client/src/helpers/client/project.ts
@@ -0,0 +1,69 @@
+import { useRootStore } from "@/store";
+import { ProjectWithMeta } from "@/types/store/project";
+import { getData, postData } from "@/utils/api";
+import asaw from "@/utils/asaw";
+import { toast } from "sonner";
+import getMessage from "@/constants/messages";
+import { fetchDatabaseConfigList, pingActiveDatabaseConfig } from "./database-config";
+
+export const fetchProjectList = async (organisationId?: string) => {
+ const currentOrgId =
+ organisationId || useRootStore.getState().organisation.current?.id;
+
+ if (!currentOrgId) {
+ useRootStore.getState().project.setList([]);
+ return [];
+ }
+
+ useRootStore.getState().project.setIsLoading(true);
+ 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 [];
+ }
+
+ useRootStore.getState().project.setList(data);
+ return data as ProjectWithMeta[];
+};
+
+export const changeActiveProject = async (
+ projectId: string,
+ successCb?: () => void
+) => {
+ const messages = getMessage();
+ const currentOrgId = useRootStore.getState().organisation.current?.id;
+
+ if (!currentOrgId) return;
+
+ const [err, data] = await asaw(
+ postData({
+ url: `/api/organisation/${currentOrgId}/projects/current/${projectId}`,
+ data: {},
+ })
+ );
+
+ if (err || data?.err) {
+ toast.error(err || data?.err || messages.PROJECT_SWITCH_FAILED, {
+ id: "project-switch",
+ });
+ return;
+ }
+
+ const nextProject = useRootStore
+ .getState()
+ .project.list?.find((project) => project.id === projectId);
+ if (nextProject) {
+ useRootStore.getState().project.setCurrent(nextProject);
+ }
+
+ await fetchDatabaseConfigList(() => {});
+ await pingActiveDatabaseConfig();
+ successCb?.();
+};
diff --git a/src/client/src/lib/db-config.ts b/src/client/src/lib/db-config.ts
index 45ca3e4f..01e06b0e 100644
--- a/src/client/src/lib/db-config.ts
+++ b/src/client/src/lib/db-config.ts
@@ -6,7 +6,7 @@ import migrations from "@/clickhouse/migrations";
import getMessage from "@/constants/messages";
import { throwIfError } from "@/utils/error";
import { consoleLog } from "@/utils/log";
-import { getCurrentOrganisation } from "./organisation";
+import { getCurrentOrganisation, getCurrentProjectForOrganisation } from "./organisation";
import { validateDatabaseHost } from "@/utils/validation";
export const getDBConfigByUser = async (currentOnly?: boolean) => {
@@ -16,16 +16,19 @@ export const getDBConfigByUser = async (currentOnly?: boolean) => {
// Get current organisation
const currentOrg = await getCurrentOrganisation();
+ const currentProject = currentOrg?.id
+ ? await getCurrentProjectForOrganisation(currentOrg.id)
+ : null;
- // Auto-migrate orphaned configs: If user has a current org, move any orphaned configs
- // they have access to into that org. This handles edge cases where migration didn't run
+ // Auto-migrate orphaned configs: If user has a current organisation, move any orphaned configs
+ // they have access to into its current project. This handles edge cases where migration didn't run
// or new orphaned configs were created.
if (currentOrg?.id) {
const userOrphanedLinks = await prisma.databaseConfigUser.findMany({
where: {
userId: user.id,
databaseConfig: {
- organisationId: null,
+ projectId: null,
},
},
select: { databaseConfigId: true },
@@ -38,7 +41,7 @@ export const getDBConfigByUser = async (currentOnly?: boolean) => {
await prisma.databaseConfig.updateMany({
where: { id: { in: orphanedConfigIds } },
- data: { organisationId: currentOrg.id },
+ data: { projectId: currentProject?.id },
});
consoleLog(
@@ -52,10 +55,10 @@ export const getDBConfigByUser = async (currentOnly?: boolean) => {
where: {
userId: user.id,
isCurrent: true,
- // Always filter by current organisation to maintain data isolation
- // If no current org, only return orphaned configs (organisationId: null)
+ // Always filter by current project to maintain data isolation
+ // If no current organisation, only return orphaned configs (projectId: null)
databaseConfig: {
- organisationId: currentOrg?.id ?? null,
+ projectId: currentProject?.id ?? null,
},
},
select: {
@@ -69,10 +72,10 @@ export const getDBConfigByUser = async (currentOnly?: boolean) => {
const dbUserConfigs = await prisma.databaseConfigUser.findMany({
where: {
userId: user.id,
- // Always filter by current organisation to maintain data isolation
- // If no current org, only return orphaned configs (organisationId: null)
+ // Always filter by current project to maintain data isolation
+ // If no current organisation, only return orphaned configs (projectId: null)
databaseConfig: {
- organisationId: currentOrg?.id ?? null,
+ projectId: currentProject?.id ?? null,
},
},
select: {
@@ -144,11 +147,14 @@ export const upsertDBConfig = async (
// Get current organisation
const currentOrg = await getCurrentOrganisation();
+ const currentProject = currentOrg?.id
+ ? await getCurrentProjectForOrganisation(currentOrg.id)
+ : null;
const existingDBName = await prisma.databaseConfig.findFirst({
where: {
name: dbConfig.name,
- organisationId: currentOrg?.id || null,
+ projectId: currentProject?.id || null,
NOT: {
id,
},
@@ -172,7 +178,7 @@ export const upsertDBConfig = async (
create: {
...(dbConfig as any),
createdByUserId: user!.id,
- organisationId: currentOrg?.id,
+ projectId: currentProject?.id,
},
update: {
...dbConfig,
@@ -182,12 +188,12 @@ export const upsertDBConfig = async (
if (err) throw err;
createddbConfig = result;
}
- // When creating with an organisation, use compound unique constraint
- else if (currentOrg?.id) {
+ // When creating with a project, use compound unique constraint
+ else if (currentProject?.id) {
const whereObject = {
- name_organisationId: {
+ name_projectId: {
name: dbConfig.name,
- organisationId: currentOrg.id,
+ projectId: currentProject.id,
},
};
const [err, result] = await asaw(
@@ -196,7 +202,7 @@ export const upsertDBConfig = async (
create: {
...(dbConfig as any),
createdByUserId: user!.id,
- organisationId: currentOrg.id,
+ projectId: currentProject.id,
},
update: {
...dbConfig,
@@ -206,14 +212,14 @@ export const upsertDBConfig = async (
if (err) throw err;
createddbConfig = result;
}
- // When creating without organisation (null organisationId),
+ // When creating without a project (null projectId),
// Prisma doesn't support null in compound unique constraints,
// so we use findFirst + create/update pattern
else {
const existing = await prisma.databaseConfig.findFirst({
where: {
name: dbConfig.name,
- organisationId: null,
+ projectId: null,
},
});
@@ -231,7 +237,7 @@ export const upsertDBConfig = async (
data: {
...(dbConfig as any),
createdByUserId: user!.id,
- organisationId: null,
+ projectId: null,
},
});
}
@@ -279,6 +285,22 @@ export async function setCurrentDBConfig(id: string) {
if (!user) throw new Error(getMessage().UNAUTHORIZED_USER);
+ const currentOrg = await getCurrentOrganisation();
+ const currentProject = currentOrg?.id
+ ? await getCurrentProjectForOrganisation(currentOrg.id)
+ : null;
+ const targetConfig = await prisma.databaseConfig.findFirst({
+ where: {
+ id,
+ projectId: currentProject?.id ?? null,
+ },
+ select: { id: true },
+ });
+
+ if (!targetConfig) {
+ throw new Error(getMessage().DB_CONFIG_NOT_IN_CURRENT_PROJECT);
+ }
+
const currentConfig = await getDBConfigByUser(true);
if ((currentConfig as DatabaseConfig)?.id) {
@@ -307,7 +329,7 @@ export async function setCurrentDBConfig(id: string) {
},
});
- return "Current DB config set successfully!";
+ return getMessage().CURRENT_DB_CONFIG_SET_SUCCESS;
}
export async function shareDBConfig({
@@ -468,19 +490,19 @@ async function addDatabaseConfigUserEntry(
canShare: boolean;
}
) {
- // Get the database config to find its organisation
+ // Get the database config to find its project
const dbConfig = await prisma.databaseConfig.findUnique({
where: { id: databaseConfigId },
- select: { organisationId: true },
+ select: { projectId: true },
});
- // Check if user has any current database config in the SAME organisation
+ // Check if user has any current database config in the same project
const existingCurrentConfigInOrg = await prisma.databaseConfigUser.findFirst({
where: {
userId: userId,
isCurrent: true,
databaseConfig: {
- organisationId: dbConfig?.organisationId || null,
+ projectId: dbConfig?.projectId || null,
},
},
});
diff --git a/src/client/src/lib/edition.ts b/src/client/src/lib/edition.ts
new file mode 100644
index 00000000..7a51d98e
--- /dev/null
+++ b/src/client/src/lib/edition.ts
@@ -0,0 +1,21 @@
+export const EDITIONS = ["oss", "enterprise", "cloud"] as const;
+
+export type OpenLitEdition = (typeof EDITIONS)[number];
+
+export function getOpenLitEdition(): OpenLitEdition {
+ const edition = process.env.OPENLIT_EDITION;
+
+ if (edition === "enterprise" || edition === "cloud") {
+ return edition;
+ }
+
+ return "oss";
+}
+
+export function isEnterpriseEdition() {
+ return getOpenLitEdition() === "enterprise";
+}
+
+export function isCloudEdition() {
+ return getOpenLitEdition() === "cloud";
+}
diff --git a/src/client/src/lib/organisation.ts b/src/client/src/lib/organisation.ts
index 492e407c..640482eb 100644
--- a/src/client/src/lib/organisation.ts
+++ b/src/client/src/lib/organisation.ts
@@ -87,6 +87,173 @@ async function getUserRoleInOrganisation(
return membership?.role || null;
}
+async function getMembershipCurrentProjectId(
+ organisationId: string,
+ userId: string
+) {
+ const rows = await prisma.$queryRaw<{ current_project_id: string | null }[]>`
+ SELECT current_project_id
+ FROM organisation_users
+ WHERE organisation_id = ${organisationId}
+ AND user_id = ${userId}
+ LIMIT 1
+ `;
+
+ return rows[0]?.current_project_id || null;
+}
+
+async function setMembershipCurrentProjectId(
+ organisationId: string,
+ userId: string,
+ projectId: string
+) {
+ await prisma.$executeRaw`
+ UPDATE organisation_users
+ SET current_project_id = ${projectId}
+ WHERE organisation_id = ${organisationId}
+ AND user_id = ${userId}
+ `;
+}
+
+export async function getDefaultProjectForOrganisation(organisationId: string) {
+ const existingProject = await prisma.project.findFirst({
+ where: { organisationId, isDefault: true },
+ orderBy: { createdAt: "asc" },
+ });
+
+ if (existingProject) return existingProject;
+
+ return prisma.project.create({
+ data: {
+ organisationId,
+ name: "Default Project",
+ slug: "default",
+ isDefault: true,
+ },
+ });
+}
+
+export async function getCurrentProjectForOrganisation(organisationId: string) {
+ const user = await getCurrentUser();
+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+
+ const membership = await prisma.organisationUser.findUnique({
+ where: {
+ organisationId_userId: {
+ organisationId,
+ userId: user!.id,
+ },
+ },
+ select: { id: true },
+ });
+
+ throwIfError(!membership, getMessage().NOT_ORGANISATION_MEMBER);
+
+ const currentProjectId = await getMembershipCurrentProjectId(
+ organisationId,
+ user!.id
+ );
+
+ if (currentProjectId) {
+ const currentProject = await prisma.project.findFirst({
+ where: {
+ id: currentProjectId,
+ organisationId,
+ },
+ });
+
+ if (currentProject) return currentProject;
+ }
+
+ const defaultProject = await getDefaultProjectForOrganisation(organisationId);
+ await setMembershipCurrentProjectId(organisationId, user!.id, defaultProject.id);
+
+ return defaultProject;
+}
+
+export async function setCurrentProject(
+ organisationId: string,
+ projectId: string
+) {
+ const user = await getCurrentUser();
+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+
+ const membership = await prisma.organisationUser.findUnique({
+ where: {
+ organisationId_userId: {
+ organisationId,
+ userId: user!.id,
+ },
+ },
+ });
+
+ throwIfError(!membership, getMessage().NOT_ORGANISATION_MEMBER);
+
+ const project = await prisma.project.findUnique({
+ where: { id: projectId },
+ });
+
+ throwIfError(
+ !project || project!.organisationId !== organisationId,
+ getMessage().PROJECT_NOT_FOUND
+ );
+
+ await setMembershipCurrentProjectId(organisationId, user!.id, project!.id);
+
+ return { success: true };
+}
+
+function slugify(name: string): string {
+ return name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-|-$/g, "");
+}
+
+export async function createOrganisationProject(
+ organisationId: string,
+ name: string
+) {
+ const user = await getCurrentUser();
+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+
+ const trimmedName = name.trim();
+ throwIfError(
+ trimmedName.length < 1 || trimmedName.length > 120,
+ getMessage().PROJECT_NAME_LENGTH_RANGE_ERROR
+ );
+
+ const isAdmin = await hasAdminOrOwnerRole(organisationId, user!.id);
+ throwIfError(!isAdmin, getMessage().ONLY_ADMIN_CAN_UPDATE_ORGANISATION);
+
+ const baseSlug = slugify(trimmedName) || "project";
+ for (let attempt = 0; attempt < 10; attempt++) {
+ const suffix = Math.random().toString(36).substring(2, 8);
+ const slug = `${baseSlug}-${suffix}`;
+ const existing = await prisma.project.findUnique({
+ where: {
+ organisationId_slug: {
+ organisationId,
+ slug,
+ },
+ },
+ select: { id: true },
+ });
+
+ if (!existing) {
+ return prisma.project.create({
+ data: {
+ organisationId,
+ name: trimmedName,
+ slug,
+ },
+ });
+ }
+ }
+
+ throw new Error("Unable to generate a unique project slug.");
+}
+
/**
* Create a new organisation
*/
@@ -101,6 +268,16 @@ export async function createOrganisation(name: string) {
name,
slug,
createdByUserId: user!.id,
+ projects: {
+ create: {
+ name: "Default Project",
+ slug: "default",
+ isDefault: true,
+ },
+ },
+ },
+ include: {
+ projects: true,
},
});
@@ -113,6 +290,13 @@ export async function createOrganisation(name: string) {
isCurrent: false, // Don't auto-switch to new org
},
});
+ if (organisation.projects?.[0]?.id) {
+ await setMembershipCurrentProjectId(
+ organisation.id,
+ user!.id,
+ organisation.projects[0].id
+ );
+ }
// Migrate orphaned configs and shared users to the new org
await migrateUserConfigsToOrganisation(organisation.id, user!.id);
@@ -216,6 +400,11 @@ export async function setCurrentOrganisation(organisationId: string) {
// Atomically unset all current orgs and set the new one in a transaction
// This prevents a race condition where concurrent requests could see
// no current organisation between the two operations
+ const defaultProject = await getDefaultProjectForOrganisation(organisationId);
+ const currentProjectId =
+ (await getMembershipCurrentProjectId(organisationId, user!.id)) ||
+ defaultProject.id;
+
await prisma.$transaction([
// Unset all current orgs for this user
prisma.organisationUser.updateMany({
@@ -240,6 +429,7 @@ export async function setCurrentOrganisation(organisationId: string) {
},
}),
]);
+ await setMembershipCurrentProjectId(organisationId, user!.id, currentProjectId);
return { success: true };
}
@@ -656,7 +846,9 @@ export async function removeUserFromOrganisation(
where: {
userId,
databaseConfig: {
- organisationId,
+ project: {
+ organisationId,
+ },
},
},
});
@@ -931,12 +1123,14 @@ async function migrateUserConfigsToOrganisation(
organisationId: string,
userId: string
) {
+ const project = await getDefaultProjectForOrganisation(organisationId);
+
// Find all orphaned DB configs the user has access to
const userConfigLinks = await prisma.databaseConfigUser.findMany({
where: {
userId,
databaseConfig: {
- organisationId: null,
+ projectId: null,
},
},
select: { databaseConfigId: true },
@@ -948,10 +1142,10 @@ async function migrateUserConfigsToOrganisation(
(link) => link.databaseConfigId
);
- // Move those configs to the new org
+ // Move those configs to the new organisation default project
await prisma.databaseConfig.updateMany({
where: { id: { in: orphanedConfigIds } },
- data: { organisationId },
+ data: { projectId: project.id },
});
// Find other users who share those configs
@@ -989,6 +1183,11 @@ async function migrateUserConfigsToOrganisation(
isCurrent: !hasCurrentOrg,
},
});
+ await setMembershipCurrentProjectId(
+ organisationId,
+ sharedUserId,
+ project.id
+ );
} else if (!hasCurrentOrg) {
// Existing membership but no current org — fix it
await prisma.organisationUser.update({
@@ -1000,6 +1199,11 @@ async function migrateUserConfigsToOrganisation(
},
data: { isCurrent: true },
});
+ await setMembershipCurrentProjectId(
+ organisationId,
+ sharedUserId,
+ project.id
+ );
}
// Share org DB configs with the new member
@@ -1020,9 +1224,11 @@ async function shareOrganisationDatabaseConfigs(
organisationId: string,
userId: string
) {
+ const project = await getDefaultProjectForOrganisation(organisationId);
+
// Get all database configs for this organisation
const databaseConfigs = await prisma.databaseConfig.findMany({
- where: { organisationId },
+ where: { projectId: project.id },
orderBy: {
createdAt: "asc",
},
@@ -1030,13 +1236,13 @@ async function shareOrganisationDatabaseConfigs(
if (databaseConfigs.length === 0) return;
- // Check if user has any current database config in THIS organisation
+ // Check if user has any current database config in this project
const existingCurrentConfig = await prisma.databaseConfigUser.findFirst({
where: {
userId,
isCurrent: true,
databaseConfig: {
- organisationId,
+ projectId: project.id,
},
},
});
diff --git a/src/client/src/selectors/project.ts b/src/client/src/selectors/project.ts
new file mode 100644
index 00000000..964bacbf
--- /dev/null
+++ b/src/client/src/selectors/project.ts
@@ -0,0 +1,7 @@
+import { RootStore } from "@/types/store/root";
+
+export const getProjectList = (state: RootStore) => state.project.list;
+
+export const getCurrentProject = (state: RootStore) => state.project.current;
+
+export const getProjectIsLoading = (state: RootStore) => state.project.isLoading;
diff --git a/src/client/src/store/index.ts b/src/client/src/store/index.ts
index e4bd7f3a..ab3d8808 100644
--- a/src/client/src/store/index.ts
+++ b/src/client/src/store/index.ts
@@ -9,6 +9,7 @@ import { pageStoreSlice } from "./page";
import { RootStore } from "@/types/store/root";
import { dashboardStoreSlice } from "./dashboards";
import { organisationStoreSlice } from "./organisation";
+import { projectStoreSlice } from "./project";
import { ruleEngineStoreSlice } from "./rule-engine";
import { chatStoreSlice } from "./chat";
import { agentsInstrumentationStoreSlice } from "./agents-instrumentation";
@@ -23,6 +24,7 @@ export const useRootStore = create<RootStore>()(
page: pageStoreSlice,
dashboards: dashboardStoreSlice,
organisation: organisationStoreSlice,
+ project: projectStoreSlice,
ruleEngine: ruleEngineStoreSlice,
chat: chatStoreSlice,
agentsInstrumentation: agentsInstrumentationStoreSlice,
diff --git a/src/client/src/store/project.ts b/src/client/src/store/project.ts
new file mode 100644
index 00000000..51e16443
--- /dev/null
+++ b/src/client/src/store/project.ts
@@ -0,0 +1,47 @@
+"use client";
+
+import { lens } from "@dhmk/zustand-lens";
+import { ProjectStore } from "@/types/store/project";
+
+const initialState = {
+ list: undefined,
+ current: undefined,
+ isLoading: false,
+};
+
+export const projectStoreSlice: ProjectStore = lens((setStore, getStore) => ({
+ ...initialState,
+ setList: (list) =>
+ setStore(() => ({
+ ...getStore(),
+ list,
+ current:
+ list.find((project) => project.isCurrent) ||
+ list.find((project) => project.isDefault) ||
+ list[0],
+ isLoading: false,
+ })),
+ setCurrent: (project) =>
+ setStore(() => {
+ const currentList = getStore().list || [];
+ const updatedList = currentList.map((item) => ({
+ ...item,
+ isCurrent: item.id === project?.id,
+ }));
+
+ return {
+ ...getStore(),
+ list: updatedList,
+ current: updatedList.find((item) => item.id === project?.id),
+ };
+ }),
+ setIsLoading: (isLoading) =>
+ setStore(() => ({
+ ...getStore(),
+ isLoading,
+ })),
+ reset: () =>
+ setStore(() => ({
+ ...initialState,
+ })),
+}));
diff --git a/src/client/src/types/store/project.ts b/src/client/src/types/store/project.ts
new file mode 100644
index 00000000..9d3bb8b0
--- /dev/null
+++ b/src/client/src/types/store/project.ts
@@ -0,0 +1,19 @@
+export type ProjectWithMeta = {
+ id: string;
+ organisationId: string;
+ name: string;
+ slug: string;
+ isDefault: boolean;
+ isCurrent: boolean;
+ createdAt: string;
+};
+
+export type ProjectStore = {
+ list?: ProjectWithMeta[];
+ current?: ProjectWithMeta;
+ isLoading: boolean;
+ setList: (list: ProjectWithMeta[]) => void;
+ setCurrent: (project?: ProjectWithMeta) => void;
+ setIsLoading: (loading: boolean) => void;
+ reset: () => void;
+};
diff --git a/src/client/src/types/store/root.ts b/src/client/src/types/store/root.ts
index 28e95d02..fc752350 100644
--- a/src/client/src/types/store/root.ts
+++ b/src/client/src/types/store/root.ts
@@ -5,6 +5,7 @@ import { OpengroundStore } from "@/types/store/openground";
import { PageStore } from "@/types/store/page";
import { DashboardStore } from "./dashboards";
import { OrganisationStore } from "./organisation";
+import { ProjectStore } from "./project";
import { RuleEngineStore } from "./rule-engine";
import { ChatStore } from "./chat";
import { AgentInstrumentationStore } from "./agents-instrumentation";
@@ -17,6 +18,7 @@ export type RootStore = {
page: PageStore;
dashboards: DashboardStore;
organisation: OrganisationStore;
+ project: ProjectStore;
ruleEngine: RuleEngineStore;
chat: ChatStore;
agentsInstrumentation: AgentInstrumentationStore;