Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
[Feature]: Enhanced Organisation Management with Role-Based Access and Compact UI (#988)
Aman Agarwal51da84d3393e
diff --git a/src/Dockerfile b/src/Dockerfileindex ec85bf3e..23efca3b 100644--- a/src/Dockerfile+++ b/src/Dockerfile@@ -34,8 +34,8 @@ WORKDIR /app/client# Copy package.json and package-lock.json to the working directory & the rest of the application codeCOPY ./client/ .-# Install dependencies & Build the Next.js application-RUN npm install && npm run build+# Install dependencies, generate Prisma client & Build the Next.js application+RUN npm install && npx prisma generate && npm run build# Opamp server build from sourcediff --git a/src/client/package-lock.json b/src/client/package-lock.jsonindex 14bcea8e..77f95047 100644--- a/src/client/package-lock.json+++ b/src/client/package-lock.json@@ -1,12 +1,12 @@{"name": "openlit",- "version": "1.15.4",+ "version": "1.16.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "openlit",- "version": "1.15.4",+ "version": "1.16.0","dependencies": {"@ai-sdk/anthropic": "^3.0.6","@ai-sdk/cohere": "^3.0.3",@@ -21,6 +21,7 @@"@next-auth/prisma-adapter": "^1.0.7","@prisma/client": "^5.15.0","@radix-ui/react-accordion": "^1.2.1",+ "@radix-ui/react-alert-dialog": "^1.1.15","@radix-ui/react-avatar": "^1.1.10","@radix-ui/react-checkbox": "^1.1.0","@radix-ui/react-collapsible": "^1.1.0",@@ -2924,6 +2925,372 @@}}},+ "node_modules/@radix-ui/react-alert-dialog": {+ "version": "1.1.15",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.1.15.tgz",+ "integrity": "sha512-oTVLkEw5GpdRe29BqJ0LSDFWI3qu0vR1M0mUkOQWDIUnY/QIkLpgDMWuKxP94c2NAC2LGcgVhG1ImF3jkZ5wXw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-dialog": "1.1.15",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/primitive": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",+ "integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",+ "license": "MIT"+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-compose-refs": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz",+ "integrity": "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-context": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.2.tgz",+ "integrity": "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-dialog": {+ "version": "1.1.15",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.15.tgz",+ "integrity": "sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-dismissable-layer": "1.1.11",+ "@radix-ui/react-focus-guards": "1.1.3",+ "@radix-ui/react-focus-scope": "1.1.7",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-portal": "1.1.9",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-slot": "1.2.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "aria-hidden": "^1.2.4",+ "react-remove-scroll": "^2.6.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-dismissable-layer": {+ "version": "1.1.11",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.11.tgz",+ "integrity": "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-escape-keydown": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-focus-guards": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",+ "integrity": "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-focus-scope": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.7.tgz",+ "integrity": "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-callback-ref": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-id": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",+ "integrity": "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-portal": {+ "version": "1.1.9",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.9.tgz",+ "integrity": "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-presence": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.5.tgz",+ "integrity": "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-primitive": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",+ "integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-slot": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "1.1.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-use-callback-ref": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",+ "integrity": "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-use-controllable-state": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz",+ "integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-effect-event": "0.0.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-use-escape-keydown": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.1.tgz",+ "integrity": "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-callback-ref": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-use-layout-effect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",+ "integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-alert-dialog/node_modules/react-remove-scroll": {+ "version": "2.7.2",+ "resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.2.tgz",+ "integrity": "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==",+ "license": "MIT",+ "dependencies": {+ "react-remove-scroll-bar": "^2.3.7",+ "react-style-singleton": "^2.2.3",+ "tslib": "^2.1.0",+ "use-callback-ref": "^1.3.3",+ "use-sidecar": "^1.1.3"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-arrow": {"version": "1.0.3","resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.0.3.tgz",@@ -4606,6 +4973,39 @@}}},+ "node_modules/@radix-ui/react-use-effect-event": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.2.tgz",+ "integrity": "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-use-effect-event/node_modules/@radix-ui/react-use-layout-effect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",+ "integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-use-escape-keydown": {"version": "1.0.3","resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.0.3.tgz",@@ -8677,14 +9077,6 @@"node": ">=12"}},- "node_modules/invariant": {- "version": "2.2.4",- "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz",- "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==",- "dependencies": {- "loose-envify": "^1.0.0"- }- },"node_modules/is-alphabetical": {"version": "1.0.4","resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-1.0.4.tgz",@@ -11295,19 +11687,20 @@}},"node_modules/react-remove-scroll-bar": {- "version": "2.3.6",- "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.6.tgz",- "integrity": "sha512-DtSYaao4mBmX+HDo5YWYdBWQwYIQQshUV/dVxFxK+KM26Wjwp1gZ6rv6OC3oujI6Bfu6Xyg3TwK533AQutsn/g==",+ "version": "2.3.8",+ "resolved": "https://registry.npmjs.org/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.8.tgz",+ "integrity": "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==",+ "license": "MIT","dependencies": {- "react-style-singleton": "^2.2.1",+ "react-style-singleton": "^2.2.2","tslib": "^2.0.0"},"engines": {"node": ">=10"},"peerDependencies": {- "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0",- "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"},"peerDependenciesMeta": {"@types/react": {@@ -11352,20 +11745,20 @@}},"node_modules/react-style-singleton": {- "version": "2.2.1",- "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.1.tgz",- "integrity": "sha512-ZWj0fHEMyWkHzKYUr2Bs/4zU6XLmq9HsgBURm7g5pAVfyn49DgUiNgY2d4lXRlYSiCif9YBGpQleewkcqddc7g==",+ "version": "2.2.3",+ "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",+ "integrity": "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==",+ "license": "MIT","dependencies": {"get-nonce": "^1.0.0",- "invariant": "^2.2.4","tslib": "^2.0.0"},"engines": {"node": ">=10"},"peerDependencies": {- "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0",- "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"},"peerDependenciesMeta": {"@types/react": {@@ -12728,9 +13121,10 @@"integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA=="},"node_modules/use-callback-ref": {- "version": "1.3.2",- "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.2.tgz",- "integrity": "sha512-elOQwe6Q8gqZgDA8mrh44qRTQqpIHDcZ3hXTLjBe1i4ph8XpNJnO+aQf3NaG+lriLopI4HMx9VjQLfPQ6vhnoA==",+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz",+ "integrity": "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==",+ "license": "MIT","dependencies": {"tslib": "^2.0.0"},@@ -12738,8 +13132,8 @@"node": ">=10"},"peerDependencies": {- "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0",- "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"},"peerDependenciesMeta": {"@types/react": {@@ -12756,9 +13150,10 @@}},"node_modules/use-sidecar": {- "version": "1.1.2",- "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.2.tgz",- "integrity": "sha512-epTbsLuzZ7lPClpz2TyryBfztm7m+28DlEv2ZCQ3MDr5ssiwyOwGH/e5F9CkfWjJ1t4clvI58yF822/GUkjjhw==",+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/use-sidecar/-/use-sidecar-1.1.3.tgz",+ "integrity": "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==",+ "license": "MIT","dependencies": {"detect-node-es": "^1.1.0","tslib": "^2.0.0"@@ -12767,8 +13162,8 @@"node": ">=10"},"peerDependencies": {- "@types/react": "^16.9.0 || ^17.0.0 || ^18.0.0",- "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ "@types/react": "*",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"},"peerDependenciesMeta": {"@types/react": {diff --git a/src/client/package.json b/src/client/package.jsonindex c0f6e800..ad30bb81 100644--- a/src/client/package.json+++ b/src/client/package.json@@ -1,6 +1,6 @@{"name": "openlit",- "version": "1.15.4",+ "version": "1.16.0","private": true,"scripts": {"dev": "next dev",@@ -23,6 +23,7 @@"@next-auth/prisma-adapter": "^1.0.7","@prisma/client": "^5.15.0","@radix-ui/react-accordion": "^1.2.1",+ "@radix-ui/react-alert-dialog": "^1.1.15","@radix-ui/react-avatar": "^1.1.10","@radix-ui/react-checkbox": "^1.1.0","@radix-ui/react-collapsible": "^1.1.0",diff --git a/src/client/prisma/migrations/20260121091006_add_organisation_feature/migration.sql b/src/client/prisma/migrations/20260121091006_add_organisation_feature/migration.sqlnew file mode 100644index 00000000..990384b2--- /dev/null+++ b/src/client/prisma/migrations/20260121091006_add_organisation_feature/migration.sql@@ -0,0 +1,82 @@+-- CreateTable+CREATE TABLE "organisations" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "name" TEXT NOT NULL,+ "slug" TEXT NOT NULL,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" DATETIME NOT NULL,+ "created_by_user_id" TEXT NOT NULL+);++-- CreateTable+CREATE TABLE "organisation_users" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "organisation_id" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "isCurrent" BOOLEAN NOT NULL DEFAULT false,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" DATETIME NOT NULL,+ CONSTRAINT "organisation_users_organisation_id_fkey" FOREIGN KEY ("organisation_id") REFERENCES "organisations" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "organisation_users_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE+);++-- CreateTable+CREATE TABLE "organisation_invited_users" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "organisation_id" TEXT NOT NULL,+ "email" TEXT NOT NULL,+ "invited_by_user_id" TEXT NOT NULL,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ CONSTRAINT "organisation_invited_users_organisation_id_fkey" FOREIGN KEY ("organisation_id") REFERENCES "organisations" ("id") ON DELETE CASCADE ON UPDATE CASCADE+);++-- RedefineTables+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,+ "organisation_id" TEXT,+ CONSTRAINT "databaseconfig_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "databaseconfig_organisation_id_fkey" FOREIGN KEY ("organisation_id") REFERENCES "organisations" ("id") ON DELETE SET NULL ON UPDATE CASCADE+);+INSERT INTO "new_databaseconfig" ("createdAt", "database", "environment", "host", "id", "name", "password", "port", "query", "updatedAt", "user_id", "username") SELECT "createdAt", "database", "environment", "host", "id", "name", "password", "port", "query", "updatedAt", "user_id", "username" FROM "databaseconfig";+DROP TABLE "databaseconfig";+ALTER TABLE "new_databaseconfig" RENAME TO "databaseconfig";+CREATE UNIQUE INDEX "databaseconfig_name_organisation_id_key" ON "databaseconfig"("name", "organisation_id");+CREATE TABLE "new_users" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "name" TEXT,+ "email" TEXT NOT NULL,+ "email_verified" DATETIME,+ "password" TEXT,+ "image" TEXT,+ "has_completed_onboarding" BOOLEAN NOT NULL DEFAULT false,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" DATETIME NOT NULL+);+INSERT INTO "new_users" ("createdAt", "email", "email_verified", "id", "image", "name", "password", "updatedAt") SELECT "createdAt", "email", "email_verified", "id", "image", "name", "password", "updatedAt" FROM "users";+DROP TABLE "users";+ALTER TABLE "new_users" RENAME TO "users";+CREATE UNIQUE INDEX "users_email_key" ON "users"("email");+PRAGMA foreign_keys=ON;+PRAGMA defer_foreign_keys=OFF;++-- CreateIndex+CREATE UNIQUE INDEX "organisations_slug_key" ON "organisations"("slug");++-- CreateIndex+CREATE UNIQUE INDEX "organisation_users_organisation_id_user_id_key" ON "organisation_users"("organisation_id", "user_id");++-- CreateIndex+CREATE UNIQUE INDEX "organisation_invited_users_organisation_id_email_key" ON "organisation_invited_users"("organisation_id", "email");diff --git a/src/client/prisma/migrations/20260127203815_add_role_to_organisation_user/migration.sql b/src/client/prisma/migrations/20260127203815_add_role_to_organisation_user/migration.sqlnew file mode 100644index 00000000..08fb1d80--- /dev/null+++ b/src/client/prisma/migrations/20260127203815_add_role_to_organisation_user/migration.sql@@ -0,0 +1,27 @@+-- RedefineTables+PRAGMA defer_foreign_keys=ON;+PRAGMA foreign_keys=OFF;+CREATE TABLE "new_organisation_users" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "organisation_id" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "role" TEXT NOT NULL DEFAULT 'member',+ "isCurrent" BOOLEAN NOT NULL DEFAULT false,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" DATETIME NOT NULL,+ CONSTRAINT "organisation_users_organisation_id_fkey" FOREIGN KEY ("organisation_id") REFERENCES "organisations" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "organisation_users_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE+);+INSERT INTO "new_organisation_users" ("createdAt", "id", "isCurrent", "organisation_id", "updatedAt", "user_id") SELECT "createdAt", "id", "isCurrent", "organisation_id", "updatedAt", "user_id" FROM "organisation_users";+DROP TABLE "organisation_users";+ALTER TABLE "new_organisation_users" RENAME TO "organisation_users";+CREATE UNIQUE INDEX "organisation_users_organisation_id_user_id_key" ON "organisation_users"("organisation_id", "user_id");+PRAGMA foreign_keys=ON;+PRAGMA defer_foreign_keys=OFF;++-- Update existing organisation creators to have 'owner' role+UPDATE organisation_users+SET role = 'owner'+WHERE user_id IN (+ SELECT created_by_user_id FROM organisations WHERE id = organisation_users.organisation_id+);diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prismaindex d4a53ec2..7c1b306d 100644--- a/src/client/prisma/schema.prisma+++ b/src/client/prisma/schema.prisma@@ -42,21 +42,23 @@ model Session {}model User {- id String @id @default(uuid())- name String?- email String @unique- emailVerified DateTime? @map("email_verified")- password String?- image String?- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt- accounts Account[]- sessions Session[]- dbConfigs DatabaseConfigUser[]- createdDBConfigs DatabaseConfig[]- createdApiKeys APIKeys[] @relation("createdByUser")- deletedApiKeys APIKeys[] @relation("deletedByUser")- opengrounds OpenGround[]+ id String @id @default(uuid())+ name String?+ email String @unique+ emailVerified DateTime? @map("email_verified")+ password String?+ image String?+ hasCompletedOnboarding Boolean @default(false) @map("has_completed_onboarding")+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ accounts Account[]+ sessions Session[]+ dbConfigs DatabaseConfigUser[]+ createdDBConfigs DatabaseConfig[]+ createdApiKeys APIKeys[] @relation("createdByUser")+ deletedApiKeys APIKeys[] @relation("deletedByUser")+ opengrounds OpenGround[]+ organisations OrganisationUser[]@@map("users")}@@ -73,6 +75,48 @@ model VerificationRequest {@@map("verificationrequest")}+// Organisation+model Organisation {+ id String @id @default(cuid())+ name String+ slug String @unique+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ createdByUserId String @map("created_by_user_id")+ members OrganisationUser[]+ invitedUsers OrganisationInvitedUser[]+ databaseConfigs DatabaseConfig[]++ @@map("organisations")+}++model OrganisationUser {+ id String @id @default(cuid())+ organisationId String @map("organisation_id")+ organisation Organisation @relation(fields: [organisationId], references: [id], onDelete: Cascade)+ userId String @map("user_id")+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ role String @default("member")+ isCurrent Boolean @default(false)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@unique([organisationId, userId])+ @@map("organisation_users")+}++model OrganisationInvitedUser {+ id String @id @default(cuid())+ organisationId String @map("organisation_id")+ organisation Organisation @relation(fields: [organisationId], references: [id], onDelete: Cascade)+ email String+ invitedByUserId String @map("invited_by_user_id")+ createdAt DateTime @default(now())++ @@unique([organisationId, email])+ @@map("organisation_invited_users")+}+// Database Configmodel DatabaseConfig {id String @id @default(cuid())@@ -89,11 +133,13 @@ model DatabaseConfig {updatedAt DateTime @updatedAtcreatedByUserId String @map("user_id")createdByUser User @relation(fields: [createdByUserId], references: [id])+ organisationId String? @map("organisation_id")+ organisation Organisation? @relation(fields: [organisationId], references: [id])dbInvitedUsers DatabaseConfigInvitedUser[]apiKeys APIKeys[]opengrounds OpenGround[]- @@unique([name])+ @@unique([name, organisationId])@@map("databaseconfig")}diff --git a/src/client/prisma/seed.js b/src/client/prisma/seed.jsindex 0c2cb238..2eb93e10 100644--- a/src/client/prisma/seed.js+++ b/src/client/prisma/seed.js@@ -7,11 +7,41 @@ async function main() {"$2a$10$gh6Odw7fhLRrE1A1OxaHfeWOWKiZEEQpkOAhhCQ.RHx8VWOngwlHO";const user = await prisma.user.upsert({where: { email: "[email protected]" },- update: {},+ update: {+ hasCompletedOnboarding: true,+ },create: {email: "[email protected]",password: hashedPassword,name: "User",+ hasCompletedOnboarding: true,+ },+ });++ // Create default organisation+ const defaultOrg = await prisma.organisation.upsert({+ where: { slug: "default" },+ update: {},+ create: {+ name: "Default Organisation",+ slug: "default",+ createdByUserId: user.id,+ },+ });++ // Link user to default organisation+ await prisma.organisationUser.upsert({+ where: {+ organisationId_userId: {+ organisationId: defaultOrg.id,+ userId: user.id,+ },+ },+ update: {},+ create: {+ organisationId: defaultOrg.id,+ userId: user.id,+ isCurrent: true,},});@@ -24,14 +54,78 @@ async function main() {};if (environmentDBConfig.host && environmentDBConfig.port) {+ // First, migrate any orphaned "Default DB" configs to the default org+ // This must happen before deleteMany to avoid foreign key constraint violations+ // from databaseconfiguser records that reference these configs+ const orphanedDefaultDBConfigs = await prisma.databaseConfig.findMany({+ where: {+ name: "Default DB",+ organisationId: null,+ },+ });++ if (orphanedDefaultDBConfigs.length > 0) {+ // Check if a "Default DB" config already exists in the default org+ const existingDefaultDB = await prisma.databaseConfig.findUnique({+ where: {+ name_organisationId: {+ name: "Default DB",+ organisationId: defaultOrg.id,+ },+ },+ });++ if (existingDefaultDB) {+ // If one exists, we need to handle the orphaned configs+ // Delete only orphaned configs that have no databaseconfiguser references+ for (const orphanedConfig of orphanedDefaultDBConfigs) {+ const hasReferences = await prisma.databaseConfigUser.findFirst({+ where: { databaseConfigId: orphanedConfig.id },+ });++ if (!hasReferences) {+ // Safe to delete - no foreign key constraints+ await prisma.databaseConfig.delete({+ where: { id: orphanedConfig.id },+ });+ } else {+ // Has references - migrate it by updating to a unique name+ // Use a timestamp-based suffix to ensure uniqueness+ await prisma.databaseConfig.update({+ where: { id: orphanedConfig.id },+ data: {+ name: `Default DB (${orphanedConfig.id.slice(0, 8)})`,+ organisationId: defaultOrg.id,+ },+ });+ }+ }+ } else {+ // No existing "Default DB" in default org - safe to migrate all orphaned ones+ await prisma.databaseConfig.updateMany({+ where: {+ name: "Default DB",+ organisationId: null,+ },+ data: { organisationId: defaultOrg.id },+ });+ }+ }+const dbConfig = await prisma.databaseConfig.upsert({- where: { name: "Default DB", AND: { createdByUserId: user.id } },+ where: {+ name_organisationId: {+ name: "Default DB",+ organisationId: defaultOrg.id,+ },+ },update: {},create: {environment: "production",name: "Default DB",...environmentDBConfig,createdByUserId: user.id,+ organisationId: defaultOrg.id,},});@@ -53,8 +147,101 @@ async function main() {},});}++ // Migrate existing data if needed (for upgrades)+ await migrateExistingData(defaultOrg.id, user.id);+console.log("Seeding End.....");}++// Migration logic for existing installations+// Migrates ALL orphaned configs into the default org, then ensures+// all users sharing configs in the default org are also members.+async function migrateExistingData(defaultOrgId, seedUserId) {+ // Step 1: Move ALL orphaned DB configs into the default org+ // This ensures no user loses access to their configs when they join/create an org+ const allOrphanedConfigs = await prisma.databaseConfig.findMany({+ where: {+ organisationId: null,+ },+ select: { id: true },+ });++ if (allOrphanedConfigs.length > 0) {+ const orphanedConfigIds = allOrphanedConfigs.map((config) => config.id);++ await prisma.databaseConfig.updateMany({+ where: { id: { in: orphanedConfigIds } },+ data: { organisationId: defaultOrgId },+ });++ console.log(+ `Migrated ${orphanedConfigIds.length} orphaned database configs to default organisation`+ );+ }++ // Step 2: Find ALL configs now in the default org and ensure shared users are members+ const orgConfigs = await prisma.databaseConfig.findMany({+ where: { organisationId: defaultOrgId },+ select: { id: true },+ });++ if (orgConfigs.length === 0) return;++ const orgConfigIds = orgConfigs.map((c) => c.id);++ // Find users who have access to these configs but aren't in the default org+ const sharedUserLinks = await prisma.databaseConfigUser.findMany({+ where: {+ databaseConfigId: { in: orgConfigIds },+ userId: { not: seedUserId },+ },+ select: { userId: true },+ distinct: ["userId"],+ });++ for (const { userId } of sharedUserLinks) {+ const existingMembership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId: defaultOrgId,+ userId,+ },+ },+ });++ // Check if the user already has any current org+ const hasCurrentOrg = await prisma.organisationUser.findFirst({+ where: { userId, isCurrent: true },+ });++ if (!existingMembership) {+ await prisma.organisationUser.create({+ data: {+ organisationId: defaultOrgId,+ userId,+ isCurrent: !hasCurrentOrg,+ },+ });+ } else if (!hasCurrentOrg) {+ // Existing membership but no current org — fix it+ await prisma.organisationUser.update({+ where: {+ organisationId_userId: {+ organisationId: defaultOrgId,+ userId,+ },+ },+ data: { isCurrent: true },+ });+ }++ await prisma.user.update({+ where: { id: userId },+ data: { hasCompletedOnboarding: true },+ });+ }+}main().then(async () => {await prisma.$disconnect();diff --git a/src/client/src/app/(playground)/onboarding/page.tsx b/src/client/src/app/(playground)/onboarding/page.tsxnew file mode 100644index 00000000..916333ac--- /dev/null+++ b/src/client/src/app/(playground)/onboarding/page.tsx@@ -0,0 +1,285 @@+"use client";++import { useState, useEffect } from "react";+import { useSession } from "next-auth/react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Building2, Mail, Check, X, ArrowRight, Users } from "lucide-react";+import { useRootStore } from "@/store";+import {+ getOrganisationPendingInvitations,+ getOrganisationList,+} from "@/selectors/organisation";+import {+ acceptInvitation,+ declineInvitation,+ fetchOrganisationList,+ fetchPendingInvitations,+} from "@/helpers/client/organisation";+import { postData } from "@/utils/api";+import asaw from "@/utils/asaw";+import getMessage from "@/constants/messages";+import { DEFAULT_LOGGED_IN_ROUTE } from "@/constants/route";++export default function OnboardingPage() {+ const { update: updateSession } = useSession();+ const messages = getMessage();+ const [orgName, setOrgName] = useState("");+ const [isCreating, setIsCreating] = useState(false);+ const [isSkipping, setIsSkipping] = useState(false);+ const [isSelectingOrg, setIsSelectingOrg] = useState<string | null>(null);+ const [isCompleting, setIsCompleting] = useState(false);+ const pendingInvitations = useRootStore(getOrganisationPendingInvitations);+ const organisationList = useRootStore(getOrganisationList);++ // Filter out orgs that are already current (shouldn't happen, but just in case)+ const existingMemberships = organisationList?.filter((org) => !org.isCurrent) || [];++ useEffect(() => {+ // Fetch organisations and invitations on mount+ fetchOrganisationList();+ fetchPendingInvitations();+ }, []);++ const setCurrentOrgAndComplete = async (orgId: string) => {+ // Prevent multiple calls+ if (isCompleting) return false;+ setIsCompleting(true);++ // Set current org via API directly (skip DB config fetch/ping for speed)+ const [setOrgErr] = await asaw(+ postData({ url: `/api/organisation/current/${orgId}`, data: {} })+ );+ if (setOrgErr) {+ setIsCompleting(false);+ return false;+ }++ // Mark onboarding complete+ const [completeErr] = await asaw(+ postData({ url: "/api/user/complete-onboarding", data: {} })+ );+ if (completeErr) {+ setIsCompleting(false);+ return false;+ }++ // Refresh JWT token and redirect — home page AppInit will load DB configs+ await updateSession();+ window.location.href = DEFAULT_LOGGED_IN_ROUTE;+ return true;+ };++ const handleCreateOrganisation = async () => {+ if (!orgName.trim() || isCompleting) return;++ setIsCreating(true);+ try {+ const [err, result] = await asaw(+ postData({ url: "/api/organisation", data: { name: orgName.trim() } })+ );++ if (err || !result?.id) {+ return;+ }++ await setCurrentOrgAndComplete(result.id);+ } finally {+ setIsCreating(false);+ }+ };++ const handleSkip = async () => {+ if (isCompleting) return;++ setIsSkipping(true);+ try {+ const [err, result] = await asaw(+ postData({+ url: "/api/organisation",+ data: { name: messages.PERSONAL_ORGANISATION },+ })+ );++ if (err || !result?.id) {+ return;+ }++ await setCurrentOrgAndComplete(result.id);+ } finally {+ setIsSkipping(false);+ }+ };++ const handleSelectOrganisation = async (orgId: string) => {+ if (isCompleting) return;++ setIsSelectingOrg(orgId);+ try {+ await setCurrentOrgAndComplete(orgId);+ } finally {+ setIsSelectingOrg(null);+ }+ };++ const handleAcceptInvitation = async (invitationId: string) => {+ await acceptInvitation(invitationId);+ };++ const handleDeclineInvitation = async (invitationId: string) => {+ await declineInvitation(invitationId);+ };++ return (+ <div className="min-h-screen w-full flex items-center justify-center bg-background p-4">+ <div className="w-full max-w-2xl space-y-6">+ <div className="text-center space-y-2">+ <h1 className="text-3xl font-bold">{messages.ONBOARDING_WELCOME}</h1>+ <p className="text-muted-foreground">{messages.ONBOARDING_SUBTITLE}</p>+ </div>++ {existingMemberships.length > 0 && (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <Users className="h-5 w-5" />+ {messages.YOUR_ORGANISATIONS}+ </CardTitle>+ <CardDescription>+ {messages.YOUR_ORGANISATIONS_ONBOARDING_DESCRIPTION}+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-3">+ {existingMemberships.map((org) => (+ <div+ key={org.id}+ className="flex items-center justify-between p-3 border border-stone-200 dark:border-stone-800 rounded-lg"+ >+ <div>+ <p className="font-medium">{org.name}</p>+ <p className="text-sm text-muted-foreground">+ {org.memberCount} {org.memberCount === 1 ? messages.MEMBER : messages.MEMBERS}+ </p>+ </div>+ <Button+ size="sm"+ onClick={() => handleSelectOrganisation(org.id)}+ disabled={isSelectingOrg === org.id}+ >+ {isSelectingOrg === org.id ? (+ messages.SELECTING+ ) : (+ <>+ <Check className="h-4 w-4 mr-1" />+ {messages.SELECT}+ </>+ )}+ </Button>+ </div>+ ))}+ </CardContent>+ </Card>+ )}++ {pendingInvitations.length > 0 && (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <Mail className="h-5 w-5" />+ {messages.PENDING_INVITATIONS}+ </CardTitle>+ <CardDescription>+ {messages.PENDING_INVITATIONS_ONBOARDING_DESCRIPTION}+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-3">+ {pendingInvitations.map((invitation) => (+ <div+ key={invitation.id}+ className="flex items-center justify-between p-3 border border-stone-200 dark:border-stone-800 rounded-lg"+ >+ <div>+ <p className="font-medium">{invitation.organisationName}</p>+ </div>+ <div className="flex gap-2">+ <Button+ size="sm"+ variant="outline"+ onClick={() => handleDeclineInvitation(invitation.id)}+ >+ <X className="h-4 w-4" />+ </Button>+ <Button+ size="sm"+ onClick={() => handleAcceptInvitation(invitation.id)}+ >+ <Check className="h-4 w-4 mr-1" />+ {messages.JOIN}+ </Button>+ </div>+ </div>+ ))}+ </CardContent>+ </Card>+ )}++ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <Building2 className="h-5 w-5" />+ {messages.CREATE_ORGANISATION}+ </CardTitle>+ <CardDescription>+ {messages.ONBOARDING_CREATE_DESCRIPTION}+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="org-name">{messages.ORGANISATION_NAME}</Label>+ <Input+ id="org-name"+ placeholder={messages.ORGANISATION_NAME_PLACEHOLDER}+ value={orgName}+ onChange={(e) => setOrgName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ handleCreateOrganisation();+ }+ }}+ />+ </div>+ <div className="flex gap-3">+ <Button+ className="flex-1"+ onClick={handleCreateOrganisation}+ disabled={!orgName.trim() || isCreating}+ >+ {isCreating ? messages.CREATING : messages.CREATE_ORGANISATION}+ {!isCreating && <ArrowRight className="h-4 w-4 ml-2" />}+ </Button>+ </div>+ </CardContent>+ </Card>++ <div className="text-center">+ <Button+ variant="ghost"+ onClick={handleSkip}+ disabled={isSkipping}+ className="text-muted-foreground"+ >+ {isSkipping ? messages.SETTING_UP : messages.ONBOARDING_SKIP}+ </Button>+ </div>+ </div>+ </div>+ );+}diff --git a/src/client/src/app/(playground)/settings/layout.tsx b/src/client/src/app/(playground)/settings/layout.tsxindex 879afe85..4a0988fc 100644--- a/src/client/src/app/(playground)/settings/layout.tsx+++ b/src/client/src/app/(playground)/settings/layout.tsx@@ -14,6 +14,11 @@ export default function SettingsLayout({const pathname = usePathname();const tabs = [+ {+ value: "organisation",+ label: "Organisation",+ path: "/settings/organisation",+ },{value: "evaluation",label: "Evaluation Settings",@@ -46,7 +51,7 @@ export default function SettingsLayout({className="w-full flex flex-col h-full"><div className="flex items-center justify-between gap-4 mb-4">- <TabsList className="p-0 h-[30px] grid grid-cols-4 self-start border border-stone-200 dark:border-stone-800">+ <TabsList className="p-0 h-[30px] grid grid-cols-5 self-start border border-stone-200 dark:border-stone-800">{tabs.map((tab) => (<TabsTrigger key={tab.value} value={tab.value} className="py-1.5 text-xs rounded-md">{tab.label}diff --git a/src/client/src/app/(playground)/settings/organisation/page.tsx b/src/client/src/app/(playground)/settings/organisation/page.tsxnew file mode 100644index 00000000..8d08e865--- /dev/null+++ b/src/client/src/app/(playground)/settings/organisation/page.tsx@@ -0,0 +1,689 @@+"use client";++import { useState, useEffect } from "react";+import { useRouter } from "next/navigation";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import { Badge } from "@/components/ui/badge";+import {+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from "@/components/ui/tabs";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ Building2,+ Mail,+ Check,+ X,+ Trash2,+ UserPlus,+ Crown,+ LogOut,+ Loader2,+ Save,+ Users,+ Settings,+ Clock,+} from "lucide-react";+import { useRootStore } from "@/store";+import {+ getCurrentOrganisation,+ getOrganisationList,+ getOrganisationPendingInvitations,+ getOrganisationIsLoading,+} from "@/selectors/organisation";+import { getCurrentUserId } from "@/selectors/user";+import {+ updateOrganisation,+ deleteOrganisation,+ inviteToOrganisation,+ acceptInvitation,+ declineInvitation,+ removeOrganisationMember,+ cancelOrganisationInvitation,+ fetchOrganisationList,+ fetchPendingInvitations,+ changeActiveOrganisation,+ updateMemberRole,+} from "@/helpers/client/organisation";+import { getData } from "@/utils/api";+import asaw from "@/utils/asaw";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";+import CreateOrganisationDialog from "@/components/(playground)/sidebar/create-organisation-dialog";+import getMessage from "@/constants/messages";++interface Member {+ id: string;+ email: string;+ name: string | null;+ image: string | null;+ isCreator: boolean;+ role: "owner" | "admin" | "member";+ joinedAt: string;+}++interface PendingInvite {+ id: string;+ email: string;+ invitedAt: string;+}++export default function OrganisationSettingsPage() {+ const router = useRouter();+ const messages = getMessage();+ const currentOrg = useRootStore(getCurrentOrganisation);+ const organisations = useRootStore(getOrganisationList) || [];+ const pendingInvitations = useRootStore(getOrganisationPendingInvitations);+ const currentUserId = useRootStore(getCurrentUserId);+ const isOrgLoading = useRootStore(getOrganisationIsLoading);++ const [orgName, setOrgName] = useState("");+ const [inviteEmail, setInviteEmail] = useState("");+ const [members, setMembers] = useState<Member[]>([]);+ const [orgPendingInvites, setOrgPendingInvites] = useState<PendingInvite[]>(+ []+ );+ const [isLoading, setIsLoading] = useState(false);+ const [isSaving, setIsSaving] = useState(false);+ const [isInviting, setIsInviting] = useState(false);+ const [createDialogOpen, setCreateDialogOpen] = useState(false);+ const [hasFetchedOrgs, setHasFetchedOrgs] = useState(false);++ const isCreator = currentOrg?.createdByUserId === currentUserId;++ // Get current user's role and permissions+ const currentUserMember = members.find(m => m.id === currentUserId);+ const currentUserRole = currentUserMember?.role;+ const hasAdminPermissions = currentUserRole === 'owner' || currentUserRole === 'admin';++ // Fetch organisations on mount+ useEffect(() => {+ const fetchData = async () => {+ await fetchOrganisationList();+ await fetchPendingInvitations();+ setHasFetchedOrgs(true);+ };+ fetchData();+ }, []);++ // Redirect to onboarding if user has no organisations after fetch completes+ useEffect(() => {+ if (hasFetchedOrgs && !isOrgLoading && organisations.length === 0) {+ router.push("/onboarding");+ }+ }, [hasFetchedOrgs, isOrgLoading, organisations.length, router]);++ useEffect(() => {+ if (currentOrg) {+ setOrgName(currentOrg.name);+ fetchMembers();+ }+ }, [currentOrg?.id]);++ const fetchMembers = async () => {+ if (!currentOrg) return;++ setIsLoading(true);+ const [err, data] = await asaw(+ getData({+ url: `/api/organisation/${currentOrg.id}/members`,+ method: "GET",+ })+ );+ setIsLoading(false);++ if (!err && data) {+ setMembers(data.members || []);+ setOrgPendingInvites(data.pendingInvites || []);+ }+ };++ const handleSaveName = async () => {+ if (!currentOrg || !orgName.trim() || orgName === currentOrg.name) return;++ setIsSaving(true);+ await updateOrganisation(currentOrg.id, orgName.trim());+ setIsSaving(false);+ };++ const handleInvite = async () => {+ if (!currentOrg || !inviteEmail.trim()) return;++ setIsInviting(true);+ await inviteToOrganisation(currentOrg.id, [inviteEmail.trim()], () => {+ setInviteEmail("");+ fetchMembers();+ });+ setIsInviting(false);+ };++ const handleRemoveMember = async (userId: string) => {+ if (!currentOrg) return;+ await removeOrganisationMember(currentOrg.id, userId, fetchMembers);+ };++ const handleCancelInvite = async (inviteId: string) => {+ await cancelOrganisationInvitation(inviteId, fetchMembers);+ };++ const handleUpdateRole = async (userId: string, role: string) => {+ if (!currentOrg) return;+ await updateMemberRole(currentOrg.id, userId, role, fetchMembers);+ };++ const handleLeaveOrg = async () => {+ if (!currentOrg || !currentUserId) return;++ await removeOrganisationMember(currentOrg.id, currentUserId, async () => {+ await fetchOrganisationList();+ // The server already sets the correct current org based on organisationUser.createdAt+ // Only switch if no current org was set (edge case)+ const state = useRootStore.getState().organisation;+ const newCurrent = state.current;+ if (!newCurrent && state.list && state.list.length > 0) {+ // Fallback: use the org marked as current by the server, or first one if none marked+ const serverSelected = state.list.find((org) => org.isCurrent) || state.list[0];+ if (serverSelected) {+ await changeActiveOrganisation(serverSelected.id);+ }+ }+ });+ };++ const handleDeleteOrg = async () => {+ if (!currentOrg) return;++ await deleteOrganisation(currentOrg.id, async () => {+ // The server already sets the correct current org based on organisationUser.createdAt+ // Only switch if no current org was set (edge case)+ const state = useRootStore.getState().organisation;+ const newCurrent = state.current;+ if (!newCurrent && state.list && state.list.length > 0) {+ // Fallback: use the org marked as current by the server, or first one if none marked+ const serverSelected = state.list.find((org) => org.isCurrent) || state.list[0];+ if (serverSelected) {+ await changeActiveOrganisation(serverSelected.id);+ }+ }+ });+ };++ const handleAcceptInvitation = async (invitationId: string) => {+ await acceptInvitation(invitationId);+ };++ const handleDeclineInvitation = async (invitationId: string) => {+ await declineInvitation(invitationId);+ };++ return (+ <div className="p-4 space-y-4 overflow-auto w-full text-stone-700 dark:text-stone-300">+ <div className="flex items-center justify-between">+ <div>+ <h1 className="text-xl font-bold">{messages.ORGANISATION_SETTINGS}</h1>+ <p className="text-sm text-muted-foreground">+ {messages.ORGANISATION_SETTINGS_DESCRIPTION}+ </p>+ </div>+ <Button onClick={() => setCreateDialogOpen(true)} size="sm">+ <Building2 className="h-3.5 w-3.5 mr-1.5" />+ {messages.NEW_ORGANISATION}+ </Button>+ </div>++ {pendingInvitations.length > 0 && (+ <Card className="border-primary/20 bg-primary/5 dark:border-primary/30 dark:bg-primary/10">+ <CardHeader className="pb-3">+ <CardTitle className="text-base flex items-center gap-2">+ <Mail className="h-4 w-4" />+ {messages.PENDING_INVITATIONS}+ </CardTitle>+ </CardHeader>+ <CardContent className="space-y-2">+ {pendingInvitations.map((invitation) => (+ <div+ key={invitation.id}+ className="flex items-center justify-between p-2 border border-stone-200 dark:border-stone-800 rounded-md bg-background"+ >+ <p className="text-sm font-medium">{invitation.organisationName}</p>+ <div className="flex gap-1">+ <Button+ size="sm"+ variant="ghost"+ className="h-7 w-7 p-0"+ onClick={() => handleDeclineInvitation(invitation.id)}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ <Button+ size="sm"+ className="h-7"+ onClick={() => handleAcceptInvitation(invitation.id)}+ >+ <Check className="h-3.5 w-3.5 mr-1" />+ {messages.JOIN}+ </Button>+ </div>+ </div>+ ))}+ </CardContent>+ </Card>+ )}++ {currentOrg && (+ <Tabs defaultValue="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="members" className="text-xs text-stone-700 dark:text-stone-300">+ <Users className="h-3.5 w-3.5 mr-1.5" />+ {messages.MEMBERS} ({members.length})+ </TabsTrigger>+ {orgPendingInvites.length > 0 && (+ <TabsTrigger value="pending" className="text-xs text-stone-700 dark:text-stone-300">+ <Clock className="h-3.5 w-3.5 mr-1.5" />+ {messages.PENDING} ({orgPendingInvites.length})+ </TabsTrigger>+ )}+ <TabsTrigger value="all" className="text-xs text-stone-700 dark:text-stone-300">+ <Building2 className="h-3.5 w-3.5 mr-1.5" />+ {messages.ORGANISATIONS}+ </TabsTrigger>+ </TabsList>++ <TabsContent value="details" className="space-y-4 mt-0">+ {hasAdminPermissions ? (+ <div className="space-y-3 py-4">+ <div className="space-y-1.5">+ <Label htmlFor="org-name" className="text-sm">+ {messages.ORGANISATION_NAME}+ </Label>+ <div className="flex gap-2">+ <Input+ id="org-name"+ value={orgName}+ onChange={(e) => setOrgName(e.target.value)}+ className="h-9"+ />+ <Button+ onClick={handleSaveName}+ disabled={+ isSaving ||+ !orgName.trim() ||+ orgName === currentOrg.name+ }+ size="sm"+ className="h-9"+ >+ <Save className="h-3.5 w-3.5 mr-1.5" />+ {isSaving ? messages.SAVING : messages.SAVE}+ </Button>+ </div>+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="invite-email" className="text-sm">+ {messages.INVITE_NEW_MEMBER}+ </Label>+ <div className="flex gap-2">+ <Input+ id="invite-email"+ placeholder="[email protected]"+ type="email"+ value={inviteEmail}+ onChange={(e) => setInviteEmail(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ handleInvite();+ }+ }}+ className="h-9"+ />+ <Button+ onClick={handleInvite}+ disabled={isInviting || !inviteEmail.trim()}+ size="sm"+ className="h-9"+ >+ <UserPlus className="h-3.5 w-3.5 mr-1.5" />+ {isInviting ? messages.INVITING : messages.INVITE}+ </Button>+ </div>+ </div>+ </div>+ ) : (+ <div className="py-4">+ <Card className="border-stone-200 dark:border-stone-800">+ <CardContent className="pt-6">+ <p className="text-sm text-muted-foreground">+ {messages.INSUFFICIENT_PERMISSIONS}+ </p>+ </CardContent>+ </Card>+ </div>+ )}++ {isCreator && (+ <div className="border-t border-stone-200 dark:border-stone-800 pt-4 px-4 pb-4">+ <div className="space-y-2">+ <h4 className="text-sm font-medium text-destructive">+ {messages.DANGER_ZONE}+ </h4>+ <p className="text-xs text-muted-foreground">+ {messages.DANGER_ZONE_DESCRIPTION}+ </p>+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button+ variant="destructive"+ size="sm"+ className="h-8"+ disabled={members.length > 1}+ >+ <Trash2 className="h-3.5 w-3.5 mr-1.5" />+ {messages.DELETE_ORGANISATION}+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {messages.DELETE_ORGANISATION}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {messages.DELETE_ORGANISATION_CONFIRMATION}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>+ {messages.CANCEL}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleDeleteOrg}>+ {messages.DELETE}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ {members.length > 1 && (+ <p className="text-xs text-stone-600 dark:text-stone-400">+ {messages.ORGANISATION_DELETE_DESCRIPTION}+ </p>+ )}+ </div>+ </div>+ )}+ </TabsContent>++ <TabsContent value="members" className="mt-0 p-0 pt-2">+ {isLoading ? (+ <div className="flex items-center justify-center py-8">+ <Loader2 className="h-5 w-5 animate-spin" />+ </div>+ ) : (+ <Table>+ <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">+ <TableRow className="text-xs">+ <TableHead className="h-8 pl-2">{messages.MEMBER}</TableHead>+ <TableHead className="h-8">{messages.ROLE}</TableHead>+ <TableHead className="h-8 text-right">+ {messages.ACTIONS}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {members.map((member) => (+ <TableRow key={member.id} className="text-sm">+ <TableCell className="py-2 pl-2">+ <div>+ <p className="font-medium">+ {member.name || member.email}+ </p>+ {member.name && (+ <p className="text-xs text-muted-foreground">+ {member.email}+ </p>+ )}+ </div>+ </TableCell>+ <TableCell className="py-2">+ {member.isCreator ? (+ <Badge+ variant="secondary"+ className="text-xs h-5 px-2"+ >+ <Crown className="h-3 w-3 mr-1" />+ {messages.OWNER}+ </Badge>+ ) : hasAdminPermissions ? (+ <Select+ value={member.role}+ onValueChange={(value) =>+ handleUpdateRole(member.id, value)+ }+ >+ <SelectTrigger className="h-7 w-auto text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="admin" className="text-xs">+ {messages.ADMIN}+ </SelectItem>+ <SelectItem value="member" className="text-xs">+ {messages.MEMBER}+ </SelectItem>+ </SelectContent>+ </Select>+ ) : (+ <Badge variant="outline" className="text-xs h-5 px-2">+ {member.role === "admin"+ ? messages.ADMIN+ : messages.MEMBER}+ </Badge>+ )}+ </TableCell>+ <TableCell className="py-2 text-right">+ <div className="flex justify-end gap-1">+ {!member.isCreator && hasAdminPermissions && (+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="h-7 w-7 p-0 text-destructive"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {messages.REMOVE_MEMBER}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {messages.REMOVE_MEMBER_CONFIRMATION}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>+ {messages.CANCEL}+ </AlertDialogCancel>+ <AlertDialogAction+ onClick={() =>+ handleRemoveMember(member.id)+ }+ >+ {messages.DELETE}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )}+ {member.id === currentUserId && !member.isCreator && (+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ className="h-7 w-7 p-0 text-destructive"+ >+ <LogOut className="h-3.5 w-3.5" />+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {messages.LEAVE_ORGANISATION}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {messages.LEAVE_ORGANISATION_CONFIRMATION}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>+ {messages.CANCEL}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleLeaveOrg}>+ {messages.LEAVE}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )}+ </div>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}+ </TabsContent>++ {orgPendingInvites.length > 0 && (+ <TabsContent value="pending" className="mt-0 p-4">+ <Table>+ <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">+ <TableRow className="text-xs">+ <TableHead className="h-8 pl-2">{messages.EMAIL}</TableHead>+ <TableHead className="h-8">{messages.INVITED}</TableHead>+ <TableHead className="h-8 text-right">+ {messages.ACTIONS}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {orgPendingInvites.map((invite) => (+ <TableRow key={invite.id} className="text-sm">+ <TableCell className="py-2 pl-2">{invite.email}</TableCell>+ <TableCell className="py-2 text-xs text-muted-foreground">+ {new Date(invite.invitedAt).toLocaleDateString()}+ </TableCell>+ <TableCell className="py-2 text-right">+ <Button+ variant="ghost"+ size="sm"+ className="h-7 w-7 p-0 text-destructive"+ onClick={() => handleCancelInvite(invite.id)}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </TabsContent>+ )}++ <TabsContent value="all" className="mt-0 p-0 pt-2">+ <Table>+ <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">+ <TableRow className="text-xs">+ <TableHead className="h-8 pl-2">{messages.NAME}</TableHead>+ <TableHead className="h-8">{messages.MEMBERS}</TableHead>+ <TableHead className="h-8">{messages.STATUS}</TableHead>+ <TableHead className="h-8 text-right">+ {messages.ACTIONS}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {organisations.map((org) => (+ <TableRow key={org.id} className="text-sm">+ <TableCell className="py-2 font-medium pl-2">+ {org.name}+ </TableCell>+ <TableCell className="py-2 text-xs text-muted-foreground">+ {org.memberCount} {messages.MEMBER}+ {org.memberCount !== 1 ? "s" : ""}+ </TableCell>+ <TableCell className="py-2">+ {org.isCurrent ? (+ <Badge className="text-xs h-5 px-2">+ {messages.ACTIVE}+ </Badge>+ ) : (+ <span className="text-xs text-muted-foreground">-</span>+ )}+ </TableCell>+ <TableCell className="py-2 text-right">+ {!org.isCurrent && (+ <Button+ variant="outline"+ size="sm"+ className="h-7 text-xs"+ onClick={() => changeActiveOrganisation(org.id)}+ >+ {messages.SWITCH_ORGANISATION}+ </Button>+ )}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </TabsContent>+ </Tabs>+ )}++ <CreateOrganisationDialog+ open={createDialogOpen}+ onOpenChange={setCreateDialogOpen}+ />+ </div>+ );+}diff --git a/src/client/src/app/api/organisation/[id]/invite/route.ts b/src/client/src/app/api/organisation/[id]/invite/route.tsnew file mode 100644index 00000000..8914ffbb--- /dev/null+++ b/src/client/src/app/api/organisation/[id]/invite/route.ts@@ -0,0 +1,60 @@+import { inviteUserToOrganisation } from "@/lib/organisation";+import asaw from "@/utils/asaw";++// Email validation regex - using a safer pattern that avoids ReDoS vulnerability+// This pattern is more restrictive but safe from catastrophic backtracking+const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;++export async function POST(+ request: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;+ const formData = await request.json();+ const { emails } = formData;++ if (!emails || !Array.isArray(emails) || emails.length === 0) {+ return Response.json("At least one email is required", {+ status: 400,+ });+ }++ const results = await Promise.all(+ emails.map(async (email: string) => {+ // Validate email format and content before processing+ const trimmedEmail = typeof email === "string" ? email.trim() : "";++ if (!trimmedEmail) {+ return {+ email: email,+ error: "Email cannot be empty",+ result: null,+ };+ }++ if (!EMAIL_REGEX.test(trimmedEmail)) {+ return {+ email: trimmedEmail,+ error: "Invalid email format",+ result: null,+ };+ }++ const [err, res] = await asaw(inviteUserToOrganisation(id, trimmedEmail));+ return {+ email: trimmedEmail,+ error: err ? String(err).replace(/^Error:\s*/, "") : null,+ result: res,+ };+ })+ );++ const hasErrors = results.some((r) => r.error);+ if (hasErrors) {+ return Response.json(results, {+ status: 207, // Multi-status+ });+ }++ return Response.json(results);+}diff --git a/src/client/src/app/api/organisation/[id]/members/[userId]/route.ts b/src/client/src/app/api/organisation/[id]/members/[userId]/route.tsnew file mode 100644index 00000000..bb55a27c--- /dev/null+++ b/src/client/src/app/api/organisation/[id]/members/[userId]/route.ts@@ -0,0 +1,40 @@+import { removeUserFromOrganisation, updateMemberRole } from "@/lib/organisation";+import asaw from "@/utils/asaw";++export async function DELETE(+ request: Request,+ { params }: { params: Promise<{ id: string; userId: string }> }+) {+ const { id, userId } = await params;++ const [err, res] = await asaw(removeUserFromOrganisation(id, userId));++ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}++export async function PATCH(+ request: Request,+ { params }: { params: Promise<{ id: string; userId: string }> }+) {+ const { id, userId } = await params;+ const body = await request.json();+ const { role } = body;++ if (!role) {+ return Response.json({ error: "Role is required" }, { status: 400 });+ }++ const [err, res] = await asaw(updateMemberRole(id, userId, role));++ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}diff --git a/src/client/src/app/api/organisation/[id]/members/route.ts b/src/client/src/app/api/organisation/[id]/members/route.tsnew file mode 100644index 00000000..8d57bee1--- /dev/null+++ b/src/client/src/app/api/organisation/[id]/members/route.ts@@ -0,0 +1,31 @@+import {+ getOrganisationMembers,+ getOrganisationPendingInvites,+} from "@/lib/organisation";+import asaw from "@/utils/asaw";++export async function GET(+ request: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;++ const [membersErr, members] = await asaw(getOrganisationMembers(id));+ if (membersErr)+ return Response.json(membersErr, {+ status: 400,+ });++ const [invitesErr, pendingInvites] = await asaw(+ getOrganisationPendingInvites(id)+ );+ if (invitesErr)+ return Response.json(invitesErr, {+ status: 400,+ });++ return Response.json({+ members,+ pendingInvites,+ });+}diff --git a/src/client/src/app/api/organisation/[id]/route.ts b/src/client/src/app/api/organisation/[id]/route.tsnew file mode 100644index 00000000..951ffe5c--- /dev/null+++ b/src/client/src/app/api/organisation/[id]/route.ts@@ -0,0 +1,56 @@+import {+ getOrganisationById,+ updateOrganisation,+ deleteOrganisation,+} from "@/lib/organisation";+import asaw from "@/utils/asaw";++export async function GET(+ request: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;++ const [err, res] = await asaw(getOrganisationById(id));+ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}++export async function PUT(+ request: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;+ const formData = await request.json();++ const [err, res] = await asaw(+ updateOrganisation(id, { name: formData.name })+ );++ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}++export async function DELETE(+ request: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;++ const [err, res] = await asaw(deleteOrganisation(id));++ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}diff --git a/src/client/src/app/api/organisation/current/[id]/route.ts b/src/client/src/app/api/organisation/current/[id]/route.tsnew file mode 100644index 00000000..22a53fc2--- /dev/null+++ b/src/client/src/app/api/organisation/current/[id]/route.ts@@ -0,0 +1,18 @@+import { setCurrentOrganisation } from "@/lib/organisation";+import asaw from "@/utils/asaw";++export async function POST(+ request: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;++ const [err, res] = await asaw(setCurrentOrganisation(id));++ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}diff --git a/src/client/src/app/api/organisation/invitation/[id]/route.ts b/src/client/src/app/api/organisation/invitation/[id]/route.tsnew file mode 100644index 00000000..234b97d2--- /dev/null+++ b/src/client/src/app/api/organisation/invitation/[id]/route.ts@@ -0,0 +1,44 @@+import {+ acceptInvitation,+ declineInvitation,+ cancelInvitation,+} from "@/lib/organisation";+import asaw from "@/utils/asaw";++// Accept invitation+export async function POST(+ request: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;++ const [err, res] = await asaw(acceptInvitation(id));++ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}++// Decline or cancel invitation+export async function DELETE(+ request: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;+ const url = new URL(request.url);+ const isCancel = url.searchParams.get("cancel") === "true";++ const [err, res] = await asaw(+ isCancel ? cancelInvitation(id) : declineInvitation(id)+ );++ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}diff --git a/src/client/src/app/api/organisation/invitation/route.ts b/src/client/src/app/api/organisation/invitation/route.tsnew file mode 100644index 00000000..40b3468c--- /dev/null+++ b/src/client/src/app/api/organisation/invitation/route.ts@@ -0,0 +1,12 @@+import { getPendingInvitationsForUser } from "@/lib/organisation";+import asaw from "@/utils/asaw";++export async function GET() {+ const [err, res] = await asaw(getPendingInvitationsForUser());+ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}diff --git a/src/client/src/app/api/organisation/route.ts b/src/client/src/app/api/organisation/route.tsnew file mode 100644index 00000000..cb90b24e--- /dev/null+++ b/src/client/src/app/api/organisation/route.ts@@ -0,0 +1,35 @@+import {+ createOrganisation,+ getOrganisationsByUser,+} from "@/lib/organisation";+import asaw from "@/utils/asaw";++export async function GET() {+ const [err, res] = await asaw(getOrganisationsByUser());+ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}++export async function POST(request: Request) {+ const formData = await request.json();+ const { name } = formData;++ if (!name) {+ return Response.json("Name is required", {+ status: 400,+ });+ }++ const [err, res] = await asaw(createOrganisation(name));++ if (err)+ return Response.json(err, {+ status: 400,+ });++ return Response.json(res);+}diff --git a/src/client/src/app/api/user/complete-onboarding/route.ts b/src/client/src/app/api/user/complete-onboarding/route.tsnew file mode 100644index 00000000..3c6c14c4--- /dev/null+++ b/src/client/src/app/api/user/complete-onboarding/route.ts@@ -0,0 +1,20 @@+import prisma from "@/lib/prisma";+import { getCurrentUser } from "@/lib/session";+import asaw from "@/utils/asaw";++export async function POST() {+ const [err, user] = await asaw(getCurrentUser());++ if (err || !user) {+ return Response.json("Unauthorized", {+ status: 401,+ });+ }++ await prisma.user.update({+ where: { id: user.id },+ data: { hasCompletedOnboarding: true },+ });++ return Response.json({ success: true });+}diff --git a/src/client/src/app/auth.ts b/src/client/src/app/auth.tsindex b422b28d..1be25add 100644--- a/src/client/src/app/auth.ts+++ b/src/client/src/app/auth.ts@@ -15,10 +15,30 @@ import {const prisma = new PrismaClient();+// Create a custom adapter that normalizes emails+function createNormalizedEmailAdapter(p: PrismaClient) {+ const baseAdapter = PrismaAdapter(p);+ return {+ ...baseAdapter,+ async createUser(user: any) {+ // Normalize email before creating user+ if (user.email) {+ user.email = user.email.toLowerCase().trim();+ }+ return baseAdapter.createUser!(user);+ },+ async getUserByEmail(email: string) {+ // Normalize email before lookup+ const normalizedEmail = email.toLowerCase().trim();+ return baseAdapter.getUserByEmail!(normalizedEmail);+ },+ };+}+export const authOptions = {- adapter: PrismaAdapter(prisma),+ adapter: createNormalizedEmailAdapter(prisma),callbacks: {- async jwt({ token, account, user }) {+ async jwt({ token, account, user, trigger }) {// Persist the OAuth access_token and or the user id to the token right after signinif (account) {token.accessToken = account.access_token;@@ -28,26 +48,69 @@ export const authOptions = {token.id = user.id;}- // Validate that the user still exists in the database for existing tokens- // This prevents issues when starting with a fresh database but stale cookies- if (token?.id && !user) {+ // Handle explicit session update requests (e.g., after completing onboarding)+ if (trigger === "update" && token?.id) {try {const [, existingUser] = await asaw(getUserById({ id: token.id as string }));- // If user doesn't exist in database, invalidate the tokenif (!existingUser) {return null;}++ // Update hasCompletedOnboarding status from database+ token.hasCompletedOnboarding = existingUser.hasCompletedOnboarding;} catch (error) {- // If there's a database connection error during startup,- // allow the token to pass through to avoid blocking the app- // The error will be handled at the application level- console.error("Database error during JWT validation:", error);+ console.error("Database error during JWT update:", error);}}+ // Validate that the user still exists in the database for existing tokens+ // This prevents issues when starting with a fresh database but stale cookies+ if (token?.id && !user && trigger !== "update") {+ try {+ const [, existingUser] = await asaw(+ getUserById({ id: token.id as string })+ );++ // If user doesn't exist in database, invalidate the token+ if (!existingUser) {+ return null;+ }++ // Update hasCompletedOnboarding status on every token refresh+ token.hasCompletedOnboarding = existingUser.hasCompletedOnboarding;+ } catch (error) {+ // If there's a database connection error during startup,+ // allow the token to pass through to avoid blocking the app+ // The error will be handled at the application level+ console.error("Database error during JWT validation:", error);+ }+ }++ // Set initial hasCompletedOnboarding for new users or OAuth logins+ // For OAuth logins, the user object doesn't include custom fields, so fetch from database+ if (user && token?.id) {+ try {+ const [, existingUser] = await asaw(+ getUserById({ id: token.id as string })+ );++ if (existingUser) {+ // Use the value from database (handles OAuth logins correctly)+ token.hasCompletedOnboarding = existingUser.hasCompletedOnboarding;+ } else {+ // Fallback for brand new users (credentials provider during registration)+ token.hasCompletedOnboarding = (user as any).hasCompletedOnboarding ?? false;+ }+ } catch (error) {+ // Fallback to user object value if database query fails+ console.error("Database error during JWT user setup:", error);+ token.hasCompletedOnboarding = (user as any).hasCompletedOnboarding ?? false;+ }+ }+return token;},signIn: async ({ user, account, profile }) => {@@ -143,10 +206,16 @@ export const authOptions = {// Run custom setup for new usersif (user.email && user.id) {try {+ // Normalize email for consistency+ const normalizedEmail = user.email.toLowerCase().trim();+const { moveSharedDBConfigToDBUser } = await import("@/lib/db-config");- await moveSharedDBConfigToDBUser(user.email, user.id);+ await moveSharedDBConfigToDBUser(normalizedEmail, user.id);++ const { moveInvitationsToMembership } = await import("@/lib/organisation");+ await moveInvitationsToMembership(normalizedEmail, user.id);} catch (error) {- console.error("Error moving shared db configs to new user:", error);+ console.error("Error during new user setup:", error);}}}diff --git a/src/client/src/app/layout.tsx b/src/client/src/app/layout.tsxindex 477f28f8..00cf5eb9 100644--- a/src/client/src/app/layout.tsx+++ b/src/client/src/app/layout.tsx@@ -3,6 +3,7 @@ import { cookies } from "next/headers";import localFont from "next/font/local";import "./globals.css";import { Toaster } from "@/components/ui/sonner";+import Providers from "@/components/common/providers";const inter = localFont({src: "../../public/fonts/Inter.ttf",@@ -29,8 +30,10 @@ export default function RootLayout({<html lang="en" className={`scroll-smooth ${theme?.value || ""}`}>{/* bg-[linear-gradient(360deg,rgba(243,108,6,0.7)_0%,white_25%)] dark:bg-[linear-gradient(360deg,rgba(243,108,6,0.8)_0%,black_25%)] */}<body className={`${inter.className} bg-stone-50 dark:bg-stone-950`}>- {children}- <Toaster position="bottom-right" />+ <Providers>+ {children}+ <Toaster position="bottom-right" />+ </Providers></body></html>);diff --git a/src/client/src/components/(playground)/getting-started/openground/index.tsx b/src/client/src/components/(playground)/getting-started/openground/index.tsxindex 74c394a4..63dbf1c3 100644--- a/src/client/src/components/(playground)/getting-started/openground/index.tsx+++ b/src/client/src/components/(playground)/getting-started/openground/index.tsx@@ -14,7 +14,7 @@ export default function OpengroundGettingStarted() {{getMessage().GET_STARTED_WITH_OPENGROUND_DESCRIPTION}</p>- <OpengroundHeader validateResponse={false} className='flex mb-8 items-center justify-center' />+ <OpengroundHeader validateResponse={false} /><div className="grid grid-cols-1 md:grid-cols-2 gap-6">{getMessage().GET_STARTED_WITH_OPENGROUND_FEATURE_DETAILS.map((item) => (diff --git a/src/client/src/components/(playground)/sidebar/create-organisation-dialog.tsx b/src/client/src/components/(playground)/sidebar/create-organisation-dialog.tsxnew file mode 100644index 00000000..d16f498c--- /dev/null+++ b/src/client/src/components/(playground)/sidebar/create-organisation-dialog.tsx@@ -0,0 +1,82 @@+"use client";+import { useState } from "react";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { createOrganisation } from "@/helpers/client/organisation";+import getMessage from "@/constants/messages";++interface CreateOrganisationDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onSuccess?: () => void;+}++export default function CreateOrganisationDialog({+ open,+ onOpenChange,+ onSuccess,+}: CreateOrganisationDialogProps) {+ const messages = getMessage();+ const [name, setName] = useState("");+ const [isLoading, setIsLoading] = useState(false);++ const handleCreate = async () => {+ if (!name.trim()) return;++ setIsLoading(true);+ const result = await createOrganisation(name.trim());+ setIsLoading(false);++ if (result) {+ setName("");+ onOpenChange(false);+ onSuccess?.();+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[425px] text-stone-700 dark:text-stone-300">+ <DialogHeader>+ <DialogTitle>{messages.CREATE_ORGANISATION}</DialogTitle>+ <DialogDescription>+ {messages.ORGANISATION_CREATE_DESCRIPTION}+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4 py-4">+ <div className="grid gap-2">+ <Label htmlFor="name">{messages.ORGANISATION_NAME}</Label>+ <Input+ id="name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={messages.ORGANISATION_NAME_PLACEHOLDER}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ handleCreate();+ }+ }}+ />+ </div>+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {messages.CANCEL}+ </Button>+ <Button onClick={handleCreate} disabled={!name.trim() || isLoading}>+ {isLoading ? messages.CREATING : messages.CREATE}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/client/src/components/(playground)/sidebar/database-config-switch.tsx b/src/client/src/components/(playground)/sidebar/database-config-switch.tsxindex a4cf3ab3..f51fcd2a 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,4 @@-import { ChevronsUpDown, Database, Plus } from "lucide-react";+import { ChevronsUpDown, Database, Plus, Settings } from "lucide-react";import { getDatabaseConfigList } from "@/selectors/database-config";import { useRootStore } from "@/store";import { useEffect } from "react";@@ -12,9 +12,13 @@ import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMeimport { 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";export default function DatabaseConfigSwitch() {const posthog = usePostHog();+ const router = useRouter();+ const messages = getMessage();const list = useRootStore(getDatabaseConfigList) || [];const activeDatabase = list.find((item) => !!item.isCurrent);const onClickItem = (id: string) => {@@ -31,24 +35,41 @@ export default function DatabaseConfigSwitch() {});}, []);- if (!activeDatabase) return null;+ // Show manage button when no database configs exist+ if (list.length === 0) {+ 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"+ 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">+ {messages.MANAGE_DB_CONFIG}+ </span>+ </Button>+ );+ }++ const activeDatabaseId = activeDatabase?.id;+ const displayDatabaseName = activeDatabase?.name || messages.PLEASE_SELECT;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">{activeDatabase?.name}</span>+ <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></DropdownMenuTrigger><DropdownMenuContent className="w-56" side="right" align="start">- <DropdownMenuLabel>Databases</DropdownMenuLabel>+ <DropdownMenuLabel>{messages.DATABASES}</DropdownMenuLabel><DropdownMenuSeparator />{list.map((item) => (<DropdownMenuCheckboxItemkey={item.id}- checked={item.id === activeDatabase.id}+ checked={item.id === activeDatabaseId}onCheckedChange={() => onClickItem(item.id)}><div className="flex items-start text-muted-foreground ">@@ -68,7 +89,7 @@ export default function DatabaseConfigSwitch() {<DropdownMenuSeparator /><DropdownMenuItem className="py-1.5 pl-8 pr-2"><Link href="/settings/database-config" className=" flex items-center">- Add New Config+ {messages.ADD_NEW_CONFIG}</Link></DropdownMenuItem></DropdownMenuContent>diff --git a/src/client/src/components/(playground)/sidebar/index.tsx b/src/client/src/components/(playground)/sidebar/index.tsxindex d0df20da..e62f868d 100644--- a/src/client/src/components/(playground)/sidebar/index.tsx+++ b/src/client/src/components/(playground)/sidebar/index.tsx@@ -16,6 +16,7 @@ import version from "../../../../package.json";import UserActions from "./user-actions";import { Accordion, AccordionTrigger, AccordionItem, AccordionContent } from "@/components/ui/accordion";import { PRIMARY_BACKGROUND } from "@/constants/common-classes";+import getMessage from "@/constants/messages";const getIfSidebarItemClasses = (pathname: string, item: SidebarItemProps) => {const commonClasses = "flex gap-2 group-data-[state=open]:w-auto group-data-[state=open]:justify-start p-2.5 font-normal ";@@ -145,6 +146,7 @@ const SidebarItem = ({ item, className, pathname }: { item: SidebarItemProps, clexport default function Sidebar() {const pathname = usePathname();+ const messages = getMessage();const [isExpanded, setIsExpanded] = useState<boolean>(true);const toggleExpansion = () => setIsExpanded(e => !e);@@ -168,7 +170,7 @@ export default function Sidebar() {<span>OpenLIT</span><span className="text-xs font-normal text-primary/80 mt-1">({version.version})</span></p>- <Button variant="ghost" size="icon" aria-label="Expand" onClick={toggleExpansion} className="absolute top-1/2 right-0 -translate-y-1/2 translate-x-1/2 rounded-md h-auto w-auto text-stone-500 dark:text-stone-300 p-0.5 cursor-pointer bg-stone-50 hover:bg-stone-50 dark:bg-stone-900 dark:hover:bg-stone-900">+ <Button variant="ghost" size="icon" aria-label={messages.EXPAND} onClick={toggleExpansion} className="absolute top-1/2 right-0 -translate-y-1/2 translate-x-1/2 rounded-md h-auto w-auto text-stone-500 dark:text-stone-300 p-0.5 cursor-pointer bg-stone-50 hover:bg-stone-50 dark:bg-stone-900 dark:hover:bg-stone-900">{isExpanded ? <PanelRightOpen className="w-5 h-5" /> : <PanelRightClose className="w-5 h-5" />}</Button></div>diff --git a/src/client/src/components/(playground)/sidebar/organisation-switch.tsx b/src/client/src/components/(playground)/sidebar/organisation-switch.tsxnew file mode 100644index 00000000..f5de7304--- /dev/null+++ b/src/client/src/components/(playground)/sidebar/organisation-switch.tsx@@ -0,0 +1,135 @@+"use client";+import { Building2, ChevronsUpDown, Plus, Mail } from "lucide-react";+import {+ getCurrentOrganisation,+ getOrganisationList,+ getPendingInvitationsCount,+} from "@/selectors/organisation";+import { useRootStore } from "@/store";+import { useEffect, useState } from "react";+import { changeActiveOrganisation } from "@/helpers/client/organisation";+import { usePostHog } from "posthog-js/react";+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 { Badge } from "@/components/ui/badge";+import CreateOrganisationDialog from "./create-organisation-dialog";+import getMessage from "@/constants/messages";+import { CLIENT_EVENTS } from "@/constants/events";++export default function OrganisationSwitch() {+ const posthog = usePostHog();+ const messages = getMessage();+ const list = useRootStore(getOrganisationList) || [];+ const currentOrg = useRootStore(getCurrentOrganisation);+ const pendingInvitationsCount = useRootStore(getPendingInvitationsCount);+ const [createDialogOpen, setCreateDialogOpen] = useState(false);++ const onClickItem = (id: string) => {+ if (id === currentOrg?.id) return;+ changeActiveOrganisation(id, () => {+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_SWITCHED);+ });+ };++ if (!currentOrg) return null;++ 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 relative"+ >+ <Building2 className={`${ICON_CLASSES} shrink-0`} />+ <span className="block group-data-[state=close]:hidden text-ellipsis overflow-hidden whitespace-nowrap grow text-left">+ {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"+ >+ {pendingInvitationsCount}+ </Badge>+ )}+ <ChevronsUpDown+ className={`size-4 block group-data-[state=close]:hidden shrink-0`}+ />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-56" side="right" align="start">+ <DropdownMenuLabel>{messages.ORGANISATIONS}</DropdownMenuLabel>+ <DropdownMenuSeparator />+ {list.map((item) => (+ <DropdownMenuCheckboxItem+ key={item.id}+ checked={item.id === currentOrg.id}+ onCheckedChange={() => onClickItem(item.id)}+ >+ <div className="flex items-start text-muted-foreground">+ <div className="grid">+ <p>+ <span className="font-medium text-foreground">+ {item.name}+ </span>+ </p>+ <p className="text-xs" data-description>+ {item.memberCount} {messages.MEMBER}{item.memberCount !== 1 ? "s" : ""}+ </p>+ </div>+ </div>+ </DropdownMenuCheckboxItem>+ ))}+ <DropdownMenuSeparator />+ {pendingInvitationsCount > 0 && (+ <>+ <DropdownMenuItem className="py-1.5 pl-8 pr-2">+ <Link+ href="/settings/organisation"+ className="flex items-center gap-2"+ >+ <Mail className="size-4" />+ {pendingInvitationsCount} {messages.PENDING_INVITATION}+ {pendingInvitationsCount !== 1 ? "s" : ""}+ </Link>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuItem+ className="py-1.5 pl-8 pr-2"+ onSelect={() => setCreateDialogOpen(true)}+ >+ <div className="flex items-center gap-2">+ <Plus className="size-4" />+ {messages.CREATE_ORGANISATION}+ </div>+ </DropdownMenuItem>+ <DropdownMenuItem className="py-1.5 pl-8 pr-2">+ <Link+ href="/settings/organisation"+ className="flex items-center w-full"+ >+ {messages.MANAGE_ORGANISATIONS}+ </Link>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <CreateOrganisationDialog+ open={createDialogOpen}+ onOpenChange={setCreateDialogOpen}+ />+ </>+ );+}diff --git a/src/client/src/components/(playground)/sidebar/user-actions.tsx b/src/client/src/components/(playground)/sidebar/user-actions.tsxindex 7272c209..cc3ca7a6 100644--- a/src/client/src/components/(playground)/sidebar/user-actions.tsx+++ b/src/client/src/components/(playground)/sidebar/user-actions.tsx@@ -8,12 +8,14 @@ import { signOut } from "next-auth/react";import Link from "next/link";import { usePostHog } from "posthog-js/react";import { useEffect } from "react";+import getMessage from "@/constants/messages";const DROPDOWN_MENU_ITEM_CLASS = "flex w-full text-xs gap-2 hover:bg-primary/10 dark:hover:bg-primary/10 px-2 py-1.5";const DROPDOWN_MENU_ICON_CLASS = "w-4 h-4";export default function UserActions() {const posthog = usePostHog();+ const messages = getMessage();const user = useRootStore(getUserDetails);const resetUserFn = useRootStore(resetUser);const onClickSignout = () => {@@ -68,7 +70,7 @@ export default function UserActions() {<DropdownMenuItem className="p-0"><Link href="/settings/profile" className={DROPDOWN_MENU_ITEM_CLASS}><Pencil className={DROPDOWN_MENU_ICON_CLASS} />- Edit details+ {messages.EDIT_DETAILS}</Link></DropdownMenuItem></DropdownMenuGroup>@@ -76,7 +78,7 @@ export default function UserActions() {<DropdownMenuItem className="p-0" onClick={onClickSignout}><div className={DROPDOWN_MENU_ITEM_CLASS}><LogOut className={DROPDOWN_MENU_ICON_CLASS} />- Log out+ {messages.LOG_OUT}</div></DropdownMenuItem></DropdownMenuContent>diff --git a/src/client/src/components/common/app-init.tsx b/src/client/src/components/common/app-init.tsxindex adfb7afb..a116548c 100644--- a/src/client/src/components/common/app-init.tsx+++ b/src/client/src/components/common/app-init.tsx@@ -1,15 +1,43 @@"use client";import { useEffect } from "react";+import { usePathname } from "next/navigation";import { fetchAndPopulateCurrentUserStore } from "@/helpers/client/user";+import {+ fetchOrganisationList,+ fetchPendingInvitations,+} from "@/helpers/client/organisation";import { getIsUserFetched } from "@/selectors/user";+import { getOrganisationList } from "@/selectors/organisation";import { useRootStore } from "@/store";export default function AppInit() {const isFetched = useRootStore(getIsUserFetched);+ const organisationList = useRootStore(getOrganisationList);+ const isOrgLoading = useRootStore(+ (state) => state.organisation.isLoading+ );+ const pathname = usePathname();+useEffect(() => {- if (!isFetched) fetchAndPopulateCurrentUserStore();+ if (!isFetched) {+ fetchAndPopulateCurrentUserStore();+ fetchOrganisationList();+ fetchPendingInvitations();+ }}, [isFetched]);+ // Redirect to onboarding if user has no organisations+ useEffect(() => {+ if (+ !isOrgLoading &&+ Array.isArray(organisationList) &&+ organisationList.length === 0 &&+ pathname !== "/onboarding"+ ) {+ window.location.href = "/onboarding";+ }+ }, [isOrgLoading, organisationList, pathname]);+return null;}diff --git a/src/client/src/components/common/providers.tsx b/src/client/src/components/common/providers.tsxnew file mode 100644index 00000000..d59d8eaa--- /dev/null+++ b/src/client/src/components/common/providers.tsx@@ -0,0 +1,12 @@+"use client";++import { SessionProvider } from "next-auth/react";+import { ReactNode } from "react";++interface ProvidersProps {+ children: ReactNode;+}++export default function Providers({ children }: ProvidersProps) {+ return <SessionProvider>{children}</SessionProvider>;+}diff --git a/src/client/src/components/ui/alert-dialog.tsx b/src/client/src/components/ui/alert-dialog.tsxnew file mode 100644index 00000000..2a7b548f--- /dev/null+++ b/src/client/src/components/ui/alert-dialog.tsx@@ -0,0 +1,141 @@+"use client"++import * as React from "react"+import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"++import { cn } from "@/lib/utils"+import { buttonVariants } from "@/components/ui/button"++const AlertDialog = AlertDialogPrimitive.Root++const AlertDialogTrigger = AlertDialogPrimitive.Trigger++const AlertDialogPortal = AlertDialogPrimitive.Portal++const AlertDialogOverlay = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Overlay>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Overlay+ className={cn(+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",+ className+ )}+ {...props}+ ref={ref}+ />+))+AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName++const AlertDialogContent = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>+>(({ className, ...props }, ref) => (+ <AlertDialogPortal>+ <AlertDialogOverlay />+ <AlertDialogPrimitive.Content+ ref={ref}+ className={cn(+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-stone-200 bg-white p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg dark:border-stone-800 dark:bg-stone-950",+ className+ )}+ {...props}+ />+ </AlertDialogPortal>+))+AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName++const AlertDialogHeader = ({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) => (+ <div+ className={cn(+ "flex flex-col space-y-2 text-center sm:text-left",+ className+ )}+ {...props}+ />+)+AlertDialogHeader.displayName = "AlertDialogHeader"++const AlertDialogFooter = ({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) => (+ <div+ className={cn(+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",+ className+ )}+ {...props}+ />+)+AlertDialogFooter.displayName = "AlertDialogFooter"++const AlertDialogTitle = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Title>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Title+ ref={ref}+ className={cn("text-lg font-semibold text-stone-900 dark:text-stone-50", className)}+ {...props}+ />+))+AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName++const AlertDialogDescription = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Description>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Description+ ref={ref}+ className={cn("text-sm text-stone-500 dark:text-stone-400", className)}+ {...props}+ />+))+AlertDialogDescription.displayName =+ AlertDialogPrimitive.Description.displayName++const AlertDialogAction = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Action>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Action+ ref={ref}+ className={cn(buttonVariants(), className)}+ {...props}+ />+))+AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName++const AlertDialogCancel = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Cancel>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Cancel+ ref={ref}+ className={cn(+ buttonVariants({ variant: "outline" }),+ "mt-2 sm:mt-0",+ className+ )}+ {...props}+ />+))+AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName++export {+ AlertDialog,+ AlertDialogPortal,+ AlertDialogOverlay,+ AlertDialogTrigger,+ AlertDialogContent,+ AlertDialogHeader,+ AlertDialogFooter,+ AlertDialogTitle,+ AlertDialogDescription,+ AlertDialogAction,+ AlertDialogCancel,+}diff --git a/src/client/src/constants/events.ts b/src/client/src/constants/events.tsindex 450383cf..1e8fb858 100644--- a/src/client/src/constants/events.ts+++ b/src/client/src/constants/events.ts@@ -77,6 +77,18 @@ export const CLIENT_EVENTS = {FLEET_HUB_VIEWED: "FLEET_HUB_VIEWED",FLEET_HUB_AGENT_VIEWED: "FLEET_HUB_AGENT_VIEWED",FLEET_HUB_AGENT_CONFIG_SAVED: "FLEET_HUB_AGENT_CONFIG_SAVED",++ // organisation+ ORGANISATION_SWITCHED: "ORGANISATION_SWITCHED",+ ORGANISATION_CREATED: "ORGANISATION_CREATED",+ ORGANISATION_UPDATED: "ORGANISATION_UPDATED",+ ORGANISATION_DELETED: "ORGANISATION_DELETED",+ ORGANISATION_MEMBER_INVITED: "ORGANISATION_MEMBER_INVITED",+ ORGANISATION_MEMBER_REMOVED: "ORGANISATION_MEMBER_REMOVED",+ ORGANISATION_MEMBER_ROLE_UPDATED: "ORGANISATION_MEMBER_ROLE_UPDATED",+ ORGANISATION_INVITATION_ACCEPTED: "ORGANISATION_INVITATION_ACCEPTED",+ ORGANISATION_INVITATION_DECLINED: "ORGANISATION_INVITATION_DECLINED",+ ORGANISATION_INVITATION_CANCELLED: "ORGANISATION_INVITATION_CANCELLED",};export const SERVER_EVENTS = {diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.tsindex a4850167..41bab356 100644--- a/src/client/src/constants/messages/en.ts+++ b/src/client/src/constants/messages/en.ts@@ -352,5 +352,125 @@ export const CONFIGURED = "Configured";export const SELECTED = "Selected";export const CANCEL = "Cancel";export const DELETE = "Delete";+export const LEAVE = "Leave";export const CLOSE = "Close";-export const ACTIONS = "Actions";\ No newline at end of file+export const ACTIONS = "Actions";+export const JOIN = "Join";+export const CREATE = "Create";+export const CREATING = "Creating...";+export const SETTING_UP = "Setting up...";+export const SELECTING = "Selecting...";+export const EDIT_DETAILS = "Edit details";+export const LOG_OUT = "Log out";+export const EXPAND = "Expand";+export const DATABASES = "Databases";+export const ADD_NEW_CONFIG = "Add New Config";+export const MANAGE_DB_CONFIG = "Manage DB Config";+export const PENDING_INVITATION = "Pending Invitation";++// Organisation+export const ORGANISATION = "Organisation";+export const ORGANISATIONS = "Organisations";+export const ORGANISATION_NAME = "Organisation Name";+export const ORGANISATION_NAME_PLACEHOLDER = "My Company";+export const CREATE_ORGANISATION = "Create Organisation";+export const NEW_ORGANISATION = "New Organisation";+export const MANAGE_ORGANISATIONS = "Manage Organisations";+export const SWITCH_ORGANISATION = "Switch Organisation";+export const ORGANISATION_SETTINGS = "Organisation Settings";+export const ORGANISATION_SETTINGS_DESCRIPTION = "Manage your organisations and team members";+export const CURRENT_ORGANISATION = "Current Organisation";+export const UPDATE_ORGANISATION_DETAILS = "Update your organisation details";+export const YOUR_ORGANISATIONS = "Your Organisations";+export const YOUR_ORGANISATIONS_DESCRIPTION = "All organisations you are a member of";+export const YOUR_ORGANISATIONS_ONBOARDING_DESCRIPTION = "You're already a member of these organisations. Select one to get started.";+export const ORGANISATION_CREATED = "Organisation created successfully";+export const ORGANISATION_UPDATED = "Organisation updated successfully";+export const ORGANISATION_DELETED = "Organisation deleted successfully";+export const ORGANISATION_SWITCHED = "Switched organisation successfully";+export const ORGANISATION_SWITCH_FAILED = "Failed to switch organisation";+export const ORGANISATION_CREATE_FAILED = "Failed to create organisation";+export const ORGANISATION_UPDATE_FAILED = "Failed to update organisation";+export const ORGANISATION_DELETE_FAILED = "Failed to delete organisation";+export const ORGANISATION_CREATE_DESCRIPTION = "Create a new organisation to manage your databases and team members.";+export const ORGANISATION_DELETE_DESCRIPTION = "Remove all members before deleting this organisation.";++// Organisation Members+export const MEMBERS = "Members";+export const MEMBER = "Member";+export const OWNER = "Owner";+export const ADMIN = "Admin";+export const ROLE = "Role";+export const CHANGE_ROLE = "Change Role";+export const MEMBER_ROLE_UPDATED = "Member role updated successfully";+export const MEMBER_ROLE_UPDATE_FAILED = "Failed to update member role";+export const INVITE_MEMBERS = "Invite Members";+export const INVITE_MEMBERS_DESCRIPTION = "Invite new members to your organisation";+export const INVITE_NEW_MEMBER = "Invite New Member";+export const INVITE = "Invite";+export const INVITING = "Inviting...";+export const INVITATIONS_SENT = "Invitations sent successfully";+export const INVITATION_FAILED = "Failed to send invitations";+export const INVITATIONS_PARTIAL_SUCCESS = "Sent {success} invitation(s), {fail} failed";+export const REMOVE_MEMBER = "Remove Member";+export const REMOVE_MEMBER_CONFIRMATION = "Are you sure you want to remove this member from the organisation?";+export const MEMBER_REMOVED = "Member removed successfully";+export const LEAVE_ORGANISATION = "Leave Organisation";+export const LEAVE_ORGANISATION_CONFIRMATION = "Are you sure you want to leave this organisation?";+export const DELETE_ORGANISATION = "Delete Organisation";+export const DELETE_ORGANISATION_CONFIRMATION = "Are you sure you want to delete this organisation? This action cannot be undone.";+export const DANGER_ZONE = "Danger Zone";+export const DANGER_ZONE_DESCRIPTION = "Irreversible actions for this organisation";+export const GENERAL = "General";+export const DETAILS = "Details";+export const PENDING = "Pending";+export const NAME = "Name";+export const EMAIL = "Email";+export const SAVE = "Save";+export const ACTIVE = "Active";+export const STATUS = "Status";++// Organisation Errors+export const NOT_ORGANISATION_MEMBER = "You are not a member of this organisation";+export const ORGANISATION_NOT_FOUND = "Organisation not found";+export const ORGANISATION_NOTHING_TO_UPDATE = "Nothing to update";+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 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";+export const ONLY_CREATOR_CAN_REMOVE_MEMBERS = "Only the organisation creator can remove other members";+export const ONLY_ADMIN_CAN_REMOVE_MEMBERS = "Only organisation admins or owner can remove members";+export const INSUFFICIENT_PERMISSIONS = "You don't have permission to perform this action";+export const ONLY_ADMIN_CAN_INVITE = "Only organisation admins or owner can invite new members";+export const ONLY_ADMIN_CAN_CANCEL_INVITATION = "Only organisation admins or owner can cancel invitations";+export const ONLY_ADMIN_CAN_UPDATE_ORGANISATION = "Only organisation admins or owner can update organisation settings";+export const CANNOT_REMOVE_ADMIN_OR_OWNER = "Only the owner can remove admins or other owners";+export const CANNOT_LEAVE_WITH_MEMBERS = "Cannot leave organisation while other members exist. Transfer ownership or remove other members first.";+export const CREATOR_CANNOT_LEAVE_ALONE = "Cannot leave organisation as the sole member. Delete the organisation instead.";+export const ONLY_ADMIN_OR_OWNER_CAN_UPDATE_ROLES = "Only organisation admins or owner can update member roles";+export const CANNOT_CHANGE_OWNER_ROLE = "Cannot change the owner's role";+export const CANNOT_CHANGE_ADMIN_ROLE = "Only the owner can change admin roles";+export const INVALID_MEMBER_ROLE = "Invalid role. Must be 'member' or 'admin'";++// Organisation Invitations+export const PENDING_INVITATIONS = "Pending Invitations";+export const PENDING_INVITES = "Pending Invites";+export const PENDING_INVITES_DESCRIPTION = "Invitations sent but not yet accepted";+export const PENDING_INVITATIONS_DESCRIPTION = "You have been invited to join the following organisations";+export const PENDING_INVITATIONS_ONBOARDING_DESCRIPTION = "You've been invited to join the following organisations";+export const INVITATION_ACCEPTED = "Joined organisation successfully";+export const INVITATION_DECLINED = "Invitation declined";+export const INVITATION_CANCELLED = "Invitation cancelled";+export const INVITATION_ACCEPT_FAILED = "Failed to accept invitation";+export const INVITATION_DECLINE_FAILED = "Failed to decline invitation";+export const INVITATION_CANCEL_FAILED = "Failed to cancel invitation";+export const INVITED = "Invited";++// Onboarding+export const ONBOARDING_WELCOME = "Welcome to OpenLIT";+export const ONBOARDING_SUBTITLE = "Let's get you set up with an organisation";+export const ONBOARDING_CREATE_DESCRIPTION = "Create a new organisation to get started";+export const ONBOARDING_SKIP = "Skip for now (create a Personal organisation)";+export const PERSONAL_ORGANISATION = "Personal";\ No newline at end of filediff --git a/src/client/src/constants/route.ts b/src/client/src/constants/route.tsindex 0bc8b8ac..4cf615ec 100644--- a/src/client/src/constants/route.ts+++ b/src/client/src/constants/route.ts@@ -1,4 +1,4 @@-export const DEFAULT_LOGGED_IN_ROUTE = "/getting-started";+export const DEFAULT_LOGGED_IN_ROUTE = "/home";export const ALLOWED_OPENLIT_ROUTES_WITHOUT_TOKEN = ["/api/prompt/get-compiled","/api/vault/get-secrets",@@ -6,6 +6,22 @@ export const ALLOWED_OPENLIT_ROUTES_WITHOUT_TOKEN = [export const CRON_JOB_ROUTES = ["/api/evaluation/auto"];+// Non-API routes that are accessible without completing onboarding+export const ONBOARDING_WHITELIST_ROUTES = ["/onboarding"];++// API routes that are accessible without completing onboarding.+// Prefix entries must include a trailing slash to avoid overmatching sibling routes.+export const ONBOARDING_WHITELIST_API_ROUTES = {+ exact: {+ GET: ["/api/organisation", "/api/organisation/invitation", "/api/user/profile", "/api/auth/session"],+ POST: ["/api/organisation", "/api/user/complete-onboarding", "/api/auth/session"],+ },+ prefix: {+ POST: ["/api/organisation/current/", "/api/organisation/invitation/"],+ DELETE: ["/api/organisation/invitation/"],+ },+} as const;+// Route format is methodtype: routepathregex[]export const RESTRICTED_DEMO_ACCOUNT_ROUTES: Record<string, string[]> = {POST: ["/api/db-config", "/api/user/profile"],diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsxindex d770cc74..516cc415 100644--- a/src/client/src/constants/sidebar.tsx+++ b/src/client/src/constants/sidebar.tsx@@ -13,10 +13,22 @@ import {} 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";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",diff --git a/src/client/src/helpers/client/organisation.ts b/src/client/src/helpers/client/organisation.tsnew file mode 100644index 00000000..e3c0f45e--- /dev/null+++ b/src/client/src/helpers/client/organisation.ts@@ -0,0 +1,392 @@+import { useRootStore } from "@/store";+import { deleteData, getData, postData } from "@/utils/api";+import asaw from "@/utils/asaw";+import { toast } from "sonner";+import { fetchDatabaseConfigList, pingActiveDatabaseConfig } from "./database-config";+import { OrganisationWithMeta } from "@/types/store/organisation";+import getMessage from "@/constants/messages";+import { CLIENT_EVENTS } from "@/constants/events";+import posthog from "posthog-js";++export const fetchOrganisationList = async () => {+ useRootStore.getState().organisation.setIsLoading(true);+ const [err, data] = await asaw(+ getData({+ url: "/api/organisation",+ method: "GET",+ })+ );++ if (err) {+ useRootStore.getState().organisation.setIsLoading(false);+ return;+ }++ useRootStore.getState().organisation.setList(data || []);+};++export const fetchPendingInvitations = async () => {+ const [err, data] = await asaw(+ getData({+ url: "/api/organisation/invitation",+ method: "GET",+ })+ );++ if (!err) {+ useRootStore.getState().organisation.setPendingInvitations(data || []);+ }+};++export const changeActiveOrganisation = async (+ organisationId: string,+ successCb?: () => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ postData({+ url: `/api/organisation/current/${organisationId}`,+ data: {},+ })+ );++ if (err || data?.err) {+ toast.error(err || data?.err || messages.ORGANISATION_SWITCH_FAILED, {+ id: "organisation-switch",+ });+ return;+ }++ // Update the current organisation in store+ const list = useRootStore.getState().organisation.list || [];+ const newCurrent = list.find((org) => org.id === organisationId);+ if (newCurrent) {+ useRootStore.getState().organisation.setCurrent(newCurrent);+ }++ toast.success(messages.ORGANISATION_SWITCHED, {+ id: "organisation-switch",+ });++ // Refetch database configs for the new organisation+ await fetchDatabaseConfigList(() => {});+ await pingActiveDatabaseConfig();++ successCb?.();+};++export const createOrganisation = async (+ name: string,+ successCb?: (org: OrganisationWithMeta) => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ postData({+ url: "/api/organisation",+ data: { name },+ })+ );++ if (err || data?.err) {+ toast.error(err || data?.err || messages.ORGANISATION_CREATE_FAILED, {+ id: "organisation-create",+ });+ return null;+ }++ toast.success(messages.ORGANISATION_CREATED, {+ id: "organisation-create",+ });++ // Track event+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_CREATED);++ // Refetch organisation list+ await fetchOrganisationList();++ const newOrg = useRootStore+ .getState()+ .organisation.list?.find((org) => org.id === data.id);+ if (newOrg) {+ successCb?.(newOrg);+ }++ return data;+};++export const updateOrganisation = async (+ id: string,+ name: string,+ successCb?: () => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ getData({+ url: `/api/organisation/${id}`,+ method: "PUT",+ data: { name },+ })+ );++ if (err || data?.err) {+ toast.error(err || data?.err || messages.ORGANISATION_UPDATE_FAILED, {+ id: "organisation-update",+ });+ return;+ }++ toast.success(messages.ORGANISATION_UPDATED, {+ id: "organisation-update",+ });++ // Track event+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_UPDATED);++ // Refetch organisation list+ await fetchOrganisationList();+ successCb?.();+};++export const deleteOrganisation = async (+ id: string,+ successCb?: () => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ deleteData({+ url: `/api/organisation/${id}`,+ })+ );++ if (err || data?.err) {+ toast.error(err || data?.err || messages.ORGANISATION_DELETE_FAILED, {+ id: "organisation-delete",+ });+ return;+ }++ toast.success(messages.ORGANISATION_DELETED, {+ id: "organisation-delete",+ });++ // Track event+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_DELETED);++ // Refetch organisation list+ await fetchOrganisationList();+ successCb?.();+};++export const inviteToOrganisation = async (+ organisationId: string,+ emails: string[],+ successCb?: () => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ postData({+ url: `/api/organisation/${organisationId}/invite`,+ data: { emails },+ })+ );++ if (err) {+ toast.error(err || messages.INVITATION_FAILED, {+ id: "organisation-invite",+ });+ return;+ }++ const results = data as { email: string; error?: string; result?: unknown }[];+ const successCount = results.filter((r) => !r.error).length;+ const failCount = results.filter((r) => r.error).length;++ if (failCount > 0 && successCount > 0) {+ const firstError = results.find((r) => r.error)?.error;+ toast.warning(+ firstError ||+ messages.INVITATIONS_PARTIAL_SUCCESS+ .replace("{success}", String(successCount))+ .replace("{fail}", String(failCount)),+ {+ id: "organisation-invite",+ }+ );+ // Track partial success+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_MEMBER_INVITED, {+ success_count: successCount,+ fail_count: failCount,+ status: "partial"+ });+ } else if (failCount > 0) {+ const firstError = results.find((r) => r.error)?.error;+ toast.error(firstError || messages.INVITATION_FAILED, {+ id: "organisation-invite",+ });+ return; // Don't call successCb when all invitations failed+ } else {+ toast.success(messages.INVITATIONS_SENT, {+ id: "organisation-invite",+ });+ // Track success+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_MEMBER_INVITED, {+ count: successCount,+ status: "success"+ });+ }++ successCb?.();+};++export const acceptInvitation = async (+ invitationId: string,+ successCb?: () => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ postData({+ url: `/api/organisation/invitation/${invitationId}`,+ data: {},+ })+ );++ if (err || data?.err) {+ toast.error(err || data?.err || messages.INVITATION_ACCEPT_FAILED, {+ id: "organisation-invitation",+ });+ return;+ }++ toast.success(messages.INVITATION_ACCEPTED, {+ id: "organisation-invitation",+ });++ // Track event+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_INVITATION_ACCEPTED);++ // Refetch organisations and invitations+ await fetchOrganisationList();+ await fetchPendingInvitations();+ successCb?.();+};++export const declineInvitation = async (+ invitationId: string,+ successCb?: () => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ deleteData({+ url: `/api/organisation/invitation/${invitationId}`,+ })+ );++ if (err || data?.err) {+ toast.error(err || data?.err || messages.INVITATION_DECLINE_FAILED, {+ id: "organisation-invitation",+ });+ return;+ }++ toast.success(messages.INVITATION_DECLINED, {+ id: "organisation-invitation",+ });++ // Track event+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_INVITATION_DECLINED);++ // Refetch invitations+ await fetchPendingInvitations();+ successCb?.();+};++export const removeOrganisationMember = async (+ organisationId: string,+ userId: string,+ successCb?: () => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ deleteData({+ url: `/api/organisation/${organisationId}/members/${userId}`,+ })+ );++ if (err || data?.err) {+ toast.error(err || data?.err || messages.SOME_ERROR_OCCURRED, {+ id: "organisation-member",+ });+ return;+ }++ toast.success(messages.MEMBER_REMOVED, {+ id: "organisation-member",+ });++ // Track event+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_MEMBER_REMOVED);++ successCb?.();+};++export const cancelOrganisationInvitation = async (+ invitationId: string,+ successCb?: () => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ deleteData({+ url: `/api/organisation/invitation/${invitationId}?cancel=true`,+ })+ );++ if (err || data?.err) {+ toast.error(err || data?.err || messages.INVITATION_CANCEL_FAILED, {+ id: "organisation-invitation-cancel",+ });+ return;+ }++ toast.success(messages.INVITATION_CANCELLED, {+ id: "organisation-invitation-cancel",+ });++ // Track event+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_INVITATION_CANCELLED);++ successCb?.();+};++export const updateMemberRole = async (+ organisationId: string,+ userId: string,+ role: string,+ successCb?: () => void+) => {+ const messages = getMessage();+ const [err, data] = await asaw(+ getData({+ url: `/api/organisation/${organisationId}/members/${userId}`,+ method: "PATCH",+ data: { role },+ })+ );++ if (err || data?.err) {+ toast.error(err || data?.err || messages.MEMBER_ROLE_UPDATE_FAILED, {+ id: "organisation-member-role",+ });+ return;+ }++ toast.success(messages.MEMBER_ROLE_UPDATED, {+ id: "organisation-member-role",+ });++ // Track event+ posthog?.capture(CLIENT_EVENTS.ORGANISATION_MEMBER_ROLE_UPDATED, {+ new_role: role+ });++ successCb?.();+};diff --git a/src/client/src/lib/db-config.ts b/src/client/src/lib/db-config.tsindex db8edfef..8a8993ea 100644--- a/src/client/src/lib/db-config.ts+++ b/src/client/src/lib/db-config.ts@@ -6,17 +6,56 @@ import migrations from "@/clickhouse/migrations";import getMessage from "@/constants/messages";import { throwIfError } from "@/utils/error";import { consoleLog } from "@/utils/log";+import { getCurrentOrganisation } from "./organisation";export const getDBConfigByUser = async (currentOnly?: boolean) => {const user = await getCurrentUser();if (!user) throw new Error(getMessage().UNAUTHORIZED_USER);+ // Get current organisation+ const currentOrg = await getCurrentOrganisation();++ // 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+ // or new orphaned configs were created.+ if (currentOrg?.id) {+ const userOrphanedLinks = await prisma.databaseConfigUser.findMany({+ where: {+ userId: user.id,+ databaseConfig: {+ organisationId: null,+ },+ },+ select: { databaseConfigId: true },+ });++ if (userOrphanedLinks.length > 0) {+ const orphanedConfigIds = userOrphanedLinks.map(+ (link) => link.databaseConfigId+ );++ await prisma.databaseConfig.updateMany({+ where: { id: { in: orphanedConfigIds } },+ data: { organisationId: currentOrg.id },+ });++ consoleLog(+ `Auto-migrated ${orphanedConfigIds.length} orphaned configs for user ${user.id} to org ${currentOrg.id}`+ );+ }+ }+if (currentOnly) {const dbConfig = await prisma.databaseConfigUser.findFirst({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)+ databaseConfig: {+ organisationId: currentOrg?.id ?? null,+ },},select: {databaseConfig: true,@@ -29,6 +68,11 @@ 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)+ databaseConfig: {+ organisationId: currentOrg?.id ?? null,+ },},select: {databaseConfigId: true,@@ -82,9 +126,13 @@ export const upsertDBConfig = async (throwIfError(!user, getMessage().UNAUTHORIZED_USER);- const existingDBName = await prisma.databaseConfig.findUnique({+ // Get current organisation+ const currentOrg = await getCurrentOrganisation();++ const existingDBName = await prisma.databaseConfig.findFirst({where: {name: dbConfig.name,+ organisationId: currentOrg?.id || null,NOT: {id,},@@ -93,26 +141,85 @@ export const upsertDBConfig = async (if (existingDBName?.id) throw new Error("DB config Name already exists");- const whereObject: any = {};- if (id) whereObject.id = id;- else whereObject.name = dbConfig.name;-if (id) {await checkPermissionForDbAction(user!.id, id, "EDIT");}- const [err, createddbConfig] = await asaw(- prisma.databaseConfig.upsert({- where: whereObject,- create: {- ...(dbConfig as any),- createdByUserId: user!.id,+ let createddbConfig: DatabaseConfig;++ // When updating by id, use upsert with id+ if (id) {+ const whereObject = { id };+ const [err, result] = await asaw(+ prisma.databaseConfig.upsert({+ where: whereObject,+ create: {+ ...(dbConfig as any),+ createdByUserId: user!.id,+ organisationId: currentOrg?.id,+ },+ update: {+ ...dbConfig,+ },+ })+ );+ if (err) throw err;+ createddbConfig = result;+ }+ // When creating with an organisation, use compound unique constraint+ else if (currentOrg?.id) {+ const whereObject = {+ name_organisationId: {+ name: dbConfig.name,+ organisationId: currentOrg.id,},- update: {- ...dbConfig,+ };+ const [err, result] = await asaw(+ prisma.databaseConfig.upsert({+ where: whereObject,+ create: {+ ...(dbConfig as any),+ createdByUserId: user!.id,+ organisationId: currentOrg.id,+ },+ update: {+ ...dbConfig,+ },+ })+ );+ if (err) throw err;+ createddbConfig = result;+ }+ // When creating without organisation (null organisationId),+ // 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,},- })- );+ });++ if (existing) {+ // Update existing config+ createddbConfig = await prisma.databaseConfig.update({+ where: { id: existing.id },+ data: {+ ...dbConfig,+ },+ });+ } else {+ // Create new config+ createddbConfig = await prisma.databaseConfig.create({+ data: {+ ...(dbConfig as any),+ createdByUserId: user!.id,+ organisationId: null,+ },+ });+ }+ }if (!id) {await addDatabaseConfigUserEntry(user!.id, createddbConfig.id, {@@ -223,10 +330,13 @@ export async function shareDBConfig({canShare: false,},}) => {+ // Normalize email to lowercase for case-insensitive comparison+ const normalizedEmail = email.toLowerCase().trim();+const [, user] = await asaw(prisma.user.findUnique({where: {- email,+ email: normalizedEmail,},}));@@ -246,12 +356,12 @@ export async function shareDBConfig({return [, { success: true }];}- return [`Already shared to ${email}`, { success: false }];+ return [`Already shared to ${normalizedEmail}`, { success: false }];} else {const [createErr] = await asaw(prisma.databaseConfigInvitedUser.create({data: {- email,+ email: normalizedEmail,databaseConfigId: id,canEdit: dbUserConfig.canEdit && permissions.canEdit,canDelete: dbUserConfig.canDelete && permissions.canDelete,@@ -342,16 +452,28 @@ async function addDatabaseConfigUserEntry(canShare: boolean;}) {- const ifFirstDBConfigCreated = await prisma.databaseConfigUser.count({+ // Get the database config to find its organisation+ const dbConfig = await prisma.databaseConfig.findUnique({+ where: { id: databaseConfigId },+ select: { organisationId: true },+ });++ // Check if user has any current database config in the SAME organisation+ const existingCurrentConfigInOrg = await prisma.databaseConfigUser.findFirst({where: {userId: userId,+ isCurrent: true,+ databaseConfig: {+ organisationId: dbConfig?.organisationId || null,+ },},});+await prisma.databaseConfigUser.create({data: {userId,databaseConfigId,- isCurrent: !ifFirstDBConfigCreated,+ isCurrent: !existingCurrentConfigInOrg,...permissions,},});diff --git a/src/client/src/lib/organisation.ts b/src/client/src/lib/organisation.tsnew file mode 100644index 00000000..492e407c--- /dev/null+++ b/src/client/src/lib/organisation.ts@@ -0,0 +1,1081 @@+import prisma from "./prisma";+import { getCurrentUser } from "./session";+import getMessage from "@/constants/messages";+import { throwIfError } from "@/utils/error";++/**+ * Generate a URL-safe slug from a name+ */+function generateOrganisationSlug(name: string): string {+ const baseSlug = name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-|-$/g, "");++ // Add a random suffix for uniqueness+ const randomSuffix = Math.random().toString(36).substring(2, 8);+ return `${baseSlug}-${randomSuffix}`;+}++/**+ * Generate a unique organisation slug with retry logic+ */+async function generateUniqueOrganisationSlug(+ name: string,+ maxRetries: number = 10+): Promise<string> {+ for (let attempt = 0; attempt < maxRetries; attempt++) {+ const slug = generateOrganisationSlug(name);++ // Check if slug already exists+ const existing = await prisma.organisation.findUnique({+ where: { slug },+ select: { id: true },+ });++ if (!existing) {+ return slug;+ }+ }++ // If we've exhausted all retries, throw a meaningful error+ throw new Error(+ "Unable to generate a unique organisation slug. Please try again or use a different name."+ );+}++/**+ * Check if a user has admin or owner role in an organisation+ */+async function hasAdminOrOwnerRole(+ organisationId: string,+ userId: string+): Promise<boolean> {+ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId,+ userId,+ },+ },+ select: { role: true },+ });++ if (!membership) return false;++ // Owner or admin have elevated permissions+ return membership.role === "owner" || membership.role === "admin";+}++/**+ * Get a user's role in an organisation+ */+async function getUserRoleInOrganisation(+ organisationId: string,+ userId: string+): Promise<string | null> {+ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId,+ userId,+ },+ },+ select: { role: true },+ });++ return membership?.role || null;+}++/**+ * Create a new organisation+ */+export async function createOrganisation(name: string) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ const slug = await generateUniqueOrganisationSlug(name);++ const organisation = await prisma.organisation.create({+ data: {+ name,+ slug,+ createdByUserId: user!.id,+ },+ });++ // Add creator as a member with owner role+ await prisma.organisationUser.create({+ data: {+ organisationId: organisation.id,+ userId: user!.id,+ role: "owner",+ isCurrent: false, // Don't auto-switch to new org+ },+ });++ // Migrate orphaned configs and shared users to the new org+ await migrateUserConfigsToOrganisation(organisation.id, user!.id);++ return organisation;+}++/**+ * Get all organisations for the current user+ */+export async function getOrganisationsByUser() {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ const orgUsers = await prisma.organisationUser.findMany({+ where: {+ userId: user!.id,+ },+ include: {+ organisation: {+ include: {+ _count: {+ select: { members: true },+ },+ },+ },+ },+ orderBy: {+ organisation: {+ createdAt: "asc",+ },+ },+ });++ return orgUsers.map((orgUser) => ({+ id: orgUser.organisation.id,+ name: orgUser.organisation.name,+ slug: orgUser.organisation.slug,+ isCurrent: orgUser.isCurrent,+ memberCount: orgUser.organisation._count.members,+ createdByUserId: orgUser.organisation.createdByUserId,+ }));+}++/**+ * Get the current active organisation for a user+ */+export async function getCurrentOrganisation() {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ const orgUser = await prisma.organisationUser.findFirst({+ where: {+ userId: user!.id,+ isCurrent: true,+ },+ include: {+ organisation: {+ include: {+ _count: {+ select: { members: true },+ },+ },+ },+ },+ });++ if (!orgUser) {+ return null;+ }++ return {+ id: orgUser.organisation.id,+ name: orgUser.organisation.name,+ slug: orgUser.organisation.slug,+ isCurrent: true,+ memberCount: orgUser.organisation._count.members,+ createdByUserId: orgUser.organisation.createdByUserId,+ };+}++/**+ * Set the current organisation for a user+ */+export async function setCurrentOrganisation(organisationId: string) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ // Verify user is a member of the organisation+ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId,+ userId: user!.id,+ },+ },+ });++ throwIfError(!membership, getMessage().NOT_ORGANISATION_MEMBER);++ // 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+ await prisma.$transaction([+ // Unset all current orgs for this user+ prisma.organisationUser.updateMany({+ where: {+ userId: user!.id,+ isCurrent: true,+ },+ data: {+ isCurrent: false,+ },+ }),+ // Set the new current org+ prisma.organisationUser.update({+ where: {+ organisationId_userId: {+ organisationId,+ userId: user!.id,+ },+ },+ data: {+ isCurrent: true,+ },+ }),+ ]);++ return { success: true };+}++/**+ * Update organisation details+ */+export async function updateOrganisation(+ id: string,+ data: { name?: string }+) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ // Verify user has admin or owner role+ const hasPermission = await hasAdminOrOwnerRole(id, user!.id);+ throwIfError(!hasPermission, getMessage().ONLY_ADMIN_CAN_UPDATE_ORGANISATION);++ const updateData: { name?: string } = {};+ if (data.name) {+ updateData.name = data.name;+ }++ if (Object.keys(updateData).length === 0) {+ throw new Error(getMessage().ORGANISATION_NOTHING_TO_UPDATE);+ }++ return await prisma.organisation.update({+ where: { id },+ data: updateData,+ });+}++/**+ * Delete an organisation (only if creator and sole member)+ */+export async function deleteOrganisation(id: string) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ const organisation = await prisma.organisation.findUnique({+ where: { id },+ include: {+ _count: {+ select: { members: true },+ },+ },+ });++ throwIfError(!organisation, getMessage().ORGANISATION_NOT_FOUND);+ throwIfError(+ organisation!.createdByUserId !== user!.id,+ getMessage().ORGANISATION_ONLY_CREATOR_CAN_DELETE+ );+ throwIfError(+ organisation!._count.members > 1,+ getMessage().ORGANISATION_CANNOT_DELETE_WITH_MEMBERS+ );++ // Check if this is the user's current organisation before deletion+ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId: id,+ userId: user!.id,+ },+ },+ });++ const wasCurrentOrg = membership?.isCurrent;++ // Delete the organisation (cascade will handle members)+ await prisma.organisation.delete({+ where: { id },+ });++ // If this was the user's current org, set another org as current+ if (wasCurrentOrg) {+ const remainingOrgs = await prisma.organisationUser.findFirst({+ where: {+ userId: user!.id,+ },+ orderBy: {+ createdAt: "asc", // Set the oldest org as current+ },+ });++ if (remainingOrgs) {+ await prisma.organisationUser.update({+ where: {+ id: remainingOrgs.id,+ },+ data: {+ isCurrent: true,+ },+ });+ }+ }++ return { success: true };+}++/**+ * Invite a user to an organisation+ */+export async function inviteUserToOrganisation(+ organisationId: string,+ email: string+) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ // Verify inviter has admin or owner role+ const hasPermission = await hasAdminOrOwnerRole(organisationId, user!.id);+ throwIfError(!hasPermission, getMessage().ONLY_ADMIN_CAN_INVITE);++ // Validate and normalize email+ const normalizedEmail = email.toLowerCase().trim();++ // Validate email is not empty+ if (!normalizedEmail) {+ throw new Error("Email cannot be empty");+ }++ // Validate email format - using a safer regex pattern that avoids ReDoS+ // This pattern is more restrictive but safe from catastrophic backtracking+ const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;+ if (!EMAIL_REGEX.test(normalizedEmail)) {+ throw new Error("Invalid email format");+ }++ // Check if user already exists+ const existingUser = await prisma.user.findUnique({+ where: { email: normalizedEmail },+ });++ if (existingUser) {+ // Check if already a member+ const existingMembership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId,+ userId: existingUser.id,+ },+ },+ });++ if (existingMembership) {+ throw new Error(getMessage().USER_ALREADY_ORGANISATION_MEMBER);+ }++ // Add them directly as a member+ await prisma.organisationUser.create({+ data: {+ organisationId,+ userId: existingUser.id,+ role: "member",+ isCurrent: false,+ },+ });++ // Share all organisation database configs with the new member+ await shareOrganisationDatabaseConfigs(organisationId, existingUser.id);++ return { added: true, invited: false };+ }++ // Check if already invited+ const existingInvite = await prisma.organisationInvitedUser.findUnique({+ where: {+ organisationId_email: {+ organisationId,+ email: normalizedEmail,+ },+ },+ });++ if (existingInvite) {+ throw new Error(getMessage().USER_ALREADY_INVITED);+ }++ // Create invitation+ await prisma.organisationInvitedUser.create({+ data: {+ organisationId,+ email: normalizedEmail,+ invitedByUserId: user!.id,+ },+ });++ return { added: false, invited: true };+}++/**+ * Get pending invitations for a user+ */+export async function getPendingInvitationsForUser() {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ // Normalize email to lowercase for case-insensitive comparison+ const normalizedEmail = user!.email.toLowerCase().trim();++ const invitations = await prisma.organisationInvitedUser.findMany({+ where: {+ email: normalizedEmail,+ },+ include: {+ organisation: true,+ },+ });++ return invitations.map((invite) => ({+ id: invite.id,+ organisationId: invite.organisationId,+ organisationName: invite.organisation.name,+ invitedByUserId: invite.invitedByUserId,+ createdAt: invite.createdAt,+ }));+}++/**+ * Accept an invitation+ */+export async function acceptInvitation(invitationId: string) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ const invitation = await prisma.organisationInvitedUser.findUnique({+ where: { id: invitationId },+ });++ throwIfError(!invitation, getMessage().INVITATION_NOT_FOUND);++ // Normalize both emails to lowercase for case-insensitive comparison+ const normalizedInvitationEmail = invitation!.email.toLowerCase().trim();+ const normalizedUserEmail = user!.email.toLowerCase().trim();++ throwIfError(+ normalizedInvitationEmail !== normalizedUserEmail,+ getMessage().INVITATION_NOT_FOR_YOU+ );++ // Create membership+ await prisma.organisationUser.create({+ data: {+ organisationId: invitation!.organisationId,+ userId: user!.id,+ role: "member",+ isCurrent: false,+ },+ });++ // Share all organisation database configs with the new member+ await shareOrganisationDatabaseConfigs(invitation!.organisationId, user!.id);++ // Delete invitation+ await prisma.organisationInvitedUser.delete({+ where: { id: invitationId },+ });++ return { success: true };+}++/**+ * Decline an invitation+ */+export async function declineInvitation(invitationId: string) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ const invitation = await prisma.organisationInvitedUser.findUnique({+ where: { id: invitationId },+ });++ throwIfError(!invitation, getMessage().INVITATION_NOT_FOUND);++ // Normalize both emails to lowercase for case-insensitive comparison+ const normalizedInvitationEmail = invitation!.email.toLowerCase().trim();+ const normalizedUserEmail = user!.email.toLowerCase().trim();++ throwIfError(+ normalizedInvitationEmail !== normalizedUserEmail,+ getMessage().INVITATION_NOT_FOR_YOU+ );++ await prisma.organisationInvitedUser.delete({+ where: { id: invitationId },+ });++ return { success: true };+}++/**+ * Move pending invitations to membership when a user is created+ */+export async function moveInvitationsToMembership(+ email: string,+ userId: string+) {+ // Normalize email to lowercase for case-insensitive comparison+ const normalizedEmail = email.toLowerCase().trim();++ const invitations = await prisma.organisationInvitedUser.findMany({+ where: { email: normalizedEmail },+ });++ for (const invitation of invitations) {+ // Create membership+ await prisma.organisationUser.create({+ data: {+ organisationId: invitation.organisationId,+ userId,+ role: "member",+ isCurrent: false,+ },+ });++ // Share all organisation database configs with the new member+ await shareOrganisationDatabaseConfigs(invitation.organisationId, userId);++ // Delete invitation+ await prisma.organisationInvitedUser.delete({+ where: { id: invitation.id },+ });+ }+}++/**+ * Remove a user from an organisation+ */+export async function removeUserFromOrganisation(+ organisationId: string,+ userId: string+) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ const organisation = await prisma.organisation.findUnique({+ where: { id: organisationId },+ });++ throwIfError(!organisation, getMessage().ORGANISATION_NOT_FOUND);++ // Check if user removing themselves+ const isSelfRemoval = userId === user!.id;++ if (isSelfRemoval) {+ // Creator cannot remove themselves at all+ if (userId === organisation!.createdByUserId) {+ const memberCount = await prisma.organisationUser.count({+ where: { organisationId },+ });+ if (memberCount > 1) {+ throw new Error(getMessage().CANNOT_LEAVE_WITH_MEMBERS);+ } else {+ // memberCount === 1, they are the sole member+ throw new Error(getMessage().CREATOR_CANNOT_LEAVE_ALONE);+ }+ }+ // Regular members and admins can remove themselves+ } else {+ // Removing someone else - need admin or owner permissions+ const currentUserRole = await getUserRoleInOrganisation(+ organisationId,+ user!.id+ );+ throwIfError(+ !currentUserRole,+ getMessage().NOT_ORGANISATION_MEMBER+ );++ const targetUserRole = await getUserRoleInOrganisation(+ organisationId,+ userId+ );++ // Only admins and owners can remove other members+ const hasPermission =+ currentUserRole === "owner" || currentUserRole === "admin";+ throwIfError(+ !hasPermission,+ getMessage().ONLY_ADMIN_CAN_REMOVE_MEMBERS+ );++ // Only owner can remove admins or other owners+ if (+ (targetUserRole === "admin" || targetUserRole === "owner") &&+ currentUserRole !== "owner"+ ) {+ throw new Error(getMessage().CANNOT_REMOVE_ADMIN_OR_OWNER);+ }++ // Owner cannot be removed+ if (userId === organisation!.createdByUserId) {+ throw new Error(getMessage().CANNOT_REMOVE_ADMIN_OR_OWNER);+ }+ }++ // Check if this is the user's current organisation+ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId,+ userId,+ },+ },+ });++ const wasCurrentOrg = membership?.isCurrent;++ // Remove user from all database configs in this organisation+ await prisma.databaseConfigUser.deleteMany({+ where: {+ userId,+ databaseConfig: {+ organisationId,+ },+ },+ });++ // Remove user from organisation+ await prisma.organisationUser.delete({+ where: {+ organisationId_userId: {+ organisationId,+ userId,+ },+ },+ });++ // If this was the user's current org, set another org as current+ if (wasCurrentOrg) {+ const remainingOrgs = await prisma.organisationUser.findFirst({+ where: {+ userId,+ },+ orderBy: {+ createdAt: "asc", // Set the oldest org as current+ },+ });++ if (remainingOrgs) {+ await prisma.organisationUser.update({+ where: {+ id: remainingOrgs.id,+ },+ data: {+ isCurrent: true,+ },+ });+ }+ }++ return { success: true };+}++/**+ * Get members of an organisation+ */+export async function getOrganisationMembers(organisationId: string) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ // Verify user is a member+ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId,+ userId: user!.id,+ },+ },+ });++ throwIfError(!membership, getMessage().NOT_ORGANISATION_MEMBER);++ const members = await prisma.organisationUser.findMany({+ where: { organisationId },+ include: {+ user: {+ select: {+ id: true,+ email: true,+ name: true,+ image: true,+ },+ },+ },+ orderBy: {+ createdAt: "asc",+ },+ });++ const organisation = await prisma.organisation.findUnique({+ where: { id: organisationId },+ });++ return members.map((member) => ({+ id: member.user.id,+ email: member.user.email,+ name: member.user.name,+ image: member.user.image,+ isCreator: member.user.id === organisation!.createdByUserId,+ role: member.user.id === organisation!.createdByUserId ? "owner" : member.role,+ joinedAt: member.createdAt,+ }));+}++/**+ * Update member role in an organisation+ */+export async function updateMemberRole(+ organisationId: string,+ userId: string,+ role: string+) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ const organisation = await prisma.organisation.findUnique({+ where: { id: organisationId },+ });++ throwIfError(!organisation, getMessage().ORGANISATION_NOT_FOUND);++ // Validate role+ throwIfError(+ !["member", "admin"].includes(role),+ getMessage().INVALID_MEMBER_ROLE+ );++ // Cannot change owner's role+ throwIfError(+ userId === organisation!.createdByUserId,+ getMessage().CANNOT_CHANGE_OWNER_ROLE+ );++ // Get current user's role+ const currentUserRole = await getUserRoleInOrganisation(+ organisationId,+ user!.id+ );+ throwIfError(!currentUserRole, getMessage().NOT_ORGANISATION_MEMBER);++ // Get target user's current role+ const targetUserRole = await getUserRoleInOrganisation(+ organisationId,+ userId+ );+ throwIfError(!targetUserRole, getMessage().NOT_ORGANISATION_MEMBER);++ // Only admins and owners can update roles+ const hasPermission =+ currentUserRole === "owner" || currentUserRole === "admin";+ throwIfError(!hasPermission, getMessage().ONLY_ADMIN_OR_OWNER_CAN_UPDATE_ROLES);++ // Only owner can change admin roles (demote admin to member)+ // Admins can promote members to admin+ if (targetUserRole === "admin") {+ throwIfError(+ currentUserRole !== "owner",+ getMessage().CANNOT_CHANGE_ADMIN_ROLE+ );+ }++ await prisma.organisationUser.update({+ where: {+ organisationId_userId: {+ organisationId,+ userId,+ },+ },+ data: {+ role,+ },+ });++ return { success: true };+}++/**+ * Get pending invites for an organisation+ */+export async function getOrganisationPendingInvites(organisationId: string) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ // Verify user is a member+ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId,+ userId: user!.id,+ },+ },+ });++ throwIfError(!membership, getMessage().NOT_ORGANISATION_MEMBER);++ const invites = await prisma.organisationInvitedUser.findMany({+ where: { organisationId },+ orderBy: {+ createdAt: "desc",+ },+ });++ return invites.map((invite) => ({+ id: invite.id,+ email: invite.email,+ invitedAt: invite.createdAt,+ }));+}++/**+ * Cancel an invitation+ */+export async function cancelInvitation(invitationId: string) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ const invitation = await prisma.organisationInvitedUser.findUnique({+ where: { id: invitationId },+ include: { organisation: true },+ });++ throwIfError(!invitation, getMessage().INVITATION_NOT_FOUND);++ // Verify user has admin or owner role+ const hasPermission = await hasAdminOrOwnerRole(+ invitation!.organisationId,+ user!.id+ );+ throwIfError(!hasPermission, getMessage().ONLY_ADMIN_CAN_CANCEL_INVITATION);++ await prisma.organisationInvitedUser.delete({+ where: { id: invitationId },+ });++ return { success: true };+}++/**+ * Get organisation by ID+ */+export async function getOrganisationById(id: string) {+ const user = await getCurrentUser();+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);++ // Verify user is a member+ const membership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId: id,+ userId: user!.id,+ },+ },+ });++ throwIfError(!membership, getMessage().NOT_ORGANISATION_MEMBER);++ const organisation = await prisma.organisation.findUnique({+ where: { id },+ include: {+ _count: {+ select: { members: true },+ },+ },+ });++ if (!organisation) {+ return null;+ }++ return {+ id: organisation.id,+ name: organisation.name,+ slug: organisation.slug,+ isCurrent: membership!.isCurrent,+ memberCount: organisation._count.members,+ createdByUserId: organisation.createdByUserId,+ };+}++/**+ * Migrate a user's orphaned DB configs to an organisation.+ * Also adds users who share those configs as members of the org.+ */+async function migrateUserConfigsToOrganisation(+ organisationId: string,+ userId: string+) {+ // Find all orphaned DB configs the user has access to+ const userConfigLinks = await prisma.databaseConfigUser.findMany({+ where: {+ userId,+ databaseConfig: {+ organisationId: null,+ },+ },+ select: { databaseConfigId: true },+ });++ if (userConfigLinks.length === 0) return;++ const orphanedConfigIds = userConfigLinks.map(+ (link) => link.databaseConfigId+ );++ // Move those configs to the new org+ await prisma.databaseConfig.updateMany({+ where: { id: { in: orphanedConfigIds } },+ data: { organisationId },+ });++ // Find other users who share those configs+ const sharedUserLinks = await prisma.databaseConfigUser.findMany({+ where: {+ databaseConfigId: { in: orphanedConfigIds },+ userId: { not: userId },+ },+ select: { userId: true },+ distinct: ["userId"],+ });++ for (const { userId: sharedUserId } of sharedUserLinks) {+ // Check if already a member+ const existingMembership = await prisma.organisationUser.findUnique({+ where: {+ organisationId_userId: {+ organisationId,+ userId: sharedUserId,+ },+ },+ });++ // Check if the user already has a current org+ const hasCurrentOrg = await prisma.organisationUser.findFirst({+ where: { userId: sharedUserId, isCurrent: true },+ });++ if (!existingMembership) {+ await prisma.organisationUser.create({+ data: {+ organisationId,+ userId: sharedUserId,+ role: "member",+ isCurrent: !hasCurrentOrg,+ },+ });+ } else if (!hasCurrentOrg) {+ // Existing membership but no current org — fix it+ await prisma.organisationUser.update({+ where: {+ organisationId_userId: {+ organisationId,+ userId: sharedUserId,+ },+ },+ data: { isCurrent: true },+ });+ }++ // Share org DB configs with the new member+ await shareOrganisationDatabaseConfigs(organisationId, sharedUserId);++ // Mark as onboarded+ await prisma.user.update({+ where: { id: sharedUserId },+ data: { hasCompletedOnboarding: true },+ });+ }+}++/**+ * Share all database configs in an organisation with a user+ */+async function shareOrganisationDatabaseConfigs(+ organisationId: string,+ userId: string+) {+ // Get all database configs for this organisation+ const databaseConfigs = await prisma.databaseConfig.findMany({+ where: { organisationId },+ orderBy: {+ createdAt: "asc",+ },+ });++ if (databaseConfigs.length === 0) return;++ // Check if user has any current database config in THIS organisation+ const existingCurrentConfig = await prisma.databaseConfigUser.findFirst({+ where: {+ userId,+ isCurrent: true,+ databaseConfig: {+ organisationId,+ },+ },+ });+ let hasAssignedCurrentToNewShare = false;++ // Add user to each database config with view permissions+ for (let i = 0; i < databaseConfigs.length; i++) {+ const config = databaseConfigs[i];++ // Check if user already has access+ const existingAccess = await prisma.databaseConfigUser.findUnique({+ where: {+ databaseConfigId_userId: {+ databaseConfigId: config.id,+ userId,+ },+ },+ });++ // Only add if they don't already have access+ if (!existingAccess) {+ // Set the first config actually shared as current if user has no current config+ const shouldBeCurrent =+ !existingCurrentConfig && !hasAssignedCurrentToNewShare;++ await prisma.databaseConfigUser.create({+ data: {+ databaseConfigId: config.id,+ userId,+ isCurrent: shouldBeCurrent,+ canEdit: false,+ canShare: false,+ canDelete: false,+ },+ });++ if (shouldBeCurrent) {+ hasAssignedCurrentToNewShare = true;+ }+ }+ }+}diff --git a/src/client/src/lib/user.ts b/src/client/src/lib/user.tsindex 2f15c699..5c2d8634 100644--- a/src/client/src/lib/user.ts+++ b/src/client/src/lib/user.ts@@ -4,6 +4,7 @@ import asaw from "@/utils/asaw";import { getCurrentUser } from "./session";import { User } from "@prisma/client";import { moveSharedDBConfigToDBUser } from "./db-config";+import { moveInvitationsToMembership } from "./organisation";import getMessage from "@/constants/messages";function exclude<User extends Record<string, unknown>, K extends keyof User>(@@ -25,9 +26,13 @@ export const getUserByEmail = async ({selectPassword?: boolean;}) => {if (!email) throw new Error("No email Provided");++ // Normalize email to lowercase for case-insensitive comparison+ const normalizedEmail = email.toLowerCase().trim();+const user = await prisma.user.findUnique({where: {- email,+ email: normalizedEmail,},});@@ -65,20 +70,25 @@ export const createNewUser = async (},options?: { selectPassword?: boolean }) => {- const [, existingUser] = await asaw(getUserByEmail({ email }));+ // Normalize email to lowercase for case-insensitive comparison+ const normalizedEmail = email.toLowerCase().trim();++ const [, existingUser] = await asaw(getUserByEmail({ email: normalizedEmail }));if (existingUser) throw new Error("User already exists! Please signin!");const hashedPassword = getHashedPassword(password);let createdUser = await prisma.user.create({data: {- email,+ email: normalizedEmail,password: hashedPassword,+ hasCompletedOnboarding: false,},});if (createdUser?.id) {- await moveSharedDBConfigToDBUser(email, createdUser.id);+ await moveSharedDBConfigToDBUser(normalizedEmail, createdUser.id);+ await moveInvitationsToMembership(normalizedEmail, createdUser.id);return exclude(createdUser, options?.selectPassword ? [] : undefined);}diff --git a/src/client/src/middleware.ts b/src/client/src/middleware.tsindex f2edab78..ed258138 100644--- a/src/client/src/middleware.ts+++ b/src/client/src/middleware.ts@@ -20,11 +20,12 @@ export const config = {"/exceptions","/prompt-hub","/vault",- "/settings",+ "/settings/:path*","/telemetry-enabled","/home","/dashboards/:path*","/d/:path*",- "/fleet-hub"+ "/fleet-hub",+ "/onboarding"],};diff --git a/src/client/src/middleware/check-auth.ts b/src/client/src/middleware/check-auth.tsindex 05b07978..a72eaa34 100644--- a/src/client/src/middleware/check-auth.ts+++ b/src/client/src/middleware/check-auth.ts@@ -10,6 +10,8 @@ import {DEFAULT_LOGGED_IN_ROUTE,ALLOWED_OPENLIT_ROUTES_WITHOUT_TOKEN,CRON_JOB_ROUTES,+ ONBOARDING_WHITELIST_ROUTES,+ ONBOARDING_WHITELIST_API_ROUTES,} from "@/constants/route";export default function checkAuth(next: NextMiddleware) {@@ -33,9 +35,38 @@ export default function checkAuth(next: NextMiddleware) {const isAuthPage =pathname.startsWith("/login") || pathname.startsWith("/register");const isApiPage = pathname.startsWith("/api");-+ const method = request.method.toUpperCase();+ const isOnboardingWhitelistedPage = ONBOARDING_WHITELIST_ROUTES.includes(+ pathname+ );+ const exactApiRoutes: readonly string[] =+ method in ONBOARDING_WHITELIST_API_ROUTES.exact+ ? ONBOARDING_WHITELIST_API_ROUTES.exact[+ method as keyof typeof ONBOARDING_WHITELIST_API_ROUTES.exact+ ]+ : [];+ const prefixApiRoutes: readonly string[] =+ method in ONBOARDING_WHITELIST_API_ROUTES.prefix+ ? ONBOARDING_WHITELIST_API_ROUTES.prefix[+ method as keyof typeof ONBOARDING_WHITELIST_API_ROUTES.prefix+ ]+ : [];+ const isOnboardingWhitelistedApi =+ isApiPage &&+ (exactApiRoutes.includes(pathname) ||+ prefixApiRoutes.some((route: string) =>+ pathname.startsWith(route)+ ));+ const isOnboardingWhitelisted =+ isOnboardingWhitelistedPage || isOnboardingWhitelistedApi;if (isAuthPage) {if (isAuth) {+ // Check if user needs onboarding+ if (token.hasCompletedOnboarding === false) {+ return NextResponse.redirect(+ new URL("/onboarding", request.url)+ );+ }return NextResponse.redirect(new URL(DEFAULT_LOGGED_IN_ROUTE, request.url));@@ -52,6 +83,20 @@ export default function checkAuth(next: NextMiddleware) {return NextResponse.next();}}+ // Enforce onboarding restrictions for authenticated API calls.+ // Only explicitly whitelisted API routes should work before onboarding.+ // Routes that are allowed without token should also bypass onboarding check.+ if (+ isAuth &&+ token.hasCompletedOnboarding === false &&+ !isOnboardingWhitelisted &&+ !isAllowedRequestWithoutToken+ ) {+ return NextResponse.json(+ { error: "Please complete onboarding first" },+ { status: 403 }+ );+ }return NextResponse.next();}}@@ -67,6 +112,17 @@ export default function checkAuth(next: NextMiddleware) {);}+ // Check if authenticated user needs onboarding+ if (+ isAuth &&+ token.hasCompletedOnboarding === false &&+ !isOnboardingWhitelisted+ ) {+ return NextResponse.redirect(+ new URL("/onboarding", request.url)+ );+ }+return NextResponse.next();} catch (error) {// If there's an error getting the token (e.g., invalid/corrupted token),diff --git a/src/client/src/selectors/organisation.ts b/src/client/src/selectors/organisation.tsnew file mode 100644index 00000000..fa719759--- /dev/null+++ b/src/client/src/selectors/organisation.ts@@ -0,0 +1,16 @@+import { RootStore } from "@/types/store/root";++export const getOrganisationList = (state: RootStore) =>+ state.organisation.list;++export const getCurrentOrganisation = (state: RootStore) =>+ state.organisation.current;++export const getOrganisationPendingInvitations = (state: RootStore) =>+ state.organisation.pendingInvitations;++export const getOrganisationIsLoading = (state: RootStore) =>+ state.organisation.isLoading;++export const getPendingInvitationsCount = (state: RootStore) =>+ state.organisation.pendingInvitations.length;diff --git a/src/client/src/selectors/user.ts b/src/client/src/selectors/user.tsindex 9809823c..03cadb0e 100644--- a/src/client/src/selectors/user.ts+++ b/src/client/src/selectors/user.ts@@ -7,3 +7,5 @@ export const getIsUserFetched = (state: RootStore) => state.user.isFetched;export const setUser = (state: RootStore) => state.user.set;export const resetUser = (state: RootStore) => state.user.reset;++export const getCurrentUserId = (state: RootStore) => state.user.details?.id;diff --git a/src/client/src/store/index.ts b/src/client/src/store/index.tsindex b2cd0527..4ece4353 100644--- a/src/client/src/store/index.ts+++ b/src/client/src/store/index.ts@@ -8,6 +8,7 @@ import { opengroundStoreSlice } from "./openground";import { pageStoreSlice } from "./page";import { RootStore } from "@/types/store/root";import { dashboardStoreSlice } from "./dashboards";+import { organisationStoreSlice } from "./organisation";export const useRootStore = create<RootStore>()(devtools(@@ -18,6 +19,7 @@ export const useRootStore = create<RootStore>()(openground: opengroundStoreSlice,page: pageStoreSlice,dashboards: dashboardStoreSlice,+ organisation: organisationStoreSlice,})));diff --git a/src/client/src/store/organisation.ts b/src/client/src/store/organisation.tsnew file mode 100644index 00000000..08724a4d--- /dev/null+++ b/src/client/src/store/organisation.ts@@ -0,0 +1,51 @@+"use client";+import { OrganisationStore } from "@/types/store/organisation";+import { lens } from "@dhmk/zustand-lens";++const initialState = {+ list: undefined,+ current: undefined,+ pendingInvitations: [],+ isLoading: false,+};++export const organisationStoreSlice: OrganisationStore = lens(+ (setStore, getStore) => ({+ ...initialState,+ setList: (list) =>+ setStore(() => ({+ ...getStore(),+ list,+ current: list.find((org) => org.isCurrent),+ isLoading: false,+ })),+ setCurrent: (org) =>+ setStore(() => {+ const currentList = getStore().list || [];+ const updatedList = currentList.map((item) => ({+ ...item,+ isCurrent: item.id === org?.id,+ }));+ const updatedCurrent = updatedList.find((item) => item.id === org?.id);+ return {+ ...getStore(),+ list: updatedList,+ current: updatedCurrent,+ };+ }),+ setPendingInvitations: (invites) =>+ setStore(() => ({+ ...getStore(),+ pendingInvitations: invites,+ })),+ setIsLoading: (isLoading) =>+ setStore(() => ({+ ...getStore(),+ isLoading,+ })),+ reset: () =>+ setStore(() => ({+ ...initialState,+ })),+ })+);diff --git a/src/client/src/types/store/organisation.ts b/src/client/src/types/store/organisation.tsnew file mode 100644index 00000000..7726329a--- /dev/null+++ b/src/client/src/types/store/organisation.ts@@ -0,0 +1,28 @@+export type OrganisationWithMeta = {+ id: string;+ name: string;+ slug: string;+ isCurrent: boolean;+ memberCount: number;+ createdByUserId: string;+};++export type OrganisationInvitation = {+ id: string;+ organisationId: string;+ organisationName: string;+ invitedByUserId: string;+ createdAt: string;+};++export type OrganisationStore = {+ list?: OrganisationWithMeta[];+ current?: OrganisationWithMeta;+ pendingInvitations: OrganisationInvitation[];+ isLoading: boolean;+ setList: (list: OrganisationWithMeta[]) => void;+ setCurrent: (org?: OrganisationWithMeta) => void;+ setPendingInvitations: (invites: OrganisationInvitation[]) => void;+ setIsLoading: (loading: boolean) => void;+ reset: () => void;+};diff --git a/src/client/src/types/store/root.ts b/src/client/src/types/store/root.tsindex 306a55d5..f741ea78 100644--- a/src/client/src/types/store/root.ts+++ b/src/client/src/types/store/root.ts@@ -4,6 +4,7 @@ import { DatabaseConfigStore } from "@/types/store/database-config";import { OpengroundStore } from "@/types/store/openground";import { PageStore } from "@/types/store/page";import { DashboardStore } from "./dashboards";+import { OrganisationStore } from "./organisation";export type RootStore = {user: UserStore;@@ -12,4 +13,5 @@ export type RootStore = {openground: OpengroundStore;page: PageStore;dashboards: DashboardStore;+ organisation: OrganisationStore;};diff --git a/src/client/src/utils/api.ts b/src/client/src/utils/api.tsindex 8e6b0283..68538217 100644--- a/src/client/src/utils/api.ts+++ b/src/client/src/utils/api.ts@@ -2,10 +2,15 @@ type GET_DATA = {body?: string;method?: "GET" | "POST" | "PUT" | "PATCH";url: string;+ data?: Record<string, unknown>;};-export async function getData({ body, method = "POST", url }: GET_DATA) {- const res = await fetch(url, { body, method });+export async function getData({ body, method = "POST", url, data }: GET_DATA) {+ const res = await fetch(url, {+ body: body || (data ? JSON.stringify(data) : undefined),+ method,+ headers: data ? { "Content-Type": "application/json" } : undefined,+ });if (!res.ok) {// This will activate the closest `error.js` Error Boundaryconst error = await res.json();@@ -15,6 +20,25 @@ export async function getData({ body, method = "POST", url }: GET_DATA) {return res.json();}+type POST_DATA = {+ url: string;+ data: Record<string, unknown>;+};++export async function postData({ url, data }: POST_DATA) {+ const res = await fetch(url, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(data),+ });+ if (!res.ok) {+ const error = await res.json();+ throw new Error(error);+ }++ return res.json();+}+type DELETE_DATA = {url: string;};