diff --git a/data/.dockerignore b/data/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..958b26c9d6ea21bea38f9de590fc01075da016a9
--- /dev/null
+++ b/data/.dockerignore
@@ -0,0 +1,5 @@
+node_modules
+.git
+.gitignore
+*.md
+dist
\ No newline at end of file
diff --git a/data/.nvmrc b/data/.nvmrc
new file mode 100644
index 0000000000000000000000000000000000000000..593cb75bc5c212129bc486a51f13015214a07cd1
--- /dev/null
+++ b/data/.nvmrc
@@ -0,0 +1 @@
+20.16.0
\ No newline at end of file
diff --git a/data/CONTRIBUTING.md b/data/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..0ac5a3581b24e20deb32da6327f09be811191065
--- /dev/null
+++ b/data/CONTRIBUTING.md
@@ -0,0 +1,179 @@
+# Contributing
+
+Hey, thanks for your interest in contributing to Dokploy! We appreciate your help and taking your time to contribute.
+
+Before you start, please first discuss the feature/bug you want to add with the owners and comunity via github issues.
+
+We have a few guidelines to follow when contributing to this project:
+
+- [Commit Convention](#commit-convention)
+- [Setup](#setup)
+- [Development](#development)
+- [Build](#build)
+- [Pull Request](#pull-request)
+
+## Commit Convention
+
+Before you create a Pull Request, please make sure your commit message follows the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification.
+
+### Commit Message Format
+
+```
+[optional scope]:
+
+[optional body]
+
+[optional footer(s)]
+```
+
+#### Type
+
+Must be one of the following:
+
+- **feat**: A new feature
+- **fix**: A bug fix
+- **docs**: Documentation only changes
+- **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
+- **refactor**: A code change that neither fixes a bug nor adds a feature
+- **perf**: A code change that improves performance
+- **test**: Adding missing tests or correcting existing tests
+- **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
+- **ci**: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
+- **chore**: Other changes that don't modify `src` or `test` files
+- **revert**: Reverts a previous commit
+
+Example:
+
+```
+feat: add new feature
+```
+
+## Setup
+
+Before you start, please make the clone based on the `canary` branch, since the `main` branch is the source of truth and should always reflect the latest stable release, also the PRs will be merged to the `canary` branch.
+
+We use Node v20.16.0 and recommend this specific version. If you have nvm installed, you can run `nvm install 20.16.0 && nvm use` in the root directory.
+
+```bash
+git clone https://github.com/dokploy/dokploy.git
+cd dokploy
+pnpm install
+cp apps/dokploy/.env.example apps/dokploy/.env
+```
+
+## Requirements
+
+- [Docker](/GUIDES.md#docker)
+
+### Setup
+
+Run the command that will spin up all the required services and files.
+
+```bash
+pnpm run dokploy:setup
+```
+
+Run this script
+
+```bash
+pnpm run server:script
+```
+
+Now run the development server.
+
+```bash
+pnpm run dokploy:dev
+```
+
+Go to http://localhost:3000 to see the development server
+
+Note: this project uses Biome. If your editor is configured to use another formatter such as Prettier, it's recommended to either change it to use Biome or turn it off.
+
+## Build
+
+```bash
+pnpm run dokploy:build
+```
+
+## Docker
+
+To build the docker image
+
+```bash
+pnpm run docker:build
+```
+
+To push the docker image
+
+```bash
+pnpm run docker:push
+```
+
+## Password Reset
+
+In the case you lost your password, you can reset it using the following command
+
+```bash
+pnpm run reset-password
+```
+
+If you want to test the webhooks on development mode using localtunnel, make sure to install `localtunnel`
+
+```bash
+bunx lt --port 3000
+```
+
+If you run into permission issues of docker run the following command
+
+```bash
+sudo chown -R USERNAME dokploy or sudo chown -R $(whoami) ~/.docker
+```
+
+## Application deploy
+
+In case you want to deploy the application on your machine and you selected nixpacks or buildpacks, you need to install first.
+
+```bash
+# Install Nixpacks
+curl -sSL https://nixpacks.com/install.sh -o install.sh \
+ && chmod +x install.sh \
+ && ./install.sh
+```
+
+```bash
+# Install Railpack
+curl -sSL https://railpack.com/install.sh | sh
+```
+
+```bash
+# Install Buildpacks
+curl -sSL "https://github.com/buildpacks/pack/releases/download/v0.35.0/pack-v0.35.0-linux.tgz" | tar -C /usr/local/bin/ --no-same-owner -xzv pack
+```
+
+## Pull Request
+
+- The `main` branch is the source of truth and should always reflect the latest stable release.
+- Create a new branch for each feature or bug fix.
+- Make sure to add tests for your changes.
+- Make sure to update the documentation for any changes Go to the [docs.dokploy.com](https://docs.dokploy.com) website to see the changes.
+- When creating a pull request, please provide a clear and concise description of the changes made.
+- If you include a video or screenshot, would be awesome so we can see the changes in action.
+- If your pull request fixes an open issue, please reference the issue in the pull request description.
+- Once your pull request is merged, you will be automatically added as a contributor to the project.
+
+Thank you for your contribution!
+
+## Templates
+
+To add a new template, go to `https://github.com/Dokploy/templates` repository and read the README.md file.
+
+### Recommendations
+
+- Use the same name of the folder as the id of the template.
+- The logo should be in the public folder.
+- If you want to show a domain in the UI, please add the `_HOST` suffix at the end of the variable name.
+- Test first on a vps or a server to make sure the template works.
+
+## Docs & Website
+
+To contribute to the Dokploy docs or website, please go to this [repository](https://github.com/Dokploy/website).
diff --git a/data/Dockerfile b/data/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..00043b0c2ac9683234a2141eac3272cb82b11fe0
--- /dev/null
+++ b/data/Dockerfile
@@ -0,0 +1,66 @@
+FROM node:20.9-slim AS base
+ENV PNPM_HOME="/pnpm"
+ENV PATH="$PNPM_HOME:$PATH"
+RUN corepack enable
+
+FROM base AS build
+COPY . /usr/src/app
+WORKDIR /usr/src/app
+
+RUN apt-get update && apt-get install -y python3 make g++ git python3-pip pkg-config libsecret-1-dev && rm -rf /var/lib/apt/lists/*
+
+# Install dependencies
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile
+
+# Deploy only the dokploy app
+
+ENV NODE_ENV=production
+RUN pnpm --filter=@dokploy/server build
+RUN pnpm --filter=./apps/dokploy run build
+
+RUN pnpm --filter=./apps/dokploy --prod deploy /prod/dokploy
+
+RUN cp -R /usr/src/app/apps/dokploy/.next /prod/dokploy/.next
+RUN cp -R /usr/src/app/apps/dokploy/dist /prod/dokploy/dist
+
+FROM base AS dokploy
+WORKDIR /app
+
+# Set production
+ENV NODE_ENV=production
+
+RUN apt-get update && apt-get install -y curl unzip zip apache2-utils iproute2 rsync git-lfs && git lfs install && rm -rf /var/lib/apt/lists/*
+
+# Copy only the necessary files
+COPY --from=build /prod/dokploy/.next ./.next
+COPY --from=build /prod/dokploy/dist ./dist
+COPY --from=build /prod/dokploy/next.config.mjs ./next.config.mjs
+COPY --from=build /prod/dokploy/public ./public
+COPY --from=build /prod/dokploy/package.json ./package.json
+COPY --from=build /prod/dokploy/drizzle ./drizzle
+COPY .env.production ./.env
+COPY --from=build /prod/dokploy/components.json ./components.json
+COPY --from=build /prod/dokploy/node_modules ./node_modules
+
+
+# Install docker
+RUN curl -fsSL https://get.docker.com -o get-docker.sh && sh get-docker.sh && rm get-docker.sh && curl https://rclone.org/install.sh | bash
+
+# Install Nixpacks and tsx
+# | VERBOSE=1 VERSION=1.21.0 bash
+
+ARG NIXPACKS_VERSION=1.39.0
+RUN curl -sSL https://nixpacks.com/install.sh -o install.sh \
+ && chmod +x install.sh \
+ && ./install.sh \
+ && pnpm install -g tsx
+
+# Install Railpack
+ARG RAILPACK_VERSION=0.0.64
+RUN curl -sSL https://railpack.com/install.sh | bash
+
+# Install buildpacks
+COPY --from=buildpacksio/pack:0.35.0 /usr/local/bin/pack /usr/local/bin/pack
+
+EXPOSE 3000
+CMD [ "pnpm", "start" ]
diff --git a/data/Dockerfile.cloud b/data/Dockerfile.cloud
new file mode 100644
index 0000000000000000000000000000000000000000..c1b6679638ebd8a726385db26f4adcba3019d61b
--- /dev/null
+++ b/data/Dockerfile.cloud
@@ -0,0 +1,61 @@
+FROM node:20.9-slim AS base
+ENV PNPM_HOME="/pnpm"
+ENV PATH="$PNPM_HOME:$PATH"
+RUN corepack enable
+
+FROM base AS build
+COPY . /usr/src/app
+WORKDIR /usr/src/app
+
+RUN apt-get update && apt-get install -y python3 make g++ git python3-pip pkg-config libsecret-1-dev && rm -rf /var/lib/apt/lists/*
+
+# Install dependencies
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm --filter=@dokploy/server --filter=./apps/dokploy install --frozen-lockfile
+
+
+# Deploy only the dokploy app
+ARG NEXT_PUBLIC_UMAMI_HOST
+ENV NEXT_PUBLIC_UMAMI_HOST=$NEXT_PUBLIC_UMAMI_HOST
+
+ARG NEXT_PUBLIC_UMAMI_WEBSITE_ID
+ENV NEXT_PUBLIC_UMAMI_WEBSITE_ID=$NEXT_PUBLIC_UMAMI_WEBSITE_ID
+
+ARG NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
+ENV NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=$NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
+
+ENV NODE_ENV=production
+RUN pnpm --filter=@dokploy/server build
+RUN pnpm --filter=./apps/dokploy run build
+
+RUN pnpm --filter=./apps/dokploy --prod deploy /prod/dokploy
+
+RUN cp -R /usr/src/app/apps/dokploy/.next /prod/dokploy/.next
+RUN cp -R /usr/src/app/apps/dokploy/dist /prod/dokploy/dist
+
+FROM base AS dokploy
+WORKDIR /app
+
+# Set production
+ENV NODE_ENV=production
+
+RUN apt-get update && apt-get install -y curl unzip apache2-utils && rm -rf /var/lib/apt/lists/*
+
+# Copy only the necessary files
+COPY --from=build /prod/dokploy/.next ./.next
+COPY --from=build /prod/dokploy/dist ./dist
+COPY --from=build /prod/dokploy/next.config.mjs ./next.config.mjs
+COPY --from=build /prod/dokploy/public ./public
+COPY --from=build /prod/dokploy/package.json ./package.json
+COPY --from=build /prod/dokploy/drizzle ./drizzle
+COPY --from=build /prod/dokploy/components.json ./components.json
+COPY --from=build /prod/dokploy/node_modules ./node_modules
+
+
+# Install RCLONE
+RUN curl https://rclone.org/install.sh | bash
+
+# tsx
+RUN pnpm install -g tsx
+
+EXPOSE 3000
+CMD [ "pnpm", "start" ]
\ No newline at end of file
diff --git a/data/Dockerfile.monitoring b/data/Dockerfile.monitoring
new file mode 100644
index 0000000000000000000000000000000000000000..814625dbf0cba882d01ab112a262e7961a59d276
--- /dev/null
+++ b/data/Dockerfile.monitoring
@@ -0,0 +1,41 @@
+# Build stage
+FROM golang:1.21-alpine3.19 AS builder
+
+# Instalar dependencias necesarias
+RUN apk add --no-cache gcc musl-dev sqlite-dev
+
+# Establecer el directorio de trabajo
+WORKDIR /app
+
+# Copiar todo el código fuente primero
+COPY . .
+
+# Movernos al directorio de la aplicación golang
+WORKDIR /app/apps/monitoring
+
+# Descargar dependencias
+RUN go mod download
+
+# Compilar la aplicación
+RUN CGO_ENABLED=1 GOOS=linux go build -o main main.go
+
+# Etapa final
+FROM alpine:3.19
+
+# Instalar SQLite y otras dependencias necesarias
+RUN apk add --no-cache sqlite-libs docker-cli
+
+WORKDIR /app
+
+# Copiar el binario compilado y el archivo monitor.go
+COPY --from=builder /app/apps/monitoring/main ./main
+COPY --from=builder /app/apps/monitoring/main.go ./monitor.go
+
+# COPY --from=builder /app/apps/golang/.env ./.env
+
+# Exponer el puerto
+ENV PORT=3001
+EXPOSE 3001
+
+# Ejecutar la aplicación
+CMD ["./main"]
\ No newline at end of file
diff --git a/data/Dockerfile.schedule b/data/Dockerfile.schedule
new file mode 100644
index 0000000000000000000000000000000000000000..eba08f7ba91b2695ab2957341b29774cd8309214
--- /dev/null
+++ b/data/Dockerfile.schedule
@@ -0,0 +1,36 @@
+FROM node:20.9-slim AS base
+ENV PNPM_HOME="/pnpm"
+ENV PATH="$PNPM_HOME:$PATH"
+RUN corepack enable
+
+FROM base AS build
+COPY . /usr/src/app
+WORKDIR /usr/src/app
+
+RUN apt-get update && apt-get install -y python3 make g++ git python3-pip pkg-config libsecret-1-dev && rm -rf /var/lib/apt/lists/*
+
+# Install dependencies
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm --filter=@dokploy/server --filter=./apps/schedules install --frozen-lockfile
+
+# Deploy only the dokploy app
+
+ENV NODE_ENV=production
+RUN pnpm --filter=@dokploy/server build
+RUN pnpm --filter=./apps/schedules run build
+
+RUN pnpm --filter=./apps/schedules --prod deploy /prod/schedules
+
+RUN cp -R /usr/src/app/apps/schedules/dist /prod/schedules/dist
+
+FROM base AS dokploy
+WORKDIR /app
+
+# Set production
+ENV NODE_ENV=production
+
+# Copy only the necessary files
+COPY --from=build /prod/schedules/dist ./dist
+COPY --from=build /prod/schedules/package.json ./package.json
+COPY --from=build /prod/schedules/node_modules ./node_modules
+
+CMD HOSTNAME=0.0.0.0 && pnpm start
\ No newline at end of file
diff --git a/data/Dockerfile.server b/data/Dockerfile.server
new file mode 100644
index 0000000000000000000000000000000000000000..8fef514221f9dc279073b283227076c55c644e42
--- /dev/null
+++ b/data/Dockerfile.server
@@ -0,0 +1,36 @@
+FROM node:20.9-slim AS base
+ENV PNPM_HOME="/pnpm"
+ENV PATH="$PNPM_HOME:$PATH"
+RUN corepack enable
+
+FROM base AS build
+COPY . /usr/src/app
+WORKDIR /usr/src/app
+
+RUN apt-get update && apt-get install -y python3 make g++ git python3-pip pkg-config libsecret-1-dev && rm -rf /var/lib/apt/lists/*
+
+# Install dependencies
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm --filter=@dokploy/server --filter=./apps/api install --frozen-lockfile
+
+# Deploy only the dokploy app
+
+ENV NODE_ENV=production
+RUN pnpm --filter=@dokploy/server build
+RUN pnpm --filter=./apps/api run build
+
+RUN pnpm --filter=./apps/api --prod deploy /prod/api
+
+RUN cp -R /usr/src/app/apps/api/dist /prod/api/dist
+
+FROM base AS dokploy
+WORKDIR /app
+
+# Set production
+ENV NODE_ENV=production
+
+# Copy only the necessary files
+COPY --from=build /prod/api/dist ./dist
+COPY --from=build /prod/api/package.json ./package.json
+COPY --from=build /prod/api/node_modules ./node_modules
+
+CMD HOSTNAME=0.0.0.0 && pnpm start
\ No newline at end of file
diff --git a/data/GUIDES.md b/data/GUIDES.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfb7cd8128aea5681d1f1a909fd059a147b5a415
--- /dev/null
+++ b/data/GUIDES.md
@@ -0,0 +1,49 @@
+# Docker
+
+Here's how to install docker on different operating systems:
+
+## macOS
+
+1. Visit [Docker Desktop for Mac](https://www.docker.com/products/docker-desktop)
+2. Download the Docker Desktop installer
+3. Double-click the downloaded `.dmg` file
+4. Drag Docker to your Applications folder
+5. Open Docker Desktop from Applications
+6. Follow the onboarding tutorial if desired
+
+## Linux
+
+### Ubuntu
+
+```bash
+# Update package index
+sudo apt-get update
+
+# Install prerequisites
+sudo apt-get install \
+ apt-transport-https \
+ ca-certificates \
+ curl \
+ gnupg \
+ lsb-release
+
+# Add Docker's official GPG key
+curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
+
+# Set up stable repository
+echo \
+ "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
+ $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
+
+# Install Docker Engine
+sudo apt-get update
+sudo apt-get install docker-ce docker-ce-cli containerd.io
+```
+
+## Windows
+
+1. Enable WSL2 if not already enabled
+2. Visit [Docker Desktop for Windows](https://www.docker.com/products/docker-desktop)
+3. Download the installer
+4. Run the installer and follow the prompts
+5. Start Docker Desktop from the Start menu
\ No newline at end of file
diff --git a/data/LICENSE.MD b/data/LICENSE.MD
new file mode 100644
index 0000000000000000000000000000000000000000..7e49a35ba8290ec9ab377c87deedf12255744130
--- /dev/null
+++ b/data/LICENSE.MD
@@ -0,0 +1,26 @@
+# License
+
+## Core License (Apache License 2.0)
+
+Copyright 2024 Mauricio Siu.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and limitations under the License.
+
+## Additional Terms for Specific Features
+
+The following additional terms apply to the multi-node support, Docker Compose file, Preview Deployments and Multi Server features of Dokploy. In the event of a conflict, these provisions shall take precedence over those in the Apache License:
+
+- **Self-Hosted Version Free**: All features of Dokploy, including multi-node support, Docker Compose file support, Schedules, Preview Deployments and Multi Server, will always be free to use in the self-hosted version.
+- **Restriction on Resale**: The multi-node support, Docker Compose file support, Schedules, Preview Deployments and Multi Server features cannot be sold or offered as a service by any party other than the copyright holder without prior written consent.
+- **Modification Distribution**: Any modifications to the multi-node support, Docker Compose file support, Schedules, Preview Deployments and Multi Server features must be distributed freely and cannot be sold or offered as a service.
+
+For further inquiries or permissions, please contact us directly.
diff --git a/data/SECURITY.md b/data/SECURITY.md
new file mode 100644
index 0000000000000000000000000000000000000000..47633ab95f474f73b3efd9c0a798e375d7598f9f
--- /dev/null
+++ b/data/SECURITY.md
@@ -0,0 +1,28 @@
+# Dokploy Security Policy
+
+At Dokploy, security is a top priority. We appreciate the help of security researchers and the community in identifying and reporting vulnerabilities.
+
+## How to Report a Vulnerability
+
+If you have discovered a security vulnerability in Dokploy, we ask that you report it responsibly by following these guidelines:
+
+1. **Contact us:** Send an email to [contact@dokploy.com](mailto:contact@dokploy.com).
+2. **Provide clear details:** Include as much information as possible to help us understand and reproduce the vulnerability. This should include:
+ * A clear description of the vulnerability.
+ * Steps to reproduce the vulnerability.
+ * Any sample code, screenshots, or videos that might be helpful.
+ * The potential impact of the vulnerability.
+3. **Do not make the vulnerability public:** Please refrain from publicly disclosing the vulnerability until we have had the opportunity to investigate and address it. This is crucial for protecting our users.
+4. **Allow us time:** We will endeavor to acknowledge receipt of your report as soon as possible and keep you informed of our progress. The time to resolve the vulnerability may vary depending on its complexity and severity.
+
+## What We Expect From You
+
+* Do not access user data or systems beyond what is necessary to demonstrate the vulnerability.
+* Do not perform denial-of-service (DoS) attacks, spamming, or social engineering.
+* Do not modify or destroy data that does not belong to you.
+
+## Our Commitment
+
+We are committed to working with you quickly and responsibly to address any legitimate security vulnerability.
+
+Thank you for helping us keep Dokploy secure for everyone.
diff --git a/data/TERMS_AND_CONDITIONS.md b/data/TERMS_AND_CONDITIONS.md
new file mode 100644
index 0000000000000000000000000000000000000000..56ef97fb14100f7b7d655a1800563b7dce7c058e
--- /dev/null
+++ b/data/TERMS_AND_CONDITIONS.md
@@ -0,0 +1,22 @@
+# Terms & Conditions
+
+**Dokploy core** is a free and open-source solution intended as an alternative to established cloud platforms like Vercel and Netlify.
+
+The Dokploy team endeavors to mitigate potential defects and issues through stringent testing and adherence to principles of clean coding. Dokploy is provided "AS IS" without any warranties, express or implied. Refer to the [License](https://github.com/Dokploy/Dokploy/blob/main/LICENSE) for details on permissions and restrictions.
+
+
+### Description of Service:
+
+**Dokploy core** is an open-source tool designed to simplify the deployment of applications for both personal and business use. Users are permitted to install, modify, and operate Dokploy independently or within their organizations to improve their development and deployment operations. It is important to note that any commercial resale or redistribution of Dokploy as a service is strictly forbidden without explicit consent. This prohibition ensures the preservation of Dokploy's open-source character for the benefit of the entire community.
+
+### Our Responsibility
+
+The Dokploy development team commits to maintaining the functionality of the software and addressing major issues promptly. While we welcome suggestions for new features, the decision to include them rests solely with the core developers of Dokploy.
+
+### Usage Data
+
+**Dokploy** does not collect any user data. It is distributed as a free and open-source tool under the terms of "AS IS", without any implied warranties or conditions.
+
+### Future Changes
+
+The Terms of Service and Terms & Conditions are subject to change without prior notice.
diff --git a/data/apps/api/.env.example b/data/apps/api/.env.example
new file mode 100644
index 0000000000000000000000000000000000000000..647e2a077c66b0526cb9ee9afffc44527f3fabcf
--- /dev/null
+++ b/data/apps/api/.env.example
@@ -0,0 +1,2 @@
+LEMON_SQUEEZY_API_KEY=""
+LEMON_SQUEEZY_STORE_ID=""
\ No newline at end of file
diff --git a/data/apps/api/package.json b/data/apps/api/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..56ea56952d6c2fd3d34ddef00d64eea19737c527
--- /dev/null
+++ b/data/apps/api/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "@dokploy/api",
+ "version": "0.0.1",
+ "type": "module",
+ "scripts": {
+ "dev": "PORT=4000 tsx watch src/index.ts",
+ "build": "tsc --project tsconfig.json",
+ "start": "node dist/index.js",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "pino": "9.4.0",
+ "pino-pretty": "11.2.2",
+ "@hono/zod-validator": "0.3.0",
+ "zod": "^3.23.4",
+ "react": "18.2.0",
+ "react-dom": "18.2.0",
+ "@dokploy/server": "workspace:*",
+ "@hono/node-server": "^1.12.1",
+ "hono": "^4.5.8",
+ "dotenv": "^16.3.1",
+ "redis": "4.7.0",
+ "@nerimity/mimiqueue": "1.2.3"
+ },
+ "devDependencies": {
+ "typescript": "^5.4.2",
+ "@types/react": "^18.2.37",
+ "@types/react-dom": "^18.2.15",
+ "@types/node": "^20.11.17",
+ "tsx": "^4.7.1"
+ },
+ "packageManager": "pnpm@9.5.0"
+}
diff --git a/data/apps/api/src/index.ts b/data/apps/api/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..0db565995008d2370295f4faf81e45f1d044734b
--- /dev/null
+++ b/data/apps/api/src/index.ts
@@ -0,0 +1,61 @@
+import { serve } from "@hono/node-server";
+import { Hono } from "hono";
+import "dotenv/config";
+import { zValidator } from "@hono/zod-validator";
+import { Queue } from "@nerimity/mimiqueue";
+import { createClient } from "redis";
+import { logger } from "./logger.js";
+import { type DeployJob, deployJobSchema } from "./schema.js";
+import { deploy } from "./utils.js";
+
+const app = new Hono();
+const redisClient = createClient({
+ url: process.env.REDIS_URL,
+});
+
+app.use(async (c, next) => {
+ if (c.req.path === "/health") {
+ return next();
+ }
+ const authHeader = c.req.header("X-API-Key");
+
+ if (process.env.API_KEY !== authHeader) {
+ return c.json({ message: "Invalid API Key" }, 403);
+ }
+
+ return next();
+});
+
+app.post("/deploy", zValidator("json", deployJobSchema), (c) => {
+ const data = c.req.valid("json");
+ queue.add(data, { groupName: data.serverId });
+ return c.json(
+ {
+ message: "Deployment Added",
+ },
+ 200,
+ );
+});
+
+app.get("/health", async (c) => {
+ return c.json({ status: "ok" });
+});
+
+const queue = new Queue({
+ name: "deployments",
+ process: async (job: DeployJob) => {
+ logger.info("Deploying job", job);
+ return await deploy(job);
+ },
+ redisClient,
+});
+
+(async () => {
+ await redisClient.connect();
+ await redisClient.flushAll();
+ logger.info("Redis Cleaned");
+})();
+
+const port = Number.parseInt(process.env.PORT || "3000");
+logger.info("Starting Deployments Server ✅", port);
+serve({ fetch: app.fetch, port });
diff --git a/data/apps/api/src/logger.ts b/data/apps/api/src/logger.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3d8b5840f488c2db4507c08c8aa61d4b1875eabd
--- /dev/null
+++ b/data/apps/api/src/logger.ts
@@ -0,0 +1,10 @@
+import pino from "pino";
+
+export const logger = pino({
+ transport: {
+ target: "pino-pretty",
+ options: {
+ colorize: true,
+ },
+ },
+});
diff --git a/data/apps/api/src/schema.ts b/data/apps/api/src/schema.ts
new file mode 100644
index 0000000000000000000000000000000000000000..609289bf70ef85fcc71e9747f94713418a461d32
--- /dev/null
+++ b/data/apps/api/src/schema.ts
@@ -0,0 +1,34 @@
+import { z } from "zod";
+
+export const deployJobSchema = z.discriminatedUnion("applicationType", [
+ z.object({
+ applicationId: z.string(),
+ titleLog: z.string(),
+ descriptionLog: z.string(),
+ server: z.boolean().optional(),
+ type: z.enum(["deploy", "redeploy"]),
+ applicationType: z.literal("application"),
+ serverId: z.string().min(1),
+ }),
+ z.object({
+ composeId: z.string(),
+ titleLog: z.string(),
+ descriptionLog: z.string(),
+ server: z.boolean().optional(),
+ type: z.enum(["deploy", "redeploy"]),
+ applicationType: z.literal("compose"),
+ serverId: z.string().min(1),
+ }),
+ z.object({
+ applicationId: z.string(),
+ previewDeploymentId: z.string(),
+ titleLog: z.string(),
+ descriptionLog: z.string(),
+ server: z.boolean().optional(),
+ type: z.enum(["deploy"]),
+ applicationType: z.literal("application-preview"),
+ serverId: z.string().min(1),
+ }),
+]);
+
+export type DeployJob = z.infer;
diff --git a/data/apps/api/src/utils.ts b/data/apps/api/src/utils.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3f3c9698b69ef96c9a9a5c7209b1ee815334d91b
--- /dev/null
+++ b/data/apps/api/src/utils.ts
@@ -0,0 +1,82 @@
+import {
+ deployRemoteApplication,
+ deployRemoteCompose,
+ deployRemotePreviewApplication,
+ rebuildRemoteApplication,
+ rebuildRemoteCompose,
+ updateApplicationStatus,
+ updateCompose,
+ updatePreviewDeployment,
+} from "@dokploy/server";
+import type { DeployJob } from "./schema";
+
+export const deploy = async (job: DeployJob) => {
+ try {
+ if (job.applicationType === "application") {
+ await updateApplicationStatus(job.applicationId, "running");
+ if (job.server) {
+ if (job.type === "redeploy") {
+ await rebuildRemoteApplication({
+ applicationId: job.applicationId,
+ titleLog: job.titleLog,
+ descriptionLog: job.descriptionLog,
+ });
+ } else if (job.type === "deploy") {
+ await deployRemoteApplication({
+ applicationId: job.applicationId,
+ titleLog: job.titleLog,
+ descriptionLog: job.descriptionLog,
+ });
+ }
+ }
+ } else if (job.applicationType === "compose") {
+ await updateCompose(job.composeId, {
+ composeStatus: "running",
+ });
+
+ if (job.server) {
+ if (job.type === "redeploy") {
+ await rebuildRemoteCompose({
+ composeId: job.composeId,
+ titleLog: job.titleLog,
+ descriptionLog: job.descriptionLog,
+ });
+ } else if (job.type === "deploy") {
+ await deployRemoteCompose({
+ composeId: job.composeId,
+ titleLog: job.titleLog,
+ descriptionLog: job.descriptionLog,
+ });
+ }
+ }
+ } else if (job.applicationType === "application-preview") {
+ await updatePreviewDeployment(job.previewDeploymentId, {
+ previewStatus: "running",
+ });
+ if (job.server) {
+ if (job.type === "deploy") {
+ await deployRemotePreviewApplication({
+ applicationId: job.applicationId,
+ titleLog: job.titleLog,
+ descriptionLog: job.descriptionLog,
+ previewDeploymentId: job.previewDeploymentId,
+ });
+ }
+ }
+ }
+ } catch (_) {
+ if (job.applicationType === "application") {
+ await updateApplicationStatus(job.applicationId, "error");
+ } else if (job.applicationType === "compose") {
+ await updateCompose(job.composeId, {
+ composeStatus: "error",
+ });
+ } else if (job.applicationType === "application-preview") {
+ await updatePreviewDeployment(job.previewDeploymentId, {
+ previewStatus: "error",
+ });
+ }
+ }
+
+ return true;
+};
diff --git a/data/apps/api/tsconfig.json b/data/apps/api/tsconfig.json
new file mode 100644
index 0000000000000000000000000000000000000000..e47c6267d4400397c72bac6467e2afe7bf9a560e
--- /dev/null
+++ b/data/apps/api/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "Node",
+ "strict": true,
+ "skipLibCheck": true,
+ "outDir": "dist",
+ "jsx": "react-jsx",
+ "jsxImportSource": "hono/jsx",
+ "baseUrl": ".",
+ "paths": {
+ "@/*": ["./*"],
+ "@dokploy/server/*": ["../../packages/server/src/*"]
+ }
+ },
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/data/apps/dokploy/.dockerignore b/data/apps/dokploy/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..958b26c9d6ea21bea38f9de590fc01075da016a9
--- /dev/null
+++ b/data/apps/dokploy/.dockerignore
@@ -0,0 +1,5 @@
+node_modules
+.git
+.gitignore
+*.md
+dist
\ No newline at end of file
diff --git a/data/apps/dokploy/.env.example b/data/apps/dokploy/.env.example
new file mode 100644
index 0000000000000000000000000000000000000000..ba57ec7bedbc17ab9382be0e3f27cbcd9142c7b8
--- /dev/null
+++ b/data/apps/dokploy/.env.example
@@ -0,0 +1,3 @@
+DATABASE_URL="postgres://dokploy:amukds4wi9001583845717ad2@localhost:5432/dokploy"
+PORT=3000
+NODE_ENV=development
\ No newline at end of file
diff --git a/data/apps/dokploy/.env.production.example b/data/apps/dokploy/.env.production.example
new file mode 100644
index 0000000000000000000000000000000000000000..41e934c3a696f41fabc594431c35b0f2f5f4b968
--- /dev/null
+++ b/data/apps/dokploy/.env.production.example
@@ -0,0 +1,3 @@
+DATABASE_URL="postgres://dokploy:amukds4wi9001583845717ad2@dokploy-postgres:5432/dokploy"
+PORT=3000
+NODE_ENV=production
\ No newline at end of file
diff --git a/data/apps/dokploy/.nvmrc b/data/apps/dokploy/.nvmrc
new file mode 100644
index 0000000000000000000000000000000000000000..593cb75bc5c212129bc486a51f13015214a07cd1
--- /dev/null
+++ b/data/apps/dokploy/.nvmrc
@@ -0,0 +1 @@
+20.16.0
\ No newline at end of file
diff --git a/data/apps/dokploy/LICENSE.MD b/data/apps/dokploy/LICENSE.MD
new file mode 100644
index 0000000000000000000000000000000000000000..8a508efb410931c2858a4f88d2aa811cd1292709
--- /dev/null
+++ b/data/apps/dokploy/LICENSE.MD
@@ -0,0 +1,26 @@
+# License
+
+## Core License (Apache License 2.0)
+
+Copyright 2024 Mauricio Siu.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and limitations under the License.
+
+## Additional Terms for Specific Features
+
+The following additional terms apply to the multi-node support, Docker Compose file, Preview Deployments and Multi Server features of Dokploy. In the event of a conflict, these provisions shall take precedence over those in the Apache License:
+
+- **Self-Hosted Version Free**: All features of Dokploy, including multi-node support, Docker Compose file support, Preview Deployments and Multi Server, will always be free to use in the self-hosted version.
+- **Restriction on Resale**: The multi-node support, Docker Compose file support, Preview Deployments and Multi Server features cannot be sold or offered as a service by any party other than the copyright holder without prior written consent.
+- **Modification Distribution**: Any modifications to the multi-node support, Docker Compose file support, Preview Deployments and Multi Server features must be distributed freely and cannot be sold or offered as a service.
+
+For further inquiries or permissions, please contact us directly.
diff --git a/data/apps/dokploy/__test__/compose/compose.test.ts b/data/apps/dokploy/__test__/compose/compose.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..9d4ba20f5ae679b3401923f50a393d03b0efb512
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/compose.test.ts
@@ -0,0 +1,476 @@
+import { addSuffixToAllProperties } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFile1 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ container_name: web_container
+ depends_on:
+ - app
+ networks:
+ - frontend
+ volumes_from:
+ - data
+ links:
+ - db
+ extends:
+ service: base_service
+ configs:
+ - source: web_config
+
+ app:
+ image: node:14
+ networks:
+ - backend
+ - frontend
+
+ db:
+ image: postgres:13
+ networks:
+ - backend
+
+ data:
+ image: busybox
+ volumes:
+ - /data
+
+ base_service:
+ image: base:latest
+
+networks:
+ frontend:
+ driver: bridge
+ backend:
+ driver: bridge
+
+volumes:
+ web_data:
+ driver: local
+
+configs:
+ web_config:
+ file: ./web_config.yml
+
+secrets:
+ db_password:
+ file: ./db_password.txt
+`;
+
+const expectedComposeFile1 = load(`
+version: "3.8"
+
+services:
+ web-testhash:
+ image: nginx:latest
+ container_name: web_container-testhash
+ depends_on:
+ - app-testhash
+ networks:
+ - frontend-testhash
+ volumes_from:
+ - data-testhash
+ links:
+ - db-testhash
+ extends:
+ service: base_service-testhash
+ configs:
+ - source: web_config-testhash
+
+ app-testhash:
+ image: node:14
+ networks:
+ - backend-testhash
+ - frontend-testhash
+
+ db-testhash:
+ image: postgres:13
+ networks:
+ - backend-testhash
+
+ data-testhash:
+ image: busybox
+ volumes:
+ - /data
+
+ base_service-testhash:
+ image: base:latest
+
+networks:
+ frontend-testhash:
+ driver: bridge
+ backend-testhash:
+ driver: bridge
+
+volumes:
+ web_data-testhash:
+ driver: local
+
+configs:
+ web_config-testhash:
+ file: ./web_config.yml
+
+secrets:
+ db_password-testhash:
+ file: ./db_password.txt
+`) as ComposeSpecification;
+
+test("Add suffix to all properties in compose file 1", () => {
+ const composeData = load(composeFile1) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllProperties(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile1);
+});
+
+const composeFile2 = `
+version: "3.8"
+
+services:
+ frontend:
+ image: nginx:latest
+ depends_on:
+ - backend
+ networks:
+ - public
+ volumes_from:
+ - logs
+ links:
+ - cache
+ extends:
+ service: shared_service
+ secrets:
+ - db_password
+
+ backend:
+ image: node:14
+ networks:
+ - private
+ - public
+
+ cache:
+ image: redis:latest
+ networks:
+ - private
+
+ logs:
+ image: busybox
+ volumes:
+ - /logs
+
+ shared_service:
+ image: shared:latest
+
+networks:
+ public:
+ driver: bridge
+ private:
+ driver: bridge
+
+volumes:
+ logs:
+ driver: local
+
+configs:
+ app_config:
+ file: ./app_config.yml
+
+secrets:
+ db_password:
+ file: ./db_password.txt
+`;
+
+const expectedComposeFile2 = load(`
+version: "3.8"
+
+services:
+ frontend-testhash:
+ image: nginx:latest
+ depends_on:
+ - backend-testhash
+ networks:
+ - public-testhash
+ volumes_from:
+ - logs-testhash
+ links:
+ - cache-testhash
+ extends:
+ service: shared_service-testhash
+ secrets:
+ - db_password-testhash
+
+ backend-testhash:
+ image: node:14
+ networks:
+ - private-testhash
+ - public-testhash
+
+ cache-testhash:
+ image: redis:latest
+ networks:
+ - private-testhash
+
+ logs-testhash:
+ image: busybox
+ volumes:
+ - /logs
+
+ shared_service-testhash:
+ image: shared:latest
+
+networks:
+ public-testhash:
+ driver: bridge
+ private-testhash:
+ driver: bridge
+
+volumes:
+ logs-testhash:
+ driver: local
+
+configs:
+ app_config-testhash:
+ file: ./app_config.yml
+
+secrets:
+ db_password-testhash:
+ file: ./db_password.txt
+`) as ComposeSpecification;
+
+test("Add suffix to all properties in compose file 2", () => {
+ const composeData = load(composeFile2) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllProperties(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile2);
+});
+
+const composeFile3 = `
+version: "3.8"
+
+services:
+ service_a:
+ image: service_a:latest
+ depends_on:
+ - service_b
+ networks:
+ - net_a
+ volumes_from:
+ - data_volume
+ links:
+ - service_c
+ extends:
+ service: common_service
+ configs:
+ - source: service_a_config
+
+ service_b:
+ image: service_b:latest
+ networks:
+ - net_b
+ - net_a
+
+ service_c:
+ image: service_c:latest
+ networks:
+ - net_b
+
+ data_volume:
+ image: busybox
+ volumes:
+ - /data
+
+ common_service:
+ image: common:latest
+
+networks:
+ net_a:
+ driver: bridge
+ net_b:
+ driver: bridge
+
+volumes:
+ data_volume:
+ driver: local
+
+configs:
+ service_a_config:
+ file: ./service_a_config.yml
+
+secrets:
+ service_secret:
+ file: ./service_secret.txt
+`;
+
+const expectedComposeFile3 = load(`
+version: "3.8"
+
+services:
+ service_a-testhash:
+ image: service_a:latest
+ depends_on:
+ - service_b-testhash
+ networks:
+ - net_a-testhash
+ volumes_from:
+ - data_volume-testhash
+ links:
+ - service_c-testhash
+ extends:
+ service: common_service-testhash
+ configs:
+ - source: service_a_config-testhash
+
+ service_b-testhash:
+ image: service_b:latest
+ networks:
+ - net_b-testhash
+ - net_a-testhash
+
+ service_c-testhash:
+ image: service_c:latest
+ networks:
+ - net_b-testhash
+
+ data_volume-testhash:
+ image: busybox
+ volumes:
+ - /data
+
+ common_service-testhash:
+ image: common:latest
+
+networks:
+ net_a-testhash:
+ driver: bridge
+ net_b-testhash:
+ driver: bridge
+
+volumes:
+ data_volume-testhash:
+ driver: local
+
+configs:
+ service_a_config-testhash:
+ file: ./service_a_config.yml
+
+secrets:
+ service_secret-testhash:
+ file: ./service_secret.txt
+`) as ComposeSpecification;
+
+test("Add suffix to all properties in compose file 3", () => {
+ const composeData = load(composeFile3) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllProperties(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile3);
+});
+
+const composeFile = `
+version: "3.8"
+
+services:
+ plausible_db:
+ image: postgres:16-alpine
+ restart: always
+ volumes:
+ - db-data:/var/lib/postgresql/data
+ environment:
+ - POSTGRES_PASSWORD=postgres
+
+ plausible_events_db:
+ image: clickhouse/clickhouse-server:24.3.3.102-alpine
+ restart: always
+ volumes:
+ - event-data:/var/lib/clickhouse
+ - event-logs:/var/log/clickhouse-server
+ - ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro
+ - ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro
+ ulimits:
+ nofile:
+ soft: 262144
+ hard: 262144
+
+ plausible:
+ image: ghcr.io/plausible/community-edition:v2.1.0
+ restart: always
+ command: sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh run"
+ depends_on:
+ - plausible_db
+ - plausible_events_db
+ ports:
+ - 127.0.0.1:8000:8000
+ env_file:
+ - plausible-conf.env
+
+volumes:
+ db-data:
+ driver: local
+ event-data:
+ driver: local
+ event-logs:
+ driver: local
+`;
+
+const expectedComposeFile = load(`
+version: "3.8"
+
+services:
+ plausible_db-testhash:
+ image: postgres:16-alpine
+ restart: always
+ volumes:
+ - db-data-testhash:/var/lib/postgresql/data
+ environment:
+ - POSTGRES_PASSWORD=postgres
+
+ plausible_events_db-testhash:
+ image: clickhouse/clickhouse-server:24.3.3.102-alpine
+ restart: always
+ volumes:
+ - event-data-testhash:/var/lib/clickhouse
+ - event-logs-testhash:/var/log/clickhouse-server
+ - ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro
+ - ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro
+ ulimits:
+ nofile:
+ soft: 262144
+ hard: 262144
+
+ plausible-testhash:
+ image: ghcr.io/plausible/community-edition:v2.1.0
+ restart: always
+ command: sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh run"
+ depends_on:
+ - plausible_db-testhash
+ - plausible_events_db-testhash
+ ports:
+ - 127.0.0.1:8000:8000
+ env_file:
+ - plausible-conf.env
+
+volumes:
+ db-data-testhash:
+ driver: local
+ event-data-testhash:
+ driver: local
+ event-logs-testhash:
+ driver: local
+`) as ComposeSpecification;
+
+test("Add suffix to all properties in Plausible compose file", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllProperties(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile);
+});
diff --git a/data/apps/dokploy/__test__/compose/config/config-root.test.ts b/data/apps/dokploy/__test__/compose/config/config-root.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..4b40c073ee562da5cd7b26b1c94540d4208c07ca
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/config/config-root.test.ts
@@ -0,0 +1,178 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToConfigsRoot } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+const composeFile = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+
+configs:
+ web-config:
+ file: ./web-config.yml
+`;
+
+test("Add suffix to configs in root property", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.configs) {
+ return;
+ }
+ const configs = addSuffixToConfigsRoot(composeData.configs, suffix);
+
+ expect(configs).toBeDefined();
+ for (const configKey of Object.keys(configs)) {
+ expect(configKey).toContain(`-${suffix}`);
+ expect(configs[configKey]).toBeDefined();
+ }
+});
+
+const composeFileMultipleConfigs = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web-config
+ target: /etc/nginx/nginx.conf
+ - source: another-config
+ target: /etc/nginx/another.conf
+
+configs:
+ web-config:
+ file: ./web-config.yml
+ another-config:
+ file: ./another-config.yml
+`;
+
+test("Add suffix to multiple configs in root property", () => {
+ const composeData = load(composeFileMultipleConfigs) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.configs) {
+ return;
+ }
+ const configs = addSuffixToConfigsRoot(composeData.configs, suffix);
+
+ expect(configs).toBeDefined();
+ for (const configKey of Object.keys(configs)) {
+ expect(configKey).toContain(`-${suffix}`);
+ expect(configs[configKey]).toBeDefined();
+ }
+ expect(configs).toHaveProperty(`web-config-${suffix}`);
+ expect(configs).toHaveProperty(`another-config-${suffix}`);
+});
+
+const composeFileDifferentProperties = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+
+configs:
+ web-config:
+ file: ./web-config.yml
+ special-config:
+ external: true
+`;
+
+test("Add suffix to configs with different properties in root property", () => {
+ const composeData = load(
+ composeFileDifferentProperties,
+ ) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.configs) {
+ return;
+ }
+ const configs = addSuffixToConfigsRoot(composeData.configs, suffix);
+
+ expect(configs).toBeDefined();
+ for (const configKey of Object.keys(configs)) {
+ expect(configKey).toContain(`-${suffix}`);
+ expect(configs[configKey]).toBeDefined();
+ }
+ expect(configs).toHaveProperty(`web-config-${suffix}`);
+ expect(configs).toHaveProperty(`special-config-${suffix}`);
+});
+
+const composeFileConfigRoot = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+
+ app:
+ image: node:latest
+
+ db:
+ image: postgres:latest
+
+configs:
+ web_config:
+ file: ./web-config.yml
+
+ app_config:
+ file: ./app-config.json
+
+ db_config:
+ file: ./db-config.yml
+`;
+
+// Expected compose file con el prefijo `testhash`
+const expectedComposeFileConfigRoot = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+
+ app:
+ image: node:latest
+
+ db:
+ image: postgres:latest
+
+configs:
+ web_config-testhash:
+ file: ./web-config.yml
+
+ app_config-testhash:
+ file: ./app-config.json
+
+ db_config-testhash:
+ file: ./db-config.yml
+`) as ComposeSpecification;
+
+test("Add suffix to configs in root property", () => {
+ const composeData = load(composeFileConfigRoot) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ if (!composeData?.configs) {
+ return;
+ }
+ const configs = addSuffixToConfigsRoot(composeData.configs, suffix);
+ const updatedComposeData = { ...composeData, configs };
+
+ // Verificar que el resultado coincide con el archivo esperado
+ expect(updatedComposeData).toEqual(expectedComposeFileConfigRoot);
+});
diff --git a/data/apps/dokploy/__test__/compose/config/config-service.test.ts b/data/apps/dokploy/__test__/compose/config/config-service.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..de014eb5e986c1a6805ba50d576c53d654229b1c
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/config/config-service.test.ts
@@ -0,0 +1,197 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToConfigsInServices } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFile = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web-config
+ target: /etc/nginx/nginx.conf
+
+configs:
+ web-config:
+ file: ./web-config.yml
+`;
+
+test("Add suffix to configs in services", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.services) {
+ return;
+ }
+ const services = addSuffixToConfigsInServices(composeData.services, suffix);
+ const actualComposeData = { ...composeData, services };
+
+ expect(actualComposeData.services?.web?.configs).toContainEqual({
+ source: `web-config-${suffix}`,
+ target: "/etc/nginx/nginx.conf",
+ });
+});
+
+const composeFileSingleServiceConfig = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web-config
+ target: /etc/nginx/nginx.conf
+
+configs:
+ web-config:
+ file: ./web-config.yml
+`;
+
+test("Add suffix to configs in services with single config", () => {
+ const composeData = load(
+ composeFileSingleServiceConfig,
+ ) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.services) {
+ return;
+ }
+ const services = addSuffixToConfigsInServices(composeData.services, suffix);
+
+ expect(services).toBeDefined();
+ for (const serviceKey of Object.keys(services)) {
+ const serviceConfigs = services?.[serviceKey]?.configs;
+ if (serviceConfigs) {
+ for (const config of serviceConfigs) {
+ if (typeof config === "object") {
+ expect(config.source).toContain(`-${suffix}`);
+ }
+ }
+ }
+ }
+});
+
+const composeFileMultipleServicesConfigs = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web-config
+ target: /etc/nginx/nginx.conf
+ - source: common-config
+ target: /etc/nginx/common.conf
+
+ app:
+ image: node:14
+ configs:
+ - source: app-config
+ target: /usr/src/app/config.json
+ - source: common-config
+ target: /usr/src/app/common.json
+
+configs:
+ web-config:
+ file: ./web-config.yml
+ app-config:
+ file: ./app-config.json
+ common-config:
+ file: ./common-config.yml
+`;
+
+test("Add suffix to configs in services with multiple configs", () => {
+ const composeData = load(
+ composeFileMultipleServicesConfigs,
+ ) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.services) {
+ return;
+ }
+ const services = addSuffixToConfigsInServices(composeData.services, suffix);
+
+ expect(services).toBeDefined();
+ for (const serviceKey of Object.keys(services)) {
+ const serviceConfigs = services?.[serviceKey]?.configs;
+ if (serviceConfigs) {
+ for (const config of serviceConfigs) {
+ if (typeof config === "object") {
+ expect(config.source).toContain(`-${suffix}`);
+ }
+ }
+ }
+ }
+});
+
+const composeFileConfigServices = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web_config
+ target: /etc/nginx/nginx.conf
+
+ app:
+ image: node:latest
+ configs:
+ - source: app_config
+ target: /usr/src/app/config.json
+
+ db:
+ image: postgres:latest
+ configs:
+ - source: db_config
+ target: /etc/postgresql/postgresql.conf
+
+`;
+
+// Expected compose file con el prefijo `testhash`
+const expectedComposeFileConfigServices = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web_config-testhash
+ target: /etc/nginx/nginx.conf
+
+ app:
+ image: node:latest
+ configs:
+ - source: app_config-testhash
+ target: /usr/src/app/config.json
+
+ db:
+ image: postgres:latest
+ configs:
+ - source: db_config-testhash
+ target: /etc/postgresql/postgresql.conf
+
+`) as ComposeSpecification;
+
+test("Add suffix to configs in services", () => {
+ const composeData = load(composeFileConfigServices) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ if (!composeData?.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToConfigsInServices(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ expect(actualComposeData).toEqual(expectedComposeFileConfigServices);
+});
diff --git a/data/apps/dokploy/__test__/compose/config/config.test.ts b/data/apps/dokploy/__test__/compose/config/config.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..aed3350f5bccb82c4add19bdd48d0a1254b595ff
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/config/config.test.ts
@@ -0,0 +1,246 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToAllConfigs } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+const composeFileCombinedConfigs = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web_config
+ target: /etc/nginx/nginx.conf
+
+ app:
+ image: node:14
+ configs:
+ - source: app_config
+ target: /usr/src/app/config.json
+
+ db:
+ image: postgres:13
+ configs:
+ - source: db_config
+ target: /etc/postgresql/postgresql.conf
+
+configs:
+ web_config:
+ file: ./web-config.yml
+
+ app_config:
+ file: ./app-config.json
+
+ db_config:
+ file: ./db-config.yml
+`;
+
+const expectedComposeFileCombinedConfigs = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web_config-testhash
+ target: /etc/nginx/nginx.conf
+
+ app:
+ image: node:14
+ configs:
+ - source: app_config-testhash
+ target: /usr/src/app/config.json
+
+ db:
+ image: postgres:13
+ configs:
+ - source: db_config-testhash
+ target: /etc/postgresql/postgresql.conf
+
+configs:
+ web_config-testhash:
+ file: ./web-config.yml
+
+ app_config-testhash:
+ file: ./app-config.json
+
+ db_config-testhash:
+ file: ./db-config.yml
+`) as ComposeSpecification;
+
+test("Add suffix to all configs in root and services", () => {
+ const composeData = load(composeFileCombinedConfigs) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllConfigs(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFileCombinedConfigs);
+});
+
+const composeFileWithEnvAndExternal = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web_config
+ target: /etc/nginx/nginx.conf
+ environment:
+ - NGINX_CONFIG=/etc/nginx/nginx.conf
+
+ app:
+ image: node:14
+ configs:
+ - source: app_config
+ target: /usr/src/app/config.json
+
+ db:
+ image: postgres:13
+ configs:
+ - source: db_config
+ target: /etc/postgresql/postgresql.conf
+
+configs:
+ web_config:
+ external: true
+
+ app_config:
+ file: ./app-config.json
+
+ db_config:
+ environment: dev
+ file: ./db-config.yml
+`;
+
+const expectedComposeFileWithEnvAndExternal = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web_config-testhash
+ target: /etc/nginx/nginx.conf
+ environment:
+ - NGINX_CONFIG=/etc/nginx/nginx.conf
+
+ app:
+ image: node:14
+ configs:
+ - source: app_config-testhash
+ target: /usr/src/app/config.json
+
+ db:
+ image: postgres:13
+ configs:
+ - source: db_config-testhash
+ target: /etc/postgresql/postgresql.conf
+
+configs:
+ web_config-testhash:
+ external: true
+
+ app_config-testhash:
+ file: ./app-config.json
+
+ db_config-testhash:
+ environment: dev
+ file: ./db-config.yml
+`) as ComposeSpecification;
+
+test("Add suffix to configs with environment and external", () => {
+ const composeData = load(
+ composeFileWithEnvAndExternal,
+ ) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllConfigs(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFileWithEnvAndExternal);
+});
+
+const composeFileWithTemplateDriverAndLabels = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web_config
+ target: /etc/nginx/nginx.conf
+
+ app:
+ image: node:14
+ configs:
+ - source: app_config
+ target: /usr/src/app/config.json
+
+configs:
+ web_config:
+ file: ./web-config.yml
+ template_driver: golang
+
+ app_config:
+ file: ./app-config.json
+ labels:
+ - app=frontend
+
+ db_config:
+ file: ./db-config.yml
+`;
+
+const expectedComposeFileWithTemplateDriverAndLabels = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ configs:
+ - source: web_config-testhash
+ target: /etc/nginx/nginx.conf
+
+ app:
+ image: node:14
+ configs:
+ - source: app_config-testhash
+ target: /usr/src/app/config.json
+
+configs:
+ web_config-testhash:
+ file: ./web-config.yml
+ template_driver: golang
+
+ app_config-testhash:
+ file: ./app-config.json
+ labels:
+ - app=frontend
+
+ db_config-testhash:
+ file: ./db-config.yml
+`) as ComposeSpecification;
+
+test("Add suffix to configs with template driver and labels", () => {
+ const composeData = load(
+ composeFileWithTemplateDriverAndLabels,
+ ) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllConfigs(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(
+ expectedComposeFileWithTemplateDriverAndLabels,
+ );
+});
diff --git a/data/apps/dokploy/__test__/compose/domain/labels.test.ts b/data/apps/dokploy/__test__/compose/domain/labels.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..c5f45810f97a078d152368a581bcd1123c491544
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/domain/labels.test.ts
@@ -0,0 +1,109 @@
+import type { Domain } from "@dokploy/server";
+import { createDomainLabels } from "@dokploy/server";
+import { describe, expect, it } from "vitest";
+
+describe("createDomainLabels", () => {
+ const appName = "test-app";
+ const baseDomain: Domain = {
+ host: "example.com",
+ port: 8080,
+ https: false,
+ uniqueConfigKey: 1,
+ customCertResolver: null,
+ certificateType: "none",
+ applicationId: "",
+ composeId: "",
+ domainType: "compose",
+ serviceName: "test-app",
+ domainId: "",
+ path: "/",
+ createdAt: "",
+ previewDeploymentId: "",
+ };
+
+ it("should create basic labels for web entrypoint", async () => {
+ const labels = await createDomainLabels(appName, baseDomain, "web");
+ expect(labels).toEqual([
+ "traefik.http.routers.test-app-1-web.rule=Host(`example.com`)",
+ "traefik.http.routers.test-app-1-web.entrypoints=web",
+ "traefik.http.services.test-app-1-web.loadbalancer.server.port=8080",
+ "traefik.http.routers.test-app-1-web.service=test-app-1-web",
+ ]);
+ });
+
+ it("should create labels for websecure entrypoint", async () => {
+ const labels = await createDomainLabels(appName, baseDomain, "websecure");
+ expect(labels).toEqual([
+ "traefik.http.routers.test-app-1-websecure.rule=Host(`example.com`)",
+ "traefik.http.routers.test-app-1-websecure.entrypoints=websecure",
+ "traefik.http.services.test-app-1-websecure.loadbalancer.server.port=8080",
+ "traefik.http.routers.test-app-1-websecure.service=test-app-1-websecure",
+ ]);
+ });
+
+ it("should add the path prefix if is different than / empty", async () => {
+ const labels = await createDomainLabels(
+ appName,
+ {
+ ...baseDomain,
+ path: "/hello",
+ },
+ "websecure",
+ );
+
+ expect(labels).toEqual([
+ "traefik.http.routers.test-app-1-websecure.rule=Host(`example.com`) && PathPrefix(`/hello`)",
+ "traefik.http.routers.test-app-1-websecure.entrypoints=websecure",
+ "traefik.http.services.test-app-1-websecure.loadbalancer.server.port=8080",
+ "traefik.http.routers.test-app-1-websecure.service=test-app-1-websecure",
+ ]);
+ });
+
+ it("should add redirect middleware for https on web entrypoint", async () => {
+ const httpsBaseDomain = { ...baseDomain, https: true };
+ const labels = await createDomainLabels(appName, httpsBaseDomain, "web");
+ expect(labels).toContain(
+ "traefik.http.routers.test-app-1-web.middlewares=redirect-to-https@file",
+ );
+ });
+
+ it("should add Let's Encrypt configuration for websecure with letsencrypt certificate", async () => {
+ const letsencryptDomain = {
+ ...baseDomain,
+ https: true,
+ certificateType: "letsencrypt" as const,
+ };
+ const labels = await createDomainLabels(
+ appName,
+ letsencryptDomain,
+ "websecure",
+ );
+ expect(labels).toContain(
+ "traefik.http.routers.test-app-1-websecure.tls.certresolver=letsencrypt",
+ );
+ });
+
+ it("should not add Let's Encrypt configuration for non-letsencrypt certificate", async () => {
+ const nonLetsencryptDomain = {
+ ...baseDomain,
+ https: true,
+ certificateType: "none" as const,
+ };
+ const labels = await createDomainLabels(
+ appName,
+ nonLetsencryptDomain,
+ "websecure",
+ );
+ expect(labels).not.toContain(
+ "traefik.http.routers.test-app-1-websecure.tls.certresolver=letsencrypt",
+ );
+ });
+
+ it("should handle different ports correctly", async () => {
+ const customPortDomain = { ...baseDomain, port: 3000 };
+ const labels = await createDomainLabels(appName, customPortDomain, "web");
+ expect(labels).toContain(
+ "traefik.http.services.test-app-1-web.loadbalancer.server.port=3000",
+ );
+ });
+});
diff --git a/data/apps/dokploy/__test__/compose/domain/network-root.test.ts b/data/apps/dokploy/__test__/compose/domain/network-root.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..73b850a4579144d97eb9f6a01bb414bb555ef478
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/domain/network-root.test.ts
@@ -0,0 +1,29 @@
+import { addDokployNetworkToRoot } from "@dokploy/server";
+import { describe, expect, it } from "vitest";
+
+describe("addDokployNetworkToRoot", () => {
+ it("should create network object if networks is undefined", () => {
+ const result = addDokployNetworkToRoot(undefined);
+ expect(result).toEqual({ "dokploy-network": { external: true } });
+ });
+
+ it("should add network to an empty object", () => {
+ const result = addDokployNetworkToRoot({});
+ expect(result).toEqual({ "dokploy-network": { external: true } });
+ });
+
+ it("should not modify existing network configuration", () => {
+ const existing = { "dokploy-network": { external: false } };
+ const result = addDokployNetworkToRoot(existing);
+ expect(result).toEqual({ "dokploy-network": { external: true } });
+ });
+
+ it("should add network alongside existing networks", () => {
+ const existing = { "other-network": { external: true } };
+ const result = addDokployNetworkToRoot(existing);
+ expect(result).toEqual({
+ "other-network": { external: true },
+ "dokploy-network": { external: true },
+ });
+ });
+});
diff --git a/data/apps/dokploy/__test__/compose/domain/network-service.test.ts b/data/apps/dokploy/__test__/compose/domain/network-service.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b8d03c75141ae12b8ed3ef1c062b43c6ea5d9ef8
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/domain/network-service.test.ts
@@ -0,0 +1,24 @@
+import { addDokployNetworkToService } from "@dokploy/server";
+import { describe, expect, it } from "vitest";
+
+describe("addDokployNetworkToService", () => {
+ it("should add network to an empty array", () => {
+ const result = addDokployNetworkToService([]);
+ expect(result).toEqual(["dokploy-network"]);
+ });
+
+ it("should not add duplicate network to an array", () => {
+ const result = addDokployNetworkToService(["dokploy-network"]);
+ expect(result).toEqual(["dokploy-network"]);
+ });
+
+ it("should add network to an existing array with other networks", () => {
+ const result = addDokployNetworkToService(["other-network"]);
+ expect(result).toEqual(["other-network", "dokploy-network"]);
+ });
+
+ it("should add network to an object if networks is an object", () => {
+ const result = addDokployNetworkToService({ "other-network": {} });
+ expect(result).toEqual({ "other-network": {}, "dokploy-network": {} });
+ });
+});
diff --git a/data/apps/dokploy/__test__/compose/network/network-root.test.ts b/data/apps/dokploy/__test__/compose/network/network-root.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..980502fff8ab00a5b0550b0fe89dcb0af85571c5
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/network/network-root.test.ts
@@ -0,0 +1,310 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToNetworksRoot } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFile = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend
+
+networks:
+ frontend:
+ driver: bridge
+ driver_opts:
+ com.docker.network.driver.mtu: 1200
+
+ backend:
+ driver: bridge
+ attachable: true
+
+ external_network:
+ external: true
+
+`;
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+test("Add suffix to networks root property", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.networks) {
+ return;
+ }
+ const networks = addSuffixToNetworksRoot(composeData.networks, suffix);
+
+ expect(networks).toBeDefined();
+ for (const volumeKey of Object.keys(networks)) {
+ expect(volumeKey).toContain(`-${suffix}`);
+ }
+});
+
+const composeFile2 = `
+version: "3.8"
+
+services:
+ app:
+ image: myapp:latest
+ networks:
+ - app_net
+
+networks:
+ app_net:
+ driver: bridge
+ driver_opts:
+ com.docker.network.driver.mtu: 1500
+ ipam:
+ driver: default
+ config:
+ - subnet: 172.20.0.0/16
+
+ database_net:
+ driver: overlay
+ attachable: true
+
+ monitoring_net:
+ driver: bridge
+ internal: true
+`;
+
+test("Add suffix to advanced networks root property (2 TRY)", () => {
+ const composeData = load(composeFile2) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.networks) {
+ return;
+ }
+ const networks = addSuffixToNetworksRoot(composeData.networks, suffix);
+
+ expect(networks).toBeDefined();
+ for (const networkKey of Object.keys(networks)) {
+ expect(networkKey).toContain(`-${suffix}`);
+ }
+});
+
+const composeFile3 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend
+ - backend
+
+networks:
+ frontend:
+ external:
+ name: my_external_network
+
+ backend:
+ driver: bridge
+ labels:
+ - "com.example.description=Backend network"
+ - "com.example.environment=production"
+
+ external_network:
+ external: true
+`;
+
+test("Add suffix to networks with external properties", () => {
+ const composeData = load(composeFile3) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.networks) {
+ return;
+ }
+ const networks = addSuffixToNetworksRoot(composeData.networks, suffix);
+
+ expect(networks).toBeDefined();
+ for (const networkKey of Object.keys(networks)) {
+ expect(networkKey).toContain(`-${suffix}`);
+ }
+});
+
+const composeFile4 = `
+version: "3.8"
+
+services:
+ db:
+ image: postgres:13
+ networks:
+ - db_net
+
+networks:
+ db_net:
+ driver: bridge
+ ipam:
+ config:
+ - subnet: 192.168.1.0/24
+ - gateway: 192.168.1.1
+ - aux_addresses:
+ host1: 192.168.1.2
+ host2: 192.168.1.3
+
+ external_network:
+ external: true
+`;
+
+test("Add suffix to networks with IPAM configurations", () => {
+ const composeData = load(composeFile4) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.networks) {
+ return;
+ }
+ const networks = addSuffixToNetworksRoot(composeData.networks, suffix);
+
+ expect(networks).toBeDefined();
+ for (const networkKey of Object.keys(networks)) {
+ expect(networkKey).toContain(`-${suffix}`);
+ }
+});
+
+const composeFile5 = `
+version: "3.8"
+
+services:
+ api:
+ image: myapi:latest
+ networks:
+ - api_net
+
+networks:
+ api_net:
+ driver: bridge
+ options:
+ com.docker.network.bridge.name: br0
+ enable_ipv6: true
+ ipam:
+ driver: default
+ config:
+ - subnet: "2001:db8:1::/64"
+ - gateway: "2001:db8:1::1"
+
+ external_network:
+ external: true
+`;
+
+test("Add suffix to networks with custom options", () => {
+ const composeData = load(composeFile5) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.networks) {
+ return;
+ }
+ const networks = addSuffixToNetworksRoot(composeData.networks, suffix);
+
+ expect(networks).toBeDefined();
+ for (const networkKey of Object.keys(networks)) {
+ expect(networkKey).toContain(`-${suffix}`);
+ }
+});
+
+const composeFile6 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend
+
+networks:
+ frontend:
+ driver: bridge
+ driver_opts:
+ com.docker.network.driver.mtu: 1200
+
+ backend:
+ driver: bridge
+ attachable: true
+
+ external_network:
+ external: true
+`;
+
+// Expected compose file with static suffix `testhash`
+const expectedComposeFile6 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend-testhash
+
+networks:
+ frontend-testhash:
+ driver: bridge
+ driver_opts:
+ com.docker.network.driver.mtu: 1200
+
+ backend-testhash:
+ driver: bridge
+ attachable: true
+
+ external_network-testhash:
+ external: true
+`;
+
+test("Add suffix to networks with static suffix", () => {
+ const composeData = load(composeFile6) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ if (!composeData?.networks) {
+ return;
+ }
+ const networks = addSuffixToNetworksRoot(composeData.networks, suffix);
+
+ const expectedComposeData = load(
+ expectedComposeFile6,
+ ) as ComposeSpecification;
+ expect(networks).toStrictEqual(expectedComposeData.networks);
+});
+
+const composeFile7 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - dokploy-network
+
+networks:
+ dokploy-network:
+`;
+
+test("It shoudn't add suffix to dokploy-network", () => {
+ const composeData = load(composeFile7) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.networks) {
+ return;
+ }
+ const networks = addSuffixToNetworksRoot(composeData.networks, suffix);
+
+ expect(networks).toBeDefined();
+ for (const networkKey of Object.keys(networks)) {
+ expect(networkKey).toContain("dokploy-network");
+ }
+});
diff --git a/data/apps/dokploy/__test__/compose/network/network-service.test.ts b/data/apps/dokploy/__test__/compose/network/network-service.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ee07d9de96bd1dd86c46878dd9b2592a26279e02
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/network/network-service.test.ts
@@ -0,0 +1,273 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToServiceNetworks } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFile = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend
+ - backend
+
+ api:
+ image: myapi:latest
+ networks:
+ - backend
+`;
+
+test("Add suffix to networks in services", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.services) {
+ return;
+ }
+ const services = addSuffixToServiceNetworks(composeData.services, suffix);
+ const actualComposeData = { ...composeData, services };
+
+ expect(actualComposeData?.services?.web?.networks).toContain(
+ `frontend-${suffix}`,
+ );
+
+ expect(actualComposeData?.services?.api?.networks).toContain(
+ `backend-${suffix}`,
+ );
+
+ const apiNetworks = actualComposeData?.services?.api?.networks;
+
+ expect(apiNetworks).toBeDefined();
+ expect(actualComposeData?.services?.api?.networks).toContain(
+ `backend-${suffix}`,
+ );
+});
+
+// Caso 2: Objeto con aliases
+const composeFile2 = `
+version: "3.8"
+
+services:
+ api:
+ image: myapi:latest
+ networks:
+ frontend:
+ aliases:
+ - api
+
+networks:
+ frontend:
+ driver: bridge
+`;
+
+test("Add suffix to networks in services with aliases", () => {
+ const composeData = load(composeFile2) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.services) {
+ return;
+ }
+ const services = addSuffixToServiceNetworks(composeData.services, suffix);
+ const actualComposeData = { ...composeData, services };
+
+ expect(actualComposeData.services?.api?.networks).toHaveProperty(
+ `frontend-${suffix}`,
+ );
+
+ const networkConfig = actualComposeData?.services?.api?.networks as {
+ [key: string]: { aliases?: string[] };
+ };
+ expect(networkConfig[`frontend-${suffix}`]).toBeDefined();
+ expect(networkConfig[`frontend-${suffix}`]?.aliases).toContain("api");
+
+ expect(actualComposeData.services?.api?.networks).not.toHaveProperty(
+ "frontend-ash",
+ );
+});
+
+const composeFile3 = `
+version: "3.8"
+
+services:
+ redis:
+ image: redis:alpine
+ networks:
+ backend:
+
+networks:
+ backend:
+ driver: bridge
+`;
+
+test("Add suffix to networks in services (Object with simple networks)", () => {
+ const composeData = load(composeFile3) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.services) {
+ return;
+ }
+ const services = addSuffixToServiceNetworks(composeData.services, suffix);
+ const actualComposeData = { ...composeData, services };
+
+ expect(actualComposeData.services?.redis?.networks).toHaveProperty(
+ `backend-${suffix}`,
+ );
+});
+
+const composeFileCombined = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend
+ - backend
+
+ api:
+ image: myapi:latest
+ networks:
+ frontend:
+ aliases:
+ - api
+
+ redis:
+ image: redis:alpine
+ networks:
+ backend:
+
+networks:
+ frontend:
+ driver: bridge
+
+ backend:
+ driver: bridge
+`;
+
+test("Add suffix to networks in services (combined case)", () => {
+ const composeData = load(composeFileCombined) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.services) {
+ return;
+ }
+ const services = addSuffixToServiceNetworks(composeData.services, suffix);
+ const actualComposeData = { ...composeData, services };
+
+ // Caso 1: ListOfStrings
+ expect(actualComposeData.services?.web?.networks).toContain(
+ `frontend-${suffix}`,
+ );
+ expect(actualComposeData.services?.web?.networks).toContain(
+ `backend-${suffix}`,
+ );
+
+ // Caso 2: Objeto con aliases
+ const apiNetworks = actualComposeData.services?.api?.networks as {
+ [key: string]: unknown;
+ };
+ expect(apiNetworks).toHaveProperty(`frontend-${suffix}`);
+ expect(apiNetworks[`frontend-${suffix}`]).toBeDefined();
+ expect(apiNetworks).not.toHaveProperty("frontend");
+
+ // Caso 3: Objeto con redes simples
+ const redisNetworks = actualComposeData.services?.redis?.networks;
+ expect(redisNetworks).toHaveProperty(`backend-${suffix}`);
+ expect(redisNetworks).not.toHaveProperty("backend");
+});
+
+const composeFile7 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - dokploy-network
+`;
+
+test("It shoudn't add suffix to dokploy-network in services", () => {
+ const composeData = load(composeFile7) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.services) {
+ return;
+ }
+ const networks = addSuffixToServiceNetworks(composeData.services, suffix);
+ const service = networks.web;
+
+ expect(service).toBeDefined();
+ expect(service?.networks).toContain("dokploy-network");
+});
+
+const composeFile8 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend
+ - backend
+ - dokploy-network
+
+
+ api:
+ image: myapi:latest
+ networks:
+ frontend:
+ aliases:
+ - api
+ dokploy-network:
+ aliases:
+ - api
+ redis:
+ image: redis:alpine
+ networks:
+ dokploy-network:
+ db:
+ image: myapi:latest
+ networks:
+ dokploy-network:
+ aliases:
+ - apid
+
+`;
+
+test("It shoudn't add suffix to dokploy-network in services multiples cases", () => {
+ const composeData = load(composeFile8) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.services) {
+ return;
+ }
+ const networks = addSuffixToServiceNetworks(composeData.services, suffix);
+ const service = networks.web;
+ const api = networks.api;
+ const redis = networks.redis;
+ const db = networks.db;
+
+ const dbNetworks = db?.networks as {
+ [key: string]: unknown;
+ };
+
+ const apiNetworks = api?.networks as {
+ [key: string]: unknown;
+ };
+
+ expect(service).toBeDefined();
+ expect(service?.networks).toContain("dokploy-network");
+
+ expect(redis?.networks).toHaveProperty("dokploy-network");
+ expect(dbNetworks["dokploy-network"]).toBeDefined();
+ expect(apiNetworks["dokploy-network"]).toBeDefined();
+});
diff --git a/data/apps/dokploy/__test__/compose/network/network.test.ts b/data/apps/dokploy/__test__/compose/network/network.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..39cf03958877815b46cf5a78ad84bd666b501050
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/network/network.test.ts
@@ -0,0 +1,334 @@
+import { generateRandomHash } from "@dokploy/server";
+import {
+ addSuffixToAllNetworks,
+ addSuffixToServiceNetworks,
+} from "@dokploy/server";
+import { addSuffixToNetworksRoot } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFileCombined = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend
+ - backend
+
+ api:
+ image: myapi:latest
+ networks:
+ frontend:
+ aliases:
+ - api
+
+ redis:
+ image: redis:alpine
+ networks:
+ backend:
+
+networks:
+ frontend:
+ driver: bridge
+
+ backend:
+ driver: bridge
+`;
+
+test("Add suffix to networks in services and root (combined case)", () => {
+ const composeData = load(composeFileCombined) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ // Prefijo para redes definidas en el root
+ if (composeData.networks) {
+ composeData.networks = addSuffixToNetworksRoot(
+ composeData.networks,
+ suffix,
+ );
+ }
+
+ // Prefijo para redes definidas en los servicios
+ if (composeData.services) {
+ composeData.services = addSuffixToServiceNetworks(
+ composeData.services,
+ suffix,
+ );
+ }
+
+ const actualComposeData = { ...composeData };
+
+ // Verificar redes en root
+ expect(actualComposeData.networks).toHaveProperty(`frontend-${suffix}`);
+ expect(actualComposeData.networks).toHaveProperty(`backend-${suffix}`);
+ expect(actualComposeData.networks).not.toHaveProperty("frontend");
+ expect(actualComposeData.networks).not.toHaveProperty("backend");
+
+ // Caso 1: ListOfStrings
+ expect(actualComposeData.services?.web?.networks).toContain(
+ `frontend-${suffix}`,
+ );
+ expect(actualComposeData.services?.web?.networks).toContain(
+ `backend-${suffix}`,
+ );
+
+ // Caso 2: Objeto con aliases
+ const apiNetworks = actualComposeData.services?.api?.networks as {
+ [key: string]: { aliases?: string[] };
+ };
+ expect(apiNetworks).toHaveProperty(`frontend-${suffix}`);
+ expect(apiNetworks?.[`frontend-${suffix}`]?.aliases).toContain("api");
+ expect(apiNetworks).not.toHaveProperty("frontend");
+
+ // Caso 3: Objeto con redes simples
+ const redisNetworks = actualComposeData.services?.redis?.networks;
+ expect(redisNetworks).toHaveProperty(`backend-${suffix}`);
+ expect(redisNetworks).not.toHaveProperty("backend");
+});
+
+const expectedComposeFile = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend-testhash
+ - backend-testhash
+
+ api:
+ image: myapi:latest
+ networks:
+ frontend-testhash:
+ aliases:
+ - api
+
+ redis:
+ image: redis:alpine
+ networks:
+ backend-testhash:
+
+networks:
+ frontend-testhash:
+ driver: bridge
+
+ backend-testhash:
+ driver: bridge
+`);
+
+test("Add suffix to networks in compose file", () => {
+ const composeData = load(composeFileCombined) as ComposeSpecification;
+
+ const suffix = "testhash";
+ if (!composeData?.networks) {
+ return;
+ }
+ const updatedComposeData = addSuffixToAllNetworks(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile);
+});
+
+const composeFile2 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend
+ - backend
+
+ db:
+ image: postgres:latest
+ networks:
+ backend:
+ aliases:
+ - db
+
+networks:
+ frontend:
+ external: true
+
+ backend:
+ driver: bridge
+`;
+
+const expectedComposeFile2 = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ networks:
+ - frontend-testhash
+ - backend-testhash
+
+ db:
+ image: postgres:latest
+ networks:
+ backend-testhash:
+ aliases:
+ - db
+
+networks:
+ frontend-testhash:
+ external: true
+
+ backend-testhash:
+ driver: bridge
+`);
+
+test("Add suffix to networks in compose file with external and internal networks", () => {
+ const composeData = load(composeFile2) as ComposeSpecification;
+
+ const suffix = "testhash";
+ const updatedComposeData = addSuffixToAllNetworks(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile2);
+});
+
+const composeFile3 = `
+version: "3.8"
+
+services:
+ app:
+ image: myapp:latest
+ networks:
+ frontend:
+ aliases:
+ - app
+ backend:
+
+ worker:
+ image: worker:latest
+ networks:
+ - backend
+
+networks:
+ frontend:
+ driver: bridge
+ attachable: true
+
+ backend:
+ driver: bridge
+ driver_opts:
+ com.docker.network.bridge.enable_icc: "true"
+`;
+
+const expectedComposeFile3 = load(`
+version: "3.8"
+
+services:
+ app:
+ image: myapp:latest
+ networks:
+ frontend-testhash:
+ aliases:
+ - app
+ backend-testhash:
+
+ worker:
+ image: worker:latest
+ networks:
+ - backend-testhash
+
+networks:
+ frontend-testhash:
+ driver: bridge
+ attachable: true
+
+ backend-testhash:
+ driver: bridge
+ driver_opts:
+ com.docker.network.bridge.enable_icc: "true"
+`);
+
+test("Add suffix to networks in compose file with multiple services and complex network configurations", () => {
+ const composeData = load(composeFile3) as ComposeSpecification;
+
+ const suffix = "testhash";
+ const updatedComposeData = addSuffixToAllNetworks(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile3);
+});
+
+const composeFile4 = `
+version: "3.8"
+
+services:
+ app:
+ image: myapp:latest
+ networks:
+ frontend:
+ aliases:
+ - app
+ backend:
+ dokploy-network:
+
+ worker:
+ image: worker:latest
+ networks:
+ - backend
+ - dokploy-network
+
+networks:
+ frontend:
+ driver: bridge
+ attachable: true
+
+ backend:
+ driver: bridge
+ driver_opts:
+ com.docker.network.bridge.enable_icc: "true"
+
+ dokploy-network:
+ driver: bridge
+
+`;
+
+const expectedComposeFile4 = load(`
+version: "3.8"
+
+services:
+ app:
+ image: myapp:latest
+ networks:
+ frontend-testhash:
+ aliases:
+ - app
+ backend-testhash:
+ dokploy-network:
+
+ worker:
+ image: worker:latest
+ networks:
+ - backend-testhash
+ - dokploy-network
+
+networks:
+ frontend-testhash:
+ driver: bridge
+ attachable: true
+
+ backend-testhash:
+ driver: bridge
+ driver_opts:
+ com.docker.network.bridge.enable_icc: "true"
+
+ dokploy-network:
+ driver: bridge
+
+
+
+`);
+
+test("Expect don't add suffix to dokploy-network in compose file with multiple services and complex network configurations", () => {
+ const composeData = load(composeFile4) as ComposeSpecification;
+
+ const suffix = "testhash";
+ const updatedComposeData = addSuffixToAllNetworks(composeData, suffix);
+ expect(updatedComposeData).toEqual(expectedComposeFile4);
+});
diff --git a/data/apps/dokploy/__test__/compose/secrets/secret-root.test.ts b/data/apps/dokploy/__test__/compose/secrets/secret-root.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..1b1898c59c9f10fde825a35fb481cae7a9eecce8
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/secrets/secret-root.test.ts
@@ -0,0 +1,103 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToSecretsRoot } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+const composeFileSecretsRoot = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+
+secrets:
+ db_password:
+ file: ./db_password.txt
+`;
+
+test("Add suffix to secrets in root property", () => {
+ const composeData = load(composeFileSecretsRoot) as ComposeSpecification;
+ const suffix = generateRandomHash();
+
+ if (!composeData?.secrets) {
+ return;
+ }
+ const secrets = addSuffixToSecretsRoot(composeData.secrets, suffix);
+ expect(secrets).toBeDefined();
+ if (secrets) {
+ for (const secretKey of Object.keys(secrets)) {
+ expect(secretKey).toContain(`-${suffix}`);
+ expect(secrets[secretKey]).toBeDefined();
+ }
+ }
+});
+
+const composeFileSecretsRoot1 = `
+version: "3.8"
+
+services:
+ api:
+ image: myapi:latest
+
+secrets:
+ api_key:
+ file: ./api_key.txt
+`;
+
+test("Add suffix to secrets in root property (Test 1)", () => {
+ const composeData = load(composeFileSecretsRoot1) as ComposeSpecification;
+ const suffix = generateRandomHash();
+
+ if (!composeData?.secrets) {
+ return;
+ }
+ const secrets = addSuffixToSecretsRoot(composeData.secrets, suffix);
+ expect(secrets).toBeDefined();
+
+ if (secrets) {
+ for (const secretKey of Object.keys(secrets)) {
+ expect(secretKey).toContain(`-${suffix}`);
+ expect(secrets[secretKey]).toBeDefined();
+ }
+ }
+});
+
+const composeFileSecretsRoot2 = `
+version: "3.8"
+
+services:
+ frontend:
+ image: nginx:latest
+
+secrets:
+ frontend_secret:
+ file: ./frontend_secret.txt
+ db_password:
+ external: true
+`;
+
+test("Add suffix to secrets in root property (Test 2)", () => {
+ const composeData = load(composeFileSecretsRoot2) as ComposeSpecification;
+ const suffix = generateRandomHash();
+
+ if (!composeData?.secrets) {
+ return;
+ }
+ const secrets = addSuffixToSecretsRoot(composeData.secrets, suffix);
+ expect(secrets).toBeDefined();
+
+ if (secrets) {
+ for (const secretKey of Object.keys(secrets)) {
+ expect(secretKey).toContain(`-${suffix}`);
+ expect(secrets[secretKey]).toBeDefined();
+ }
+ }
+});
diff --git a/data/apps/dokploy/__test__/compose/secrets/secret-services.test.ts b/data/apps/dokploy/__test__/compose/secrets/secret-services.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..5206bbbaf1ecd44e1ada3c625ead512734259159
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/secrets/secret-services.test.ts
@@ -0,0 +1,113 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToSecretsInServices } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFileSecretsServices = `
+version: "3.8"
+
+services:
+ db:
+ image: postgres:latest
+ secrets:
+ - db_password
+
+secrets:
+ db_password:
+ file: ./db_password.txt
+`;
+
+test("Add suffix to secrets in services", () => {
+ const composeData = load(composeFileSecretsServices) as ComposeSpecification;
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+
+ const updatedComposeData = addSuffixToSecretsInServices(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ expect(actualComposeData.services?.db?.secrets).toContain(
+ `db_password-${suffix}`,
+ );
+});
+
+const composeFileSecretsServices1 = `
+version: "3.8"
+
+services:
+ app:
+ image: node:14
+ secrets:
+ - app_secret
+
+secrets:
+ app_secret:
+ file: ./app_secret.txt
+`;
+
+test("Add suffix to secrets in services (Test 1)", () => {
+ const composeData = load(composeFileSecretsServices1) as ComposeSpecification;
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+
+ const updatedComposeData = addSuffixToSecretsInServices(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ expect(actualComposeData.services?.app?.secrets).toContain(
+ `app_secret-${suffix}`,
+ );
+});
+
+const composeFileSecretsServices2 = `
+version: "3.8"
+
+services:
+ backend:
+ image: backend:latest
+ secrets:
+ - backend_secret
+ frontend:
+ image: frontend:latest
+ secrets:
+ - frontend_secret
+
+secrets:
+ backend_secret:
+ file: ./backend_secret.txt
+ frontend_secret:
+ file: ./frontend_secret.txt
+`;
+
+test("Add suffix to secrets in services (Test 2)", () => {
+ const composeData = load(composeFileSecretsServices2) as ComposeSpecification;
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+
+ const updatedComposeData = addSuffixToSecretsInServices(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ expect(actualComposeData.services?.backend?.secrets).toContain(
+ `backend_secret-${suffix}`,
+ );
+ expect(actualComposeData.services?.frontend?.secrets).toContain(
+ `frontend_secret-${suffix}`,
+ );
+});
diff --git a/data/apps/dokploy/__test__/compose/secrets/secret.test.ts b/data/apps/dokploy/__test__/compose/secrets/secret.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d874dc5e786758043f3ce9143ab1db6b6d81100d
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/secrets/secret.test.ts
@@ -0,0 +1,159 @@
+import { addSuffixToAllSecrets } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFileCombinedSecrets = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ secrets:
+ - web_secret
+
+ app:
+ image: node:14
+ secrets:
+ - app_secret
+
+secrets:
+ web_secret:
+ file: ./web_secret.txt
+
+ app_secret:
+ file: ./app_secret.txt
+`;
+
+const expectedComposeFileCombinedSecrets = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ secrets:
+ - web_secret-testhash
+
+ app:
+ image: node:14
+ secrets:
+ - app_secret-testhash
+
+secrets:
+ web_secret-testhash:
+ file: ./web_secret.txt
+
+ app_secret-testhash:
+ file: ./app_secret.txt
+`) as ComposeSpecification;
+
+test("Add suffix to all secrets", () => {
+ const composeData = load(composeFileCombinedSecrets) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllSecrets(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFileCombinedSecrets);
+});
+
+const composeFileCombinedSecrets3 = `
+version: "3.8"
+
+services:
+ api:
+ image: myapi:latest
+ secrets:
+ - api_key
+
+ cache:
+ image: redis:latest
+ secrets:
+ - cache_secret
+
+secrets:
+ api_key:
+ file: ./api_key.txt
+ cache_secret:
+ file: ./cache_secret.txt
+`;
+
+const expectedComposeFileCombinedSecrets3 = load(`
+version: "3.8"
+
+services:
+ api:
+ image: myapi:latest
+ secrets:
+ - api_key-testhash
+
+ cache:
+ image: redis:latest
+ secrets:
+ - cache_secret-testhash
+
+secrets:
+ api_key-testhash:
+ file: ./api_key.txt
+ cache_secret-testhash:
+ file: ./cache_secret.txt
+`) as ComposeSpecification;
+
+test("Add suffix to all secrets (3rd Case)", () => {
+ const composeData = load(composeFileCombinedSecrets3) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllSecrets(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFileCombinedSecrets3);
+});
+
+const composeFileCombinedSecrets4 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ secrets:
+ - web_secret
+
+ db:
+ image: postgres:latest
+ secrets:
+ - db_password
+
+secrets:
+ web_secret:
+ file: ./web_secret.txt
+ db_password:
+ file: ./db_password.txt
+`;
+
+const expectedComposeFileCombinedSecrets4 = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ secrets:
+ - web_secret-testhash
+
+ db:
+ image: postgres:latest
+ secrets:
+ - db_password-testhash
+
+secrets:
+ web_secret-testhash:
+ file: ./web_secret.txt
+ db_password-testhash:
+ file: ./db_password.txt
+`) as ComposeSpecification;
+
+test("Add suffix to all secrets (4th Case)", () => {
+ const composeData = load(composeFileCombinedSecrets4) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllSecrets(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFileCombinedSecrets4);
+});
diff --git a/data/apps/dokploy/__test__/compose/service/service-container-name.test.ts b/data/apps/dokploy/__test__/compose/service/service-container-name.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..bcb51fd0435a80d9672ca69a13050173bf50a3be
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/service/service-container-name.test.ts
@@ -0,0 +1,59 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToServiceNames } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFile = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ container_name: web_container
+
+ api:
+ image: myapi:latest
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+test("Add suffix to service names with container_name in compose file", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToServiceNames(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ // Verificar que el nombre del contenedor ha cambiado correctamente
+ expect(actualComposeData.services?.[`web-${suffix}`]?.container_name).toBe(
+ `web_container-${suffix}`,
+ );
+ // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe
+ expect(actualComposeData.services).toHaveProperty(`web-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("web");
+
+ // Verificar que la configuración de la imagen sigue igual
+ expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe(
+ "nginx:latest",
+ );
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+});
diff --git a/data/apps/dokploy/__test__/compose/service/service-depends-on.test.ts b/data/apps/dokploy/__test__/compose/service/service-depends-on.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b27414be5330b5a375722852bbd9d569aa430952
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/service/service-depends-on.test.ts
@@ -0,0 +1,150 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToServiceNames } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+const composeFile4 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ depends_on:
+ - db
+ - api
+
+ api:
+ image: myapi:latest
+
+ db:
+ image: postgres:latest
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Add suffix to service names with depends_on (array) in compose file", () => {
+ const composeData = load(composeFile4) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToServiceNames(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe
+ expect(actualComposeData.services).toHaveProperty(`web-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("web");
+
+ // Verificar que la configuración de la imagen sigue igual
+ expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe(
+ "nginx:latest",
+ );
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+
+ // Verificar que los nombres en depends_on tienen el prefijo
+ expect(actualComposeData.services?.[`web-${suffix}`]?.depends_on).toContain(
+ `db-${suffix}`,
+ );
+ expect(actualComposeData.services?.[`web-${suffix}`]?.depends_on).toContain(
+ `api-${suffix}`,
+ );
+
+ // Verificar que los servicios `db` y `api` también tienen el prefijo
+ expect(actualComposeData.services).toHaveProperty(`db-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("db");
+ expect(actualComposeData.services?.[`db-${suffix}`]?.image).toBe(
+ "postgres:latest",
+ );
+ expect(actualComposeData.services).toHaveProperty(`api-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("api");
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+});
+
+const composeFile5 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ depends_on:
+ db:
+ condition: service_healthy
+ api:
+ condition: service_started
+
+ api:
+ image: myapi:latest
+
+ db:
+ image: postgres:latest
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Add suffix to service names with depends_on (object) in compose file", () => {
+ const composeData = load(composeFile5) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToServiceNames(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe
+ expect(actualComposeData.services).toHaveProperty(`web-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("web");
+
+ // Verificar que la configuración de la imagen sigue igual
+ expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe(
+ "nginx:latest",
+ );
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+
+ // Verificar que los nombres en depends_on tienen el prefijo
+ const webDependsOn = actualComposeData.services?.[`web-${suffix}`]
+ ?.depends_on as Record;
+ expect(webDependsOn).toHaveProperty(`db-${suffix}`);
+ expect(webDependsOn).toHaveProperty(`api-${suffix}`);
+ expect(webDependsOn[`db-${suffix}`].condition).toBe("service_healthy");
+ expect(webDependsOn[`api-${suffix}`].condition).toBe("service_started");
+
+ // Verificar que los servicios `db` y `api` también tienen el prefijo
+ expect(actualComposeData.services).toHaveProperty(`db-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("db");
+ expect(actualComposeData.services?.[`db-${suffix}`]?.image).toBe(
+ "postgres:latest",
+ );
+ expect(actualComposeData.services).toHaveProperty(`api-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("api");
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+});
diff --git a/data/apps/dokploy/__test__/compose/service/service-extends.test.ts b/data/apps/dokploy/__test__/compose/service/service-extends.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..8309a32fd4fa3d75c6b38b9a47f690da97b85cde
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/service/service-extends.test.ts
@@ -0,0 +1,131 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToServiceNames } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+const composeFile6 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ extends: base_service
+
+ api:
+ image: myapi:latest
+
+ base_service:
+ image: base:latest
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Add suffix to service names with extends (string) in compose file", () => {
+ const composeData = load(composeFile6) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToServiceNames(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe
+ expect(actualComposeData.services).toHaveProperty(`web-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("web");
+
+ // Verificar que la configuración de la imagen sigue igual
+ expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe(
+ "nginx:latest",
+ );
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+
+ // Verificar que el nombre en extends tiene el prefijo
+ expect(actualComposeData.services?.[`web-${suffix}`]?.extends).toBe(
+ `base_service-${suffix}`,
+ );
+
+ // Verificar que el servicio `base_service` también tiene el prefijo
+ expect(actualComposeData.services).toHaveProperty(`base_service-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("base_service");
+ expect(actualComposeData.services?.[`base_service-${suffix}`]?.image).toBe(
+ "base:latest",
+ );
+});
+
+const composeFile7 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ extends:
+ service: base_service
+ file: docker-compose.base.yml
+
+ api:
+ image: myapi:latest
+
+ base_service:
+ image: base:latest
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Add suffix to service names with extends (object) in compose file", () => {
+ const composeData = load(composeFile7) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToServiceNames(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe
+ expect(actualComposeData.services).toHaveProperty(`web-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("web");
+
+ // Verificar que la configuración de la imagen sigue igual
+ expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe(
+ "nginx:latest",
+ );
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+
+ // Verificar que el nombre en extends.service tiene el prefijo
+ const webExtends = actualComposeData.services?.[`web-${suffix}`]?.extends;
+ if (typeof webExtends !== "string") {
+ expect(webExtends?.service).toBe(`base_service-${suffix}`);
+ }
+
+ // Verificar que el servicio `base_service` también tiene el prefijo
+ expect(actualComposeData.services).toHaveProperty(`base_service-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("base_service");
+ expect(actualComposeData.services?.[`base_service-${suffix}`]?.image).toBe(
+ "base:latest",
+ );
+});
diff --git a/data/apps/dokploy/__test__/compose/service/service-links.test.ts b/data/apps/dokploy/__test__/compose/service/service-links.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..5f9b01ab28d524225c18d6c52c2659e4ff44970c
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/service/service-links.test.ts
@@ -0,0 +1,76 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToServiceNames } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+const composeFile2 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ links:
+ - db
+
+ api:
+ image: myapi:latest
+
+ db:
+ image: postgres:latest
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Add suffix to service names with links in compose file", () => {
+ const composeData = load(composeFile2) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToServiceNames(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe
+ expect(actualComposeData.services).toHaveProperty(`web-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("web");
+
+ // Verificar que la configuración de la imagen sigue igual
+ expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe(
+ "nginx:latest",
+ );
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+
+ // Verificar que los nombres en links tienen el prefijo
+ expect(actualComposeData.services?.[`web-${suffix}`]?.links).toContain(
+ `db-${suffix}`,
+ );
+
+ // Verificar que los servicios `db` y `api` también tienen el prefijo
+ expect(actualComposeData.services).toHaveProperty(`db-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("db");
+ expect(actualComposeData.services?.[`db-${suffix}`]?.image).toBe(
+ "postgres:latest",
+ );
+ expect(actualComposeData.services).toHaveProperty(`api-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("api");
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+});
diff --git a/data/apps/dokploy/__test__/compose/service/service-names.test.ts b/data/apps/dokploy/__test__/compose/service/service-names.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..936a32ecc2036dc88390146dee7eabe9a7756ef7
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/service/service-names.test.ts
@@ -0,0 +1,49 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToServiceNames } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+const composeFile = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+
+ api:
+ image: myapi:latest
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Add suffix to service names in compose file", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToServiceNames(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ // Verificar que los nombres de los servicios han cambiado correctamente
+ expect(actualComposeData.services).toHaveProperty(`web-${suffix}`);
+ expect(actualComposeData.services).toHaveProperty(`api-${suffix}`);
+ // Verificar que las claves originales no existen
+ expect(actualComposeData.services).not.toHaveProperty("web");
+ expect(actualComposeData.services).not.toHaveProperty("api");
+});
diff --git a/data/apps/dokploy/__test__/compose/service/service.test.ts b/data/apps/dokploy/__test__/compose/service/service.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..c6050f75a2e4fd1248398c3bd15236996ad6573d
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/service/service.test.ts
@@ -0,0 +1,375 @@
+import {
+ addSuffixToAllServiceNames,
+ addSuffixToServiceNames,
+} from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFileCombinedAllCases = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ container_name: web_container
+ links:
+ - api
+ depends_on:
+ - api
+ extends: base_service
+
+ api:
+ image: myapi:latest
+ depends_on:
+ db:
+ condition: service_healthy
+ volumes_from:
+ - db
+
+ db:
+ image: postgres:latest
+
+ base_service:
+ image: base:latest
+
+networks:
+ default:
+ driver: bridge
+`;
+
+const expectedComposeFile = load(`
+version: "3.8"
+
+services:
+ web-testhash:
+ image: nginx:latest
+ container_name: web_container-testhash
+ links:
+ - api-testhash
+ depends_on:
+ - api-testhash
+ extends: base_service-testhash
+
+ api-testhash:
+ image: myapi:latest
+ depends_on:
+ db-testhash:
+ condition: service_healthy
+ volumes_from:
+ - db-testhash
+
+ db-testhash:
+ image: postgres:latest
+
+ base_service-testhash:
+ image: base:latest
+
+networks:
+ default:
+ driver: bridge
+`);
+
+test("Add suffix to all service names in compose file", () => {
+ const composeData = load(composeFileCombinedAllCases) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ if (!composeData.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToServiceNames(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ expect(actualComposeData).toEqual(expectedComposeFile);
+});
+
+const composeFile1 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ container_name: web_container
+ depends_on:
+ - app
+ networks:
+ - frontend
+ volumes_from:
+ - data
+ links:
+ - db
+ extends:
+ service: base_service
+
+ app:
+ image: node:14
+ networks:
+ - backend
+ - frontend
+
+ db:
+ image: postgres:13
+ networks:
+ - backend
+
+ data:
+ image: busybox
+ volumes:
+ - /data
+
+ base_service:
+ image: base:latest
+
+networks:
+ frontend:
+ driver: bridge
+ backend:
+ driver: bridge
+`;
+
+const expectedComposeFile1 = load(`
+version: "3.8"
+
+services:
+ web-testhash:
+ image: nginx:latest
+ container_name: web_container-testhash
+ depends_on:
+ - app-testhash
+ networks:
+ - frontend
+ volumes_from:
+ - data-testhash
+ links:
+ - db-testhash
+ extends:
+ service: base_service-testhash
+
+ app-testhash:
+ image: node:14
+ networks:
+ - backend
+ - frontend
+
+ db-testhash:
+ image: postgres:13
+ networks:
+ - backend
+
+ data-testhash:
+ image: busybox
+ volumes:
+ - /data
+
+ base_service-testhash:
+ image: base:latest
+
+networks:
+ frontend:
+ driver: bridge
+ backend:
+ driver: bridge
+`) as ComposeSpecification;
+
+test("Add suffix to all service names in compose file 1", () => {
+ const composeData = load(composeFile1) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllServiceNames(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile1);
+});
+
+const composeFile2 = `
+version: "3.8"
+
+services:
+ frontend:
+ image: nginx:latest
+ depends_on:
+ - backend
+ networks:
+ - public
+ volumes_from:
+ - logs
+ links:
+ - cache
+ extends:
+ service: shared_service
+
+ backend:
+ image: node:14
+ networks:
+ - private
+ - public
+
+ cache:
+ image: redis:latest
+ networks:
+ - private
+
+ logs:
+ image: busybox
+ volumes:
+ - /logs
+
+ shared_service:
+ image: shared:latest
+
+networks:
+ public:
+ driver: bridge
+ private:
+ driver: bridge
+`;
+
+const expectedComposeFile2 = load(`
+version: "3.8"
+
+services:
+ frontend-testhash:
+ image: nginx:latest
+ depends_on:
+ - backend-testhash
+ networks:
+ - public
+ volumes_from:
+ - logs-testhash
+ links:
+ - cache-testhash
+ extends:
+ service: shared_service-testhash
+
+ backend-testhash:
+ image: node:14
+ networks:
+ - private
+ - public
+
+ cache-testhash:
+ image: redis:latest
+ networks:
+ - private
+
+ logs-testhash:
+ image: busybox
+ volumes:
+ - /logs
+
+ shared_service-testhash:
+ image: shared:latest
+
+networks:
+ public:
+ driver: bridge
+ private:
+ driver: bridge
+`) as ComposeSpecification;
+
+test("Add suffix to all service names in compose file 2", () => {
+ const composeData = load(composeFile2) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllServiceNames(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile2);
+});
+
+const composeFile3 = `
+version: "3.8"
+
+services:
+ service_a:
+ image: service_a:latest
+ depends_on:
+ - service_b
+ networks:
+ - net_a
+ volumes_from:
+ - data_volume
+ links:
+ - service_c
+ extends:
+ service: common_service
+
+ service_b:
+ image: service_b:latest
+ networks:
+ - net_b
+ - net_a
+
+ service_c:
+ image: service_c:latest
+ networks:
+ - net_b
+
+ data_volume:
+ image: busybox
+ volumes:
+ - /data
+
+ common_service:
+ image: common:latest
+
+networks:
+ net_a:
+ driver: bridge
+ net_b:
+ driver: bridge
+`;
+
+const expectedComposeFile3 = load(`
+version: "3.8"
+
+services:
+ service_a-testhash:
+ image: service_a:latest
+ depends_on:
+ - service_b-testhash
+ networks:
+ - net_a
+ volumes_from:
+ - data_volume-testhash
+ links:
+ - service_c-testhash
+ extends:
+ service: common_service-testhash
+
+ service_b-testhash:
+ image: service_b:latest
+ networks:
+ - net_b
+ - net_a
+
+ service_c-testhash:
+ image: service_c:latest
+ networks:
+ - net_b
+
+ data_volume-testhash:
+ image: busybox
+ volumes:
+ - /data
+
+ common_service-testhash:
+ image: common:latest
+
+networks:
+ net_a:
+ driver: bridge
+ net_b:
+ driver: bridge
+`) as ComposeSpecification;
+
+test("Add suffix to all service names in compose file 3", () => {
+ const composeData = load(composeFile3) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllServiceNames(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedComposeFile3);
+});
diff --git a/data/apps/dokploy/__test__/compose/service/sevice-volumes-from.test.ts b/data/apps/dokploy/__test__/compose/service/sevice-volumes-from.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..8066a6dd7dfd1ab62a12628cc57abb4908127391
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/service/sevice-volumes-from.test.ts
@@ -0,0 +1,78 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToServiceNames } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+const composeFile3 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ volumes_from:
+ - shared
+
+ api:
+ image: myapi:latest
+ volumes_from:
+ - shared
+
+ shared:
+ image: busybox
+ volumes:
+ - /data
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Add suffix to service names with volumes_from in compose file", () => {
+ const composeData = load(composeFile3) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+ const updatedComposeData = addSuffixToServiceNames(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe
+ expect(actualComposeData.services).toHaveProperty(`web-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("web");
+
+ // Verificar que la configuración de la imagen sigue igual
+ expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe(
+ "nginx:latest",
+ );
+ expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe(
+ "myapi:latest",
+ );
+
+ // Verificar que los nombres en volumes_from tienen el prefijo
+ expect(actualComposeData.services?.[`web-${suffix}`]?.volumes_from).toContain(
+ `shared-${suffix}`,
+ );
+ expect(actualComposeData.services?.[`api-${suffix}`]?.volumes_from).toContain(
+ `shared-${suffix}`,
+ );
+
+ // Verificar que el servicio shared también tiene el prefijo
+ expect(actualComposeData.services).toHaveProperty(`shared-${suffix}`);
+ expect(actualComposeData.services).not.toHaveProperty("shared");
+ expect(actualComposeData.services?.[`shared-${suffix}`]?.image).toBe(
+ "busybox",
+ );
+});
diff --git a/data/apps/dokploy/__test__/compose/volume/volume-2.test.ts b/data/apps/dokploy/__test__/compose/volume/volume-2.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..61cba82d3357affdb98dd4e4d6370a98e818139e
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/volume/volume-2.test.ts
@@ -0,0 +1,1174 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToAllVolumes, addSuffixToVolumesRoot } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFile = `
+services:
+ mail:
+ image: bytemark/smtp
+ restart: always
+
+ plausible_db:
+ image: postgres:14-alpine
+ restart: always
+ volumes:
+ - db-data:/var/lib/postgresql/data
+ environment:
+ - POSTGRES_PASSWORD=postgres
+
+ plausible_events_db:
+ image: clickhouse/clickhouse-server:23.3.7.5-alpine
+ restart: always
+ volumes:
+ - event-data:/var/lib/clickhouse
+ - event-logs:/var/log/clickhouse-server
+ - ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro
+ - ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro
+ ulimits:
+ nofile:
+ soft: 262144
+ hard: 262144
+
+ plausible:
+ image: plausible/analytics:v2.0
+ restart: always
+ command: sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh run"
+ depends_on:
+ - plausible_db
+ - plausible_events_db
+ - mail
+ ports:
+ - 127.0.0.1:8000:8000
+ env_file:
+ - plausible-conf.env
+ volumes:
+ - type: volume
+ source: plausible-data
+ target: /data
+
+ mysql:
+ image: mysql:5.7
+ restart: always
+ environment:
+ MYSQL_ROOT_PASSWORD: example
+ volumes:
+ - type: volume
+ source: db-data
+ target: /var/lib/mysql/data
+
+volumes:
+ db-data:
+ driver: local
+ event-data:
+ driver: local
+ event-logs:
+ driver: local
+`;
+
+const expectedDockerCompose = load(`
+services:
+ mail:
+ image: bytemark/smtp
+ restart: always
+
+ plausible_db:
+ image: postgres:14-alpine
+ restart: always
+ volumes:
+ - db-data-testhash:/var/lib/postgresql/data
+ environment:
+ - POSTGRES_PASSWORD=postgres
+
+ plausible_events_db:
+ image: clickhouse/clickhouse-server:23.3.7.5-alpine
+ restart: always
+ volumes:
+ - event-data-testhash:/var/lib/clickhouse
+ - event-logs-testhash:/var/log/clickhouse-server
+ - ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro
+ - ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro
+ ulimits:
+ nofile:
+ soft: 262144
+ hard: 262144
+
+ plausible:
+ image: plausible/analytics:v2.0
+ restart: always
+ command: sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh run"
+ depends_on:
+ - plausible_db
+ - plausible_events_db
+ - mail
+ ports:
+ - 127.0.0.1:8000:8000
+ env_file:
+ - plausible-conf.env
+ volumes:
+ - type: volume
+ source: plausible-data-testhash
+ target: /data
+
+ mysql:
+ image: mysql:5.7
+ restart: always
+ environment:
+ MYSQL_ROOT_PASSWORD: example
+ volumes:
+ - type: volume
+ source: db-data-testhash
+ target: /var/lib/mysql/data
+
+volumes:
+ db-data-testhash:
+ driver: local
+ event-data-testhash:
+ driver: local
+ event-logs-testhash:
+ driver: local
+`) as ComposeSpecification;
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+// Docker compose needs unique names for services, volumes, networks and containers
+// So base on a input which is a dockercompose file, it should replace the name with a hash and return a new dockercompose file
+test("Add suffix to volumes root property", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.volumes) {
+ return;
+ }
+ const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix);
+
+ // {
+ // 'db-data-af045046': { driver: 'local' },
+ // 'event-data-af045046': { driver: 'local' },
+ // 'event-logs-af045046': { driver: 'local' }
+ // }
+
+ expect(volumes).toBeDefined();
+ for (const volumeKey of Object.keys(volumes)) {
+ expect(volumeKey).toContain(`-${suffix}`);
+ }
+});
+
+test("Expect to change the suffix in all the possible places", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedDockerCompose);
+});
+
+const composeFile2 = `
+version: '3.8'
+services:
+ app:
+ image: myapp:latest
+ build:
+ context: .
+ dockerfile: Dockerfile
+ volumes:
+ - app-config:/usr/src/app/config
+ - ./config:/usr/src/app/config:ro
+ environment:
+ - NODE_ENV=production
+ mongo:
+ image: mongo:4.2
+ volumes:
+ - mongo-data:/data/db
+volumes:
+ app-config:
+ mongo-data:
+`;
+
+const expectedDockerCompose2 = load(`
+version: '3.8'
+services:
+ app:
+ image: myapp:latest
+ build:
+ context: .
+ dockerfile: Dockerfile
+ volumes:
+ - app-config-testhash:/usr/src/app/config
+ - ./config:/usr/src/app/config:ro
+ environment:
+ - NODE_ENV=production
+ mongo:
+ image: mongo:4.2
+ volumes:
+ - mongo-data-testhash:/data/db
+volumes:
+ app-config-testhash:
+ mongo-data-testhash:
+`) as ComposeSpecification;
+
+test("Expect to change the suffix in all the possible places (2 Try)", () => {
+ const composeData = load(composeFile2) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedDockerCompose2);
+});
+
+const composeFile3 = `
+version: '3.8'
+services:
+ app:
+ image: myapp:latest
+ build:
+ context: .
+ dockerfile: Dockerfile
+ volumes:
+ - app-config:/usr/src/app/config
+ - ./config:/usr/src/app/config:ro
+ environment:
+ - NODE_ENV=production
+ mongo:
+ image: mongo:4.2
+ volumes:
+ - mongo-data:/data/db
+volumes:
+ app-config:
+ mongo-data:
+`;
+
+const expectedDockerCompose3 = load(`
+version: '3.8'
+services:
+ app:
+ image: myapp:latest
+ build:
+ context: .
+ dockerfile: Dockerfile
+ volumes:
+ - app-config-testhash:/usr/src/app/config
+ - ./config:/usr/src/app/config:ro
+ environment:
+ - NODE_ENV=production
+ mongo:
+ image: mongo:4.2
+ volumes:
+ - mongo-data-testhash:/data/db
+volumes:
+ app-config-testhash:
+ mongo-data-testhash:
+`) as ComposeSpecification;
+
+test("Expect to change the suffix in all the possible places (3 Try)", () => {
+ const composeData = load(composeFile3) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedDockerCompose3);
+});
+
+const composeFileComplex = `
+version: "3.8"
+services:
+ studio:
+ container_name: supabase-studio
+ image: supabase/studio:20240422-5cf8f30
+ restart: unless-stopped
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "node",
+ "-e",
+ "require('http').get('http://localhost:3000/api/profile', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ depends_on:
+ analytics:
+ condition: service_healthy
+ environment:
+ STUDIO_PG_META_URL: http://meta:8080
+ POSTGRES_PASSWORD: \${POSTGRES_PASSWORD}
+ DEFAULT_ORGANIZATION_NAME: \${STUDIO_DEFAULT_ORGANIZATION}
+ DEFAULT_PROJECT_NAME: \${STUDIO_DEFAULT_PROJECT}
+ SUPABASE_URL: http://kong:8000
+ SUPABASE_PUBLIC_URL: \${SUPABASE_PUBLIC_URL}
+ SUPABASE_ANON_KEY: \${ANON_KEY}
+ SUPABASE_SERVICE_KEY: \${SERVICE_ROLE_KEY}
+ LOGFLARE_API_KEY: \${LOGFLARE_API_KEY}
+ LOGFLARE_URL: http://analytics:4000
+ NEXT_PUBLIC_ENABLE_LOGS: true
+ NEXT_ANALYTICS_BACKEND_PROVIDER: postgres
+
+ kong:
+ container_name: supabase-kong
+ image: kong:2.8.1
+ restart: unless-stopped
+ entrypoint: bash -c 'eval "echo \"$$(cat ~/temp.yml)\"" > ~/kong.yml && /docker-entrypoint.sh kong docker-start'
+ ports:
+ - \${KONG_HTTP_PORT}:8000/tcp
+ - \${KONG_HTTPS_PORT}:8443/tcp
+ depends_on:
+ analytics:
+ condition: service_healthy
+ environment:
+ KONG_DATABASE: "off"
+ KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml
+ KONG_DNS_ORDER: LAST,A,CNAME
+ KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth
+ KONG_NGINX_PROXY_PROXY_BUFFER_SIZE: 160k
+ KONG_NGINX_PROXY_PROXY_BUFFERS: 64 160k
+ SUPABASE_ANON_KEY: \${ANON_KEY}
+ SUPABASE_SERVICE_KEY: \${SERVICE_ROLE_KEY}
+ DASHBOARD_USERNAME: \${DASHBOARD_USERNAME}
+ DASHBOARD_PASSWORD: \${DASHBOARD_PASSWORD}
+ volumes:
+ - ./volumes/api/kong.yml:/home/kong/temp.yml:ro
+
+ auth:
+ container_name: supabase-auth
+ image: supabase/gotrue:v2.151.0
+ depends_on:
+ db:
+ condition: service_healthy
+ analytics:
+ condition: service_healthy
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "wget",
+ "--no-verbose",
+ "--tries=1",
+ "--spider",
+ "http://localhost:9999/health"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ restart: unless-stopped
+ environment:
+ GOTRUE_API_HOST: 0.0.0.0
+ GOTRUE_API_PORT: 9999
+ API_EXTERNAL_URL: \${API_EXTERNAL_URL}
+ GOTRUE_DB_DRIVER: postgres
+ GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ GOTRUE_SITE_URL: \${SITE_URL}
+ GOTRUE_URI_ALLOW_LIST: \${ADDITIONAL_REDIRECT_URLS}
+ GOTRUE_DISABLE_SIGNUP: \${DISABLE_SIGNUP}
+ GOTRUE_JWT_ADMIN_ROLES: service_role
+ GOTRUE_JWT_AUD: authenticated
+ GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated
+ GOTRUE_JWT_EXP: \${JWT_EXPIRY}
+ GOTRUE_JWT_SECRET: \${JWT_SECRET}
+ GOTRUE_EXTERNAL_EMAIL_ENABLED: \${ENABLE_EMAIL_SIGNUP}
+ GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED: \${ENABLE_ANONYMOUS_USERS}
+ GOTRUE_MAILER_AUTOCONFIRM: \${ENABLE_EMAIL_AUTOCONFIRM}
+ GOTRUE_SMTP_ADMIN_EMAIL: \${SMTP_ADMIN_EMAIL}
+ GOTRUE_SMTP_HOST: \${SMTP_HOST}
+ GOTRUE_SMTP_PORT: \${SMTP_PORT}
+ GOTRUE_SMTP_USER: \${SMTP_USER}
+ GOTRUE_SMTP_PASS: \${SMTP_PASS}
+ GOTRUE_SMTP_SENDER_NAME: \${SMTP_SENDER_NAME}
+ GOTRUE_MAILER_URLPATHS_INVITE: \${MAILER_URLPATHS_INVITE}
+ GOTRUE_MAILER_URLPATHS_CONFIRMATION: \${MAILER_URLPATHS_CONFIRMATION}
+ GOTRUE_MAILER_URLPATHS_RECOVERY: \${MAILER_URLPATHS_RECOVERY}
+ GOTRUE_MAILER_URLPATHS_EMAIL_CHANGE: \${MAILER_URLPATHS_EMAIL_CHANGE}
+ GOTRUE_EXTERNAL_PHONE_ENABLED: \${ENABLE_PHONE_SIGNUP}
+ GOTRUE_SMS_AUTOCONFIRM: \${ENABLE_PHONE_AUTOCONFIRM}
+
+ rest:
+ container_name: supabase-rest
+ image: postgrest/postgrest:v12.0.1
+ depends_on:
+ db:
+ condition: service_healthy
+ analytics:
+ condition: service_healthy
+ restart: unless-stopped
+ environment:
+ PGRST_DB_URI: postgres://authenticator:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ PGRST_DB_SCHEMAS: \${PGRST_DB_SCHEMAS}
+ PGRST_DB_ANON_ROLE: anon
+ PGRST_JWT_SECRET: \${JWT_SECRET}
+ PGRST_DB_USE_LEGACY_GUCS: "false"
+ PGRST_APP_SETTINGS_JWT_SECRET: \${JWT_SECRET}
+ PGRST_APP_SETTINGS_JWT_EXP: \${JWT_EXPIRY}
+ command: "postgrest"
+
+ realtime:
+ container_name: realtime-dev.supabase-realtime
+ image: supabase/realtime:v2.28.32
+ depends_on:
+ db:
+ condition: service_healthy
+ analytics:
+ condition: service_healthy
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "curl",
+ "-sSfL",
+ "--head",
+ "-o",
+ "/dev/null",
+ "-H",
+ "Authorization: Bearer \${ANON_KEY}",
+ "http://localhost:4000/api/tenants/realtime-dev/health"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ restart: unless-stopped
+ environment:
+ PORT: 4000
+ DB_HOST: \${POSTGRES_HOST}
+ DB_PORT: \${POSTGRES_PORT}
+ DB_USER: supabase_admin
+ DB_PASSWORD: \${POSTGRES_PASSWORD}
+ DB_NAME: \${POSTGRES_DB}
+ DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime'
+ DB_ENC_KEY: supabaserealtime
+ API_JWT_SECRET: \${JWT_SECRET}
+ FLY_ALLOC_ID: fly123
+ FLY_APP_NAME: realtime
+ SECRET_KEY_BASE: UpNVntn3cDxHJpq99YMc1T1AQgQpc8kfYTuRgBiYa15BLrx8etQoXz3gZv1/u2oq
+ ERL_AFLAGS: -proto_dist inet_tcp
+ ENABLE_TAILSCALE: "false"
+ DNS_NODES: "''"
+ command: >
+ sh -c "/app/bin/migrate && /app/bin/realtime eval 'Realtime.Release.seeds(Realtime.Repo)' && /app/bin/server"
+
+ storage:
+ container_name: supabase-storage
+ image: supabase/storage-api:v1.0.6
+ depends_on:
+ db:
+ condition: service_healthy
+ rest:
+ condition: service_started
+ imgproxy:
+ condition: service_started
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "wget",
+ "--no-verbose",
+ "--tries=1",
+ "--spider",
+ "http://localhost:5000/status"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ restart: unless-stopped
+ environment:
+ ANON_KEY: \${ANON_KEY}
+ SERVICE_KEY: \${SERVICE_ROLE_KEY}
+ POSTGREST_URL: http://rest:3000
+ PGRST_JWT_SECRET: \${JWT_SECRET}
+ DATABASE_URL: postgres://supabase_storage_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ FILE_SIZE_LIMIT: 52428800
+ STORAGE_BACKEND: file
+ FILE_STORAGE_BACKEND_PATH: /var/lib/storage
+ TENANT_ID: stub
+ REGION: stub
+ GLOBAL_S3_BUCKET: stub
+ ENABLE_IMAGE_TRANSFORMATION: "true"
+ IMGPROXY_URL: http://imgproxy:5001
+ volumes:
+ - ./volumes/storage:/var/lib/storage:z
+
+ imgproxy:
+ container_name: supabase-imgproxy
+ image: darthsim/imgproxy:v3.8.0
+ healthcheck:
+ test: [ "CMD", "imgproxy", "health" ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ environment:
+ IMGPROXY_BIND: ":5001"
+ IMGPROXY_LOCAL_FILESYSTEM_ROOT: /
+ IMGPROXY_USE_ETAG: "true"
+ IMGPROXY_ENABLE_WEBP_DETECTION: \${IMGPROXY_ENABLE_WEBP_DETECTION}
+ volumes:
+ - ./volumes/storage:/var/lib/storage:z
+
+ meta:
+ container_name: supabase-meta
+ image: supabase/postgres-meta:v0.80.0
+ depends_on:
+ db:
+ condition: service_healthy
+ analytics:
+ condition: service_healthy
+ restart: unless-stopped
+ environment:
+ PG_META_PORT: 8080
+ PG_META_DB_HOST: \${POSTGRES_HOST}
+ PG_META_DB_PORT: \${POSTGRES_PORT}
+ PG_META_DB_NAME: \${POSTGRES_DB}
+ PG_META_DB_USER: supabase_admin
+ PG_META_DB_PASSWORD: \${POSTGRES_PASSWORD}
+
+ functions:
+ container_name: supabase-edge-functions
+ image: supabase/edge-runtime:v1.45.2
+ restart: unless-stopped
+ depends_on:
+ analytics:
+ condition: service_healthy
+ environment:
+ JWT_SECRET: \${JWT_SECRET}
+ SUPABASE_URL: http://kong:8000
+ SUPABASE_ANON_KEY: \${ANON_KEY}
+ SUPABASE_SERVICE_ROLE_KEY: \${SERVICE_ROLE_KEY}
+ SUPABASE_DB_URL: postgresql://postgres:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ VERIFY_JWT: "\${FUNCTIONS_VERIFY_JWT}"
+ volumes:
+ - ./volumes/functions:/home/deno/functions:Z
+ command:
+ - start
+ - --main-service
+ - /home/deno/functions/main
+
+ analytics:
+ container_name: supabase-analytics
+ image: supabase/logflare:1.4.0
+ healthcheck:
+ test: [ "CMD", "curl", "http://localhost:4000/health" ]
+ timeout: 5s
+ interval: 5s
+ retries: 10
+ restart: unless-stopped
+ depends_on:
+ db:
+ condition: service_healthy
+ environment:
+ LOGFLARE_NODE_HOST: 127.0.0.1
+ DB_USERNAME: supabase_admin
+ DB_DATABASE: \${POSTGRES_DB}
+ DB_HOSTNAME: \${POSTGRES_HOST}
+ DB_PORT: \${POSTGRES_PORT}
+ DB_PASSWORD: \${POSTGRES_PASSWORD}
+ DB_SCHEMA: _analytics
+ LOGFLARE_API_KEY: \${LOGFLARE_API_KEY}
+ LOGFLARE_SINGLE_TENANT: true
+ LOGFLARE_SUPABASE_MODE: true
+ LOGFLARE_MIN_CLUSTER_SIZE: 1
+ POSTGRES_BACKEND_URL: postgresql://supabase_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ POSTGRES_BACKEND_SCHEMA: _analytics
+ LOGFLARE_FEATURE_FLAG_OVERRIDE: multibackend=true
+ ports:
+ - 4000:4000
+
+ db:
+ container_name: supabase-db
+ image: supabase/postgres:15.1.1.41
+ healthcheck:
+ test: pg_isready -U postgres -h localhost
+ interval: 5s
+ timeout: 5s
+ retries: 10
+ depends_on:
+ vector:
+ condition: service_healthy
+ command:
+ - postgres
+ - -c
+ - config_file=/etc/postgresql/postgresql.conf
+ - -c
+ - log_min_messages=fatal
+ restart: unless-stopped
+ ports:
+ - \${POSTGRES_PORT}:\${POSTGRES_PORT}
+ environment:
+ POSTGRES_HOST: /var/run/postgresql
+ PGPORT: \${POSTGRES_PORT}
+ POSTGRES_PORT: \${POSTGRES_PORT}
+ PGPASSWORD: \${POSTGRES_PASSWORD}
+ POSTGRES_PASSWORD: \${POSTGRES_PASSWORD}
+ PGDATABASE: \${POSTGRES_DB}
+ POSTGRES_DB: \${POSTGRES_DB}
+ JWT_SECRET: \${JWT_SECRET}
+ JWT_EXP: \${JWT_EXPIRY}
+ volumes:
+ - ./volumes/db/realtime.sql:/docker-entrypoint-initdb.d/migrations/99-realtime.sql:Z
+ - ./volumes/db/webhooks.sql:/docker-entrypoint-initdb.d/init-scripts/98-webhooks.sql:Z
+ - ./volumes/db/roles.sql:/docker-entrypoint-initdb.d/init-scripts/99-roles.sql:Z
+ - ./volumes/db/jwt.sql:/docker-entrypoint-initdb.d/init-scripts/99-jwt.sql:Z
+ - ./volumes/db/data:/var/lib/postgresql/data:Z
+ - ./volumes/db/logs.sql:/docker-entrypoint-initdb.d/migrations/99-logs.sql:Z
+ - db-config:/etc/postgresql-custom
+
+ vector:
+ container_name: supabase-vector
+ image: timberio/vector:0.28.1-alpine
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "wget",
+ "--no-verbose",
+ "--tries=1",
+ "--spider",
+ "http://vector:9001/health"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ volumes:
+ - ./volumes/logs/vector.yml:/etc/vector/vector.yml:ro
+ - "\${DOCKER_SOCKET_LOCATION}:/var/run/docker.sock:ro"
+ environment:
+ LOGFLARE_API_KEY: \${LOGFLARE_API_KEY}
+ command: [ "--config", "etc/vector/vector.yml" ]
+
+volumes:
+ db-config:
+`;
+
+const expectedDockerComposeComplex = load(`
+version: "3.8"
+services:
+ studio:
+ container_name: supabase-studio
+ image: supabase/studio:20240422-5cf8f30
+ restart: unless-stopped
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "node",
+ "-e",
+ "require('http').get('http://localhost:3000/api/profile', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ depends_on:
+ analytics:
+ condition: service_healthy
+ environment:
+ STUDIO_PG_META_URL: http://meta:8080
+ POSTGRES_PASSWORD: \${POSTGRES_PASSWORD}
+ DEFAULT_ORGANIZATION_NAME: \${STUDIO_DEFAULT_ORGANIZATION}
+ DEFAULT_PROJECT_NAME: \${STUDIO_DEFAULT_PROJECT}
+ SUPABASE_URL: http://kong:8000
+ SUPABASE_PUBLIC_URL: \${SUPABASE_PUBLIC_URL}
+ SUPABASE_ANON_KEY: \${ANON_KEY}
+ SUPABASE_SERVICE_KEY: \${SERVICE_ROLE_KEY}
+ LOGFLARE_API_KEY: \${LOGFLARE_API_KEY}
+ LOGFLARE_URL: http://analytics:4000
+ NEXT_PUBLIC_ENABLE_LOGS: true
+ NEXT_ANALYTICS_BACKEND_PROVIDER: postgres
+
+ kong:
+ container_name: supabase-kong
+ image: kong:2.8.1
+ restart: unless-stopped
+ entrypoint: bash -c 'eval "echo \"$$(cat ~/temp.yml)\"" > ~/kong.yml && /docker-entrypoint.sh kong docker-start'
+ ports:
+ - \${KONG_HTTP_PORT}:8000/tcp
+ - \${KONG_HTTPS_PORT}:8443/tcp
+ depends_on:
+ analytics:
+ condition: service_healthy
+ environment:
+ KONG_DATABASE: "off"
+ KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml
+ KONG_DNS_ORDER: LAST,A,CNAME
+ KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth
+ KONG_NGINX_PROXY_PROXY_BUFFER_SIZE: 160k
+ KONG_NGINX_PROXY_PROXY_BUFFERS: 64 160k
+ SUPABASE_ANON_KEY: \${ANON_KEY}
+ SUPABASE_SERVICE_KEY: \${SERVICE_ROLE_KEY}
+ DASHBOARD_USERNAME: \${DASHBOARD_USERNAME}
+ DASHBOARD_PASSWORD: \${DASHBOARD_PASSWORD}
+ volumes:
+ - ./volumes/api/kong.yml:/home/kong/temp.yml:ro
+
+ auth:
+ container_name: supabase-auth
+ image: supabase/gotrue:v2.151.0
+ depends_on:
+ db:
+ condition: service_healthy
+ analytics:
+ condition: service_healthy
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "wget",
+ "--no-verbose",
+ "--tries=1",
+ "--spider",
+ "http://localhost:9999/health"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ restart: unless-stopped
+ environment:
+ GOTRUE_API_HOST: 0.0.0.0
+ GOTRUE_API_PORT: 9999
+ API_EXTERNAL_URL: \${API_EXTERNAL_URL}
+ GOTRUE_DB_DRIVER: postgres
+ GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ GOTRUE_SITE_URL: \${SITE_URL}
+ GOTRUE_URI_ALLOW_LIST: \${ADDITIONAL_REDIRECT_URLS}
+ GOTRUE_DISABLE_SIGNUP: \${DISABLE_SIGNUP}
+ GOTRUE_JWT_ADMIN_ROLES: service_role
+ GOTRUE_JWT_AUD: authenticated
+ GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated
+ GOTRUE_JWT_EXP: \${JWT_EXPIRY}
+ GOTRUE_JWT_SECRET: \${JWT_SECRET}
+ GOTRUE_EXTERNAL_EMAIL_ENABLED: \${ENABLE_EMAIL_SIGNUP}
+ GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED: \${ENABLE_ANONYMOUS_USERS}
+ GOTRUE_MAILER_AUTOCONFIRM: \${ENABLE_EMAIL_AUTOCONFIRM}
+ GOTRUE_SMTP_ADMIN_EMAIL: \${SMTP_ADMIN_EMAIL}
+ GOTRUE_SMTP_HOST: \${SMTP_HOST}
+ GOTRUE_SMTP_PORT: \${SMTP_PORT}
+ GOTRUE_SMTP_USER: \${SMTP_USER}
+ GOTRUE_SMTP_PASS: \${SMTP_PASS}
+ GOTRUE_SMTP_SENDER_NAME: \${SMTP_SENDER_NAME}
+ GOTRUE_MAILER_URLPATHS_INVITE: \${MAILER_URLPATHS_INVITE}
+ GOTRUE_MAILER_URLPATHS_CONFIRMATION: \${MAILER_URLPATHS_CONFIRMATION}
+ GOTRUE_MAILER_URLPATHS_RECOVERY: \${MAILER_URLPATHS_RECOVERY}
+ GOTRUE_MAILER_URLPATHS_EMAIL_CHANGE: \${MAILER_URLPATHS_EMAIL_CHANGE}
+ GOTRUE_EXTERNAL_PHONE_ENABLED: \${ENABLE_PHONE_SIGNUP}
+ GOTRUE_SMS_AUTOCONFIRM: \${ENABLE_PHONE_AUTOCONFIRM}
+
+ rest:
+ container_name: supabase-rest
+ image: postgrest/postgrest:v12.0.1
+ depends_on:
+ db:
+ condition: service_healthy
+ analytics:
+ condition: service_healthy
+ restart: unless-stopped
+ environment:
+ PGRST_DB_URI: postgres://authenticator:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ PGRST_DB_SCHEMAS: \${PGRST_DB_SCHEMAS}
+ PGRST_DB_ANON_ROLE: anon
+ PGRST_JWT_SECRET: \${JWT_SECRET}
+ PGRST_DB_USE_LEGACY_GUCS: "false"
+ PGRST_APP_SETTINGS_JWT_SECRET: \${JWT_SECRET}
+ PGRST_APP_SETTINGS_JWT_EXP: \${JWT_EXPIRY}
+ command: "postgrest"
+
+ realtime:
+ container_name: realtime-dev.supabase-realtime
+ image: supabase/realtime:v2.28.32
+ depends_on:
+ db:
+ condition: service_healthy
+ analytics:
+ condition: service_healthy
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "curl",
+ "-sSfL",
+ "--head",
+ "-o",
+ "/dev/null",
+ "-H",
+ "Authorization: Bearer \${ANON_KEY}",
+ "http://localhost:4000/api/tenants/realtime-dev/health"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ restart: unless-stopped
+ environment:
+ PORT: 4000
+ DB_HOST: \${POSTGRES_HOST}
+ DB_PORT: \${POSTGRES_PORT}
+ DB_USER: supabase_admin
+ DB_PASSWORD: \${POSTGRES_PASSWORD}
+ DB_NAME: \${POSTGRES_DB}
+ DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime'
+ DB_ENC_KEY: supabaserealtime
+ API_JWT_SECRET: \${JWT_SECRET}
+ FLY_ALLOC_ID: fly123
+ FLY_APP_NAME: realtime
+ SECRET_KEY_BASE: UpNVntn3cDxHJpq99YMc1T1AQgQpc8kfYTuRgBiYa15BLrx8etQoXz3gZv1/u2oq
+ ERL_AFLAGS: -proto_dist inet_tcp
+ ENABLE_TAILSCALE: "false"
+ DNS_NODES: "''"
+ command: >
+ sh -c "/app/bin/migrate && /app/bin/realtime eval 'Realtime.Release.seeds(Realtime.Repo)' && /app/bin/server"
+
+ storage:
+ container_name: supabase-storage
+ image: supabase/storage-api:v1.0.6
+ depends_on:
+ db:
+ condition: service_healthy
+ rest:
+ condition: service_started
+ imgproxy:
+ condition: service_started
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "wget",
+ "--no-verbose",
+ "--tries=1",
+ "--spider",
+ "http://localhost:5000/status"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ restart: unless-stopped
+ environment:
+ ANON_KEY: \${ANON_KEY}
+ SERVICE_KEY: \${SERVICE_ROLE_KEY}
+ POSTGREST_URL: http://rest:3000
+ PGRST_JWT_SECRET: \${JWT_SECRET}
+ DATABASE_URL: postgres://supabase_storage_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ FILE_SIZE_LIMIT: 52428800
+ STORAGE_BACKEND: file
+ FILE_STORAGE_BACKEND_PATH: /var/lib/storage
+ TENANT_ID: stub
+ REGION: stub
+ GLOBAL_S3_BUCKET: stub
+ ENABLE_IMAGE_TRANSFORMATION: "true"
+ IMGPROXY_URL: http://imgproxy:5001
+ volumes:
+ - ./volumes/storage:/var/lib/storage:z
+
+ imgproxy:
+ container_name: supabase-imgproxy
+ image: darthsim/imgproxy:v3.8.0
+ healthcheck:
+ test: [ "CMD", "imgproxy", "health" ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ environment:
+ IMGPROXY_BIND: ":5001"
+ IMGPROXY_LOCAL_FILESYSTEM_ROOT: /
+ IMGPROXY_USE_ETAG: "true"
+ IMGPROXY_ENABLE_WEBP_DETECTION: \${IMGPROXY_ENABLE_WEBP_DETECTION}
+ volumes:
+ - ./volumes/storage:/var/lib/storage:z
+
+ meta:
+ container_name: supabase-meta
+ image: supabase/postgres-meta:v0.80.0
+ depends_on:
+ db:
+ condition: service_healthy
+ analytics:
+ condition: service_healthy
+ restart: unless-stopped
+ environment:
+ PG_META_PORT: 8080
+ PG_META_DB_HOST: \${POSTGRES_HOST}
+ PG_META_DB_PORT: \${POSTGRES_PORT}
+ PG_META_DB_NAME: \${POSTGRES_DB}
+ PG_META_DB_USER: supabase_admin
+ PG_META_DB_PASSWORD: \${POSTGRES_PASSWORD}
+
+ functions:
+ container_name: supabase-edge-functions
+ image: supabase/edge-runtime:v1.45.2
+ restart: unless-stopped
+ depends_on:
+ analytics:
+ condition: service_healthy
+ environment:
+ JWT_SECRET: \${JWT_SECRET}
+ SUPABASE_URL: http://kong:8000
+ SUPABASE_ANON_KEY: \${ANON_KEY}
+ SUPABASE_SERVICE_ROLE_KEY: \${SERVICE_ROLE_KEY}
+ SUPABASE_DB_URL: postgresql://postgres:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ VERIFY_JWT: "\${FUNCTIONS_VERIFY_JWT}"
+ volumes:
+ - ./volumes/functions:/home/deno/functions:Z
+ command:
+ - start
+ - --main-service
+ - /home/deno/functions/main
+
+ analytics:
+ container_name: supabase-analytics
+ image: supabase/logflare:1.4.0
+ healthcheck:
+ test: [ "CMD", "curl", "http://localhost:4000/health" ]
+ timeout: 5s
+ interval: 5s
+ retries: 10
+ restart: unless-stopped
+ depends_on:
+ db:
+ condition: service_healthy
+ environment:
+ LOGFLARE_NODE_HOST: 127.0.0.1
+ DB_USERNAME: supabase_admin
+ DB_DATABASE: \${POSTGRES_DB}
+ DB_HOSTNAME: \${POSTGRES_HOST}
+ DB_PORT: \${POSTGRES_PORT}
+ DB_PASSWORD: \${POSTGRES_PASSWORD}
+ DB_SCHEMA: _analytics
+ LOGFLARE_API_KEY: \${LOGFLARE_API_KEY}
+ LOGFLARE_SINGLE_TENANT: true
+ LOGFLARE_SUPABASE_MODE: true
+ LOGFLARE_MIN_CLUSTER_SIZE: 1
+ POSTGRES_BACKEND_URL: postgresql://supabase_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB}
+ POSTGRES_BACKEND_SCHEMA: _analytics
+ LOGFLARE_FEATURE_FLAG_OVERRIDE: multibackend=true
+ ports:
+ - 4000:4000
+
+ db:
+ container_name: supabase-db
+ image: supabase/postgres:15.1.1.41
+ healthcheck:
+ test: pg_isready -U postgres -h localhost
+ interval: 5s
+ timeout: 5s
+ retries: 10
+ depends_on:
+ vector:
+ condition: service_healthy
+ command:
+ - postgres
+ - -c
+ - config_file=/etc/postgresql/postgresql.conf
+ - -c
+ - log_min_messages=fatal
+ restart: unless-stopped
+ ports:
+ - \${POSTGRES_PORT}:\${POSTGRES_PORT}
+ environment:
+ POSTGRES_HOST: /var/run/postgresql
+ PGPORT: \${POSTGRES_PORT}
+ POSTGRES_PORT: \${POSTGRES_PORT}
+ PGPASSWORD: \${POSTGRES_PASSWORD}
+ POSTGRES_PASSWORD: \${POSTGRES_PASSWORD}
+ PGDATABASE: \${POSTGRES_DB}
+ POSTGRES_DB: \${POSTGRES_DB}
+ JWT_SECRET: \${JWT_SECRET}
+ JWT_EXP: \${JWT_EXPIRY}
+ volumes:
+ - ./volumes/db/realtime.sql:/docker-entrypoint-initdb.d/migrations/99-realtime.sql:Z
+ - ./volumes/db/webhooks.sql:/docker-entrypoint-initdb.d/init-scripts/98-webhooks.sql:Z
+ - ./volumes/db/roles.sql:/docker-entrypoint-initdb.d/init-scripts/99-roles.sql:Z
+ - ./volumes/db/jwt.sql:/docker-entrypoint-initdb.d/init-scripts/99-jwt.sql:Z
+ - ./volumes/db/data:/var/lib/postgresql/data:Z
+ - ./volumes/db/logs.sql:/docker-entrypoint-initdb.d/migrations/99-logs.sql:Z
+ - db-config-testhash:/etc/postgresql-custom
+
+ vector:
+ container_name: supabase-vector
+ image: timberio/vector:0.28.1-alpine
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "wget",
+ "--no-verbose",
+ "--tries=1",
+ "--spider",
+ "http://vector:9001/health"
+ ]
+ timeout: 5s
+ interval: 5s
+ retries: 3
+ volumes:
+ - ./volumes/logs/vector.yml:/etc/vector/vector.yml:ro
+ - \${DOCKER_SOCKET_LOCATION}:/var/run/docker.sock:ro
+ environment:
+ LOGFLARE_API_KEY: \${LOGFLARE_API_KEY}
+ command: [ "--config", "etc/vector/vector.yml" ]
+
+volumes:
+ db-config-testhash:
+`);
+
+test("Expect to change the suffix in all the possible places (4 Try)", () => {
+ const composeData = load(composeFileComplex) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedDockerComposeComplex);
+});
+
+const composeFileExample1 = `
+version: "3.8"
+services:
+ web:
+ image: nginx:latest
+ ports:
+ - "80:80"
+ networks:
+ - frontend
+ volumes:
+ - web-data:/var/www/html
+ - ./nginx.conf:/etc/nginx/nginx.conf:ro
+
+ app:
+ image: node:14
+ depends_on:
+ - db
+ networks:
+ - backend
+ - frontend
+ volumes:
+ - app-data:/usr/src/app
+ - ./src:/usr/src/app/src
+
+ db:
+ image: postgres:13
+ environment:
+ POSTGRES_PASSWORD: example
+ networks:
+ - backend
+ volumes:
+ - db-data:/var/lib/postgresql/data
+
+networks:
+ frontend:
+ driver: bridge
+ backend:
+ driver: bridge
+
+volumes:
+ web-data:
+ app-data:
+ db-data:
+`;
+
+const expectedDockerComposeExample1 = load(`
+version: "3.8"
+services:
+ web:
+ image: nginx:latest
+ ports:
+ - "80:80"
+ networks:
+ - frontend
+ volumes:
+ - web-data-testhash:/var/www/html
+ - ./nginx.conf:/etc/nginx/nginx.conf:ro
+
+ app:
+ image: node:14
+ depends_on:
+ - db
+ networks:
+ - backend
+ - frontend
+ volumes:
+ - app-data-testhash:/usr/src/app
+ - ./src:/usr/src/app/src
+
+ db:
+ image: postgres:13
+ environment:
+ POSTGRES_PASSWORD: example
+ networks:
+ - backend
+ volumes:
+ - db-data-testhash:/var/lib/postgresql/data
+
+networks:
+ frontend:
+ driver: bridge
+ backend:
+ driver: bridge
+
+volumes:
+ web-data-testhash:
+ app-data-testhash:
+ db-data-testhash:
+`) as ComposeSpecification;
+
+test("Expect to change the suffix in all the possible places (5 Try)", () => {
+ const composeData = load(composeFileExample1) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedDockerComposeExample1);
+});
+
+const composeFileBackrest = `
+services:
+ backrest:
+ image: garethgeorge/backrest:v1.7.3
+ restart: unless-stopped
+ ports:
+ - 9898
+ environment:
+ - BACKREST_PORT=9898
+ - BACKREST_DATA=/data
+ - BACKREST_CONFIG=/config/config.json
+ - XDG_CACHE_HOME=/cache
+ - TZ=\${TZ}
+ volumes:
+ - backrest/data:/data
+ - backrest/config:/config
+ - backrest/cache:/cache
+ - /:/userdata:ro
+
+volumes:
+ backrest:
+ backrest-cache:
+`;
+
+const expectedDockerComposeBackrest = load(`
+services:
+ backrest:
+ image: garethgeorge/backrest:v1.7.3
+ restart: unless-stopped
+ ports:
+ - 9898
+ environment:
+ - BACKREST_PORT=9898
+ - BACKREST_DATA=/data
+ - BACKREST_CONFIG=/config/config.json
+ - XDG_CACHE_HOME=/cache
+ - TZ=\${TZ}
+ volumes:
+ - backrest-testhash/data:/data
+ - backrest-testhash/config:/config
+ - backrest-testhash/cache:/cache
+ - /:/userdata:ro
+
+volumes:
+ backrest-testhash:
+ backrest-cache-testhash:
+`) as ComposeSpecification;
+
+test("Should handle volume paths with subdirectories correctly", () => {
+ const composeData = load(composeFileBackrest) as ComposeSpecification;
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+
+ expect(updatedComposeData).toEqual(expectedDockerComposeBackrest);
+});
diff --git a/data/apps/dokploy/__test__/compose/volume/volume-root.test.ts b/data/apps/dokploy/__test__/compose/volume/volume-root.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d91cb64d3a9fa0690ac4c19571125bc5403f2c66
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/volume/volume-root.test.ts
@@ -0,0 +1,195 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToVolumesRoot } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFile = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ volumes:
+ - web_data:/var/lib/nginx/data
+
+volumes:
+ web_data:
+ driver: local
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+test("Add suffix to volumes in root property", () => {
+ const composeData = load(composeFile) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.volumes) {
+ return;
+ }
+ const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix);
+ expect(volumes).toBeDefined();
+ for (const volumeKey of Object.keys(volumes)) {
+ expect(volumeKey).toContain(`-${suffix}`);
+ expect(volumes[volumeKey]).toBeDefined();
+ }
+});
+
+const composeFile2 = `
+version: "3.8"
+
+services:
+ app:
+ image: node:latest
+ volumes:
+ - app_data:/var/lib/app/data
+
+volumes:
+ app_data:
+ driver: local
+ driver_opts:
+ type: nfs
+ o: addr=10.0.0.1,rw
+ device: ":/exported/path"
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Add suffix to volumes in root property (Case 2)", () => {
+ const composeData = load(composeFile2) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.volumes) {
+ return;
+ }
+ const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix);
+ expect(volumes).toBeDefined();
+ for (const volumeKey of Object.keys(volumes)) {
+ expect(volumeKey).toContain(`-${suffix}`);
+ expect(volumes[volumeKey]).toBeDefined();
+ }
+});
+
+const composeFile3 = `
+version: "3.8"
+
+services:
+ db:
+ image: postgres:latest
+ volumes:
+ - db_data:/var/lib/postgresql/data
+
+volumes:
+ db_data:
+ external: true
+
+networks:
+ default:
+ driver: bridge
+`;
+
+test("Add suffix to volumes in root property (Case 3)", () => {
+ const composeData = load(composeFile3) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData?.volumes) {
+ return;
+ }
+ const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix);
+
+ expect(volumes).toBeDefined();
+ for (const volumeKey of Object.keys(volumes)) {
+ expect(volumeKey).toContain(`-${suffix}`);
+ expect(volumes[volumeKey]).toBeDefined();
+ }
+});
+
+const composeFile4 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+
+ app:
+ image: node:latest
+
+ db:
+ image: postgres:latest
+
+volumes:
+ web_data:
+ driver: local
+
+ app_data:
+ driver: local
+ driver_opts:
+ type: nfs
+ o: addr=10.0.0.1,rw
+ device: ":/exported/path"
+
+ db_data:
+ external: true
+
+
+`;
+
+// Expected compose file con el prefijo `testhash`
+const expectedComposeFile4 = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+
+ app:
+ image: node:latest
+
+ db:
+ image: postgres:latest
+
+volumes:
+ web_data-testhash:
+ driver: local
+
+ app_data-testhash:
+ driver: local
+ driver_opts:
+ type: nfs
+ o: addr=10.0.0.1,rw
+ device: ":/exported/path"
+
+ db_data-testhash:
+ external: true
+
+
+`) as ComposeSpecification;
+
+test("Add suffix to volumes in root property", () => {
+ const composeData = load(composeFile4) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ if (!composeData?.volumes) {
+ return;
+ }
+ const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix);
+ const updatedComposeData = { ...composeData, volumes };
+
+ // Verificar que el resultado coincide con el archivo esperado
+ expect(updatedComposeData).toEqual(expectedComposeFile4);
+});
diff --git a/data/apps/dokploy/__test__/compose/volume/volume-services.test.ts b/data/apps/dokploy/__test__/compose/volume/volume-services.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..04a1a45ae8b4ab4f9f97544354b539d281bffbba
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/volume/volume-services.test.ts
@@ -0,0 +1,81 @@
+import { generateRandomHash } from "@dokploy/server";
+import { addSuffixToVolumesInServices } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+test("Generate random hash with 8 characters", () => {
+ const hash = generateRandomHash();
+
+ expect(hash).toBeDefined();
+ expect(hash.length).toBe(8);
+});
+
+const composeFile1 = `
+version: "3.8"
+
+services:
+ db:
+ image: postgres:latest
+ volumes:
+ - db_data:/var/lib/postgresql/data
+`;
+
+test("Add suffix to volumes declared directly in services", () => {
+ const composeData = load(composeFile1) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+
+ const updatedComposeData = addSuffixToVolumesInServices(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+ expect(actualComposeData.services?.db?.volumes).toContain(
+ `db_data-${suffix}:/var/lib/postgresql/data`,
+ );
+});
+
+const composeFileTypeVolume = `
+version: "3.8"
+
+services:
+ db:
+ image: postgres:latest
+ volumes:
+ - type: volume
+ source: db-test
+ target: /var/lib/postgresql/data
+
+volumes:
+ db-test:
+ driver: local
+`;
+
+test("Add suffix to volumes declared directly in services (Case 2)", () => {
+ const composeData = load(composeFileTypeVolume) as ComposeSpecification;
+
+ const suffix = generateRandomHash();
+
+ if (!composeData.services) {
+ return;
+ }
+
+ const updatedComposeData = addSuffixToVolumesInServices(
+ composeData.services,
+ suffix,
+ );
+ const actualComposeData = { ...composeData, services: updatedComposeData };
+
+ expect(actualComposeData.services?.db?.volumes).toEqual([
+ {
+ type: "volume",
+ source: `db-test-${suffix}`,
+ target: "/var/lib/postgresql/data",
+ },
+ ]);
+});
diff --git a/data/apps/dokploy/__test__/compose/volume/volume.test.ts b/data/apps/dokploy/__test__/compose/volume/volume.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..6c43447623cd957c2531a26a3b37c1c8def69ea3
--- /dev/null
+++ b/data/apps/dokploy/__test__/compose/volume/volume.test.ts
@@ -0,0 +1,284 @@
+import { addSuffixToAllVolumes } from "@dokploy/server";
+import type { ComposeSpecification } from "@dokploy/server";
+import { load } from "js-yaml";
+import { expect, test } from "vitest";
+
+const composeFileTypeVolume = `
+version: "3.8"
+
+services:
+ db1:
+ image: postgres:latest
+ volumes:
+ - "db-test:/var/lib/postgresql/data"
+ db2:
+ image: postgres:latest
+ volumes:
+ - type: volume
+ source: db-test
+ target: /var/lib/postgresql/data
+
+volumes:
+ db-test:
+ driver: local
+`;
+
+const expectedComposeFileTypeVolume = load(`
+version: "3.8"
+
+services:
+ db1:
+ image: postgres:latest
+ volumes:
+ - "db-test-testhash:/var/lib/postgresql/data"
+ db2:
+ image: postgres:latest
+ volumes:
+ - type: volume
+ source: db-test-testhash
+ target: /var/lib/postgresql/data
+
+volumes:
+ db-test-testhash:
+ driver: local
+`) as ComposeSpecification;
+
+test("Add suffix to volumes with type: volume in services", () => {
+ const composeData = load(composeFileTypeVolume) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+ const actualComposeData = { ...composeData, ...updatedComposeData };
+
+ expect(actualComposeData).toEqual(expectedComposeFileTypeVolume);
+});
+
+const composeFileTypeVolume1 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ volumes:
+ - "web-data:/var/www/html"
+ - type: volume
+ source: web-logs
+ target: /var/log/nginx
+
+volumes:
+ web-data:
+ driver: local
+ web-logs:
+ driver: local
+`;
+
+const expectedComposeFileTypeVolume1 = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ volumes:
+ - "web-data-testhash:/var/www/html"
+ - type: volume
+ source: web-logs-testhash
+ target: /var/log/nginx
+
+volumes:
+ web-data-testhash:
+ driver: local
+ web-logs-testhash:
+ driver: local
+`) as ComposeSpecification;
+
+test("Add suffix to mixed volumes in services", () => {
+ const composeData = load(composeFileTypeVolume1) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+ const actualComposeData = { ...composeData, ...updatedComposeData };
+
+ expect(actualComposeData).toEqual(expectedComposeFileTypeVolume1);
+});
+
+const composeFileTypeVolume2 = `
+version: "3.8"
+
+services:
+ app:
+ image: node:latest
+ volumes:
+ - "app-data:/usr/src/app"
+ - type: volume
+ source: app-logs
+ target: /var/log/app
+ volume:
+ nocopy: true
+
+volumes:
+ app-data:
+ driver: local
+ app-logs:
+ driver: local
+ driver_opts:
+ o: bind
+ type: none
+ device: /path/to/app/logs
+`;
+
+const expectedComposeFileTypeVolume2 = load(`
+version: "3.8"
+
+services:
+ app:
+ image: node:latest
+ volumes:
+ - "app-data-testhash:/usr/src/app"
+ - type: volume
+ source: app-logs-testhash
+ target: /var/log/app
+ volume:
+ nocopy: true
+
+volumes:
+ app-data-testhash:
+ driver: local
+ app-logs-testhash:
+ driver: local
+ driver_opts:
+ o: bind
+ type: none
+ device: /path/to/app/logs
+`) as ComposeSpecification;
+
+test("Add suffix to complex volume configurations in services", () => {
+ const composeData = load(composeFileTypeVolume2) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+ const actualComposeData = { ...composeData, ...updatedComposeData };
+
+ expect(actualComposeData).toEqual(expectedComposeFileTypeVolume2);
+});
+
+const composeFileTypeVolume3 = `
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ volumes:
+ - "web-data:/usr/share/nginx/html"
+ - type: volume
+ source: web-logs
+ target: /var/log/nginx
+ volume:
+ nocopy: true
+
+ api:
+ image: node:latest
+ volumes:
+ - "api-data:/usr/src/app"
+ - type: volume
+ source: api-logs
+ target: /var/log/app
+ volume:
+ nocopy: true
+ - type: volume
+ source: shared-logs
+ target: /shared/logs
+
+volumes:
+ web-data:
+ driver: local
+ web-logs:
+ driver: local
+ driver_opts:
+ o: bind
+ type: none
+ device: /path/to/web/logs
+
+ api-data:
+ driver: local
+ api-logs:
+ driver: local
+ driver_opts:
+ o: bind
+ type: none
+ device: /path/to/api/logs
+
+ shared-logs:
+ driver: local
+ driver_opts:
+ o: bind
+ type: none
+ device: /path/to/shared/logs
+`;
+
+const expectedComposeFileTypeVolume3 = load(`
+version: "3.8"
+
+services:
+ web:
+ image: nginx:latest
+ volumes:
+ - "web-data-testhash:/usr/share/nginx/html"
+ - type: volume
+ source: web-logs-testhash
+ target: /var/log/nginx
+ volume:
+ nocopy: true
+
+ api:
+ image: node:latest
+ volumes:
+ - "api-data-testhash:/usr/src/app"
+ - type: volume
+ source: api-logs-testhash
+ target: /var/log/app
+ volume:
+ nocopy: true
+ - type: volume
+ source: shared-logs-testhash
+ target: /shared/logs
+
+volumes:
+ web-data-testhash:
+ driver: local
+ web-logs-testhash:
+ driver: local
+ driver_opts:
+ o: bind
+ type: none
+ device: /path/to/web/logs
+
+ api-data-testhash:
+ driver: local
+ api-logs-testhash:
+ driver: local
+ driver_opts:
+ o: bind
+ type: none
+ device: /path/to/api/logs
+
+ shared-logs-testhash:
+ driver: local
+ driver_opts:
+ o: bind
+ type: none
+ device: /path/to/shared/logs
+`) as ComposeSpecification;
+
+test("Add suffix to complex nested volumes configuration in services", () => {
+ const composeData = load(composeFileTypeVolume3) as ComposeSpecification;
+
+ const suffix = "testhash";
+
+ const updatedComposeData = addSuffixToAllVolumes(composeData, suffix);
+ const actualComposeData = { ...composeData, ...updatedComposeData };
+
+ expect(actualComposeData).toEqual(expectedComposeFileTypeVolume3);
+});
diff --git a/data/apps/dokploy/__test__/deploy/github.test.ts b/data/apps/dokploy/__test__/deploy/github.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..18d7619abfdec1a121c60159dce513557ecb4bd1
--- /dev/null
+++ b/data/apps/dokploy/__test__/deploy/github.test.ts
@@ -0,0 +1,98 @@
+import { extractCommitMessage } from "@/pages/api/deploy/[refreshToken]";
+import { describe, expect, it } from "vitest";
+
+describe("GitHub Webhook Skip CI", () => {
+ const mockGithubHeaders = {
+ "x-github-event": "push",
+ };
+
+ const createMockBody = (message: string) => ({
+ head_commit: {
+ message,
+ },
+ });
+
+ const skipKeywords = [
+ "[skip ci]",
+ "[ci skip]",
+ "[no ci]",
+ "[skip actions]",
+ "[actions skip]",
+ ];
+
+ it("should detect skip keywords in commit message", () => {
+ for (const keyword of skipKeywords) {
+ const message = `feat: add new feature ${keyword}`;
+ const commitMessage = extractCommitMessage(
+ mockGithubHeaders,
+ createMockBody(message),
+ );
+ expect(commitMessage.includes(keyword)).toBe(true);
+ }
+ });
+
+ it("should not detect skip keywords in normal commit message", () => {
+ const message = "feat: add new feature";
+ const commitMessage = extractCommitMessage(
+ mockGithubHeaders,
+ createMockBody(message),
+ );
+ for (const keyword of skipKeywords) {
+ expect(commitMessage.includes(keyword)).toBe(false);
+ }
+ });
+
+ it("should handle different webhook sources", () => {
+ // GitHub
+ expect(
+ extractCommitMessage(
+ { "x-github-event": "push" },
+ { head_commit: { message: "[skip ci] test" } },
+ ),
+ ).toBe("[skip ci] test");
+
+ // GitLab
+ expect(
+ extractCommitMessage(
+ { "x-gitlab-event": "push" },
+ { commits: [{ message: "[skip ci] test" }] },
+ ),
+ ).toBe("[skip ci] test");
+
+ // Bitbucket
+ expect(
+ extractCommitMessage(
+ { "x-event-key": "repo:push" },
+ {
+ push: {
+ changes: [{ new: { target: { message: "[skip ci] test" } } }],
+ },
+ },
+ ),
+ ).toBe("[skip ci] test");
+
+ // Gitea
+ expect(
+ extractCommitMessage(
+ { "x-gitea-event": "push" },
+ { commits: [{ message: "[skip ci] test" }] },
+ ),
+ ).toBe("[skip ci] test");
+ });
+
+ it("should handle missing commit message", () => {
+ expect(extractCommitMessage(mockGithubHeaders, {})).toBe("NEW COMMIT");
+ expect(extractCommitMessage({ "x-gitlab-event": "push" }, {})).toBe(
+ "NEW COMMIT",
+ );
+ expect(
+ extractCommitMessage(
+ { "x-event-key": "repo:push" },
+ { push: { changes: [] } },
+ ),
+ ).toBe("NEW COMMIT");
+ expect(extractCommitMessage({ "x-gitea-event": "push" }, {})).toBe(
+ "NEW COMMIT",
+ );
+ });
+});
diff --git a/data/apps/dokploy/__test__/drop/drop.test.test.ts b/data/apps/dokploy/__test__/drop/drop.test.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b18d7b4b1f8958866cea05a5f9df31c9c9d1dfb8
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/drop.test.test.ts
@@ -0,0 +1,217 @@
+import fs from "node:fs/promises";
+import path from "node:path";
+import { paths } from "@dokploy/server/constants";
+const { APPLICATIONS_PATH } = paths();
+import type { ApplicationNested } from "@dokploy/server";
+import { unzipDrop } from "@dokploy/server";
+import AdmZip from "adm-zip";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("@dokploy/server/constants", async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ // @ts-ignore
+ ...actual,
+ paths: () => ({
+ APPLICATIONS_PATH: "./__test__/drop/zips/output",
+ }),
+ };
+});
+
+if (typeof window === "undefined") {
+ const undici = require("undici");
+ globalThis.File = undici.File as any;
+ globalThis.FileList = undici.FileList as any;
+}
+
+const baseApp: ApplicationNested = {
+ applicationId: "",
+ herokuVersion: "",
+ giteaBranch: "",
+ giteaBuildPath: "",
+ giteaId: "",
+ giteaOwner: "",
+ giteaRepository: "",
+ cleanCache: false,
+ watchPaths: [],
+ enableSubmodules: false,
+ applicationStatus: "done",
+ triggerType: "push",
+ appName: "",
+ autoDeploy: true,
+ serverId: "",
+ registryUrl: "",
+ branch: null,
+ dockerBuildStage: "",
+ isPreviewDeploymentsActive: false,
+ previewBuildArgs: null,
+ previewCertificateType: "none",
+ previewCustomCertResolver: null,
+ previewEnv: null,
+ previewHttps: false,
+ previewPath: "/",
+ previewPort: 3000,
+ previewLimit: 0,
+ previewWildcard: "",
+ project: {
+ env: "",
+ organizationId: "",
+ name: "",
+ description: "",
+ createdAt: "",
+ projectId: "",
+ },
+ buildArgs: null,
+ buildPath: "/",
+ gitlabPathNamespace: "",
+ buildType: "nixpacks",
+ bitbucketBranch: "",
+ bitbucketBuildPath: "",
+ bitbucketId: "",
+ bitbucketRepository: "",
+ bitbucketOwner: "",
+ githubId: "",
+ gitlabProjectId: 0,
+ gitlabBranch: "",
+ gitlabBuildPath: "",
+ gitlabId: "",
+ gitlabRepository: "",
+ gitlabOwner: "",
+ command: null,
+ cpuLimit: null,
+ cpuReservation: null,
+ createdAt: "",
+ customGitBranch: "",
+ customGitBuildPath: "",
+ customGitSSHKeyId: null,
+ customGitUrl: "",
+ description: "",
+ dockerfile: null,
+ dockerImage: null,
+ dropBuildPath: null,
+ enabled: null,
+ env: null,
+ healthCheckSwarm: null,
+ labelsSwarm: null,
+ memoryLimit: null,
+ memoryReservation: null,
+ modeSwarm: null,
+ mounts: [],
+ name: "",
+ networkSwarm: null,
+ owner: null,
+ password: null,
+ placementSwarm: null,
+ ports: [],
+ projectId: "",
+ publishDirectory: null,
+ isStaticSpa: null,
+ redirects: [],
+ refreshToken: "",
+ registry: null,
+ registryId: null,
+ replicas: 1,
+ repository: null,
+ restartPolicySwarm: null,
+ rollbackConfigSwarm: null,
+ security: [],
+ sourceType: "git",
+ subtitle: null,
+ title: null,
+ updateConfigSwarm: null,
+ username: null,
+ dockerContextPath: null,
+};
+
+describe("unzipDrop using real zip files", () => {
+ // const { APPLICATIONS_PATH } = paths();
+ beforeAll(async () => {
+ await fs.rm(APPLICATIONS_PATH, { recursive: true, force: true });
+ });
+
+ afterAll(async () => {
+ await fs.rm(APPLICATIONS_PATH, { recursive: true, force: true });
+ });
+
+ it("should correctly extract a zip with a single root folder", async () => {
+ baseApp.appName = "single-file";
+ // const appName = "single-file";
+ try {
+ const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code");
+ const zip = new AdmZip("./__test__/drop/zips/single-file.zip");
+ console.log(`Output Path: ${outputPath}`);
+ const zipBuffer = zip.toBuffer();
+ const file = new File([zipBuffer], "single.zip");
+ await unzipDrop(file, baseApp);
+ const files = await fs.readdir(outputPath, { withFileTypes: true });
+ expect(files.some((f) => f.name === "test.txt")).toBe(true);
+ } catch (err) {
+ console.log(err);
+ } finally {
+ }
+ });
+});
+
+// it("should correctly extract a zip with a single root folder and a subfolder", async () => {
+// baseApp.appName = "folderwithfile";
+// // const appName = "folderwithfile";
+// const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code");
+// const zip = new AdmZip("./__test__/drop/zips/folder-with-file.zip");
+
+// const zipBuffer = zip.toBuffer();
+// const file = new File([zipBuffer], "single.zip");
+// await unzipDrop(file, baseApp);
+
+// const files = await fs.readdir(outputPath, { withFileTypes: true });
+// expect(files.some((f) => f.name === "folder1.txt")).toBe(true);
+// });
+
+// it("should correctly extract a zip with multiple root folders", async () => {
+// baseApp.appName = "two-folders";
+// // const appName = "two-folders";
+// const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code");
+// const zip = new AdmZip("./__test__/drop/zips/two-folders.zip");
+
+// const zipBuffer = zip.toBuffer();
+// const file = new File([zipBuffer], "single.zip");
+// await unzipDrop(file, baseApp);
+
+// const files = await fs.readdir(outputPath, { withFileTypes: true });
+
+// expect(files.some((f) => f.name === "folder1")).toBe(true);
+// expect(files.some((f) => f.name === "folder2")).toBe(true);
+// });
+
+// it("should correctly extract a zip with a single root with a file", async () => {
+// baseApp.appName = "nested";
+// // const appName = "nested";
+// const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code");
+// const zip = new AdmZip("./__test__/drop/zips/nested.zip");
+
+// const zipBuffer = zip.toBuffer();
+// const file = new File([zipBuffer], "single.zip");
+// await unzipDrop(file, baseApp);
+
+// const files = await fs.readdir(outputPath, { withFileTypes: true });
+
+// expect(files.some((f) => f.name === "folder1")).toBe(true);
+// expect(files.some((f) => f.name === "folder2")).toBe(true);
+// expect(files.some((f) => f.name === "folder3")).toBe(true);
+// });
+
+// it("should correctly extract a zip with a single root with a folder", async () => {
+// baseApp.appName = "folder-with-sibling-file";
+// // const appName = "folder-with-sibling-file";
+// const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code");
+// const zip = new AdmZip("./__test__/drop/zips/folder-with-sibling-file.zip");
+
+// const zipBuffer = zip.toBuffer();
+// const file = new File([zipBuffer], "single.zip");
+// await unzipDrop(file, baseApp);
+
+// const files = await fs.readdir(outputPath, { withFileTypes: true });
+
+// expect(files.some((f) => f.name === "folder1")).toBe(true);
+// expect(files.some((f) => f.name === "test.txt")).toBe(true);
+// });
+// });
diff --git a/data/apps/dokploy/__test__/drop/zips/folder-with-file.zip b/data/apps/dokploy/__test__/drop/zips/folder-with-file.zip
new file mode 100644
index 0000000000000000000000000000000000000000..3c522a9463a50e2c579e8b609806e1d418a51a43
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/zips/folder-with-file.zip
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c753d11eb45c2e64b74669db775e9e217ff5ac251732d05229146c6537d96900
+size 378
diff --git a/data/apps/dokploy/__test__/drop/zips/folder-with-sibling-file.zip b/data/apps/dokploy/__test__/drop/zips/folder-with-sibling-file.zip
new file mode 100644
index 0000000000000000000000000000000000000000..1298657002349b6f7a3b98380a63f88afd6807b9
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/zips/folder-with-sibling-file.zip
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:82d3367c279bb6292c0ffcfb0ed76958de77014e5c6562b1506b9bd71e53cbbd
+size 560
diff --git a/data/apps/dokploy/__test__/drop/zips/folder1/folder1.txt b/data/apps/dokploy/__test__/drop/zips/folder1/folder1.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b6b61b0bb8e2ad699a01c8ad60f3f6898bfef388
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/zips/folder1/folder1.txt
@@ -0,0 +1 @@
+Gogogogogogo
\ No newline at end of file
diff --git a/data/apps/dokploy/__test__/drop/zips/folder2/folder2.txt b/data/apps/dokploy/__test__/drop/zips/folder2/folder2.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3270d3de7dd881aba13e40cbf7f70d2a2ebe5e53
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/zips/folder2/folder2.txt
@@ -0,0 +1 @@
+gogogogogog
\ No newline at end of file
diff --git a/data/apps/dokploy/__test__/drop/zips/folder3/file3.txt b/data/apps/dokploy/__test__/drop/zips/folder3/file3.txt
new file mode 100644
index 0000000000000000000000000000000000000000..80474b746ebfd01f0d6629d884c17da3e610c983
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/zips/folder3/file3.txt
@@ -0,0 +1 @@
+gogogogogogogogogo
\ No newline at end of file
diff --git a/data/apps/dokploy/__test__/drop/zips/nested.zip b/data/apps/dokploy/__test__/drop/zips/nested.zip
new file mode 100644
index 0000000000000000000000000000000000000000..9df350a88eef7469b2b244550e7378ecbb34c1bc
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/zips/nested.zip
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8b8387b34768406e0554e659dfb86a63bd4f2c1c79dd9624caa5055536e7de82
+size 1270
diff --git a/data/apps/dokploy/__test__/drop/zips/single-file.zip b/data/apps/dokploy/__test__/drop/zips/single-file.zip
new file mode 100644
index 0000000000000000000000000000000000000000..f27c892c53c1d337017114a6d8dbad10d88a5b2d
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/zips/single-file.zip
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b0229e960bcc6000edb6df21c8894d3922817937994d23838ed9428bd62ada51
+size 204
diff --git a/data/apps/dokploy/__test__/drop/zips/test.txt b/data/apps/dokploy/__test__/drop/zips/test.txt
new file mode 100644
index 0000000000000000000000000000000000000000..79f2fde0070c0ea423a4a84ac81bbb4f486e538e
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/zips/test.txt
@@ -0,0 +1 @@
+dsafasdfasdf
\ No newline at end of file
diff --git a/data/apps/dokploy/__test__/drop/zips/two-folders.zip b/data/apps/dokploy/__test__/drop/zips/two-folders.zip
new file mode 100644
index 0000000000000000000000000000000000000000..80621c481d084b1a297dfd5fb65b7648227006f2
--- /dev/null
+++ b/data/apps/dokploy/__test__/drop/zips/two-folders.zip
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3cdb32e9036129b0beb5c5ef00df71bf7f406a8c096851dc92ca094aebe00187
+size 734
diff --git a/data/apps/dokploy/__test__/env/shared.test.ts b/data/apps/dokploy/__test__/env/shared.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..4a8448aa9d78da6588194acca9a85f7c1819e6f4
--- /dev/null
+++ b/data/apps/dokploy/__test__/env/shared.test.ts
@@ -0,0 +1,179 @@
+import { prepareEnvironmentVariables } from "@dokploy/server/index";
+import { describe, expect, it } from "vitest";
+
+const projectEnv = `
+ENVIRONMENT=staging
+DATABASE_URL=postgres://postgres:postgres@localhost:5432/project_db
+PORT=3000
+`;
+const serviceEnv = `
+ENVIRONMENT=\${{project.ENVIRONMENT}}
+DATABASE_URL=\${{project.DATABASE_URL}}
+SERVICE_PORT=4000
+`;
+
+describe("prepareEnvironmentVariables", () => {
+ it("resolves project variables correctly", () => {
+ const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv);
+
+ expect(resolved).toEqual([
+ "ENVIRONMENT=staging",
+ "DATABASE_URL=postgres://postgres:postgres@localhost:5432/project_db",
+ "SERVICE_PORT=4000",
+ ]);
+ });
+
+ it("handles undefined project variables", () => {
+ const incompleteProjectEnv = `
+ NODE_ENV=production
+ `;
+
+ const invalidServiceEnv = `
+ UNDEFINED_VAR=\${{project.UNDEFINED_VAR}}
+ `;
+
+ expect(
+ () =>
+ prepareEnvironmentVariables(invalidServiceEnv, incompleteProjectEnv), // Cambiado el orden
+ ).toThrow("Invalid project environment variable: project.UNDEFINED_VAR");
+ });
+ it("allows service-specific variables to override project variables", () => {
+ const serviceSpecificEnv = `
+ ENVIRONMENT=production
+ DATABASE_URL=\${{project.DATABASE_URL}}
+ `;
+
+ const resolved = prepareEnvironmentVariables(
+ serviceSpecificEnv,
+ projectEnv,
+ );
+
+ expect(resolved).toEqual([
+ "ENVIRONMENT=production", // Overrides project variable
+ "DATABASE_URL=postgres://postgres:postgres@localhost:5432/project_db",
+ ]);
+ });
+
+ it("resolves complex references for dynamic endpoints", () => {
+ const projectEnv = `
+BASE_URL=https://api.example.com
+API_VERSION=v1
+PORT=8000
+`;
+ const serviceEnv = `
+API_ENDPOINT=\${{project.BASE_URL}}/\${{project.API_VERSION}}/endpoint
+SERVICE_PORT=9000
+`;
+ const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv);
+
+ expect(resolved).toEqual([
+ "API_ENDPOINT=https://api.example.com/v1/endpoint",
+ "SERVICE_PORT=9000",
+ ]);
+ });
+
+ it("handles missing project variables gracefully", () => {
+ const projectEnv = `
+PORT=8080
+`;
+ const serviceEnv = `
+MISSING_VAR=\${{project.MISSING_KEY}}
+SERVICE_PORT=3000
+`;
+
+ expect(() => prepareEnvironmentVariables(serviceEnv, projectEnv)).toThrow(
+ "Invalid project environment variable: project.MISSING_KEY",
+ );
+ });
+
+ it("overrides project variables with service-specific values", () => {
+ const projectEnv = `
+ENVIRONMENT=staging
+DATABASE_URL=postgres://project:project@localhost:5432/project_db
+`;
+ const serviceEnv = `
+ENVIRONMENT=\${{project.ENVIRONMENT}}
+DATABASE_URL=postgres://service:service@localhost:5432/service_db
+SERVICE_NAME=my-service
+`;
+ const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv);
+
+ expect(resolved).toEqual([
+ "ENVIRONMENT=staging",
+ "DATABASE_URL=postgres://service:service@localhost:5432/service_db",
+ "SERVICE_NAME=my-service",
+ ]);
+ });
+
+ it("handles project variables with normal and unusual characters", () => {
+ const projectEnv = `
+ENVIRONMENT=PRODUCTION
+`;
+
+ // Needs to be in quotes
+ const serviceEnv = `
+NODE_ENV=\${{project.ENVIRONMENT}}
+SPECIAL_VAR="$^@$^@#$^@!#$@#$-\${{project.ENVIRONMENT}}"
+`;
+
+ const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv);
+
+ expect(resolved).toEqual([
+ "NODE_ENV=PRODUCTION",
+ "SPECIAL_VAR=$^@$^@#$^@!#$@#$-PRODUCTION",
+ ]);
+ });
+
+ it("handles complex cases with multiple references, special characters, and spaces", () => {
+ const projectEnv = `
+ENVIRONMENT=STAGING
+APP_NAME=MyApp
+`;
+
+ const serviceEnv = `
+NODE_ENV=\${{project.ENVIRONMENT}}
+COMPLEX_VAR="Prefix-$#^!@-\${{project.ENVIRONMENT}}--\${{project.APP_NAME}} Suffix "
+`;
+ const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv);
+
+ expect(resolved).toEqual([
+ "NODE_ENV=STAGING",
+ "COMPLEX_VAR=Prefix-$#^!@-STAGING--MyApp Suffix ",
+ ]);
+ });
+
+ it("handles references enclosed in single quotes", () => {
+ const projectEnv = `
+ ENVIRONMENT=STAGING
+ APP_NAME=MyApp
+ `;
+
+ const serviceEnv = `
+ NODE_ENV='\${{project.ENVIRONMENT}}'
+ COMPLEX_VAR='Prefix-$#^!@-\${{project.ENVIRONMENT}}--\${{project.APP_NAME}} Suffix'
+ `;
+ const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv);
+
+ expect(resolved).toEqual([
+ "NODE_ENV=STAGING",
+ "COMPLEX_VAR=Prefix-$#^!@-STAGING--MyApp Suffix",
+ ]);
+ });
+
+ it("handles double and single quotes combined", () => {
+ const projectEnv = `
+ENVIRONMENT=PRODUCTION
+APP_NAME=MyApp
+`;
+ const serviceEnv = `
+NODE_ENV="'\${{project.ENVIRONMENT}}'"
+COMPLEX_VAR="'Prefix \"DoubleQuoted\" and \${{project.APP_NAME}}'"
+`;
+ const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv);
+
+ expect(resolved).toEqual([
+ "NODE_ENV='PRODUCTION'",
+ "COMPLEX_VAR='Prefix \"DoubleQuoted\" and MyApp'",
+ ]);
+ });
+});
diff --git a/data/apps/dokploy/__test__/requests/request.test.ts b/data/apps/dokploy/__test__/requests/request.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..997bd9ec5f4c1a03ddd0f9a073b5d57a968f8a6a
--- /dev/null
+++ b/data/apps/dokploy/__test__/requests/request.test.ts
@@ -0,0 +1,56 @@
+import { parseRawConfig, processLogs } from "@dokploy/server";
+import { describe, expect, it } from "vitest";
+const sampleLogEntry = `{"ClientAddr":"172.19.0.1:56732","ClientHost":"172.19.0.1","ClientPort":"56732","ClientUsername":"-","DownstreamContentSize":0,"DownstreamStatus":304,"Duration":14729375,"OriginContentSize":0,"OriginDuration":14051833,"OriginStatus":304,"Overhead":677542,"RequestAddr":"s222-umami-c381af.traefik.me","RequestContentSize":0,"RequestCount":122,"RequestHost":"s222-umami-c381af.traefik.me","RequestMethod":"GET","RequestPath":"/dashboard?_rsc=1rugv","RequestPort":"-","RequestProtocol":"HTTP/1.1","RequestScheme":"http","RetryAttempts":0,"RouterName":"s222-umami-60e104-47-web@docker","ServiceAddr":"10.0.1.15:3000","ServiceName":"s222-umami-60e104-47-web@docker","ServiceURL":{"Scheme":"http","Opaque":"","User":null,"Host":"10.0.1.15:3000","Path":"","RawPath":"","ForceQuery":false,"RawQuery":"","Fragment":"","RawFragment":""},"StartLocal":"2024-08-25T04:34:37.306691884Z","StartUTC":"2024-08-25T04:34:37.306691884Z","entryPointName":"web","level":"info","msg":"","time":"2024-08-25T04:34:37Z"}`;
+
+describe("processLogs", () => {
+ it("should process a single log entry correctly", () => {
+ const result = processLogs(sampleLogEntry);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({
+ hour: "2024-08-25T04:00:00Z",
+ count: 1,
+ });
+ });
+
+ it("should process multiple log entries and group by hour", () => {
+ const sampleLogEntry = `{"ClientAddr":"172.19.0.1:58094","ClientHost":"172.19.0.1","ClientPort":"58094","ClientUsername":"-","DownstreamContentSize":50,"DownstreamStatus":200,"Duration":35914250,"OriginContentSize":50,"OriginDuration":35817959,"OriginStatus":200,"Overhead":96291,"RequestAddr":"s222-pocketbase-f4a6e5.traefik.me","RequestContentSize":0,"RequestCount":991,"RequestHost":"s222-pocketbase-f4a6e5.traefik.me","RequestMethod":"GET","RequestPath":"/api/logs/stats?filter=","RequestPort":"-","RequestProtocol":"HTTP/1.1","RequestScheme":"http","RetryAttempts":0,"RouterName":"s222-pocketbase-e94e25-44-web@docker","ServiceAddr":"10.0.1.12:80","ServiceName":"s222-pocketbase-e94e25-44-web@docker","ServiceURL":{"Scheme":"http","Opaque":"","User":null,"Host":"10.0.1.12:80","Path":"","RawPath":"","ForceQuery":false,"RawQuery":"","Fragment":"","RawFragment":""},"StartLocal":"2024-08-25T17:44:29.274072471Z","StartUTC":"2024-08-25T17:44:29.274072471Z","entryPointName":"web","level":"info","msg":"","time":"2024-08-25T17:44:29Z"}
+{"ClientAddr":"172.19.0.1:58108","ClientHost":"172.19.0.1","ClientPort":"58108","ClientUsername":"-","DownstreamContentSize":30975,"DownstreamStatus":200,"Duration":31406458,"OriginContentSize":30975,"OriginDuration":31046791,"OriginStatus":200,"Overhead":359667,"RequestAddr":"s222-pocketbase-f4a6e5.traefik.me","RequestContentSize":0,"RequestCount":992,"RequestHost":"s222-pocketbase-f4a6e5.traefik.me","RequestMethod":"GET","RequestPath":"/api/logs?page=1\u0026perPage=50\u0026sort=-rowid\u0026skipTotal=1\u0026filter=","RequestPort":"-","RequestProtocol":"HTTP/1.1","RequestScheme":"http","RetryAttempts":0,"RouterName":"s222-pocketbase-e94e25-44-web@docker","ServiceAddr":"10.0.1.12:80","ServiceName":"s222-pocketbase-e94e25-44-web@docker","ServiceURL":{"Scheme":"http","Opaque":"","User":null,"Host":"10.0.1.12:80","Path":"","RawPath":"","ForceQuery":false,"RawQuery":"","Fragment":"","RawFragment":""},"StartLocal":"2024-08-25T17:44:29.278990221Z","StartUTC":"2024-08-25T17:44:29.278990221Z","entryPointName":"web","level":"info","msg":"","time":"2024-08-25T17:44:29Z"}
+`;
+
+ const result = processLogs(sampleLogEntry);
+ expect(result).toHaveLength(1);
+ expect(result).toEqual([{ hour: "2024-08-25T17:00:00Z", count: 2 }]);
+ });
+
+ it("should return an empty array for empty input", () => {
+ expect(processLogs("")).toEqual([]);
+ expect(processLogs(null as any)).toEqual([]);
+ expect(processLogs(undefined as any)).toEqual([]);
+ });
+
+ // it("should parse a single log entry correctly", () => {
+ // const result = parseRawConfig(sampleLogEntry);
+ // expect(result).toHaveLength(1);
+ // expect(result.data[0]).toHaveProperty("ClientAddr", "172.19.0.1:56732");
+ // expect(result.data[0]).toHaveProperty(
+ // "StartUTC",
+ // "2024-08-25T04:34:37.306691884Z",
+ // );
+ // });
+
+ it("should parse multiple log entries", () => {
+ const multipleEntries = `${sampleLogEntry}\n${sampleLogEntry}`;
+ const result = parseRawConfig(multipleEntries);
+ expect(result.data).toHaveLength(2);
+
+ for (const entry of result.data) {
+ expect(entry).toHaveProperty("ClientAddr", "172.19.0.1:56732");
+ }
+ });
+
+ it("should handle whitespace and empty lines", () => {
+ const entryWithWhitespace = `\n${sampleLogEntry}\n\n${sampleLogEntry}\n`;
+ const result = parseRawConfig(entryWithWhitespace);
+ expect(result.data).toHaveLength(2);
+ });
+});
diff --git a/data/apps/dokploy/__test__/templates/config.template.test.ts b/data/apps/dokploy/__test__/templates/config.template.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..202abdf2d6535dafea4b930f7d7014789e83bc57
--- /dev/null
+++ b/data/apps/dokploy/__test__/templates/config.template.test.ts
@@ -0,0 +1,497 @@
+import type { Schema } from "@dokploy/server/templates";
+import type { CompleteTemplate } from "@dokploy/server/templates/processors";
+import { processTemplate } from "@dokploy/server/templates/processors";
+import { describe, expect, it } from "vitest";
+
+describe("processTemplate", () => {
+ // Mock schema for testing
+ const mockSchema: Schema = {
+ projectName: "test",
+ serverIp: "127.0.0.1",
+ };
+
+ describe("variables processing", () => {
+ it("should process basic variables with utility functions", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {
+ main_domain: "${domain}",
+ secret_base: "${base64:64}",
+ totp_key: "${base64:32}",
+ password: "${password:32}",
+ hash: "${hash:16}",
+ },
+ config: {
+ domains: [],
+ env: {},
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.envs).toHaveLength(0);
+ expect(result.domains).toHaveLength(0);
+ expect(result.mounts).toHaveLength(0);
+ });
+
+ it("should allow referencing variables in other variables", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {
+ main_domain: "${domain}",
+ api_domain: "api.${main_domain}",
+ },
+ config: {
+ domains: [],
+ env: {},
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.envs).toHaveLength(0);
+ expect(result.domains).toHaveLength(0);
+ expect(result.mounts).toHaveLength(0);
+ });
+
+ it("should allow creation of real jwt secret", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {
+ jwt_secret: "cQsdycq1hDLopQonF6jUTqgQc5WEZTwWLL02J6XJ",
+ anon_payload: JSON.stringify({
+ role: "tester",
+ iss: "dockploy",
+ iat: "${timestamps:2025-01-01T00:00:00Z}",
+ exp: "${timestamps:2030-01-01T00:00:00Z}",
+ }),
+ anon_key: "${jwt:jwt_secret:anon_payload}",
+ },
+ config: {
+ domains: [],
+ env: {
+ ANON_KEY: "${anon_key}",
+ },
+ },
+ };
+ const result = processTemplate(template, mockSchema);
+ expect(result.envs).toHaveLength(1);
+ expect(result.envs).toContain(
+ "ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOiIxNzM1Njg5NjAwIiwiZXhwIjoiMTg5MzQ1NjAwMCIsInJvbGUiOiJ0ZXN0ZXIiLCJpc3MiOiJkb2NrcGxveSJ9.BG5JoxL2_NaTFbPgyZdm3kRWenf_O3su_HIRKGCJ_kY",
+ );
+ expect(result.mounts).toHaveLength(0);
+ expect(result.domains).toHaveLength(0);
+ });
+ });
+
+ describe("domains processing", () => {
+ it("should process domains with explicit host", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {
+ main_domain: "${domain}",
+ },
+ config: {
+ domains: [
+ {
+ serviceName: "plausible",
+ port: 8000,
+ host: "${main_domain}",
+ },
+ ],
+ env: {},
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.domains).toHaveLength(1);
+ const domain = result.domains[0];
+ expect(domain).toBeDefined();
+ if (!domain) return;
+ expect(domain).toMatchObject({
+ serviceName: "plausible",
+ port: 8000,
+ });
+ expect(domain.host).toBeDefined();
+ expect(domain.host).toContain(mockSchema.projectName);
+ });
+
+ it("should generate random domain if host is not specified", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {},
+ config: {
+ domains: [
+ {
+ serviceName: "plausible",
+ port: 8000,
+ },
+ ],
+ env: {},
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.domains).toHaveLength(1);
+ const domain = result.domains[0];
+ expect(domain).toBeDefined();
+ if (!domain || !domain.host) return;
+ expect(domain.host).toBeDefined();
+ expect(domain.host).toContain(mockSchema.projectName);
+ });
+
+ it("should allow using ${domain} directly in host", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {},
+ config: {
+ domains: [
+ {
+ serviceName: "plausible",
+ port: 8000,
+ host: "${domain}",
+ },
+ ],
+ env: {},
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.domains).toHaveLength(1);
+ const domain = result.domains[0];
+ expect(domain).toBeDefined();
+ if (!domain || !domain.host) return;
+ expect(domain.host).toBeDefined();
+ expect(domain.host).toContain(mockSchema.projectName);
+ });
+ });
+
+ describe("environment variables processing", () => {
+ it("should process env vars with variable references", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {
+ main_domain: "${domain}",
+ secret_base: "${base64:64}",
+ },
+ config: {
+ domains: [],
+ env: {
+ BASE_URL: "http://${main_domain}",
+ SECRET_KEY_BASE: "${secret_base}",
+ },
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.envs).toHaveLength(2);
+ const baseUrl = result.envs.find((env: string) =>
+ env.startsWith("BASE_URL="),
+ );
+ const secretKey = result.envs.find((env: string) =>
+ env.startsWith("SECRET_KEY_BASE="),
+ );
+
+ expect(baseUrl).toBeDefined();
+ expect(secretKey).toBeDefined();
+ if (!baseUrl || !secretKey) return;
+
+ expect(baseUrl).toContain(mockSchema.projectName);
+ const base64Value = secretKey.split("=")[1];
+ expect(base64Value).toBeDefined();
+ if (!base64Value) return;
+ expect(base64Value).toMatch(/^[A-Za-z0-9+/]+={0,2}$/);
+ expect(base64Value.length).toBeGreaterThanOrEqual(86);
+ expect(base64Value.length).toBeLessThanOrEqual(88);
+ });
+
+ it("should process env vars when provided as an array", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {},
+ config: {
+ domains: [],
+ env: [
+ 'CLOUDFLARE_TUNNEL_TOKEN=""',
+ 'ANOTHER_VAR="some value"',
+ "DOMAIN=${domain}",
+ ],
+ mounts: [],
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.envs).toHaveLength(3);
+
+ // Should preserve exact format for static values
+ expect(result.envs[0]).toBe('CLOUDFLARE_TUNNEL_TOKEN=""');
+ expect(result.envs[1]).toBe('ANOTHER_VAR="some value"');
+
+ // Should process variables in array items
+ expect(result.envs[2]).toContain(mockSchema.projectName);
+ });
+
+ it("should allow using utility functions directly in env vars", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {},
+ config: {
+ domains: [],
+ env: {
+ RANDOM_DOMAIN: "${domain}",
+ SECRET_KEY: "${base64:32}",
+ },
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.envs).toHaveLength(2);
+ const randomDomainEnv = result.envs.find((env: string) =>
+ env.startsWith("RANDOM_DOMAIN="),
+ );
+ const secretKeyEnv = result.envs.find((env: string) =>
+ env.startsWith("SECRET_KEY="),
+ );
+ expect(randomDomainEnv).toBeDefined();
+ expect(secretKeyEnv).toBeDefined();
+ if (!randomDomainEnv || !secretKeyEnv) return;
+
+ expect(randomDomainEnv).toContain(mockSchema.projectName);
+ const base64Value = secretKeyEnv.split("=")[1];
+ expect(base64Value).toBeDefined();
+ if (!base64Value) return;
+ expect(base64Value).toMatch(/^[A-Za-z0-9+/]+={0,2}$/);
+ expect(base64Value.length).toBeGreaterThanOrEqual(42);
+ expect(base64Value.length).toBeLessThanOrEqual(44);
+ });
+
+ it("should handle boolean values in env vars when provided as an array", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {},
+ config: {
+ domains: [],
+ env: [
+ "ENABLE_USER_SIGN_UP=false",
+ "DEBUG_MODE=true",
+ "SOME_NUMBER=42",
+ ],
+ mounts: [],
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.envs).toHaveLength(3);
+ expect(result.envs).toContain("ENABLE_USER_SIGN_UP=false");
+ expect(result.envs).toContain("DEBUG_MODE=true");
+ expect(result.envs).toContain("SOME_NUMBER=42");
+ });
+
+ it("should handle boolean values in env vars when provided as an object", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {},
+ config: {
+ domains: [],
+ env: {
+ ENABLE_USER_SIGN_UP: false,
+ DEBUG_MODE: true,
+ SOME_NUMBER: 42,
+ },
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.envs).toHaveLength(3);
+ expect(result.envs).toContain("ENABLE_USER_SIGN_UP=false");
+ expect(result.envs).toContain("DEBUG_MODE=true");
+ expect(result.envs).toContain("SOME_NUMBER=42");
+ });
+ });
+
+ describe("mounts processing", () => {
+ it("should process mounts with variable references", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {
+ config_path: "/etc/config",
+ secret_key: "${base64:32}",
+ },
+ config: {
+ domains: [],
+ env: {},
+ mounts: [
+ {
+ filePath: "${config_path}/config.xml",
+ content: "secret_key=${secret_key}",
+ },
+ ],
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.mounts).toHaveLength(1);
+ const mount = result.mounts[0];
+ expect(mount).toBeDefined();
+ if (!mount) return;
+ expect(mount.filePath).toContain("/etc/config");
+ expect(mount.content).toMatch(/secret_key=[A-Za-z0-9+/]{32}/);
+ });
+
+ it("should allow using utility functions directly in mount content", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {},
+ config: {
+ domains: [],
+ env: {},
+ mounts: [
+ {
+ filePath: "/config/secrets.txt",
+ content: "random_domain=${domain}\nsecret=${base64:32}",
+ },
+ ],
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.mounts).toHaveLength(1);
+ const mount = result.mounts[0];
+ expect(mount).toBeDefined();
+ if (!mount) return;
+ expect(mount.content).toContain(mockSchema.projectName);
+ expect(mount.content).toMatch(/secret=[A-Za-z0-9+/]{32}/);
+ });
+ });
+
+ describe("complex template processing", () => {
+ it("should process a complete template with all features", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {
+ main_domain: "${domain}",
+ secret_base: "${base64:64}",
+ totp_key: "${base64:32}",
+ },
+ config: {
+ domains: [
+ {
+ serviceName: "plausible",
+ port: 8000,
+ host: "${main_domain}",
+ },
+ {
+ serviceName: "api",
+ port: 3000,
+ host: "api.${main_domain}",
+ },
+ ],
+ env: {
+ BASE_URL: "http://${main_domain}",
+ SECRET_KEY_BASE: "${secret_base}",
+ TOTP_VAULT_KEY: "${totp_key}",
+ },
+ mounts: [
+ {
+ filePath: "/config/app.conf",
+ content: `
+ domain=\${main_domain}
+ secret=\${secret_base}
+ totp=\${totp_key}
+ `,
+ },
+ ],
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+
+ // Check domains
+ expect(result.domains).toHaveLength(2);
+ const [domain1, domain2] = result.domains;
+ expect(domain1).toBeDefined();
+ expect(domain2).toBeDefined();
+ if (!domain1 || !domain2) return;
+ expect(domain1.host).toBeDefined();
+ expect(domain1.host).toContain(mockSchema.projectName);
+ expect(domain2.host).toContain("api.");
+ expect(domain2.host).toContain(mockSchema.projectName);
+
+ // Check env vars
+ expect(result.envs).toHaveLength(3);
+ const baseUrl = result.envs.find((env: string) =>
+ env.startsWith("BASE_URL="),
+ );
+ const secretKey = result.envs.find((env: string) =>
+ env.startsWith("SECRET_KEY_BASE="),
+ );
+ const totpKey = result.envs.find((env: string) =>
+ env.startsWith("TOTP_VAULT_KEY="),
+ );
+
+ expect(baseUrl).toBeDefined();
+ expect(secretKey).toBeDefined();
+ expect(totpKey).toBeDefined();
+ if (!baseUrl || !secretKey || !totpKey) return;
+
+ expect(baseUrl).toContain(mockSchema.projectName);
+
+ // Check base64 lengths and format
+ const secretKeyValue = secretKey.split("=")[1];
+ const totpKeyValue = totpKey.split("=")[1];
+
+ expect(secretKeyValue).toBeDefined();
+ expect(totpKeyValue).toBeDefined();
+ if (!secretKeyValue || !totpKeyValue) return;
+
+ expect(secretKeyValue).toMatch(/^[A-Za-z0-9+/]+={0,2}$/);
+ expect(secretKeyValue.length).toBeGreaterThanOrEqual(86);
+ expect(secretKeyValue.length).toBeLessThanOrEqual(88);
+
+ expect(totpKeyValue).toMatch(/^[A-Za-z0-9+/]+={0,2}$/);
+ expect(totpKeyValue.length).toBeGreaterThanOrEqual(42);
+ expect(totpKeyValue.length).toBeLessThanOrEqual(44);
+
+ // Check mounts
+ expect(result.mounts).toHaveLength(1);
+ const mount = result.mounts[0];
+ expect(mount).toBeDefined();
+ if (!mount) return;
+ expect(mount.content).toContain(mockSchema.projectName);
+ expect(mount.content).toMatch(/secret=[A-Za-z0-9+/]{86,88}/);
+ expect(mount.content).toMatch(/totp=[A-Za-z0-9+/]{42,44}/);
+ });
+ });
+
+ describe("Should populate envs, domains and mounts in the case we didn't used any variable", () => {
+ it("should populate envs, domains and mounts in the case we didn't used any variable", () => {
+ const template: CompleteTemplate = {
+ metadata: {} as any,
+ variables: {},
+ config: {
+ domains: [
+ {
+ serviceName: "plausible",
+ port: 8000,
+ host: "${hash}",
+ },
+ ],
+ env: {
+ BASE_URL: "http://${domain}",
+ SECRET_KEY_BASE: "${password:32}",
+ TOTP_VAULT_KEY: "${base64:128}",
+ },
+ mounts: [
+ {
+ filePath: "/config/secrets.txt",
+ content: "random_domain=${domain}\nsecret=${password:32}",
+ },
+ ],
+ },
+ };
+
+ const result = processTemplate(template, mockSchema);
+ expect(result.envs).toHaveLength(3);
+ expect(result.domains).toHaveLength(1);
+ expect(result.mounts).toHaveLength(1);
+ });
+ });
+});
diff --git a/data/apps/dokploy/__test__/templates/helpers.template.test.ts b/data/apps/dokploy/__test__/templates/helpers.template.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..1144b65fe5be31e476cb7a469680d93a6758e8f0
--- /dev/null
+++ b/data/apps/dokploy/__test__/templates/helpers.template.test.ts
@@ -0,0 +1,232 @@
+import type { Schema } from "@dokploy/server/templates";
+import { processValue } from "@dokploy/server/templates/processors";
+import { describe, expect, it } from "vitest";
+
+describe("helpers functions", () => {
+ // Mock schema for testing
+ const mockSchema: Schema = {
+ projectName: "test",
+ serverIp: "127.0.0.1",
+ };
+ // some helpers to test jwt
+ type JWTParts = [string, string, string];
+ const jwtMatchExp = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$/;
+ const jwtBase64Decode = (str: string) => {
+ const base64 = str.replace(/-/g, "+").replace(/_/g, "/");
+ const padding = "=".repeat((4 - (base64.length % 4)) % 4);
+ const decoded = Buffer.from(base64 + padding, "base64").toString("utf-8");
+ return JSON.parse(decoded);
+ };
+ const jwtCheckHeader = (jwtHeader: string) => {
+ const decodedHeader = jwtBase64Decode(jwtHeader);
+ expect(decodedHeader).toHaveProperty("alg");
+ expect(decodedHeader).toHaveProperty("typ");
+ expect(decodedHeader.alg).toEqual("HS256");
+ expect(decodedHeader.typ).toEqual("JWT");
+ };
+
+ describe("${domain}", () => {
+ it("should generate a random domain", () => {
+ const domain = processValue("${domain}", {}, mockSchema);
+ expect(domain.startsWith(`${mockSchema.projectName}-`)).toBeTruthy();
+ expect(
+ domain.endsWith(
+ `${mockSchema.serverIp.replaceAll(".", "-")}.traefik.me`,
+ ),
+ ).toBeTruthy();
+ });
+ });
+
+ describe("${base64}", () => {
+ it("should generate a base64 string", () => {
+ const base64 = processValue("${base64}", {}, mockSchema);
+ expect(base64).toMatch(/^[A-Za-z0-9+=/]+={0,2}$/);
+ });
+ it.each([
+ [4, 8],
+ [8, 12],
+ [16, 24],
+ [32, 44],
+ [64, 88],
+ [128, 172],
+ ])(
+ "should generate a base64 string from parameter %d bytes length",
+ (length, finalLength) => {
+ const base64 = processValue(`\${base64:${length}}`, {}, mockSchema);
+ expect(base64).toMatch(/^[A-Za-z0-9+=/]+={0,2}$/);
+ expect(base64.length).toBe(finalLength);
+ },
+ );
+ });
+
+ describe("${password}", () => {
+ it("should generate a password string", () => {
+ const password = processValue("${password}", {}, mockSchema);
+ expect(password).toMatch(/^[A-Za-z0-9]+$/);
+ });
+ it.each([6, 8, 12, 16, 32])(
+ "should generate a password string respecting parameter %d length",
+ (length) => {
+ const password = processValue(`\${password:${length}}`, {}, mockSchema);
+ expect(password).toMatch(/^[A-Za-z0-9]+$/);
+ expect(password.length).toBe(length);
+ },
+ );
+ });
+
+ describe("${hash}", () => {
+ it("should generate a hash string", () => {
+ const hash = processValue("${hash}", {}, mockSchema);
+ expect(hash).toMatch(/^[A-Za-z0-9]+$/);
+ });
+ it.each([6, 8, 12, 16, 32])(
+ "should generate a hash string respecting parameter %d length",
+ (length) => {
+ const hash = processValue(`\${hash:${length}}`, {}, mockSchema);
+ expect(hash).toMatch(/^[A-Za-z0-9]+$/);
+ expect(hash.length).toBe(length);
+ },
+ );
+ });
+
+ describe("${uuid}", () => {
+ it("should generate a UUID string", () => {
+ const uuid = processValue("${uuid}", {}, mockSchema);
+ expect(uuid).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
+ );
+ });
+ });
+
+ describe("${timestamp}", () => {
+ it("should generate a timestamp string in milliseconds", () => {
+ const timestamp = processValue("${timestamp}", {}, mockSchema);
+ const nowLength = Math.floor(Date.now()).toString().length;
+ expect(timestamp).toMatch(/^\d+$/);
+ expect(timestamp.length).toBe(nowLength);
+ });
+ });
+ describe("${timestampms}", () => {
+ it("should generate a timestamp string in milliseconds", () => {
+ const timestamp = processValue("${timestampms}", {}, mockSchema);
+ const nowLength = Date.now().toString().length;
+ expect(timestamp).toMatch(/^\d+$/);
+ expect(timestamp.length).toBe(nowLength);
+ });
+ it("should generate a timestamp string in milliseconds from parameter", () => {
+ const timestamp = processValue(
+ "${timestampms:2025-01-01}",
+ {},
+ mockSchema,
+ );
+ expect(timestamp).toEqual("1735689600000");
+ });
+ });
+ describe("${timestamps}", () => {
+ it("should generate a timestamp string in seconds", () => {
+ const timestamps = processValue("${timestamps}", {}, mockSchema);
+ const nowLength = Math.floor(Date.now() / 1000).toString().length;
+ expect(timestamps).toMatch(/^\d+$/);
+ expect(timestamps.length).toBe(nowLength);
+ });
+ it("should generate a timestamp string in seconds from parameter", () => {
+ const timestamps = processValue(
+ "${timestamps:2025-01-01}",
+ {},
+ mockSchema,
+ );
+ expect(timestamps).toEqual("1735689600");
+ });
+ });
+
+ describe("${randomPort}", () => {
+ it("should generate a random port string", () => {
+ const randomPort = processValue("${randomPort}", {}, mockSchema);
+ expect(randomPort).toMatch(/^\d+$/);
+ expect(Number(randomPort)).toBeLessThan(65536);
+ });
+ });
+
+ describe("${username}", () => {
+ it("should generate a username string", () => {
+ const username = processValue("${username}", {}, mockSchema);
+ expect(username).toMatch(/^[a-zA-Z0-9._-]{3,}$/);
+ });
+ });
+
+ describe("${email}", () => {
+ it("should generate an email string", () => {
+ const email = processValue("${email}", {}, mockSchema);
+ expect(email).toMatch(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/);
+ });
+ });
+
+ describe("${jwt}", () => {
+ it("should generate a JWT string", () => {
+ const jwt = processValue("${jwt}", {}, mockSchema);
+ expect(jwt).toMatch(jwtMatchExp);
+ const parts = jwt.split(".") as JWTParts;
+ const decodedPayload = jwtBase64Decode(parts[1]);
+ jwtCheckHeader(parts[0]);
+ expect(decodedPayload).toHaveProperty("iat");
+ expect(decodedPayload).toHaveProperty("iss");
+ expect(decodedPayload).toHaveProperty("exp");
+ expect(decodedPayload.iss).toEqual("dokploy");
+ });
+ it.each([6, 8, 12, 16, 32])(
+ "should generate a random hex string from parameter %d byte length",
+ (length) => {
+ const jwt = processValue(`\${jwt:${length}}`, {}, mockSchema);
+ expect(jwt).toMatch(/^[A-Za-z0-9-_.]+$/);
+ expect(jwt.length).toBeGreaterThanOrEqual(length); // bytes translated to hex can take up to 2x the length
+ expect(jwt.length).toBeLessThanOrEqual(length * 2);
+ },
+ );
+ });
+ describe("${jwt:secret}", () => {
+ it("should generate a JWT string respecting parameter secret from variable", () => {
+ const jwt = processValue(
+ "${jwt:secret}",
+ { secret: "mysecret" },
+ mockSchema,
+ );
+ expect(jwt).toMatch(jwtMatchExp);
+ const parts = jwt.split(".") as JWTParts;
+ const decodedPayload = jwtBase64Decode(parts[1]);
+ jwtCheckHeader(parts[0]);
+ expect(decodedPayload).toHaveProperty("iat");
+ expect(decodedPayload).toHaveProperty("iss");
+ expect(decodedPayload).toHaveProperty("exp");
+ expect(decodedPayload.iss).toEqual("dokploy");
+ });
+ });
+ describe("${jwt:secret:payload}", () => {
+ it("should generate a JWT string respecting parameters secret and payload from variables", () => {
+ const iat = Math.floor(new Date("2025-01-01T00:00:00Z").getTime() / 1000);
+ const expiry = iat + 3600;
+ const jwt = processValue(
+ "${jwt:secret:payload}",
+ {
+ secret: "mysecret",
+ payload: `{"iss": "test-issuer", "iat": ${iat}, "exp": ${expiry}, "customprop": "customvalue"}`,
+ },
+ mockSchema,
+ );
+ expect(jwt).toMatch(jwtMatchExp);
+ const parts = jwt.split(".") as JWTParts;
+ jwtCheckHeader(parts[0]);
+ const decodedPayload = jwtBase64Decode(parts[1]);
+ expect(decodedPayload).toHaveProperty("iat");
+ expect(decodedPayload.iat).toEqual(iat);
+ expect(decodedPayload).toHaveProperty("iss");
+ expect(decodedPayload.iss).toEqual("test-issuer");
+ expect(decodedPayload).toHaveProperty("exp");
+ expect(decodedPayload.exp).toEqual(expiry);
+ expect(decodedPayload).toHaveProperty("customprop");
+ expect(decodedPayload.customprop).toEqual("customvalue");
+ expect(jwt).toEqual(
+ "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MzU2ODk2MDAsImV4cCI6MTczNTY5MzIwMCwiaXNzIjoidGVzdC1pc3N1ZXIiLCJjdXN0b21wcm9wIjoiY3VzdG9tdmFsdWUifQ.m42U7PZSUSCf7gBOJrxJir0rQmyPq4rA59Dydr_QahI",
+ );
+ });
+ });
+});
diff --git a/data/apps/dokploy/__test__/traefik/server/update-server-config.test.ts b/data/apps/dokploy/__test__/traefik/server/update-server-config.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..6858f0f005b1dbf159931427f3f2cea704aa2895
--- /dev/null
+++ b/data/apps/dokploy/__test__/traefik/server/update-server-config.test.ts
@@ -0,0 +1,133 @@
+import { fs, vol } from "memfs";
+
+vi.mock("node:fs", () => ({
+ ...fs,
+ default: fs,
+}));
+
+import type { FileConfig, User } from "@dokploy/server";
+import {
+ createDefaultServerTraefikConfig,
+ loadOrCreateConfig,
+ updateServerTraefik,
+} from "@dokploy/server";
+import { beforeEach, expect, test, vi } from "vitest";
+
+const baseAdmin: User = {
+ https: false,
+ enablePaidFeatures: false,
+ allowImpersonation: false,
+ role: "user",
+ metricsConfig: {
+ containers: {
+ refreshRate: 20,
+ services: {
+ include: [],
+ exclude: [],
+ },
+ },
+ server: {
+ type: "Dokploy",
+ cronJob: "",
+ port: 4500,
+ refreshRate: 20,
+ retentionDays: 2,
+ token: "",
+ thresholds: {
+ cpu: 0,
+ memory: 0,
+ },
+ urlCallback: "",
+ },
+ },
+ cleanupCacheApplications: false,
+ cleanupCacheOnCompose: false,
+ cleanupCacheOnPreviews: false,
+ createdAt: new Date(),
+ serverIp: null,
+ certificateType: "none",
+ host: null,
+ letsEncryptEmail: null,
+ sshPrivateKey: null,
+ enableDockerCleanup: false,
+ logCleanupCron: null,
+ serversQuantity: 0,
+ stripeCustomerId: "",
+ stripeSubscriptionId: "",
+ banExpires: new Date(),
+ banned: true,
+ banReason: "",
+ email: "",
+ expirationDate: "",
+ id: "",
+ isRegistered: false,
+ name: "",
+ createdAt2: new Date().toISOString(),
+ emailVerified: false,
+ image: "",
+ updatedAt: new Date(),
+ twoFactorEnabled: false,
+};
+
+beforeEach(() => {
+ vol.reset();
+ createDefaultServerTraefikConfig();
+});
+
+test("Should read the configuration file", () => {
+ const config: FileConfig = loadOrCreateConfig("dokploy");
+ expect(config.http?.routers?.["dokploy-router-app"]?.service).toBe(
+ "dokploy-service-app",
+ );
+});
+
+test("Should apply redirect-to-https", () => {
+ updateServerTraefik(
+ {
+ ...baseAdmin,
+ https: true,
+ certificateType: "letsencrypt",
+ },
+ "example.com",
+ );
+
+ const config: FileConfig = loadOrCreateConfig("dokploy");
+
+ expect(config.http?.routers?.["dokploy-router-app"]?.middlewares).toContain(
+ "redirect-to-https",
+ );
+});
+
+test("Should change only host when no certificate", () => {
+ updateServerTraefik(baseAdmin, "example.com");
+
+ const config: FileConfig = loadOrCreateConfig("dokploy");
+
+ expect(config.http?.routers?.["dokploy-router-app-secure"]).toBeUndefined();
+});
+
+test("Should not touch config without host", () => {
+ const originalConfig: FileConfig = loadOrCreateConfig("dokploy");
+
+ updateServerTraefik(baseAdmin, null);
+
+ const config: FileConfig = loadOrCreateConfig("dokploy");
+
+ expect(originalConfig).toEqual(config);
+});
+
+test("Should remove websecure if https rollback to http", () => {
+ updateServerTraefik(
+ { ...baseAdmin, certificateType: "letsencrypt" },
+ "example.com",
+ );
+
+ updateServerTraefik({ ...baseAdmin, certificateType: "none" }, "example.com");
+
+ const config: FileConfig = loadOrCreateConfig("dokploy");
+
+ expect(config.http?.routers?.["dokploy-router-app-secure"]).toBeUndefined();
+ expect(
+ config.http?.routers?.["dokploy-router-app"]?.middlewares,
+ ).not.toContain("redirect-to-https");
+});
diff --git a/data/apps/dokploy/__test__/traefik/traefik.test.ts b/data/apps/dokploy/__test__/traefik/traefik.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..6c136b259dde9efaae30f7935319fe17962a0580
--- /dev/null
+++ b/data/apps/dokploy/__test__/traefik/traefik.test.ts
@@ -0,0 +1,250 @@
+import type { Domain } from "@dokploy/server";
+import type { Redirect } from "@dokploy/server";
+import type { ApplicationNested } from "@dokploy/server";
+import { createRouterConfig } from "@dokploy/server";
+import { expect, test } from "vitest";
+
+const baseApp: ApplicationNested = {
+ applicationId: "",
+ herokuVersion: "",
+ giteaRepository: "",
+ giteaOwner: "",
+ giteaBranch: "",
+ giteaBuildPath: "",
+ giteaId: "",
+ cleanCache: false,
+ applicationStatus: "done",
+ appName: "",
+ autoDeploy: true,
+ enableSubmodules: false,
+ serverId: "",
+ branch: null,
+ dockerBuildStage: "",
+ registryUrl: "",
+ watchPaths: [],
+ buildArgs: null,
+ isPreviewDeploymentsActive: false,
+ previewBuildArgs: null,
+ triggerType: "push",
+ previewCertificateType: "none",
+ previewEnv: null,
+ previewHttps: false,
+ previewPath: "/",
+ previewPort: 3000,
+ previewLimit: 0,
+ previewCustomCertResolver: null,
+ previewWildcard: "",
+ project: {
+ env: "",
+ organizationId: "",
+ name: "",
+ description: "",
+ createdAt: "",
+ projectId: "",
+ },
+ buildPath: "/",
+ gitlabPathNamespace: "",
+ buildType: "nixpacks",
+ bitbucketBranch: "",
+ bitbucketBuildPath: "",
+ bitbucketId: "",
+ bitbucketRepository: "",
+ bitbucketOwner: "",
+ githubId: "",
+ gitlabProjectId: 0,
+ gitlabBranch: "",
+ gitlabBuildPath: "",
+ gitlabId: "",
+ gitlabRepository: "",
+ gitlabOwner: "",
+ command: null,
+ cpuLimit: null,
+ cpuReservation: null,
+ createdAt: "",
+ customGitBranch: "",
+ customGitBuildPath: "",
+ customGitSSHKeyId: null,
+ customGitUrl: "",
+ description: "",
+ dockerfile: null,
+ dockerImage: null,
+ dropBuildPath: null,
+ enabled: null,
+ env: null,
+ healthCheckSwarm: null,
+ labelsSwarm: null,
+ memoryLimit: null,
+ memoryReservation: null,
+ modeSwarm: null,
+ mounts: [],
+ name: "",
+ networkSwarm: null,
+ owner: null,
+ password: null,
+ placementSwarm: null,
+ ports: [],
+ projectId: "",
+ publishDirectory: null,
+ isStaticSpa: null,
+ redirects: [],
+ refreshToken: "",
+ registry: null,
+ registryId: null,
+ replicas: 1,
+ repository: null,
+ restartPolicySwarm: null,
+ rollbackConfigSwarm: null,
+ security: [],
+ sourceType: "git",
+ subtitle: null,
+ title: null,
+ updateConfigSwarm: null,
+ username: null,
+ dockerContextPath: null,
+};
+
+const baseDomain: Domain = {
+ applicationId: "",
+ certificateType: "none",
+ createdAt: "",
+ domainId: "",
+ host: "",
+ https: false,
+ path: null,
+ port: null,
+ serviceName: "",
+ composeId: "",
+ customCertResolver: null,
+ domainType: "application",
+ uniqueConfigKey: 1,
+ previewDeploymentId: "",
+};
+
+const baseRedirect: Redirect = {
+ redirectId: "",
+ regex: "",
+ replacement: "",
+ permanent: false,
+ uniqueConfigKey: 1,
+ createdAt: "",
+ applicationId: "",
+};
+
+/** Middlewares */
+
+test("Web entrypoint on http domain", async () => {
+ const router = await createRouterConfig(
+ baseApp,
+ { ...baseDomain, https: false },
+ "web",
+ );
+
+ expect(router.middlewares).not.toContain("redirect-to-https");
+ expect(router.rule).not.toContain("PathPrefix");
+});
+
+test("Web entrypoint on http domain with custom path", async () => {
+ const router = await createRouterConfig(
+ baseApp,
+ { ...baseDomain, path: "/foo", https: false },
+ "web",
+ );
+
+ expect(router.rule).toContain("PathPrefix(`/foo`)");
+});
+
+test("Web entrypoint on http domain with redirect", async () => {
+ const router = await createRouterConfig(
+ {
+ ...baseApp,
+ appName: "test",
+ redirects: [{ ...baseRedirect, uniqueConfigKey: 1 }],
+ },
+ { ...baseDomain, https: false },
+ "web",
+ );
+
+ expect(router.middlewares).not.toContain("redirect-to-https");
+ expect(router.middlewares).toContain("redirect-test-1");
+});
+
+test("Web entrypoint on http domain with multiple redirect", async () => {
+ const router = await createRouterConfig(
+ {
+ ...baseApp,
+ appName: "test",
+ redirects: [
+ { ...baseRedirect, uniqueConfigKey: 1 },
+ { ...baseRedirect, uniqueConfigKey: 2 },
+ ],
+ },
+ { ...baseDomain, https: false },
+ "web",
+ );
+
+ expect(router.middlewares).not.toContain("redirect-to-https");
+ expect(router.middlewares).toContain("redirect-test-1");
+ expect(router.middlewares).toContain("redirect-test-2");
+});
+
+test("Web entrypoint on https domain", async () => {
+ const router = await createRouterConfig(
+ baseApp,
+ { ...baseDomain, https: true },
+ "web",
+ );
+
+ expect(router.middlewares).toContain("redirect-to-https");
+});
+
+test("Web entrypoint on https domain with redirect", async () => {
+ const router = await createRouterConfig(
+ {
+ ...baseApp,
+ appName: "test",
+ redirects: [{ ...baseRedirect, uniqueConfigKey: 1 }],
+ },
+ { ...baseDomain, https: true },
+ "web",
+ );
+
+ expect(router.middlewares).toContain("redirect-to-https");
+ expect(router.middlewares).not.toContain("redirect-test-1");
+});
+
+test("Websecure entrypoint on https domain", async () => {
+ const router = await createRouterConfig(
+ baseApp,
+ { ...baseDomain, https: true },
+ "websecure",
+ );
+
+ expect(router.middlewares).not.toContain("redirect-to-https");
+});
+
+test("Websecure entrypoint on https domain with redirect", async () => {
+ const router = await createRouterConfig(
+ {
+ ...baseApp,
+ appName: "test",
+ redirects: [{ ...baseRedirect, uniqueConfigKey: 1 }],
+ },
+ { ...baseDomain, https: true },
+ "websecure",
+ );
+
+ expect(router.middlewares).not.toContain("redirect-to-https");
+ expect(router.middlewares).toContain("redirect-test-1");
+});
+
+/** Certificates */
+
+test("CertificateType on websecure entrypoint", async () => {
+ const router = await createRouterConfig(
+ baseApp,
+ { ...baseDomain, certificateType: "letsencrypt" },
+ "websecure",
+ );
+
+ expect(router.tls?.certResolver).toBe("letsencrypt");
+});
diff --git a/data/apps/dokploy/__test__/utils/backups.test.ts b/data/apps/dokploy/__test__/utils/backups.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..2c1e5decc991b25fce568da385326149f16b0d65
--- /dev/null
+++ b/data/apps/dokploy/__test__/utils/backups.test.ts
@@ -0,0 +1,61 @@
+import { normalizeS3Path } from "@dokploy/server/utils/backups/utils";
+import { describe, expect, test } from "vitest";
+
+describe("normalizeS3Path", () => {
+ test("should handle empty and whitespace-only prefix", () => {
+ expect(normalizeS3Path("")).toBe("");
+ expect(normalizeS3Path("/")).toBe("");
+ expect(normalizeS3Path(" ")).toBe("");
+ expect(normalizeS3Path("\t")).toBe("");
+ expect(normalizeS3Path("\n")).toBe("");
+ expect(normalizeS3Path(" \n \t ")).toBe("");
+ });
+
+ test("should trim whitespace from prefix", () => {
+ expect(normalizeS3Path(" prefix")).toBe("prefix/");
+ expect(normalizeS3Path("prefix ")).toBe("prefix/");
+ expect(normalizeS3Path(" prefix ")).toBe("prefix/");
+ expect(normalizeS3Path("\tprefix\t")).toBe("prefix/");
+ expect(normalizeS3Path(" prefix/nested ")).toBe("prefix/nested/");
+ });
+
+ test("should remove leading slashes", () => {
+ expect(normalizeS3Path("/prefix")).toBe("prefix/");
+ expect(normalizeS3Path("///prefix")).toBe("prefix/");
+ });
+
+ test("should remove trailing slashes", () => {
+ expect(normalizeS3Path("prefix/")).toBe("prefix/");
+ expect(normalizeS3Path("prefix///")).toBe("prefix/");
+ });
+
+ test("should remove both leading and trailing slashes", () => {
+ expect(normalizeS3Path("/prefix/")).toBe("prefix/");
+ expect(normalizeS3Path("///prefix///")).toBe("prefix/");
+ });
+
+ test("should handle nested paths", () => {
+ expect(normalizeS3Path("prefix/nested")).toBe("prefix/nested/");
+ expect(normalizeS3Path("/prefix/nested/")).toBe("prefix/nested/");
+ expect(normalizeS3Path("///prefix/nested///")).toBe("prefix/nested/");
+ });
+
+ test("should preserve middle slashes", () => {
+ expect(normalizeS3Path("prefix/nested/deep")).toBe("prefix/nested/deep/");
+ expect(normalizeS3Path("/prefix/nested/deep/")).toBe("prefix/nested/deep/");
+ });
+
+ test("should handle special characters", () => {
+ expect(normalizeS3Path("prefix-with-dashes")).toBe("prefix-with-dashes/");
+ expect(normalizeS3Path("prefix_with_underscores")).toBe(
+ "prefix_with_underscores/",
+ );
+ expect(normalizeS3Path("prefix.with.dots")).toBe("prefix.with.dots/");
+ });
+
+ test("should handle the cases from the bug report", () => {
+ expect(normalizeS3Path("instance-backups/")).toBe("instance-backups/");
+ expect(normalizeS3Path("/instance-backups/")).toBe("instance-backups/");
+ expect(normalizeS3Path("instance-backups")).toBe("instance-backups/");
+ });
+});
diff --git a/data/apps/dokploy/__test__/vitest.config.ts b/data/apps/dokploy/__test__/vitest.config.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ddc84d6ac3058504daea00f1b1d35a1171c6846b
--- /dev/null
+++ b/data/apps/dokploy/__test__/vitest.config.ts
@@ -0,0 +1,25 @@
+import path from "node:path";
+import tsconfigPaths from "vite-tsconfig-paths";
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["__test__/**/*.test.ts"], // Incluir solo los archivos de test en el directorio __test__
+ exclude: ["**/node_modules/**", "**/dist/**", "**/.docker/**"],
+ pool: "forks",
+ },
+ define: {
+ "process.env": {
+ NODE: "test",
+ },
+ },
+ plugins: [tsconfigPaths()],
+ resolve: {
+ alias: {
+ "@dokploy/server": path.resolve(
+ __dirname,
+ "../../../packages/server/src",
+ ),
+ },
+ },
+});
diff --git a/data/apps/dokploy/components.json b/data/apps/dokploy/components.json
new file mode 100644
index 0000000000000000000000000000000000000000..81104c1e9ab89d3683d170d88d6e20f2aa670e93
--- /dev/null
+++ b/data/apps/dokploy/components.json
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://ui.shadcn.com/schema.json",
+ "style": "default",
+ "rsc": false,
+ "tsx": true,
+ "tailwind": {
+ "config": "tailwind.config.ts",
+ "css": "styles/globals.css",
+ "baseColor": "zinc",
+ "cssVariables": true,
+ "prefix": ""
+ },
+ "aliases": {
+ "components": "@/components",
+ "utils": "@/lib/utils"
+ }
+}
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/cluster/modify-swarm-settings.tsx b/data/apps/dokploy/components/dashboard/application/advanced/cluster/modify-swarm-settings.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..95a559f66280f9a1c21e56afba9f2bedb920cbd8
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/cluster/modify-swarm-settings.tsx
@@ -0,0 +1,770 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { HelpCircle, Settings } from "lucide-react";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const HealthCheckSwarmSchema = z
+ .object({
+ Test: z.array(z.string()).optional(),
+ Interval: z.number().optional(),
+ Timeout: z.number().optional(),
+ StartPeriod: z.number().optional(),
+ Retries: z.number().optional(),
+ })
+ .strict();
+
+const RestartPolicySwarmSchema = z
+ .object({
+ Condition: z.string().optional(),
+ Delay: z.number().optional(),
+ MaxAttempts: z.number().optional(),
+ Window: z.number().optional(),
+ })
+ .strict();
+
+const PreferenceSchema = z
+ .object({
+ Spread: z.object({
+ SpreadDescriptor: z.string(),
+ }),
+ })
+ .strict();
+
+const PlatformSchema = z
+ .object({
+ Architecture: z.string(),
+ OS: z.string(),
+ })
+ .strict();
+
+const PlacementSwarmSchema = z
+ .object({
+ Constraints: z.array(z.string()).optional(),
+ Preferences: z.array(PreferenceSchema).optional(),
+ MaxReplicas: z.number().optional(),
+ Platforms: z.array(PlatformSchema).optional(),
+ })
+ .strict();
+
+const UpdateConfigSwarmSchema = z
+ .object({
+ Parallelism: z.number(),
+ Delay: z.number().optional(),
+ FailureAction: z.string().optional(),
+ Monitor: z.number().optional(),
+ MaxFailureRatio: z.number().optional(),
+ Order: z.string(),
+ })
+ .strict();
+
+const ReplicatedSchema = z
+ .object({
+ Replicas: z.number().optional(),
+ })
+ .strict();
+
+const ReplicatedJobSchema = z
+ .object({
+ MaxConcurrent: z.number().optional(),
+ TotalCompletions: z.number().optional(),
+ })
+ .strict();
+
+const ServiceModeSwarmSchema = z
+ .object({
+ Replicated: ReplicatedSchema.optional(),
+ Global: z.object({}).optional(),
+ ReplicatedJob: ReplicatedJobSchema.optional(),
+ GlobalJob: z.object({}).optional(),
+ })
+ .strict();
+
+const NetworkSwarmSchema = z.array(
+ z
+ .object({
+ Target: z.string().optional(),
+ Aliases: z.array(z.string()).optional(),
+ DriverOpts: z.object({}).optional(),
+ })
+ .strict(),
+);
+
+const LabelsSwarmSchema = z.record(z.string());
+
+const createStringToJSONSchema = (schema: z.ZodTypeAny) => {
+ return z
+ .string()
+ .transform((str, ctx) => {
+ if (str === null || str === "") {
+ return null;
+ }
+ try {
+ return JSON.parse(str);
+ } catch (_e) {
+ ctx.addIssue({ code: "custom", message: "Invalid JSON format" });
+ return z.NEVER;
+ }
+ })
+ .superRefine((data, ctx) => {
+ if (data === null) {
+ return;
+ }
+
+ if (Object.keys(data).length === 0) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Object cannot be empty",
+ });
+ return;
+ }
+
+ const parseResult = schema.safeParse(data);
+ if (!parseResult.success) {
+ for (const error of parseResult.error.issues) {
+ const path = error.path.join(".");
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `${path} ${error.message}`,
+ });
+ }
+ }
+ });
+};
+
+const addSwarmSettings = z.object({
+ healthCheckSwarm: createStringToJSONSchema(HealthCheckSwarmSchema).nullable(),
+ restartPolicySwarm: createStringToJSONSchema(
+ RestartPolicySwarmSchema,
+ ).nullable(),
+ placementSwarm: createStringToJSONSchema(PlacementSwarmSchema).nullable(),
+ updateConfigSwarm: createStringToJSONSchema(
+ UpdateConfigSwarmSchema,
+ ).nullable(),
+ rollbackConfigSwarm: createStringToJSONSchema(
+ UpdateConfigSwarmSchema,
+ ).nullable(),
+ modeSwarm: createStringToJSONSchema(ServiceModeSwarmSchema).nullable(),
+ labelsSwarm: createStringToJSONSchema(LabelsSwarmSchema).nullable(),
+ networkSwarm: createStringToJSONSchema(NetworkSwarmSchema).nullable(),
+});
+
+type AddSwarmSettings = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const AddSwarmSettings = ({ applicationId }: Props) => {
+ const { data, refetch } = api.application.one.useQuery(
+ {
+ applicationId,
+ },
+ {
+ enabled: !!applicationId,
+ },
+ );
+
+ const { mutateAsync, isError, error, isLoading } =
+ api.application.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ healthCheckSwarm: null,
+ restartPolicySwarm: null,
+ placementSwarm: null,
+ updateConfigSwarm: null,
+ rollbackConfigSwarm: null,
+ modeSwarm: null,
+ labelsSwarm: null,
+ networkSwarm: null,
+ },
+ resolver: zodResolver(addSwarmSettings),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ healthCheckSwarm: data.healthCheckSwarm
+ ? JSON.stringify(data.healthCheckSwarm, null, 2)
+ : null,
+ restartPolicySwarm: data.restartPolicySwarm
+ ? JSON.stringify(data.restartPolicySwarm, null, 2)
+ : null,
+ placementSwarm: data.placementSwarm
+ ? JSON.stringify(data.placementSwarm, null, 2)
+ : null,
+ updateConfigSwarm: data.updateConfigSwarm
+ ? JSON.stringify(data.updateConfigSwarm, null, 2)
+ : null,
+ rollbackConfigSwarm: data.rollbackConfigSwarm
+ ? JSON.stringify(data.rollbackConfigSwarm, null, 2)
+ : null,
+ modeSwarm: data.modeSwarm
+ ? JSON.stringify(data.modeSwarm, null, 2)
+ : null,
+ labelsSwarm: data.labelsSwarm
+ ? JSON.stringify(data.labelsSwarm, null, 2)
+ : null,
+ networkSwarm: data.networkSwarm
+ ? JSON.stringify(data.networkSwarm, null, 2)
+ : null,
+ });
+ }
+ }, [form, form.reset, data]);
+
+ const onSubmit = async (data: AddSwarmSettings) => {
+ await mutateAsync({
+ applicationId,
+ healthCheckSwarm: data.healthCheckSwarm,
+ restartPolicySwarm: data.restartPolicySwarm,
+ placementSwarm: data.placementSwarm,
+ updateConfigSwarm: data.updateConfigSwarm,
+ rollbackConfigSwarm: data.rollbackConfigSwarm,
+ modeSwarm: data.modeSwarm,
+ labelsSwarm: data.labelsSwarm,
+ networkSwarm: data.networkSwarm,
+ })
+ .then(async () => {
+ toast.success("Swarm settings updated");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error updating the swarm settings");
+ });
+ };
+ return (
+
+
+
+
+ Swarm Settings
+
+
+
+
+ Swarm Settings
+
+ Update certain settings using a json object.
+
+
+ {isError && {error?.message} }
+
+
+ Changing settings such as placements may cause the logs/monitoring
+ to be unavailable.
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/cluster/show-cluster-settings.tsx b/data/apps/dokploy/components/dashboard/application/advanced/cluster/show-cluster-settings.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..57f851c9e2e26f905db33a3117d64ce4353473e8
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/cluster/show-cluster-settings.tsx
@@ -0,0 +1,212 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Server } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import { AddSwarmSettings } from "./modify-swarm-settings";
+
+interface Props {
+ applicationId: string;
+}
+
+const AddRedirectchema = z.object({
+ replicas: z.number().min(1, "Replicas must be at least 1"),
+ registryId: z.string(),
+});
+
+type AddCommand = z.infer;
+
+export const ShowClusterSettings = ({ applicationId }: Props) => {
+ const { data } = api.application.one.useQuery(
+ {
+ applicationId,
+ },
+ { enabled: !!applicationId },
+ );
+
+ const { data: registries } = api.registry.all.useQuery();
+
+ const utils = api.useUtils();
+
+ const { mutateAsync, isLoading } = api.application.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ registryId: data?.registryId || "",
+ replicas: data?.replicas || 1,
+ },
+ resolver: zodResolver(AddRedirectchema),
+ });
+
+ useEffect(() => {
+ if (data?.command) {
+ form.reset({
+ registryId: data?.registryId || "",
+ replicas: data?.replicas || 1,
+ });
+ }
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data?.command]);
+
+ const onSubmit = async (data: AddCommand) => {
+ await mutateAsync({
+ applicationId,
+ registryId:
+ data?.registryId === "none" || !data?.registryId
+ ? null
+ : data?.registryId,
+ replicas: data?.replicas,
+ })
+ .then(async () => {
+ toast.success("Command Updated");
+ await utils.application.one.invalidate({
+ applicationId,
+ });
+ })
+ .catch(() => {
+ toast.error("Error updating the command");
+ });
+ };
+
+ return (
+
+
+
+ Cluster Settings
+
+ Add the registry and the replicas of the application
+
+
+
+
+
+
+ Please remember to click Redeploy after modify the cluster settings to
+ apply the changes.
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx b/data/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..50e36ad7608bc43159e20dc6778dc1f494af5181
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx
@@ -0,0 +1,120 @@
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+interface Props {
+ applicationId: string;
+}
+
+const AddRedirectSchema = z.object({
+ command: z.string(),
+});
+
+type AddCommand = z.infer;
+
+export const AddCommand = ({ applicationId }: Props) => {
+ const { data } = api.application.one.useQuery(
+ {
+ applicationId,
+ },
+ { enabled: !!applicationId },
+ );
+
+ const utils = api.useUtils();
+
+ const { mutateAsync, isLoading } = api.application.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ command: "",
+ },
+ resolver: zodResolver(AddRedirectSchema),
+ });
+
+ useEffect(() => {
+ if (data?.command) {
+ form.reset({
+ command: data?.command || "",
+ });
+ }
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data?.command]);
+
+ const onSubmit = async (data: AddCommand) => {
+ await mutateAsync({
+ applicationId,
+ command: data?.command,
+ })
+ .then(async () => {
+ toast.success("Command Updated");
+ await utils.application.one.invalidate({
+ applicationId,
+ });
+ })
+ .catch(() => {
+ toast.error("Error updating the command");
+ });
+ };
+
+ return (
+
+
+
+ Run Command
+
+ Run a custom command in the container after the application
+ initialized
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/import/show-import.tsx b/data/apps/dokploy/components/dashboard/application/advanced/import/show-import.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..aa359d67bfaa3783a93ea1492aa5713925f84724
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/import/show-import.tsx
@@ -0,0 +1,347 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Separator } from "@/components/ui/separator";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Code2, Globe2, HardDrive } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const ImportSchema = z.object({
+ base64: z.string(),
+});
+
+type ImportType = z.infer;
+
+interface Props {
+ composeId: string;
+}
+
+export const ShowImport = ({ composeId }: Props) => {
+ const [showModal, setShowModal] = useState(false);
+ const [showMountContent, setShowMountContent] = useState(false);
+ const [selectedMount, setSelectedMount] = useState<{
+ filePath: string;
+ content: string;
+ } | null>(null);
+ const [templateInfo, setTemplateInfo] = useState<{
+ compose: string;
+ template: {
+ domains: Array<{
+ serviceName: string;
+ port: number;
+ path?: string;
+ host?: string;
+ }>;
+ envs: string[];
+ mounts: Array<{
+ filePath: string;
+ content: string;
+ }>;
+ };
+ } | null>(null);
+
+ const utils = api.useUtils();
+ const { mutateAsync: processTemplate, isLoading: isLoadingTemplate } =
+ api.compose.processTemplate.useMutation();
+ const {
+ mutateAsync: importTemplate,
+ isLoading: isImporting,
+ isSuccess: isImportSuccess,
+ } = api.compose.import.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ base64: "",
+ },
+ resolver: zodResolver(ImportSchema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ base64: "",
+ });
+ }, [isImportSuccess]);
+
+ const onSubmit = async () => {
+ const base64 = form.getValues("base64");
+ if (!base64) {
+ toast.error("Please enter a base64 template");
+ return;
+ }
+
+ try {
+ await importTemplate({
+ composeId,
+ base64,
+ });
+ toast.success("Template imported successfully");
+ await utils.compose.one.invalidate({
+ composeId,
+ });
+ setShowModal(false);
+ } catch (_error) {
+ toast.error("Error importing template");
+ }
+ };
+
+ const handleLoadTemplate = async () => {
+ const base64 = form.getValues("base64");
+ if (!base64) {
+ toast.error("Please enter a base64 template");
+ return;
+ }
+
+ try {
+ const result = await processTemplate({
+ composeId,
+ base64,
+ });
+ setTemplateInfo(result);
+ setShowModal(true);
+ } catch (_error) {
+ toast.error("Error processing template");
+ }
+ };
+
+ const handleShowMountContent = (mount: {
+ filePath: string;
+ content: string;
+ }) => {
+ setSelectedMount(mount);
+ setShowMountContent(true);
+ };
+
+ return (
+ <>
+
+
+ Import
+ Import your Template configuration
+
+
+
+ Warning: Importing a template will remove all existing environment
+ variables, mounts, and domains from this service.
+
+
+
+
+
+
+
+
+
+
+ {selectedMount?.filePath}
+
+ Mount File Content
+
+
+
+
+
+
+
+ setShowMountContent(false)}>Close
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/ports/handle-ports.tsx b/data/apps/dokploy/components/dashboard/application/advanced/ports/handle-ports.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c9758e37f61ae53601cd5a8867d19977c76f3eac
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/ports/handle-ports.tsx
@@ -0,0 +1,239 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon, PlusIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const AddPortSchema = z.object({
+ publishedPort: z.number().int().min(1).max(65535),
+ targetPort: z.number().int().min(1).max(65535),
+ protocol: z.enum(["tcp", "udp"], {
+ required_error: "Protocol is required",
+ }),
+});
+
+type AddPort = z.infer;
+
+interface Props {
+ applicationId: string;
+ portId?: string;
+ children?: React.ReactNode;
+}
+
+export const HandlePorts = ({
+ applicationId,
+ portId,
+ children = ,
+}: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const utils = api.useUtils();
+
+ const { data } = api.port.one.useQuery(
+ {
+ portId: portId ?? "",
+ },
+ {
+ enabled: !!portId,
+ },
+ );
+ const { mutateAsync, isLoading, error, isError } = portId
+ ? api.port.update.useMutation()
+ : api.port.create.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ publishedPort: 0,
+ targetPort: 0,
+ },
+ resolver: zodResolver(AddPortSchema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ publishedPort: data?.publishedPort ?? 0,
+ targetPort: data?.targetPort ?? 0,
+ protocol: data?.protocol ?? "tcp",
+ });
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data]);
+
+ const onSubmit = async (data: AddPort) => {
+ await mutateAsync({
+ applicationId,
+ ...data,
+ portId: portId || "",
+ })
+ .then(async () => {
+ toast.success(portId ? "Port Updated" : "Port Created");
+ await utils.application.one.invalidate({
+ applicationId,
+ });
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error(
+ portId ? "Error updating the port" : "Error creating the port",
+ );
+ });
+ };
+
+ return (
+
+
+ {portId ? (
+
+
+
+ ) : (
+ {children}
+ )}
+
+
+
+ Ports
+
+ Ports are used to expose your application to the internet.
+
+
+ {isError && {error?.message} }
+
+
+
+
+ (
+
+ Published Port
+
+ {
+ const value = e.target.value;
+ if (value === "") {
+ field.onChange(0);
+ } else {
+ const number = Number.parseInt(value, 10);
+ if (!Number.isNaN(number)) {
+ field.onChange(number);
+ }
+ }
+ }}
+ />
+
+
+
+
+ )}
+ />
+ (
+
+ Target Port
+
+ {
+ const value = e.target.value;
+ if (value === "") {
+ field.onChange(0);
+ } else {
+ const number = Number.parseInt(value, 10);
+ if (!Number.isNaN(number)) {
+ field.onChange(number);
+ }
+ }
+ }}
+ />
+
+
+
+
+ )}
+ />
+ {
+ return (
+
+ Protocol
+
+
+
+
+
+
+
+ TCP
+ UDP
+
+
+
+
+ );
+ }}
+ />
+
+
+
+
+
+ {portId ? "Update" : "Create"}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/ports/show-port.tsx b/data/apps/dokploy/components/dashboard/application/advanced/ports/show-port.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..4cd29a36d586be11db178553c6bbe2a1d4701bc7
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/ports/show-port.tsx
@@ -0,0 +1,124 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { Rss, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { HandlePorts } from "./handle-ports";
+interface Props {
+ applicationId: string;
+}
+
+export const ShowPorts = ({ applicationId }: Props) => {
+ const { data, refetch } = api.application.one.useQuery(
+ {
+ applicationId,
+ },
+ { enabled: !!applicationId },
+ );
+
+ const { mutateAsync: deletePort, isLoading: isRemoving } =
+ api.port.delete.useMutation();
+
+ return (
+
+
+
+ Ports
+
+ the ports allows you to expose your application to the internet
+
+
+
+ {data && data?.ports.length > 0 && (
+ Add Port
+ )}
+
+
+ {data?.ports.length === 0 ? (
+
+
+
+ No ports configured
+
+ Add Port
+
+ ) : (
+
+
+ Please remember to click Redeploy after adding, editing, or
+ deleting the ports to apply the changes.
+
+
+ {data?.ports.map((port) => (
+
+
+
+
+ Published Port
+
+ {port.publishedPort}
+
+
+
+ Target Port
+
+ {port.targetPort}
+
+
+
+ Protocol
+
+ {port.protocol.toUpperCase()}
+
+
+
+
+
+ {
+ await deletePort({
+ portId: port.portId,
+ })
+ .then(() => {
+ refetch();
+ toast.success("Port deleted successfully");
+ })
+ .catch(() => {
+ toast.error("Error deleting port");
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/redirects/handle-redirect.tsx b/data/apps/dokploy/components/dashboard/application/advanced/redirects/handle-redirect.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5d91d580ddb7c8cf5daa8b5b3b54dc60145cf924
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/redirects/handle-redirect.tsx
@@ -0,0 +1,282 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Separator } from "@/components/ui/separator";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon, PlusIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const AddRedirectchema = z.object({
+ regex: z.string().min(1, "Regex required"),
+ permanent: z.boolean().default(false),
+ replacement: z.string().min(1, "Replacement required"),
+});
+
+type AddRedirect = z.infer;
+
+// Default presets
+const redirectPresets = [
+ // {
+ // label: "Allow www & non-www.",
+ // redirect: {
+ // regex: "",
+ // permanent: false,
+ // replacement: "",
+ // },
+ // },
+ {
+ id: "to-www",
+ label: "Redirect to www",
+ redirect: {
+ regex: "^https?://(?:www.)?(.+)",
+ permanent: true,
+ replacement: "https://www.${1}",
+ },
+ },
+ {
+ id: "to-non-www",
+ label: "Redirect to non-www",
+ redirect: {
+ regex: "^https?://www.(.+)",
+ permanent: true,
+ replacement: "https://${1}",
+ },
+ },
+];
+
+interface Props {
+ applicationId: string;
+ redirectId?: string;
+ children?: React.ReactNode;
+}
+
+export const HandleRedirect = ({
+ applicationId,
+ redirectId,
+ children = ,
+}: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [presetSelected, setPresetSelected] = useState("");
+
+ const { data, refetch } = api.redirects.one.useQuery(
+ {
+ redirectId: redirectId || "",
+ },
+ {
+ enabled: !!redirectId,
+ },
+ );
+
+ const utils = api.useUtils();
+
+ const { mutateAsync, isLoading, error, isError } = redirectId
+ ? api.redirects.update.useMutation()
+ : api.redirects.create.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ permanent: false,
+ regex: "",
+ replacement: "",
+ },
+ resolver: zodResolver(AddRedirectchema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ permanent: data?.permanent || false,
+ regex: data?.regex || "",
+ replacement: data?.replacement || "",
+ });
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data]);
+
+ const onSubmit = async (data: AddRedirect) => {
+ await mutateAsync({
+ applicationId,
+ ...data,
+ redirectId: redirectId || "",
+ })
+ .then(async () => {
+ toast.success(redirectId ? "Redirect Updated" : "Redirect Created");
+ await utils.application.one.invalidate({
+ applicationId,
+ });
+ refetch();
+ await utils.application.readTraefikConfig.invalidate({
+ applicationId,
+ });
+ onDialogToggle(false);
+ })
+ .catch(() => {
+ toast.error(
+ redirectId
+ ? "Error updating the redirect"
+ : "Error creating the redirect",
+ );
+ });
+ };
+
+ const onDialogToggle = (open: boolean) => {
+ setIsOpen(open);
+ // commented for the moment because not reseting the form if accidentally closed the dialog can be considered as a feature instead of a bug
+ // setPresetSelected("");
+ // form.reset();
+ };
+
+ const onPresetSelect = (presetId: string) => {
+ const redirectPreset = redirectPresets.find(
+ (preset) => preset.id === presetId,
+ )?.redirect;
+ if (!redirectPreset) return;
+ const { regex, permanent, replacement } = redirectPreset;
+ form.reset({ regex, permanent, replacement }, { keepDefaultValues: true });
+ setPresetSelected(presetId);
+ };
+
+ return (
+
+
+ {redirectId ? (
+
+
+
+ ) : (
+ {children}
+ )}
+
+
+
+ Redirects
+
+ Redirects are used to redirect requests to another url.
+
+
+ {isError && {error?.message} }
+
+
+ Presets
+
+
+
+
+
+ {redirectPresets.map((preset) => (
+
+ {preset.label}
+
+ ))}
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {redirectId ? "Update" : "Create"}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/redirects/show-redirects.tsx b/data/apps/dokploy/components/dashboard/application/advanced/redirects/show-redirects.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5c2c5943c5271fbd2d34f5a5936260fc7b218023
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/redirects/show-redirects.tsx
@@ -0,0 +1,131 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { Split, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { HandleRedirect } from "./handle-redirect";
+
+interface Props {
+ applicationId: string;
+}
+
+export const ShowRedirects = ({ applicationId }: Props) => {
+ const { data, refetch } = api.application.one.useQuery(
+ {
+ applicationId,
+ },
+ { enabled: !!applicationId },
+ );
+
+ const { mutateAsync: deleteRedirect, isLoading: isRemoving } =
+ api.redirects.delete.useMutation();
+
+ const utils = api.useUtils();
+
+ return (
+
+
+
+ Redirects
+
+ If you want to redirect requests to this application use the
+ following config to setup the redirects
+
+
+
+ {data && data?.redirects.length > 0 && (
+
+ Add Redirect
+
+ )}
+
+
+ {data?.redirects.length === 0 ? (
+
+
+
+ No redirects configured
+
+
+ Add Redirect
+
+
+ ) : (
+
+
+ {data?.redirects.map((redirect) => (
+
+
+
+
+ Regex
+
+ {redirect.regex}
+
+
+
+ Replacement
+
+ {redirect.replacement}
+
+
+
+ Permanent
+
+ {redirect.permanent ? "Yes" : "No"}
+
+
+
+
+
+
+ {
+ await deleteRedirect({
+ redirectId: redirect.redirectId,
+ })
+ .then(() => {
+ refetch();
+ utils.application.readTraefikConfig.invalidate({
+ applicationId,
+ });
+ toast.success("Redirect deleted successfully");
+ })
+ .catch(() => {
+ toast.error("Error deleting redirect");
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/security/handle-security.tsx b/data/apps/dokploy/components/dashboard/application/advanced/security/handle-security.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e7bc0cd1f3e6ecb4f1be6b71dee921316abbb126
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/security/handle-security.tsx
@@ -0,0 +1,177 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon, PlusIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const AddSecuritychema = z.object({
+ username: z.string().min(1, "Username is required"),
+ password: z.string().min(1, "Password is required"),
+});
+
+type AddSecurity = z.infer;
+
+interface Props {
+ applicationId: string;
+ securityId?: string;
+ children?: React.ReactNode;
+}
+
+export const HandleSecurity = ({
+ applicationId,
+ securityId,
+ children = ,
+}: Props) => {
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+ const { data } = api.security.one.useQuery(
+ {
+ securityId: securityId ?? "",
+ },
+ {
+ enabled: !!securityId,
+ },
+ );
+
+ const { mutateAsync, isLoading, error, isError } = securityId
+ ? api.security.update.useMutation()
+ : api.security.create.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ username: "",
+ password: "",
+ },
+ resolver: zodResolver(AddSecuritychema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ username: data?.username || "",
+ password: data?.password || "",
+ });
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data]);
+
+ const onSubmit = async (data: AddSecurity) => {
+ await mutateAsync({
+ applicationId,
+ ...data,
+ securityId: securityId || "",
+ })
+ .then(async () => {
+ toast.success(securityId ? "Security Updated" : "Security Created");
+ await utils.application.one.invalidate({
+ applicationId,
+ });
+ await utils.application.readTraefikConfig.invalidate({
+ applicationId,
+ });
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error(
+ securityId
+ ? "Error updating the security"
+ : "Error creating security",
+ );
+ });
+ };
+
+ return (
+
+
+ {securityId ? (
+
+
+
+ ) : (
+ {children}
+ )}
+
+
+
+ Security
+
+ {securityId ? "Update" : "Add"} security to your application
+
+
+ {isError && {error?.message} }
+
+
+
+
+ (
+
+ Username
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Password
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+
+ {securityId ? "Update" : "Create"}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/security/show-security.tsx b/data/apps/dokploy/components/dashboard/application/advanced/security/show-security.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..92439f511770da89400c4a8aaca1a0ccf25638de
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/security/show-security.tsx
@@ -0,0 +1,120 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { LockKeyhole, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { HandleSecurity } from "./handle-security";
+
+interface Props {
+ applicationId: string;
+}
+
+export const ShowSecurity = ({ applicationId }: Props) => {
+ const { data, refetch } = api.application.one.useQuery(
+ {
+ applicationId,
+ },
+ { enabled: !!applicationId },
+ );
+
+ const { mutateAsync: deleteSecurity, isLoading: isRemoving } =
+ api.security.delete.useMutation();
+
+ const utils = api.useUtils();
+ return (
+
+
+
+ Security
+ Add basic auth to your application
+
+
+ {data && data?.security.length > 0 && (
+
+ Add Security
+
+ )}
+
+
+ {data?.security.length === 0 ? (
+
+
+
+ No security configured
+
+
+ Add Security
+
+
+ ) : (
+
+
+ {data?.security.map((security) => (
+
+
+
+
+ Username
+
+ {security.username}
+
+
+
+ Password
+
+ {security.password}
+
+
+
+
+
+ {
+ await deleteSecurity({
+ securityId: security.securityId,
+ })
+ .then(() => {
+ refetch();
+ utils.application.readTraefikConfig.invalidate({
+ applicationId,
+ });
+ toast.success("Security deleted successfully");
+ })
+ .catch(() => {
+ toast.error("Error deleting security");
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/show-resources.tsx b/data/apps/dokploy/components/dashboard/application/advanced/show-resources.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..3d26716fcf20f16c5e664f2aac4060ab17e47e66
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/show-resources.tsx
@@ -0,0 +1,287 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { InfoIcon } from "lucide-react";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const addResourcesSchema = z.object({
+ memoryReservation: z.string().optional(),
+ cpuLimit: z.string().optional(),
+ memoryLimit: z.string().optional(),
+ cpuReservation: z.string().optional(),
+});
+
+export type ServiceType =
+ | "postgres"
+ | "mongo"
+ | "redis"
+ | "mysql"
+ | "mariadb"
+ | "application";
+
+interface Props {
+ id: string;
+ type: ServiceType | "application";
+}
+
+type AddResources = z.infer;
+export const ShowResources = ({ id, type }: Props) => {
+ const queryMap = {
+ postgres: () =>
+ api.postgres.one.useQuery({ postgresId: id }, { enabled: !!id }),
+ redis: () => api.redis.one.useQuery({ redisId: id }, { enabled: !!id }),
+ mysql: () => api.mysql.one.useQuery({ mysqlId: id }, { enabled: !!id }),
+ mariadb: () =>
+ api.mariadb.one.useQuery({ mariadbId: id }, { enabled: !!id }),
+ application: () =>
+ api.application.one.useQuery({ applicationId: id }, { enabled: !!id }),
+ mongo: () => api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id }),
+ };
+ const { data, refetch } = queryMap[type]
+ ? queryMap[type]()
+ : api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id });
+
+ const mutationMap = {
+ postgres: () => api.postgres.update.useMutation(),
+ redis: () => api.redis.update.useMutation(),
+ mysql: () => api.mysql.update.useMutation(),
+ mariadb: () => api.mariadb.update.useMutation(),
+ application: () => api.application.update.useMutation(),
+ mongo: () => api.mongo.update.useMutation(),
+ };
+
+ const { mutateAsync, isLoading } = mutationMap[type]
+ ? mutationMap[type]()
+ : api.mongo.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ cpuLimit: "",
+ cpuReservation: "",
+ memoryLimit: "",
+ memoryReservation: "",
+ },
+ resolver: zodResolver(addResourcesSchema),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ cpuLimit: data?.cpuLimit || undefined,
+ cpuReservation: data?.cpuReservation || undefined,
+ memoryLimit: data?.memoryLimit || undefined,
+ memoryReservation: data?.memoryReservation || undefined,
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: AddResources) => {
+ await mutateAsync({
+ mongoId: id || "",
+ postgresId: id || "",
+ redisId: id || "",
+ mysqlId: id || "",
+ mariadbId: id || "",
+ applicationId: id || "",
+ cpuLimit: formData.cpuLimit || null,
+ cpuReservation: formData.cpuReservation || null,
+ memoryLimit: formData.memoryLimit || null,
+ memoryReservation: formData.memoryReservation || null,
+ })
+ .then(async () => {
+ toast.success("Resources Updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error updating the resources");
+ });
+ };
+
+ return (
+
+
+ Resources
+
+ If you want to decrease or increase the resources to a specific.
+ application or database
+
+
+
+
+ Please remember to click Redeploy after modify the resources to apply
+ the changes.
+
+
+
+
+
{
+ return (
+
+
+
Memory Limit
+
+
+
+
+
+
+
+ Memory hard limit in bytes. Example: 1GB =
+ 1073741824 bytes
+
+
+
+
+
+
+
+
+
+
+ );
+ }}
+ />
+ (
+
+
+
Memory Reservation
+
+
+
+
+
+
+
+ Memory soft limit in bytes. Example: 256MB =
+ 268435456 bytes
+
+
+
+
+
+
+
+
+
+
+ )}
+ />
+
+ {
+ return (
+
+
+
CPU Limit
+
+
+
+
+
+
+
+ CPU quota in units of 10^-9 CPUs. Example: 2
+ CPUs = 2000000000
+
+
+
+
+
+
+
+
+
+
+ );
+ }}
+ />
+ {
+ return (
+
+
+
CPU Reservation
+
+
+
+
+
+
+
+ CPU shares (relative weight). Example: 1 CPU =
+ 1000000000
+
+
+
+
+
+
+
+
+
+
+ );
+ }}
+ />
+
+
+
+ Save
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/traefik/show-traefik-config.tsx b/data/apps/dokploy/components/dashboard/application/advanced/traefik/show-traefik-config.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..58601fb494c2188c59e96401704ee79d5a127729
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/traefik/show-traefik-config.tsx
@@ -0,0 +1,67 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { File, Loader2 } from "lucide-react";
+import { UpdateTraefikConfig } from "./update-traefik-config";
+interface Props {
+ applicationId: string;
+}
+
+export const ShowTraefikConfig = ({ applicationId }: Props) => {
+ const { data, isLoading } = api.application.readTraefikConfig.useQuery(
+ {
+ applicationId,
+ },
+ { enabled: !!applicationId },
+ );
+
+ return (
+
+
+
+ Traefik
+
+ Modify the traefik config, in rare cases you may need to add
+ specific config, be careful because modifying incorrectly can break
+ traefik and your application
+
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : !data ? (
+
+
+
+ No traefik config detected
+
+
+ ) : (
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/traefik/update-traefik-config.tsx b/data/apps/dokploy/components/dashboard/application/advanced/traefik/update-traefik-config.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..f563f1ab49b4a95d2046cc067fe8b5e7f97c5d4c
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/traefik/update-traefik-config.tsx
@@ -0,0 +1,185 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import jsyaml from "js-yaml";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const UpdateTraefikConfigSchema = z.object({
+ traefikConfig: z.string(),
+});
+
+type UpdateTraefikConfig = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const validateAndFormatYAML = (yamlText: string) => {
+ try {
+ const obj = jsyaml.load(yamlText);
+ const formattedYaml = jsyaml.dump(obj, { indent: 4 });
+ return { valid: true, formattedYaml, error: null };
+ } catch (error) {
+ if (error instanceof jsyaml.YAMLException) {
+ return {
+ valid: false,
+ formattedYaml: yamlText,
+ error: error.message,
+ };
+ }
+ return {
+ valid: false,
+ formattedYaml: yamlText,
+ error: "An unexpected error occurred while processing the YAML.",
+ };
+ }
+};
+
+export const UpdateTraefikConfig = ({ applicationId }: Props) => {
+ const [open, setOpen] = useState(false);
+ const { data, refetch } = api.application.readTraefikConfig.useQuery(
+ {
+ applicationId,
+ },
+ { enabled: !!applicationId },
+ );
+
+ const { mutateAsync, isLoading, error, isError } =
+ api.application.updateTraefikConfig.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ traefikConfig: "",
+ },
+ resolver: zodResolver(UpdateTraefikConfigSchema),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ traefikConfig: data || "",
+ });
+ }
+ }, [data]);
+
+ const onSubmit = async (data: UpdateTraefikConfig) => {
+ const { valid, error } = validateAndFormatYAML(data.traefikConfig);
+ if (!valid) {
+ form.setError("traefikConfig", {
+ type: "manual",
+ message: error || "Invalid YAML",
+ });
+ return;
+ }
+ form.clearErrors("traefikConfig");
+ await mutateAsync({
+ applicationId,
+ traefikConfig: data.traefikConfig,
+ })
+ .then(async () => {
+ toast.success("Traefik config Updated");
+ refetch();
+ setOpen(false);
+ form.reset();
+ })
+ .catch(() => {
+ toast.error("Error updating the Traefik config");
+ });
+ };
+
+ return (
+ {
+ setOpen(open);
+ if (!open) {
+ form.reset();
+ }
+ }}
+ >
+
+ Modify
+
+
+
+ Update traefik config
+ Update the traefik config
+
+ {isError && {error?.message} }
+
+
+
+
+
(
+
+ Traefik config
+
+
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+
+ Update
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/volumes/add-volumes.tsx b/data/apps/dokploy/components/dashboard/application/advanced/volumes/add-volumes.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..718f98b726baec62af7de146fdab4460562d4bc9
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/volumes/add-volumes.tsx
@@ -0,0 +1,373 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PlusIcon } from "lucide-react";
+import type React from "react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+interface Props {
+ serviceId: string;
+ serviceType:
+ | "application"
+ | "postgres"
+ | "redis"
+ | "mongo"
+ | "redis"
+ | "mysql"
+ | "mariadb"
+ | "compose";
+ refetch: () => void;
+ children?: React.ReactNode;
+}
+
+const mountSchema = z.object({
+ mountPath: z.string().min(1, "Mount path required"),
+});
+
+const mySchema = z.discriminatedUnion("type", [
+ z
+ .object({
+ type: z.literal("bind"),
+ hostPath: z.string().min(1, "Host path required"),
+ })
+ .merge(mountSchema),
+ z
+ .object({
+ type: z.literal("volume"),
+ volumeName: z.string().min(1, "Volume name required"),
+ })
+ .merge(mountSchema),
+ z
+ .object({
+ type: z.literal("file"),
+ filePath: z.string().min(1, "File path required"),
+ content: z.string().optional(),
+ })
+ .merge(mountSchema),
+]);
+
+type AddMount = z.infer;
+
+export const AddVolumes = ({
+ serviceId,
+ serviceType,
+ refetch,
+ children = ,
+}: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const { mutateAsync } = api.mounts.create.useMutation();
+ const form = useForm({
+ defaultValues: {
+ type: serviceType === "compose" ? "file" : "bind",
+ hostPath: "",
+ mountPath: serviceType === "compose" ? "/" : "",
+ },
+ resolver: zodResolver(mySchema),
+ });
+ const type = form.watch("type");
+
+ useEffect(() => {
+ form.reset();
+ }, [form, form.reset, form.formState.isSubmitSuccessful]);
+
+ const onSubmit = async (data: AddMount) => {
+ if (data.type === "bind") {
+ await mutateAsync({
+ serviceId,
+ hostPath: data.hostPath,
+ mountPath: data.mountPath,
+ type: data.type,
+ serviceType,
+ })
+ .then(() => {
+ toast.success("Mount Created");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error creating the Bind mount");
+ });
+ } else if (data.type === "volume") {
+ await mutateAsync({
+ serviceId,
+ volumeName: data.volumeName,
+ mountPath: data.mountPath,
+ type: data.type,
+ serviceType,
+ })
+ .then(() => {
+ toast.success("Mount Created");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error creating the Volume mount");
+ });
+ } else if (data.type === "file") {
+ await mutateAsync({
+ serviceId,
+ content: data.content,
+ mountPath: data.mountPath,
+ filePath: data.filePath,
+ type: data.type,
+ serviceType,
+ })
+ .then(() => {
+ toast.success("Mount Created");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error creating the File mount");
+ });
+ }
+
+ refetch();
+ };
+
+ return (
+
+
+ {children}
+
+
+
+ Volumes / Mounts
+
+ {/* {isError && (
+
+
+
+ {error?.message}
+
+
+ )} */}
+
+
+
+ (
+
+
+ Select the Mount Type
+
+
+
+ {serviceType !== "compose" && (
+
+
+
+
+
+ Bind Mount
+
+
+
+
+ )}
+
+ {serviceType !== "compose" && (
+
+
+
+
+
+ Volume Mount
+
+
+
+
+ )}
+
+
+
+
+
+
+ File Mount
+
+
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+
+ Create
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/volumes/show-volumes.tsx b/data/apps/dokploy/components/dashboard/application/advanced/volumes/show-volumes.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2a2d2c03292d8778dbdbe69aecd072aee4dc9a1e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/volumes/show-volumes.tsx
@@ -0,0 +1,174 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { Package, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import type { ServiceType } from "../show-resources";
+import { AddVolumes } from "./add-volumes";
+import { UpdateVolume } from "./update-volume";
+interface Props {
+ id: string;
+ type: ServiceType | "compose";
+}
+
+export const ShowVolumes = ({ id, type }: Props) => {
+ const queryMap = {
+ postgres: () =>
+ api.postgres.one.useQuery({ postgresId: id }, { enabled: !!id }),
+ redis: () => api.redis.one.useQuery({ redisId: id }, { enabled: !!id }),
+ mysql: () => api.mysql.one.useQuery({ mysqlId: id }, { enabled: !!id }),
+ mariadb: () =>
+ api.mariadb.one.useQuery({ mariadbId: id }, { enabled: !!id }),
+ application: () =>
+ api.application.one.useQuery({ applicationId: id }, { enabled: !!id }),
+ mongo: () => api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id }),
+ compose: () =>
+ api.compose.one.useQuery({ composeId: id }, { enabled: !!id }),
+ };
+ const { data, refetch } = queryMap[type]
+ ? queryMap[type]()
+ : api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id });
+ const { mutateAsync: deleteVolume, isLoading: isRemoving } =
+ api.mounts.remove.useMutation();
+ return (
+
+
+
+ Volumes
+
+ If you want to persist data in this service use the following config
+ to setup the volumes
+
+
+
+ {data && data?.mounts.length > 0 && (
+
+ Add Volume
+
+ )}
+
+
+ {data?.mounts.length === 0 ? (
+
+
+
+ No volumes/mounts configured
+
+
+ Add Volume
+
+
+ ) : (
+
+
+ Please remember to click Redeploy after adding, editing, or
+ deleting a mount to apply the changes.
+
+
+ {data?.mounts.map((mount) => (
+
+
+ {/*
*/}
+
+
+ Mount Type
+
+ {mount.type.toUpperCase()}
+
+
+ {mount.type === "volume" && (
+
+ Volume Name
+
+ {mount.volumeName}
+
+
+ )}
+
+ {mount.type === "file" && (
+
+ Content
+
+ {mount.content}
+
+
+ )}
+ {mount.type === "bind" && (
+
+ Host Path
+
+ {mount.hostPath}
+
+
+ )}
+ {mount.type === "file" ? (
+
+ File Path
+
+ {mount.filePath}
+
+
+ ) : (
+
+ Mount Path
+
+ {mount.mountPath}
+
+
+ )}
+
+
+
+ {
+ await deleteVolume({
+ mountId: mount.mountId,
+ })
+ .then(() => {
+ refetch();
+ toast.success("Volume deleted successfully");
+ })
+ .catch(() => {
+ toast.error("Error deleting volume");
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/advanced/volumes/update-volume.tsx b/data/apps/dokploy/components/dashboard/application/advanced/volumes/update-volume.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8da09b58b48bd85ab2e6f49a74409fddc9bf4a1e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/advanced/volumes/update-volume.tsx
@@ -0,0 +1,319 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const mountSchema = z.object({
+ mountPath: z.string().min(1, "Mount path required"),
+});
+
+const mySchema = z.discriminatedUnion("type", [
+ z
+ .object({
+ type: z.literal("bind"),
+ hostPath: z.string().min(1, "Host path required"),
+ })
+ .merge(mountSchema),
+ z
+ .object({
+ type: z.literal("volume"),
+ volumeName: z.string().min(1, "Volume name required"),
+ })
+ .merge(mountSchema),
+ z
+ .object({
+ type: z.literal("file"),
+ content: z.string().optional(),
+ filePath: z.string().min(1, "File path required"),
+ })
+ .merge(mountSchema),
+]);
+
+type UpdateMount = z.infer;
+
+interface Props {
+ mountId: string;
+ type: "bind" | "volume" | "file";
+ refetch: () => void;
+ serviceType:
+ | "application"
+ | "postgres"
+ | "redis"
+ | "mongo"
+ | "redis"
+ | "mysql"
+ | "mariadb"
+ | "compose";
+}
+
+export const UpdateVolume = ({
+ mountId,
+ type,
+ refetch,
+ serviceType,
+}: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const _utils = api.useUtils();
+ const { data } = api.mounts.one.useQuery(
+ {
+ mountId,
+ },
+ {
+ enabled: !!mountId,
+ },
+ );
+
+ const { mutateAsync, isLoading, error, isError } =
+ api.mounts.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ type,
+ hostPath: "",
+ mountPath: "",
+ },
+ resolver: zodResolver(mySchema),
+ });
+
+ const typeForm = form.watch("type");
+
+ useEffect(() => {
+ if (data) {
+ if (typeForm === "bind") {
+ form.reset({
+ hostPath: data.hostPath || "",
+ mountPath: data.mountPath,
+ type: "bind",
+ });
+ } else if (typeForm === "volume") {
+ form.reset({
+ volumeName: data.volumeName || "",
+ mountPath: data.mountPath,
+ type: "volume",
+ });
+ } else if (typeForm === "file") {
+ form.reset({
+ content: data.content || "",
+ mountPath: serviceType === "compose" ? "/" : data.mountPath,
+ filePath: data.filePath || "",
+ type: "file",
+ });
+ }
+ }
+ }, [form, form.reset, data]);
+
+ const onSubmit = async (data: UpdateMount) => {
+ if (data.type === "bind") {
+ await mutateAsync({
+ hostPath: data.hostPath,
+ mountPath: data.mountPath,
+ type: data.type,
+ mountId,
+ })
+ .then(() => {
+ toast.success("Mount Update");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating the Bind mount");
+ });
+ } else if (data.type === "volume") {
+ await mutateAsync({
+ volumeName: data.volumeName,
+ mountPath: data.mountPath,
+ type: data.type,
+ mountId,
+ })
+ .then(() => {
+ toast.success("Mount Update");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating the Volume mount");
+ });
+ } else if (data.type === "file") {
+ await mutateAsync({
+ content: data.content,
+ mountPath: data.mountPath,
+ type: data.type,
+ filePath: data.filePath,
+ mountId,
+ })
+ .then(() => {
+ toast.success("Mount Update");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating the File mount");
+ });
+ }
+ refetch();
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Update
+ Update the mount
+
+ {isError && {error?.message} }
+ {type === "file" && (
+
+ Updating the mount will recreate the file or directory.
+
+ )}
+
+
+
+
+ {type === "bind" && (
+ (
+
+ Host Path
+
+
+
+
+
+
+ )}
+ />
+ )}
+ {type === "volume" && (
+ (
+
+ Volume Name
+
+
+
+
+
+ )}
+ />
+ )}
+
+ {type === "file" && (
+ <>
+ (
+
+ Content
+
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+ File Path
+
+
+
+
+
+ )}
+ />
+ >
+ )}
+ {serviceType !== "compose" && (
+ (
+
+ Mount Path (In the container)
+
+
+
+
+
+
+ )}
+ />
+ )}
+
+
+
+ Update
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/build/show.tsx b/data/apps/dokploy/components/dashboard/application/build/show.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..291026d4f801ae663d51e928ec7e85a6256e028a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/build/show.tsx
@@ -0,0 +1,408 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Cog } from "lucide-react";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+export enum BuildType {
+ dockerfile = "dockerfile",
+ heroku_buildpacks = "heroku_buildpacks",
+ paketo_buildpacks = "paketo_buildpacks",
+ nixpacks = "nixpacks",
+ static = "static",
+ railpack = "railpack",
+}
+
+const buildTypeDisplayMap: Record = {
+ [BuildType.dockerfile]: "Dockerfile",
+ [BuildType.railpack]: "Railpack",
+ [BuildType.nixpacks]: "Nixpacks",
+ [BuildType.heroku_buildpacks]: "Heroku Buildpacks",
+ [BuildType.paketo_buildpacks]: "Paketo Buildpacks",
+ [BuildType.static]: "Static",
+};
+
+const mySchema = z.discriminatedUnion("buildType", [
+ z.object({
+ buildType: z.literal(BuildType.dockerfile),
+ dockerfile: z
+ .string({
+ required_error: "Dockerfile path is required",
+ invalid_type_error: "Dockerfile path is required",
+ })
+ .min(1, "Dockerfile required"),
+ dockerContextPath: z.string().nullable().default(""),
+ dockerBuildStage: z.string().nullable().default(""),
+ }),
+ z.object({
+ buildType: z.literal(BuildType.heroku_buildpacks),
+ herokuVersion: z.string().nullable().default(""),
+ }),
+ z.object({
+ buildType: z.literal(BuildType.paketo_buildpacks),
+ }),
+ z.object({
+ buildType: z.literal(BuildType.nixpacks),
+ publishDirectory: z.string().optional(),
+ }),
+ z.object({
+ buildType: z.literal(BuildType.railpack),
+ }),
+ z.object({
+ buildType: z.literal(BuildType.static),
+ isStaticSpa: z.boolean().default(false),
+ }),
+]);
+
+type AddTemplate = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+interface ApplicationData {
+ buildType: BuildType;
+ dockerfile?: string | null;
+ dockerContextPath?: string | null;
+ dockerBuildStage?: string | null;
+ herokuVersion?: string | null;
+ publishDirectory?: string | null;
+ isStaticSpa?: boolean | null;
+}
+
+function isValidBuildType(value: string): value is BuildType {
+ return Object.values(BuildType).includes(value as BuildType);
+}
+
+const resetData = (data: ApplicationData): AddTemplate => {
+ switch (data.buildType) {
+ case BuildType.dockerfile:
+ return {
+ buildType: BuildType.dockerfile,
+ dockerfile: data.dockerfile || "",
+ dockerContextPath: data.dockerContextPath || "",
+ dockerBuildStage: data.dockerBuildStage || "",
+ };
+ case BuildType.heroku_buildpacks:
+ return {
+ buildType: BuildType.heroku_buildpacks,
+ herokuVersion: data.herokuVersion || "",
+ };
+ case BuildType.nixpacks:
+ return {
+ buildType: BuildType.nixpacks,
+ publishDirectory: data.publishDirectory || undefined,
+ };
+ case BuildType.paketo_buildpacks:
+ return {
+ buildType: BuildType.paketo_buildpacks,
+ };
+ case BuildType.static:
+ return {
+ buildType: BuildType.static,
+ isStaticSpa: data.isStaticSpa ?? false,
+ };
+ case BuildType.railpack:
+ return {
+ buildType: BuildType.railpack,
+ };
+ default: {
+ const buildType = data.buildType as BuildType;
+ return {
+ buildType,
+ } as AddTemplate;
+ }
+ }
+};
+
+export const ShowBuildChooseForm = ({ applicationId }: Props) => {
+ const { mutateAsync, isLoading } =
+ api.application.saveBuildType.useMutation();
+ const { data, refetch } = api.application.one.useQuery(
+ { applicationId },
+ { enabled: !!applicationId },
+ );
+
+ const form = useForm({
+ defaultValues: {
+ buildType: BuildType.nixpacks,
+ },
+ resolver: zodResolver(mySchema),
+ });
+
+ const buildType = form.watch("buildType");
+
+ useEffect(() => {
+ if (data) {
+ const typedData: ApplicationData = {
+ ...data,
+ buildType: isValidBuildType(data.buildType)
+ ? (data.buildType as BuildType)
+ : BuildType.nixpacks, // fallback
+ };
+
+ form.reset(resetData(typedData));
+ }
+ }, [data, form]);
+
+ const onSubmit = async (data: AddTemplate) => {
+ await mutateAsync({
+ applicationId,
+ buildType: data.buildType,
+ publishDirectory:
+ data.buildType === BuildType.nixpacks ? data.publishDirectory : null,
+ dockerfile:
+ data.buildType === BuildType.dockerfile ? data.dockerfile : null,
+ dockerContextPath:
+ data.buildType === BuildType.dockerfile ? data.dockerContextPath : null,
+ dockerBuildStage:
+ data.buildType === BuildType.dockerfile ? data.dockerBuildStage : null,
+ herokuVersion:
+ data.buildType === BuildType.heroku_buildpacks
+ ? data.herokuVersion
+ : null,
+ isStaticSpa:
+ data.buildType === BuildType.static ? data.isStaticSpa : null,
+ })
+ .then(async () => {
+ toast.success("Build type saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the build type");
+ });
+ };
+
+ return (
+
+
+
+
+
Build Type
+
+ Select the way of building your code
+
+
+
+
+
+
+
+
+
+
+ Builders can consume significant memory and CPU resources
+ (recommended: 4+ GB RAM and 2+ CPU cores). For production
+ environments, please review our{" "}
+
+ Production Guide
+ {" "}
+ for best practices and optimization recommendations. Builders are
+ suitable for development and prototyping purposes when you have
+ sufficient resources available.
+
+
+ (
+
+ Build Type
+
+
+ {Object.entries(buildTypeDisplayMap).map(
+ ([value, label]) => (
+
+
+
+
+
+ {label}
+ {value === BuildType.railpack && (
+ New
+ )}
+
+
+ ),
+ )}
+
+
+
+
+ )}
+ />
+ {buildType === BuildType.heroku_buildpacks && (
+ (
+
+ Heroku Version (Optional)
+
+
+
+
+
+ )}
+ />
+ )}
+ {buildType === BuildType.dockerfile && (
+ <>
+ (
+
+ Docker File
+
+
+
+
+
+ )}
+ />
+ (
+
+ Docker Context Path
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Docker Build Stage
+
+ Allows you to target a specific stage in a Multi-stage
+ Dockerfile. If empty, Docker defaults to build the
+ last defined stage.
+
+
+
+
+
+
+ )}
+ />
+ >
+ )}
+ {buildType === BuildType.nixpacks && (
+ (
+
+
+ Publish Directory
+
+ Allows you to serve a single directory via NGINX after
+ the build phase. Useful if the final build assets should
+ be served as a static site.
+
+
+
+
+
+
+
+ )}
+ />
+ )}
+ {buildType === BuildType.static && (
+ (
+
+
+
+
+
+ Single Page Application (SPA)
+
+
+
+
+
+ )}
+ />
+ )}
+
+
+ Save
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/deployments/cancel-queues.tsx b/data/apps/dokploy/components/dashboard/application/deployments/cancel-queues.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..eb85f383b686560150d0d962a177d1a51b54d654
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/deployments/cancel-queues.tsx
@@ -0,0 +1,72 @@
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { api } from "@/utils/api";
+import { Paintbrush } from "lucide-react";
+import { toast } from "sonner";
+
+interface Props {
+ id: string;
+ type: "application" | "compose";
+}
+
+export const CancelQueues = ({ id, type }: Props) => {
+ const { mutateAsync, isLoading } =
+ type === "application"
+ ? api.application.cleanQueues.useMutation()
+ : api.compose.cleanQueues.useMutation();
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+
+ if (isCloud) {
+ return null;
+ }
+
+ return (
+
+
+
+ Cancel Queues
+
+
+
+
+
+
+ Are you sure to cancel the incoming deployments?
+
+
+ This will cancel all the incoming deployments
+
+
+
+ Cancel
+ {
+ await mutateAsync({
+ applicationId: id || "",
+ composeId: id || "",
+ })
+ .then(() => {
+ toast.success("Queues are being cleaned");
+ })
+ .catch((err) => {
+ toast.error(err.message);
+ });
+ }}
+ >
+ Confirm
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/deployments/refresh-token.tsx b/data/apps/dokploy/components/dashboard/application/deployments/refresh-token.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..abfe37c3cd1fe44ca0a6d0003f6be2b3726cbb3e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/deployments/refresh-token.tsx
@@ -0,0 +1,70 @@
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { api } from "@/utils/api";
+import { RefreshCcw } from "lucide-react";
+import { toast } from "sonner";
+
+interface Props {
+ id: string;
+ type: "application" | "compose";
+}
+export const RefreshToken = ({ id, type }: Props) => {
+ const { mutateAsync } =
+ type === "application"
+ ? api.application.refreshToken.useMutation()
+ : api.compose.refreshToken.useMutation();
+ const utils = api.useUtils();
+ return (
+
+
+
+
+
+
+ Are you absolutely sure?
+
+ This action cannot be undone. This will change the refresh token and
+ other tokens will be invalidated.
+
+
+
+ Cancel
+ {
+ await mutateAsync({
+ applicationId: id || "",
+ composeId: id || "",
+ })
+ .then(() => {
+ if (type === "application") {
+ utils.application.one.invalidate({
+ applicationId: id,
+ });
+ } else {
+ utils.compose.one.invalidate({
+ composeId: id,
+ });
+ }
+ toast.success("Refresh updated");
+ })
+ .catch(() => {
+ toast.error("Error updating the refresh token");
+ });
+ }}
+ >
+ Confirm
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/deployments/show-deployment.tsx b/data/apps/dokploy/components/dashboard/application/deployments/show-deployment.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e6fdb38bec878f17f7a2f152336a77e36aa793b5
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/deployments/show-deployment.tsx
@@ -0,0 +1,185 @@
+import { Badge } from "@/components/ui/badge";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Loader2 } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { TerminalLine } from "../../docker/logs/terminal-line";
+import { type LogLine, parseLogs } from "../../docker/logs/utils";
+
+interface Props {
+ logPath: string | null;
+ open: boolean;
+ onClose: () => void;
+ serverId?: string;
+ errorMessage?: string;
+}
+export const ShowDeployment = ({
+ logPath,
+ open,
+ onClose,
+ serverId,
+ errorMessage,
+}: Props) => {
+ const [data, setData] = useState("");
+ const [showExtraLogs, setShowExtraLogs] = useState(false);
+ const [filteredLogs, setFilteredLogs] = useState([]);
+ const wsRef = useRef(null); // Ref to hold WebSocket instance
+ const [autoScroll, setAutoScroll] = useState(true);
+ const scrollRef = useRef(null);
+
+ const scrollToBottom = () => {
+ if (autoScroll && scrollRef.current) {
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ }
+ };
+
+ const handleScroll = () => {
+ if (!scrollRef.current) return;
+
+ const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;
+ const isAtBottom = Math.abs(scrollHeight - scrollTop - clientHeight) < 10;
+ setAutoScroll(isAtBottom);
+ };
+
+ useEffect(() => {
+ if (!open || !logPath) return;
+
+ setData("");
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+
+ const wsUrl = `${protocol}//${window.location.host}/listen-deployment?logPath=${logPath}${serverId ? `&serverId=${serverId}` : ""}`;
+ const ws = new WebSocket(wsUrl);
+ wsRef.current = ws; // Store WebSocket instance in ref
+
+ ws.onmessage = (e) => {
+ setData((currentData) => currentData + e.data);
+ };
+
+ ws.onerror = (error) => {
+ console.error("WebSocket error: ", error);
+ };
+
+ ws.onclose = () => {
+ wsRef.current = null; // Clear reference on close
+ };
+
+ return () => {
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
+ ws.close();
+ wsRef.current = null;
+ }
+ };
+ }, [logPath, open]);
+
+ useEffect(() => {
+ const logs = parseLogs(data);
+ let filteredLogsResult = logs;
+ if (serverId) {
+ let hideSubsequentLogs = false;
+ filteredLogsResult = logs.filter((log) => {
+ if (
+ log.message.includes(
+ "===================================EXTRA LOGS============================================",
+ )
+ ) {
+ hideSubsequentLogs = true;
+ return showExtraLogs;
+ }
+ return showExtraLogs ? true : !hideSubsequentLogs;
+ });
+ }
+
+ setFilteredLogs(filteredLogsResult);
+ }, [data, showExtraLogs]);
+
+ useEffect(() => {
+ scrollToBottom();
+
+ if (autoScroll && scrollRef.current) {
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ }
+ }, [filteredLogs, autoScroll]);
+
+ const optionalErrors = parseLogs(errorMessage || "");
+
+ return (
+ {
+ onClose();
+ if (!e) {
+ setData("");
+ }
+
+ if (wsRef.current) {
+ if (wsRef.current.readyState === WebSocket.OPEN) {
+ wsRef.current.close();
+ }
+ }
+ }}
+ >
+
+
+ Deployment
+
+
+ See all the details of this deployment |{" "}
+
+ {filteredLogs.length} lines
+
+
+
+ {serverId && (
+
+
+ )}
+
+
+
+
+ {" "}
+ {filteredLogs.length > 0 ? (
+ filteredLogs.map((log: LogLine, index: number) => (
+
+ ))
+ ) : (
+ <>
+ {optionalErrors.length > 0 ? (
+ optionalErrors.map((log: LogLine, index: number) => (
+
+ ))
+ ) : (
+
+
+
+ )}
+ >
+ )}
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/deployments/show-deployments-modal.tsx b/data/apps/dokploy/components/dashboard/application/deployments/show-deployments-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c018a97cc8e2412e087b9e7ae86032005a388825
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/deployments/show-deployments-modal.tsx
@@ -0,0 +1,69 @@
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
+
+import type { RouterOutputs } from "@/utils/api";
+import { useState } from "react";
+import { ShowDeployment } from "../deployments/show-deployment";
+import { ShowDeployments } from "./show-deployments";
+
+interface Props {
+ id: string;
+ type:
+ | "application"
+ | "compose"
+ | "schedule"
+ | "server"
+ | "backup"
+ | "previewDeployment";
+ serverId?: string;
+ refreshToken?: string;
+ children?: React.ReactNode;
+}
+
+export const formatDuration = (seconds: number) => {
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ const remainingSeconds = seconds % 60;
+ return `${minutes}m ${remainingSeconds}s`;
+};
+
+export const ShowDeploymentsModal = ({
+ id,
+ type,
+ serverId,
+ refreshToken,
+ children,
+}: Props) => {
+ const [activeLog, setActiveLog] = useState<
+ RouterOutputs["deployment"]["all"][number] | null
+ >(null);
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+
+
+ {children ? (
+ children
+ ) : (
+
+ View Logs
+
+ )}
+
+
+
+
+ setActiveLog(null)}
+ logPath={activeLog?.logPath || ""}
+ errorMessage={activeLog?.errorMessage || ""}
+ />
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/deployments/show-deployments.tsx b/data/apps/dokploy/components/dashboard/application/deployments/show-deployments.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..3cb18f98e721610544a75e40252e4ff69d12b95c
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/deployments/show-deployments.tsx
@@ -0,0 +1,179 @@
+import { DateTooltip } from "@/components/shared/date-tooltip";
+import { StatusTooltip } from "@/components/shared/status-tooltip";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { type RouterOutputs, api } from "@/utils/api";
+import { Clock, Loader2, RocketIcon } from "lucide-react";
+import React, { useEffect, useState } from "react";
+import { CancelQueues } from "./cancel-queues";
+import { RefreshToken } from "./refresh-token";
+import { ShowDeployment } from "./show-deployment";
+
+interface Props {
+ id: string;
+ type:
+ | "application"
+ | "compose"
+ | "schedule"
+ | "server"
+ | "backup"
+ | "previewDeployment";
+ refreshToken?: string;
+ serverId?: string;
+}
+
+export const formatDuration = (seconds: number) => {
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ const remainingSeconds = seconds % 60;
+ return `${minutes}m ${remainingSeconds}s`;
+};
+
+export const ShowDeployments = ({
+ id,
+ type,
+ refreshToken,
+ serverId,
+}: Props) => {
+ const [activeLog, setActiveLog] = useState<
+ RouterOutputs["deployment"]["all"][number] | null
+ >(null);
+ const { data: deployments, isLoading: isLoadingDeployments } =
+ api.deployment.allByType.useQuery(
+ {
+ id,
+ type,
+ },
+ {
+ enabled: !!id,
+ refetchInterval: 1000,
+ },
+ );
+
+ const [url, setUrl] = React.useState("");
+ useEffect(() => {
+ setUrl(document.location.origin);
+ }, []);
+
+ return (
+
+
+
+ Deployments
+
+ See all the 10 last deployments for this {type}
+
+
+ {(type === "application" || type === "compose") && (
+
+ )}
+
+
+ {refreshToken && (
+
+
+ If you want to re-deploy this application use this URL in the
+ config of your git provider or docker
+
+
+
Webhook URL:
+
+
+ {`${url}/api/deploy${type === "compose" ? "/compose" : ""}/${refreshToken}`}
+
+ {(type === "application" || type === "compose") && (
+
+ )}
+
+
+
+ )}
+
+ {isLoadingDeployments ? (
+
+
+
+ Loading deployments...
+
+
+ ) : deployments?.length === 0 ? (
+
+
+
+ No deployments found
+
+
+ ) : (
+
+ {deployments?.map((deployment, index) => (
+
+
+
+ {index + 1}. {deployment.status}
+
+
+
+ {deployment.title}
+
+ {deployment.description && (
+
+ {deployment.description}
+
+ )}
+
+
+
+
+ {deployment.startedAt && deployment.finishedAt && (
+
+
+ {formatDuration(
+ Math.floor(
+ (new Date(deployment.finishedAt).getTime() -
+ new Date(deployment.startedAt).getTime()) /
+ 1000,
+ ),
+ )}
+
+ )}
+
+
+
{
+ setActiveLog(deployment);
+ }}
+ >
+ View
+
+
+
+ ))}
+
+ )}
+ setActiveLog(null)}
+ logPath={activeLog?.logPath || ""}
+ errorMessage={activeLog?.errorMessage || ""}
+ />
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/domains/dns-helper-modal.tsx b/data/apps/dokploy/components/dashboard/application/domains/dns-helper-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e7b2f18774a3eec8d3b4965885ebb83f28e30631
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/domains/dns-helper-modal.tsx
@@ -0,0 +1,109 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Copy, HelpCircle, Server } from "lucide-react";
+import { toast } from "sonner";
+
+interface Props {
+ domain: {
+ host: string;
+ https: boolean;
+ path?: string;
+ };
+ serverIp?: string;
+}
+
+export const DnsHelperModal = ({ domain, serverIp }: Props) => {
+ const copyToClipboard = (text: string) => {
+ navigator.clipboard.writeText(text);
+ toast.success("Copied to clipboard!");
+ };
+
+ return (
+
+
+
+
+
+
+
+
+
+
+ DNS Configuration Guide
+
+
+ Follow these steps to configure your DNS records for {domain.host}
+
+
+
+
+
+ To make your domain accessible, you need to configure your DNS
+ records with your domain provider (e.g., Cloudflare, GoDaddy,
+ NameCheap).
+
+
+
+
+
1. Add A Record
+
+
+ Create an A record that points your domain to the server's IP
+ address:
+
+
+
+
+
Type: A
+
+ Name: @ or {domain.host.split(".")[0]}
+
+
+ Value: {serverIp || "Your server IP"}
+
+
+
copyToClipboard(serverIp || "")}
+ disabled={!serverIp}
+ >
+
+
+
+
+
+
+
+
+
2. Verify Configuration
+
+
+ After configuring your DNS records:
+
+
+ Wait for DNS propagation (usually 15-30 minutes)
+
+ Test your domain by visiting:{" "}
+ {domain.https ? "https://" : "http://"}
+ {domain.host}
+ {domain.path || "/"}
+
+ Use a DNS lookup tool to verify your records
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/domains/handle-domain.tsx b/data/apps/dokploy/components/dashboard/application/domains/handle-domain.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c145afcfcf1c0c66191fa94b9c036ee7a79cdf48
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/domains/handle-domain.tsx
@@ -0,0 +1,596 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input, NumberInput } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+
+import { zodResolver } from "@hookform/resolvers/zod";
+import { DatabaseZap, Dices, RefreshCw } from "lucide-react";
+import Link from "next/link";
+import z from "zod";
+
+export type CacheType = "fetch" | "cache";
+
+export const domain = z
+ .object({
+ host: z.string().min(1, { message: "Add a hostname" }),
+ path: z.string().min(1).optional(),
+ port: z
+ .number()
+ .min(1, { message: "Port must be at least 1" })
+ .max(65535, { message: "Port must be 65535 or below" })
+ .optional(),
+ https: z.boolean().optional(),
+ certificateType: z.enum(["letsencrypt", "none", "custom"]).optional(),
+ customCertResolver: z.string().optional(),
+ serviceName: z.string().optional(),
+ domainType: z.enum(["application", "compose", "preview"]).optional(),
+ })
+ .superRefine((input, ctx) => {
+ if (input.https && !input.certificateType) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["certificateType"],
+ message: "Required",
+ });
+ }
+
+ if (input.certificateType === "custom" && !input.customCertResolver) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["customCertResolver"],
+ message: "Required",
+ });
+ }
+
+ if (input.domainType === "compose" && !input.serviceName) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["serviceName"],
+ message: "Required",
+ });
+ }
+ });
+
+type Domain = z.infer;
+
+interface Props {
+ id: string;
+ type: "application" | "compose";
+ domainId?: string;
+ children: React.ReactNode;
+}
+
+export const AddDomain = ({ id, type, domainId = "", children }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [cacheType, setCacheType] = useState("cache");
+
+ const utils = api.useUtils();
+ const { data, refetch } = api.domain.one.useQuery(
+ {
+ domainId,
+ },
+ {
+ enabled: !!domainId,
+ },
+ );
+
+ const { data: application } =
+ type === "application"
+ ? api.application.one.useQuery(
+ {
+ applicationId: id,
+ },
+ {
+ enabled: !!id,
+ },
+ )
+ : api.compose.one.useQuery(
+ {
+ composeId: id,
+ },
+ {
+ enabled: !!id,
+ },
+ );
+
+ const { mutateAsync, isError, error, isLoading } = domainId
+ ? api.domain.update.useMutation()
+ : api.domain.create.useMutation();
+
+ const { mutateAsync: generateDomain, isLoading: isLoadingGenerate } =
+ api.domain.generateDomain.useMutation();
+
+ const { data: canGenerateTraefikMeDomains } =
+ api.domain.canGenerateTraefikMeDomains.useQuery({
+ serverId: application?.serverId || "",
+ });
+
+ const {
+ data: services,
+ isFetching: isLoadingServices,
+ error: errorServices,
+ refetch: refetchServices,
+ } = api.compose.loadServices.useQuery(
+ {
+ composeId: id,
+ type: cacheType,
+ },
+ {
+ retry: false,
+ refetchOnWindowFocus: false,
+ enabled: type === "compose" && !!id,
+ },
+ );
+
+ const form = useForm({
+ resolver: zodResolver(domain),
+ defaultValues: {
+ host: "",
+ path: undefined,
+ port: undefined,
+ https: false,
+ certificateType: undefined,
+ customCertResolver: undefined,
+ serviceName: undefined,
+ domainType: type,
+ },
+ mode: "onChange",
+ });
+
+ const certificateType = form.watch("certificateType");
+ const https = form.watch("https");
+ const domainType = form.watch("domainType");
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ ...data,
+ /* Convert null to undefined */
+ path: data?.path || undefined,
+ port: data?.port || undefined,
+ certificateType: data?.certificateType || undefined,
+ customCertResolver: data?.customCertResolver || undefined,
+ serviceName: data?.serviceName || undefined,
+ domainType: data?.domainType || type,
+ });
+ }
+
+ if (!domainId) {
+ form.reset({
+ host: "",
+ path: undefined,
+ port: undefined,
+ https: false,
+ certificateType: undefined,
+ customCertResolver: undefined,
+ domainType: type,
+ });
+ }
+ }, [form, data, isLoading, domainId]);
+
+ // Separate effect for handling custom cert resolver validation
+ useEffect(() => {
+ if (certificateType === "custom") {
+ form.trigger("customCertResolver");
+ }
+ }, [certificateType, form]);
+
+ const dictionary = {
+ success: domainId ? "Domain Updated" : "Domain Created",
+ error: domainId ? "Error updating the domain" : "Error creating the domain",
+ submit: domainId ? "Update" : "Create",
+ dialogDescription: domainId
+ ? "In this section you can edit a domain"
+ : "In this section you can add domains",
+ };
+
+ const onSubmit = async (data: Domain) => {
+ await mutateAsync({
+ domainId,
+ ...(data.domainType === "application" && {
+ applicationId: id,
+ }),
+ ...(data.domainType === "compose" && {
+ composeId: id,
+ }),
+ ...data,
+ })
+ .then(async () => {
+ toast.success(dictionary.success);
+
+ if (data.domainType === "application") {
+ await utils.domain.byApplicationId.invalidate({
+ applicationId: id,
+ });
+ await utils.application.readTraefikConfig.invalidate({
+ applicationId: id,
+ });
+ } else if (data.domainType === "compose") {
+ await utils.domain.byComposeId.invalidate({
+ composeId: id,
+ });
+ }
+
+ if (domainId) {
+ refetch();
+ }
+ setIsOpen(false);
+ })
+ .catch((e) => {
+ console.log(e);
+ toast.error(dictionary.error);
+ });
+ };
+ return (
+
+
+ {children}
+
+
+
+ Domain
+ {dictionary.dialogDescription}
+
+ {isError && {error?.message} }
+
+
+
+
+
+
+ {domainType === "compose" && (
+
+ {errorServices && (
+
+ {errorServices?.message}
+
+ )}
+
(
+
+ Service Name
+
+
+
+
+
+
+
+
+
+ {services?.map((service, index) => (
+
+ {service}
+
+ ))}
+
+ Empty
+
+
+
+
+
+
+ {
+ if (cacheType === "fetch") {
+ refetchServices();
+ } else {
+ setCacheType("fetch");
+ }
+ }}
+ >
+
+
+
+
+
+ Fetch: Will clone the repository and load
+ the services
+
+
+
+
+
+
+
+ {
+ if (cacheType === "cache") {
+ refetchServices();
+ } else {
+ setCacheType("cache");
+ }
+ }}
+ >
+
+
+
+
+
+ Cache: If you previously deployed this
+ compose, it will read the services from
+ the last deployment/fetch from the
+ repository
+
+
+
+
+
+
+
+
+ )}
+ />
+
+ )}
+
+
(
+
+ {!canGenerateTraefikMeDomains &&
+ field.value.includes("traefik.me") && (
+
+ You need to set an IP address in your{" "}
+
+ {application?.serverId
+ ? "Remote Servers -> Server -> Edit Server -> Update IP Address"
+ : "Web Server -> Server -> Update Server IP"}
+ {" "}
+ to make your traefik.me domain work.
+
+ )}
+ Host
+
+
+
+
+
+
+
+ {
+ generateDomain({
+ appName: application?.appName || "",
+ serverId: application?.serverId || "",
+ })
+ .then((domain) => {
+ field.onChange(domain);
+ })
+ .catch((err) => {
+ toast.error(err.message);
+ });
+ }}
+ >
+
+
+
+
+ Generate traefik.me domain
+
+
+
+
+
+
+
+ )}
+ />
+
+ {
+ return (
+
+ Path
+
+
+
+
+
+ );
+ }}
+ />
+
+ {
+ return (
+
+ Container Port
+
+ The port where your application is running inside the
+ container (e.g., 3000 for Node.js, 80 for Nginx, 8080
+ for Java)
+
+
+
+
+
+
+ );
+ }}
+ />
+
+ (
+
+
+ HTTPS
+
+ Automatically provision SSL Certificate.
+
+
+
+
+
+
+
+ )}
+ />
+
+ {https && (
+ <>
+ {
+ return (
+
+ Certificate Provider
+ {
+ field.onChange(value);
+ if (value !== "custom") {
+ form.setValue(
+ "customCertResolver",
+ undefined,
+ );
+ }
+ }}
+ value={field.value}
+ >
+
+
+
+
+
+
+ None
+
+ Let's Encrypt
+
+ Custom
+
+
+
+
+ );
+ }}
+ />
+
+ {certificateType === "custom" && (
+ {
+ return (
+
+ Custom Certificate Resolver
+
+ {
+ field.onChange(e);
+ form.trigger("customCertResolver");
+ }}
+ />
+
+
+
+ );
+ }}
+ />
+ )}
+ >
+ )}
+
+
+
+
+
+
+ {dictionary.submit}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/domains/show-domains.tsx b/data/apps/dokploy/components/dashboard/application/domains/show-domains.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..fe6373537627a754260f9f06e5e0aa452cfad460
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/domains/show-domains.tsx
@@ -0,0 +1,400 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import {
+ CheckCircle2,
+ ExternalLink,
+ GlobeIcon,
+ InfoIcon,
+ Loader2,
+ PenBoxIcon,
+ RefreshCw,
+ Server,
+ Trash2,
+ XCircle,
+} from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { DnsHelperModal } from "./dns-helper-modal";
+import { AddDomain } from "./handle-domain";
+
+export type ValidationState = {
+ isLoading: boolean;
+ isValid?: boolean;
+ error?: string;
+ resolvedIp?: string;
+ message?: string;
+};
+
+export type ValidationStates = Record;
+
+interface Props {
+ id: string;
+ type: "application" | "compose";
+}
+
+export const ShowDomains = ({ id, type }: Props) => {
+ const { data: application } =
+ type === "application"
+ ? api.application.one.useQuery(
+ {
+ applicationId: id,
+ },
+ {
+ enabled: !!id,
+ },
+ )
+ : api.compose.one.useQuery(
+ {
+ composeId: id,
+ },
+ {
+ enabled: !!id,
+ },
+ );
+ const [validationStates, setValidationStates] = useState(
+ {},
+ );
+ const { data: ip } = api.settings.getIp.useQuery();
+
+ const {
+ data,
+ refetch,
+ isLoading: isLoadingDomains,
+ } = type === "application"
+ ? api.domain.byApplicationId.useQuery(
+ {
+ applicationId: id,
+ },
+ {
+ enabled: !!id,
+ },
+ )
+ : api.domain.byComposeId.useQuery(
+ {
+ composeId: id,
+ },
+ {
+ enabled: !!id,
+ },
+ );
+
+ const { mutateAsync: validateDomain } =
+ api.domain.validateDomain.useMutation();
+ const { mutateAsync: deleteDomain, isLoading: isRemoving } =
+ api.domain.delete.useMutation();
+
+ const handleValidateDomain = async (host: string) => {
+ setValidationStates((prev) => ({
+ ...prev,
+ [host]: { isLoading: true },
+ }));
+
+ try {
+ const result = await validateDomain({
+ domain: host,
+ serverIp:
+ application?.server?.ipAddress?.toString() || ip?.toString() || "",
+ });
+
+ setValidationStates((prev) => ({
+ ...prev,
+ [host]: {
+ isLoading: false,
+ isValid: result.isValid,
+ error: result.error,
+ resolvedIp: result.resolvedIp,
+ message: result.error && result.isValid ? result.error : undefined,
+ },
+ }));
+ } catch (err) {
+ const error = err as Error;
+ setValidationStates((prev) => ({
+ ...prev,
+ [host]: {
+ isLoading: false,
+ isValid: false,
+ error: error.message || "Failed to validate domain",
+ },
+ }));
+ }
+ };
+
+ return (
+
+
+
+
+ Domains
+
+ Domains are used to access to the application
+
+
+
+
+ {data && data?.length > 0 && (
+
+
+ Add Domain
+
+
+ )}
+
+
+
+ {isLoadingDomains ? (
+
+
+
+ Loading domains...
+
+
+ ) : data?.length === 0 ? (
+
+
+
+ To access the application it is required to set at least 1
+ domain
+
+
+
+ ) : (
+
+ {data?.map((item) => {
+ const validationState = validationStates[item.host];
+ return (
+
+
+
+ {/* Service & Domain Info */}
+
+ {item.serviceName && (
+
+
+ {item.serviceName}
+
+ )}
+
+ {!item.host.includes("traefik.me") && (
+
+ )}
+
+
+
+
+
+
{
+ await deleteDomain({
+ domainId: item.domainId,
+ })
+ .then((_data) => {
+ refetch();
+ toast.success(
+ "Domain deleted successfully",
+ );
+ })
+ .catch(() => {
+ toast.error("Error deleting domain");
+ });
+ }}
+ >
+
+
+
+
+
+
+
+
+ {item.host}
+
+
+
+
+ {/* Domain Details */}
+
+
+
+
+
+
+ Path: {item.path || "/"}
+
+
+
+ URL path for this service
+
+
+
+
+
+
+
+
+
+ Port: {item.port}
+
+
+
+ Container port exposed
+
+
+
+
+
+
+
+
+ {item.https ? "HTTPS" : "HTTP"}
+
+
+
+
+ {item.https
+ ? "Secure HTTPS connection"
+ : "Standard HTTP connection"}
+
+
+
+
+
+ {item.certificateType && (
+
+
+
+
+ Cert: {item.certificateType}
+
+
+
+ SSL Certificate Provider
+
+
+
+ )}
+
+
+
+
+
+ handleValidateDomain(item.host)
+ }
+ >
+ {validationState?.isLoading ? (
+ <>
+
+ Checking DNS...
+ >
+ ) : validationState?.isValid ? (
+ <>
+
+ {validationState.message
+ ? "Behind Cloudflare"
+ : "DNS Valid"}
+ >
+ ) : validationState?.error ? (
+ <>
+
+ {validationState.error}
+ >
+ ) : (
+ <>
+
+ Validate DNS
+ >
+ )}
+
+
+
+ {validationState?.error ? (
+
+
+ Error:
+
+
{validationState.error}
+
+ ) : (
+ "Click to validate DNS configuration"
+ )}
+
+
+
+
+
+
+
+ );
+ })}
+
+ )}
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/environment/show-enviroment.tsx b/data/apps/dokploy/components/dashboard/application/environment/show-enviroment.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8a78c2745471570d930e2e894825fa4ef3e7234a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/environment/show-enviroment.tsx
@@ -0,0 +1,198 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormMessage,
+} from "@/components/ui/form";
+import { Toggle } from "@/components/ui/toggle";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { EyeIcon, EyeOffIcon } from "lucide-react";
+import { type CSSProperties, useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import type { ServiceType } from "../advanced/show-resources";
+
+const addEnvironmentSchema = z.object({
+ environment: z.string(),
+});
+
+type EnvironmentSchema = z.infer;
+
+interface Props {
+ id: string;
+ type: Exclude;
+}
+
+export const ShowEnvironment = ({ id, type }: Props) => {
+ const queryMap = {
+ postgres: () =>
+ api.postgres.one.useQuery({ postgresId: id }, { enabled: !!id }),
+ redis: () => api.redis.one.useQuery({ redisId: id }, { enabled: !!id }),
+ mysql: () => api.mysql.one.useQuery({ mysqlId: id }, { enabled: !!id }),
+ mariadb: () =>
+ api.mariadb.one.useQuery({ mariadbId: id }, { enabled: !!id }),
+ mongo: () => api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id }),
+ compose: () =>
+ api.compose.one.useQuery({ composeId: id }, { enabled: !!id }),
+ };
+ const { data, refetch } = queryMap[type]
+ ? queryMap[type]()
+ : api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id });
+ const [isEnvVisible, setIsEnvVisible] = useState(true);
+
+ const mutationMap = {
+ postgres: () => api.postgres.update.useMutation(),
+ redis: () => api.redis.update.useMutation(),
+ mysql: () => api.mysql.update.useMutation(),
+ mariadb: () => api.mariadb.update.useMutation(),
+ mongo: () => api.mongo.update.useMutation(),
+ compose: () => api.compose.update.useMutation(),
+ };
+ const { mutateAsync, isLoading } = mutationMap[type]
+ ? mutationMap[type]()
+ : api.mongo.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ environment: "",
+ },
+ resolver: zodResolver(addEnvironmentSchema),
+ });
+
+ // Watch form value
+ const currentEnvironment = form.watch("environment");
+ const hasChanges = currentEnvironment !== (data?.env || "");
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ environment: data.env || "",
+ });
+ }
+ }, [data, form]);
+
+ const onSubmit = async (formData: EnvironmentSchema) => {
+ mutateAsync({
+ mongoId: id || "",
+ postgresId: id || "",
+ redisId: id || "",
+ mysqlId: id || "",
+ mariadbId: id || "",
+ composeId: id || "",
+ env: formData.environment,
+ })
+ .then(async () => {
+ toast.success("Environments Added");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error adding environment");
+ });
+ };
+
+ const handleCancel = () => {
+ form.reset({
+ environment: data?.env || "",
+ });
+ };
+
+ return (
+
+
+
+
+ Environment Settings
+
+ You can add environment variables to your resource.
+ {hasChanges && (
+
+ (You have unsaved changes)
+
+ )}
+
+
+
+
+ {isEnvVisible ? (
+
+ ) : (
+
+ )}
+
+
+
+
+
+ (
+
+
+
+
+
+
+ )}
+ />
+
+
+ {hasChanges && (
+
+ Cancel
+
+ )}
+
+ Save
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/environment/show.tsx b/data/apps/dokploy/components/dashboard/application/environment/show.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..6f504959c11c8e0fca93e230eba3fd828c5cb4c2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/environment/show.tsx
@@ -0,0 +1,144 @@
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Form } from "@/components/ui/form";
+import { Secrets } from "@/components/ui/secrets";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const addEnvironmentSchema = z.object({
+ env: z.string(),
+ buildArgs: z.string(),
+});
+
+type EnvironmentSchema = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const ShowEnvironment = ({ applicationId }: Props) => {
+ const { mutateAsync, isLoading } =
+ api.application.saveEnvironment.useMutation();
+
+ const { data, refetch } = api.application.one.useQuery(
+ {
+ applicationId,
+ },
+ {
+ enabled: !!applicationId,
+ },
+ );
+
+ const form = useForm({
+ defaultValues: {
+ env: "",
+ buildArgs: "",
+ },
+ resolver: zodResolver(addEnvironmentSchema),
+ });
+
+ // Watch form values
+ const currentEnv = form.watch("env");
+ const currentBuildArgs = form.watch("buildArgs");
+ const hasChanges =
+ currentEnv !== (data?.env || "") ||
+ currentBuildArgs !== (data?.buildArgs || "");
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ env: data.env || "",
+ buildArgs: data.buildArgs || "",
+ });
+ }
+ }, [data, form]);
+
+ const onSubmit = async (formData: EnvironmentSchema) => {
+ mutateAsync({
+ env: formData.env,
+ buildArgs: formData.buildArgs,
+ applicationId,
+ })
+ .then(async () => {
+ toast.success("Environments Added");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error adding environment");
+ });
+ };
+
+ const handleCancel = () => {
+ form.reset({
+ env: data?.env || "",
+ buildArgs: data?.buildArgs || "",
+ });
+ };
+
+ return (
+
+
+
+
+ You can add environment variables to your resource.
+ {hasChanges && (
+
+ (You have unsaved changes)
+
+ )}
+
+ }
+ placeholder={["NODE_ENV=production", "PORT=3000"].join("\n")}
+ />
+ {data?.buildType === "dockerfile" && (
+
+ Available only at build-time. See documentation
+
+ here
+
+ .
+
+ }
+ placeholder="NPM_TOKEN=xyz"
+ />
+ )}
+
+ {hasChanges && (
+
+ Cancel
+
+ )}
+
+ Save
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/general/generic/save-bitbucket-provider.tsx b/data/apps/dokploy/components/dashboard/application/general/generic/save-bitbucket-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..befc859578ad772b83853c6242ccdb5e7d36c775
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/general/generic/save-bitbucket-provider.tsx
@@ -0,0 +1,504 @@
+import { BitbucketIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { CheckIcon, ChevronsUpDown, X } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const BitbucketProviderSchema = z.object({
+ buildPath: z.string().min(1, "Path is required").default("/"),
+ repository: z
+ .object({
+ repo: z.string().min(1, "Repo is required"),
+ owner: z.string().min(1, "Owner is required"),
+ })
+ .required(),
+ branch: z.string().min(1, "Branch is required"),
+ bitbucketId: z.string().min(1, "Bitbucket Provider is required"),
+ watchPaths: z.array(z.string()).optional(),
+ enableSubmodules: z.boolean().optional(),
+});
+
+type BitbucketProvider = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const SaveBitbucketProvider = ({ applicationId }: Props) => {
+ const { data: bitbucketProviders } =
+ api.bitbucket.bitbucketProviders.useQuery();
+ const { data, refetch } = api.application.one.useQuery({ applicationId });
+
+ const { mutateAsync, isLoading: isSavingBitbucketProvider } =
+ api.application.saveBitbucketProvider.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ buildPath: "/",
+ repository: {
+ owner: "",
+ repo: "",
+ },
+ bitbucketId: "",
+ branch: "",
+ watchPaths: [],
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(BitbucketProviderSchema),
+ });
+
+ const repository = form.watch("repository");
+ const bitbucketId = form.watch("bitbucketId");
+
+ const {
+ data: repositories,
+ isLoading: isLoadingRepositories,
+ error,
+ } = api.bitbucket.getBitbucketRepositories.useQuery(
+ {
+ bitbucketId,
+ },
+ {
+ enabled: !!bitbucketId,
+ },
+ );
+
+ const {
+ data: branches,
+ fetchStatus,
+ status,
+ } = api.bitbucket.getBitbucketBranches.useQuery(
+ {
+ owner: repository?.owner,
+ repo: repository?.repo,
+ bitbucketId,
+ },
+ {
+ enabled: !!repository?.owner && !!repository?.repo && !!bitbucketId,
+ },
+ );
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ branch: data.bitbucketBranch || "",
+ repository: {
+ repo: data.bitbucketRepository || "",
+ owner: data.bitbucketOwner || "",
+ },
+ buildPath: data.bitbucketBuildPath || "/",
+ bitbucketId: data.bitbucketId || "",
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules || false,
+ });
+ }
+ }, [form.reset, data?.applicationId, form]);
+
+ const onSubmit = async (data: BitbucketProvider) => {
+ await mutateAsync({
+ bitbucketBranch: data.branch,
+ bitbucketRepository: data.repository.repo,
+ bitbucketOwner: data.repository.owner,
+ bitbucketBuildPath: data.buildPath,
+ bitbucketId: data.bitbucketId,
+ applicationId,
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules || false,
+ })
+ .then(async () => {
+ toast.success("Service Provided Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the Bitbucket provider");
+ });
+ };
+
+ return (
+
+
+
+ {error && (
+ Repositories: {error.message}
+ )}
+
+
(
+
+ Bitbucket Account
+ {
+ field.onChange(value);
+ form.setValue("repository", {
+ owner: "",
+ repo: "",
+ });
+ form.setValue("branch", "");
+ }}
+ defaultValue={field.value}
+ value={field.value}
+ >
+
+
+
+
+
+
+ {bitbucketProviders?.map((bitbucketProvider) => (
+
+ {bitbucketProvider.gitProvider.name}
+
+ ))}
+
+
+
+
+ )}
+ />
+
+ (
+
+
+ Repository
+ {field.value.owner && field.value.repo && (
+
+
+ View Repository
+
+ )}
+
+
+
+
+
+ {isLoadingRepositories
+ ? "Loading...."
+ : field.value.owner
+ ? repositories?.find(
+ (repo) => repo.name === field.value.repo,
+ )?.name
+ : "Select repository"}
+
+
+
+
+
+
+
+
+ {isLoadingRepositories && (
+
+ Loading Repositories....
+
+ )}
+ No repositories found.
+
+
+ {repositories?.map((repo) => (
+ {
+ form.setValue("repository", {
+ owner: repo.owner.username as string,
+ repo: repo.name,
+ });
+ form.setValue("branch", "");
+ }}
+ >
+
+ {repo.name}
+
+ {repo.owner.username}
+
+
+
+
+ ))}
+
+
+
+
+
+ {form.formState.errors.repository && (
+
+ Repository is required
+
+ )}
+
+ )}
+ />
+ (
+
+ Branch
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching"
+ ? "Loading...."
+ : field.value
+ ? branches?.find(
+ (branch) => branch.name === field.value,
+ )?.name
+ : "Select branch"}
+
+
+
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching" && (
+
+ Loading Branches....
+
+ )}
+ {!repository?.owner && (
+
+ Select a repository
+
+ )}
+
+ No branch found.
+
+
+ {branches?.map((branch) => (
+ {
+ form.setValue("branch", branch.name);
+ }}
+ >
+ {branch.name}
+
+
+ ))}
+
+
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Build Path
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
Watch Paths
+
+
+
+
+ ?
+
+
+
+
+ Add paths to watch for changes. When files in these
+ paths change, a new deployment will be triggered.
+
+
+
+
+
+
+ {field.value?.map((path, index) => (
+
+ {path}
+ {
+ const newPaths = [...(field.value || [])];
+ newPaths.splice(index, 1);
+ form.setValue("watchPaths", newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }
+ }}
+ />
+ {
+ const input = document.querySelector(
+ 'input[placeholder="Enter a path to watch (e.g., src/**, dist/*.js)"]',
+ ) as HTMLInputElement;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }}
+ >
+ Add
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+ Save
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/general/generic/save-docker-provider.tsx b/data/apps/dokploy/components/dashboard/application/general/generic/save-docker-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..72b2578c5d6bd9381c4eafeb3f9f5989bbd84cc2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/general/generic/save-docker-provider.tsx
@@ -0,0 +1,163 @@
+import { Button } from "@/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const DockerProviderSchema = z.object({
+ dockerImage: z.string().min(1, {
+ message: "Docker image is required",
+ }),
+ username: z.string().optional(),
+ password: z.string().optional(),
+ registryURL: z.string().optional(),
+});
+
+type DockerProvider = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const SaveDockerProvider = ({ applicationId }: Props) => {
+ const { data, refetch } = api.application.one.useQuery({ applicationId });
+
+ const { mutateAsync } = api.application.saveDockerProvider.useMutation();
+ const form = useForm({
+ defaultValues: {
+ dockerImage: "",
+ password: "",
+ username: "",
+ registryURL: "",
+ },
+ resolver: zodResolver(DockerProviderSchema),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ dockerImage: data.dockerImage || "",
+ password: data.password || "",
+ username: data.username || "",
+ registryURL: data.registryUrl || "",
+ });
+ }
+ }, [form.reset, data?.applicationId, form]);
+
+ const onSubmit = async (values: DockerProvider) => {
+ await mutateAsync({
+ dockerImage: values.dockerImage,
+ password: values.password || null,
+ applicationId,
+ username: values.username || null,
+ registryUrl: values.registryURL || null,
+ })
+ .then(async () => {
+ toast.success("Docker Provider Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the Docker provider");
+ });
+ };
+
+ return (
+
+
+
+
+
+
+ Save{" "}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/general/generic/save-drag-n-drop.tsx b/data/apps/dokploy/components/dashboard/application/general/generic/save-drag-n-drop.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..3732860d441884dafa8a170316440091a96de702
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/general/generic/save-drag-n-drop.tsx
@@ -0,0 +1,141 @@
+import { Button } from "@/components/ui/button";
+import { Dropzone } from "@/components/ui/dropzone";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { type UploadFile, uploadFileSchema } from "@/utils/schema";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { TrashIcon } from "lucide-react";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+
+interface Props {
+ applicationId: string;
+}
+
+export const SaveDragNDrop = ({ applicationId }: Props) => {
+ const { data, refetch } = api.application.one.useQuery({ applicationId });
+
+ const { mutateAsync, isLoading } =
+ api.application.dropDeployment.useMutation();
+
+ const form = useForm({
+ defaultValues: {},
+ resolver: zodResolver(uploadFileSchema),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ dropBuildPath: data.dropBuildPath || "",
+ });
+ }
+ }, [data, form, form.reset, form.formState.isSubmitSuccessful]);
+ const zip = form.watch("zip");
+
+ const onSubmit = async (values: UploadFile) => {
+ const formData = new FormData();
+
+ formData.append("zip", values.zip);
+ formData.append("applicationId", applicationId);
+ if (values.dropBuildPath) {
+ formData.append("dropBuildPath", values.dropBuildPath);
+ }
+
+ await mutateAsync(formData)
+ .then(async () => {
+ toast.success("Deployment saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the deployment");
+ });
+ };
+
+ return (
+
+
+
+
+
+
+ Deploy{" "}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/general/generic/save-git-provider.tsx b/data/apps/dokploy/components/dashboard/application/general/generic/save-git-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..f3e8116e68d63946aa5ef88b77e95a9f60107e95
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/general/generic/save-git-provider.tsx
@@ -0,0 +1,328 @@
+import { Button } from "@/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { KeyRoundIcon, LockIcon, X } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+
+import { GitIcon } from "@/components/icons/data-tools-icons";
+import { Badge } from "@/components/ui/badge";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const GitProviderSchema = z.object({
+ buildPath: z.string().min(1, "Path is required").default("/"),
+ repositoryURL: z.string().min(1, {
+ message: "Repository URL is required",
+ }),
+ branch: z.string().min(1, "Branch required"),
+ sshKey: z.string().optional(),
+ watchPaths: z.array(z.string()).optional(),
+ enableSubmodules: z.boolean().default(false),
+});
+
+type GitProvider = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const SaveGitProvider = ({ applicationId }: Props) => {
+ const { data, refetch } = api.application.one.useQuery({ applicationId });
+ const { data: sshKeys } = api.sshKey.all.useQuery();
+ const router = useRouter();
+
+ const { mutateAsync, isLoading } =
+ api.application.saveGitProdiver.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ branch: "",
+ buildPath: "/",
+ repositoryURL: "",
+ sshKey: undefined,
+ watchPaths: [],
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(GitProviderSchema),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ sshKey: data.customGitSSHKeyId || undefined,
+ branch: data.customGitBranch || "",
+ buildPath: data.customGitBuildPath || "/",
+ repositoryURL: data.customGitUrl || "",
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules ?? false,
+ });
+ }
+ }, [form.reset, data, form]);
+
+ const onSubmit = async (values: GitProvider) => {
+ await mutateAsync({
+ customGitBranch: values.branch,
+ customGitBuildPath: values.buildPath,
+ customGitUrl: values.repositoryURL,
+ customGitSSHKeyId: values.sshKey === "none" ? null : values.sshKey,
+ applicationId,
+ watchPaths: values.watchPaths || [],
+ enableSubmodules: values.enableSubmodules,
+ })
+ .then(async () => {
+ toast.success("Git Provider Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the Git provider");
+ });
+ };
+
+ return (
+
+
+
+
+
+ {sshKeys && sshKeys.length > 0 ? (
+
(
+
+
+ SSH Key
+
+
+
+
+
+
+
+
+
+ {sshKeys?.map((sshKey) => (
+
+ {sshKey.name}
+
+ ))}
+ None
+ Keys ({sshKeys?.length})
+
+
+
+
+
+ )}
+ />
+ ) : (
+ router.push("/dashboard/settings/ssh-keys")}
+ type="button"
+ >
+ Add SSH Key
+
+ )}
+
+
+ (
+
+ Branch
+
+
+
+
+
+ )}
+ />
+
+
+
(
+
+ Build Path
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
Watch Paths
+
+
+
+
+ ?
+
+
+
+
+ Add paths to watch for changes. When files in these
+ paths change, a new deployment will be triggered. This
+ will work only when manual webhook is setup.
+
+
+
+
+
+
+ {field.value?.map((path, index) => (
+
+ {path}
+ {
+ const newPaths = [...(field.value || [])];
+ newPaths.splice(index, 1);
+ form.setValue("watchPaths", newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }
+ }}
+ />
+ {
+ const input = document.querySelector(
+ 'input[placeholder="Enter a path to watch (e.g., src/**, dist/*.js)"]',
+ ) as HTMLInputElement;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }}
+ >
+ Add
+
+
+
+
+
+ )}
+ />
+
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+
+ Save
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/general/generic/save-gitea-provider.tsx b/data/apps/dokploy/components/dashboard/application/general/generic/save-gitea-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..55fbfebdadb3368f605151bd94c8d37ca92f8e62
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/general/generic/save-gitea-provider.tsx
@@ -0,0 +1,538 @@
+import { GiteaIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { CheckIcon, ChevronsUpDown, HelpCircle, Plus, X } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+interface GiteaRepository {
+ name: string;
+ url: string;
+ id: number;
+ owner: {
+ username: string;
+ };
+}
+
+interface GiteaBranch {
+ name: string;
+ commit: {
+ id: string;
+ };
+}
+
+const GiteaProviderSchema = z.object({
+ buildPath: z.string().min(1, "Path is required").default("/"),
+ repository: z
+ .object({
+ repo: z.string().min(1, "Repo is required"),
+ owner: z.string().min(1, "Owner is required"),
+ })
+ .required(),
+ branch: z.string().min(1, "Branch is required"),
+ giteaId: z.string().min(1, "Gitea Provider is required"),
+ watchPaths: z.array(z.string()).default([]),
+ enableSubmodules: z.boolean().optional(),
+});
+
+type GiteaProvider = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const SaveGiteaProvider = ({ applicationId }: Props) => {
+ const { data: giteaProviders } = api.gitea.giteaProviders.useQuery();
+ const { data, refetch } = api.application.one.useQuery({ applicationId });
+
+ const { mutateAsync, isLoading: isSavingGiteaProvider } =
+ api.application.saveGiteaProvider.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ buildPath: "/",
+ repository: {
+ owner: "",
+ repo: "",
+ },
+ giteaId: "",
+ branch: "",
+ watchPaths: [],
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(GiteaProviderSchema),
+ });
+
+ const repository = form.watch("repository");
+ const giteaId = form.watch("giteaId");
+
+ const { data: giteaUrl } = api.gitea.getGiteaUrl.useQuery(
+ { giteaId },
+ {
+ enabled: !!giteaId,
+ },
+ );
+
+ const {
+ data: repositories,
+ isLoading: isLoadingRepositories,
+ error,
+ } = api.gitea.getGiteaRepositories.useQuery(
+ {
+ giteaId,
+ },
+ {
+ enabled: !!giteaId,
+ },
+ );
+
+ const {
+ data: branches,
+ fetchStatus,
+ status,
+ } = api.gitea.getGiteaBranches.useQuery(
+ {
+ owner: repository?.owner,
+ repositoryName: repository?.repo,
+ giteaId: giteaId,
+ },
+ {
+ enabled: !!repository?.owner && !!repository?.repo && !!giteaId,
+ },
+ );
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ branch: data.giteaBranch || "",
+ repository: {
+ repo: data.giteaRepository || "",
+ owner: data.giteaOwner || "",
+ },
+ buildPath: data.giteaBuildPath || "/",
+ giteaId: data.giteaId || "",
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules || false,
+ });
+ }
+ }, [form.reset, data?.applicationId, form]);
+
+ const onSubmit = async (data: GiteaProvider) => {
+ await mutateAsync({
+ giteaBranch: data.branch,
+ giteaRepository: data.repository.repo,
+ giteaOwner: data.repository.owner,
+ giteaBuildPath: data.buildPath,
+ giteaId: data.giteaId,
+ applicationId,
+ watchPaths: data.watchPaths,
+ enableSubmodules: data.enableSubmodules || false,
+ })
+ .then(async () => {
+ toast.success("Service Provider Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the Gitea provider");
+ });
+ };
+
+ return (
+
+
+
+ {error && {error?.message} }
+
+
(
+
+ Gitea Account
+ {
+ field.onChange(value);
+ form.setValue("repository", {
+ owner: "",
+ repo: "",
+ });
+ form.setValue("branch", "");
+ }}
+ defaultValue={field.value}
+ value={field.value}
+ >
+
+
+
+
+
+
+ {giteaProviders?.map((giteaProvider) => (
+
+ {giteaProvider.gitProvider.name}
+
+ ))}
+
+
+
+
+ )}
+ />
+
+ (
+
+
+ Repository
+ {field.value.owner && field.value.repo && (
+
+
+ View Repository
+
+ )}
+
+
+
+
+
+
+ {isLoadingRepositories
+ ? "Loading...."
+ : field.value.owner
+ ? repositories?.find(
+ (repo: GiteaRepository) =>
+ repo.name === field.value.repo,
+ )?.name
+ : "Select repository"}
+
+
+
+
+
+
+
+
+ {isLoadingRepositories && (
+
+ Loading Repositories....
+
+ )}
+ No repositories found.
+
+
+ {repositories && repositories.length === 0 && (
+
+ No repositories found.
+
+ )}
+ {repositories?.map((repo: GiteaRepository) => {
+ return (
+ {
+ form.setValue("repository", {
+ owner: repo.owner.username as string,
+ repo: repo.name,
+ });
+ form.setValue("branch", "");
+ }}
+ >
+
+ {repo.name}
+
+ {repo.owner.username}
+
+
+
+
+ );
+ })}
+
+
+
+
+
+ {form.formState.errors.repository && (
+
+ Repository is required
+
+ )}
+
+ )}
+ />
+ (
+
+ Branch
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching"
+ ? "Loading...."
+ : field.value
+ ? branches?.find(
+ (branch: GiteaBranch) =>
+ branch.name === field.value,
+ )?.name
+ : "Select branch"}
+
+
+
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching" && (
+
+ Loading Branches....
+
+ )}
+ {!repository?.owner && (
+
+ Select a repository
+
+ )}
+
+ No branch found.
+
+
+ {branches && branches.length === 0 && (
+ No branches found.
+ )}
+ {branches?.map((branch: GiteaBranch) => (
+ {
+ form.setValue("branch", branch.name);
+ }}
+ >
+ {branch.name}
+
+
+ ))}
+
+
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Build Path
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
Watch Paths
+
+
+
+
+
+
+
+ Add paths to watch for changes. When files in these
+ paths change, a new deployment will be triggered.
+
+
+
+
+
+
+ {field.value?.map((path: string, index: number) => (
+
+ {path}
+ {
+ const newPaths = [...field.value];
+ newPaths.splice(index, 1);
+ field.onChange(newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const path = input.value.trim();
+ if (path) {
+ field.onChange([...field.value, path]);
+ input.value = "";
+ }
+ }
+ }}
+ />
+
+
{
+ const input = document.querySelector(
+ 'input[placeholder*="Enter a path"]',
+ ) as HTMLInputElement;
+ const path = input.value.trim();
+ if (path) {
+ field.onChange([...field.value, path]);
+ input.value = "";
+ }
+ }}
+ >
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+ Save
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/general/generic/save-github-provider.tsx b/data/apps/dokploy/components/dashboard/application/general/generic/save-github-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c76b9ae589c9f469d33d1c6cea8910f11d58bc08
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/general/generic/save-github-provider.tsx
@@ -0,0 +1,544 @@
+import { GithubIcon } from "@/components/icons/data-tools-icons";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { CheckIcon, ChevronsUpDown, HelpCircle, Plus, X } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const GithubProviderSchema = z.object({
+ buildPath: z.string().min(1, "Path is required").default("/"),
+ repository: z
+ .object({
+ repo: z.string().min(1, "Repo is required"),
+ owner: z.string().min(1, "Owner is required"),
+ })
+ .required(),
+ branch: z.string().min(1, "Branch is required"),
+ githubId: z.string().min(1, "Github Provider is required"),
+ watchPaths: z.array(z.string()).optional(),
+ triggerType: z.enum(["push", "tag"]).default("push"),
+ enableSubmodules: z.boolean().default(false),
+});
+
+type GithubProvider = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const SaveGithubProvider = ({ applicationId }: Props) => {
+ const { data: githubProviders } = api.github.githubProviders.useQuery();
+ const { data, refetch } = api.application.one.useQuery({ applicationId });
+
+ const { mutateAsync, isLoading: isSavingGithubProvider } =
+ api.application.saveGithubProvider.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ buildPath: "/",
+ repository: {
+ owner: "",
+ repo: "",
+ },
+ githubId: "",
+ branch: "",
+ triggerType: "push",
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(GithubProviderSchema),
+ });
+
+ const repository = form.watch("repository");
+ const githubId = form.watch("githubId");
+ const triggerType = form.watch("triggerType");
+
+ const { data: repositories, isLoading: isLoadingRepositories } =
+ api.github.getGithubRepositories.useQuery(
+ {
+ githubId,
+ },
+ {
+ enabled: !!githubId,
+ },
+ );
+
+ const {
+ data: branches,
+ fetchStatus,
+ status,
+ } = api.github.getGithubBranches.useQuery(
+ {
+ owner: repository?.owner,
+ repo: repository?.repo,
+ githubId,
+ },
+ {
+ enabled: !!repository?.owner && !!repository?.repo && !!githubId,
+ },
+ );
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ branch: data.branch || "",
+ repository: {
+ repo: data.repository || "",
+ owner: data.owner || "",
+ },
+ buildPath: data.buildPath || "/",
+ githubId: data.githubId || "",
+ watchPaths: data.watchPaths || [],
+ triggerType: data.triggerType || "push",
+ enableSubmodules: data.enableSubmodules ?? false,
+ });
+ }
+ }, [form.reset, data?.applicationId, form]);
+
+ const onSubmit = async (data: GithubProvider) => {
+ await mutateAsync({
+ branch: data.branch,
+ repository: data.repository.repo,
+ applicationId,
+ owner: data.repository.owner,
+ buildPath: data.buildPath,
+ githubId: data.githubId,
+ watchPaths: data.watchPaths || [],
+ triggerType: data.triggerType,
+ enableSubmodules: data.enableSubmodules,
+ })
+ .then(async () => {
+ toast.success("Service Provided Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the github provider");
+ });
+ };
+
+ return (
+
+
+
+
+
(
+
+ Github Account
+ {
+ field.onChange(value);
+ form.setValue("repository", {
+ owner: "",
+ repo: "",
+ });
+ form.setValue("branch", "");
+ }}
+ defaultValue={field.value}
+ value={field.value}
+ >
+
+
+
+
+
+
+ {githubProviders?.map((githubProvider) => (
+
+ {githubProvider.gitProvider.name}
+
+ ))}
+
+
+
+
+ )}
+ />
+
+ (
+
+
+ Repository
+ {field.value.owner && field.value.repo && (
+
+
+ View Repository
+
+ )}
+
+
+
+
+
+ {isLoadingRepositories
+ ? "Loading...."
+ : field.value.owner
+ ? repositories?.find(
+ (repo) => repo.name === field.value.repo,
+ )?.name
+ : "Select repository"}
+
+
+
+
+
+
+
+
+ {isLoadingRepositories && (
+
+ Loading Repositories....
+
+ )}
+ No repositories found.
+
+
+ {repositories?.map((repo) => (
+ {
+ form.setValue("repository", {
+ owner: repo.owner.login as string,
+ repo: repo.name,
+ });
+ form.setValue("branch", "");
+ }}
+ >
+
+ {repo.name}
+
+ {repo.owner.login}
+
+
+
+
+ ))}
+
+
+
+
+
+ {form.formState.errors.repository && (
+
+ Repository is required
+
+ )}
+
+ )}
+ />
+ (
+
+ Branch
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching"
+ ? "Loading...."
+ : field.value
+ ? branches?.find(
+ (branch) => branch.name === field.value,
+ )?.name
+ : "Select branch"}
+
+
+
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching" && (
+
+ Loading Branches....
+
+ )}
+ {!repository?.owner && (
+
+ Select a repository
+
+ )}
+
+ No branch found.
+
+
+ {branches?.map((branch) => (
+ {
+ form.setValue("branch", branch.name);
+ }}
+ >
+ {branch.name}
+
+
+ ))}
+
+
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Build Path
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
Trigger Type
+
+
+
+
+
+
+
+ Choose when to trigger deployments: on push to the
+ selected branch or when a new tag is created.
+
+
+
+
+
+
+
+
+
+
+
+
+ On Push
+ On Tag
+
+
+
+
+ )}
+ />
+ {triggerType === "push" && (
+ (
+
+
+
Watch Paths
+
+
+
+
+
+
+
+ Add paths to watch for changes. When files in
+ these paths change, a new deployment will be
+ triggered.
+
+
+
+
+
+
+ {field.value?.map((path, index) => (
+
+ {path}
+ {
+ const newPaths = [...(field.value || [])];
+ newPaths.splice(index, 1);
+ field.onChange(newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const path = input.value.trim();
+ if (path) {
+ field.onChange([...(field.value || []), path]);
+ input.value = "";
+ }
+ }
+ }}
+ />
+
+
{
+ const input = document.querySelector(
+ 'input[placeholder*="Enter a path"]',
+ ) as HTMLInputElement;
+ const path = input.value.trim();
+ if (path) {
+ field.onChange([...(field.value || []), path]);
+ input.value = "";
+ }
+ }}
+ >
+
+
+
+
+
+ )}
+ />
+ )}
+
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+ Save
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/general/generic/save-gitlab-provider.tsx b/data/apps/dokploy/components/dashboard/application/general/generic/save-gitlab-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..b4f27da7481697bfdc23c2c56a0a7be5259ef38b
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/general/generic/save-gitlab-provider.tsx
@@ -0,0 +1,520 @@
+import { GitlabIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { CheckIcon, ChevronsUpDown, HelpCircle, Plus, X } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const GitlabProviderSchema = z.object({
+ buildPath: z.string().min(1, "Path is required").default("/"),
+ repository: z
+ .object({
+ repo: z.string().min(1, "Repo is required"),
+ owner: z.string().min(1, "Owner is required"),
+ gitlabPathNamespace: z.string().min(1),
+ id: z.number().nullable(),
+ })
+ .required(),
+ branch: z.string().min(1, "Branch is required"),
+ gitlabId: z.string().min(1, "Gitlab Provider is required"),
+ watchPaths: z.array(z.string()).optional(),
+ enableSubmodules: z.boolean().default(false),
+});
+
+type GitlabProvider = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const SaveGitlabProvider = ({ applicationId }: Props) => {
+ const { data: gitlabProviders } = api.gitlab.gitlabProviders.useQuery();
+ const { data, refetch } = api.application.one.useQuery({ applicationId });
+
+ const { mutateAsync, isLoading: isSavingGitlabProvider } =
+ api.application.saveGitlabProvider.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ buildPath: "/",
+ repository: {
+ owner: "",
+ repo: "",
+ gitlabPathNamespace: "",
+ id: null,
+ },
+ gitlabId: "",
+ branch: "",
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(GitlabProviderSchema),
+ });
+
+ const repository = form.watch("repository");
+ const gitlabId = form.watch("gitlabId");
+
+ const {
+ data: repositories,
+ isLoading: isLoadingRepositories,
+ error,
+ } = api.gitlab.getGitlabRepositories.useQuery(
+ {
+ gitlabId,
+ },
+ {
+ enabled: !!gitlabId,
+ },
+ );
+
+ const {
+ data: branches,
+ fetchStatus,
+ status,
+ } = api.gitlab.getGitlabBranches.useQuery(
+ {
+ owner: repository?.owner,
+ repo: repository?.repo,
+ id: repository?.id || 0,
+ gitlabId: gitlabId,
+ },
+ {
+ enabled: !!repository?.owner && !!repository?.repo && !!gitlabId,
+ },
+ );
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ branch: data.gitlabBranch || "",
+ repository: {
+ repo: data.gitlabRepository || "",
+ owner: data.gitlabOwner || "",
+ gitlabPathNamespace: data.gitlabPathNamespace || "",
+ id: data.gitlabProjectId,
+ },
+ buildPath: data.gitlabBuildPath || "/",
+ gitlabId: data.gitlabId || "",
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules ?? false,
+ });
+ }
+ }, [form.reset, data?.applicationId, form]);
+
+ const onSubmit = async (data: GitlabProvider) => {
+ await mutateAsync({
+ gitlabBranch: data.branch,
+ gitlabRepository: data.repository.repo,
+ gitlabOwner: data.repository.owner,
+ gitlabBuildPath: data.buildPath,
+ gitlabId: data.gitlabId,
+ applicationId,
+ gitlabProjectId: data.repository.id,
+ gitlabPathNamespace: data.repository.gitlabPathNamespace,
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules,
+ })
+ .then(async () => {
+ toast.success("Service Provided Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the gitlab provider");
+ });
+ };
+
+ return (
+
+
+
+ {error && {error?.message} }
+
+
(
+
+ Gitlab Account
+ {
+ field.onChange(value);
+ form.setValue("repository", {
+ owner: "",
+ repo: "",
+ id: null,
+ gitlabPathNamespace: "",
+ });
+ form.setValue("branch", "");
+ }}
+ defaultValue={field.value}
+ value={field.value}
+ >
+
+
+
+
+
+
+ {gitlabProviders?.map((gitlabProvider) => (
+
+ {gitlabProvider.gitProvider.name}
+
+ ))}
+
+
+
+
+ )}
+ />
+
+ (
+
+
+ Repository
+ {field.value.owner && field.value.repo && (
+
+
+ View Repository
+
+ )}
+
+
+
+
+
+ {isLoadingRepositories
+ ? "Loading...."
+ : field.value.owner
+ ? repositories?.find(
+ (repo) => repo.name === field.value.repo,
+ )?.name
+ : "Select repository"}
+
+
+
+
+
+
+
+
+ {isLoadingRepositories && (
+
+ Loading Repositories....
+
+ )}
+ No repositories found.
+
+
+ {repositories && repositories.length === 0 && (
+
+ No repositories found.
+
+ )}
+ {repositories?.map((repo) => {
+ return (
+ {
+ form.setValue("repository", {
+ owner: repo.owner.username as string,
+ repo: repo.name,
+ id: repo.id,
+ gitlabPathNamespace: repo.url,
+ });
+ form.setValue("branch", "");
+ }}
+ >
+
+ {repo.name}
+
+ {repo.owner.username}
+
+
+
+
+ );
+ })}
+
+
+
+
+
+ {form.formState.errors.repository && (
+
+ Repository is required
+
+ )}
+
+ )}
+ />
+ (
+
+ Branch
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching"
+ ? "Loading...."
+ : field.value
+ ? branches?.find(
+ (branch) => branch.name === field.value,
+ )?.name
+ : "Select branch"}
+
+
+
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching" && (
+
+ Loading Branches....
+
+ )}
+ {!repository?.owner && (
+
+ Select a repository
+
+ )}
+
+ No branch found.
+
+
+ {branches?.map((branch) => (
+ {
+ form.setValue("branch", branch.name);
+ }}
+ >
+ {branch.name}
+
+
+ ))}
+
+
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Build Path
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
Watch Paths
+
+
+
+
+
+
+
+ Add paths to watch for changes. When files in these
+ paths change, a new deployment will be triggered.
+
+
+
+
+
+
+ {field.value?.map((path, index) => (
+
+ {path}
+ {
+ const newPaths = [...(field.value || [])];
+ newPaths.splice(index, 1);
+ field.onChange(newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const path = input.value.trim();
+ if (path) {
+ field.onChange([...(field.value || []), path]);
+ input.value = "";
+ }
+ }
+ }}
+ />
+
+
{
+ const input = document.querySelector(
+ 'input[placeholder*="Enter a path"]',
+ ) as HTMLInputElement;
+ const path = input.value.trim();
+ if (path) {
+ field.onChange([...(field.value || []), path]);
+ input.value = "";
+ }
+ }}
+ >
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+ Save
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/general/generic/show.tsx b/data/apps/dokploy/components/dashboard/application/general/generic/show.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..905fe71132c28ebf1b663abd0f3bf9dd21b508e8
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/general/generic/show.tsx
@@ -0,0 +1,251 @@
+import { SaveDockerProvider } from "@/components/dashboard/application/general/generic/save-docker-provider";
+import { SaveGitProvider } from "@/components/dashboard/application/general/generic/save-git-provider";
+import { SaveGiteaProvider } from "@/components/dashboard/application/general/generic/save-gitea-provider";
+import { SaveGithubProvider } from "@/components/dashboard/application/general/generic/save-github-provider";
+import {
+ BitbucketIcon,
+ DockerIcon,
+ GitIcon,
+ GiteaIcon,
+ GithubIcon,
+ GitlabIcon,
+} from "@/components/icons/data-tools-icons";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { api } from "@/utils/api";
+import { GitBranch, Loader2, UploadCloud } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { SaveBitbucketProvider } from "./save-bitbucket-provider";
+import { SaveDragNDrop } from "./save-drag-n-drop";
+import { SaveGitlabProvider } from "./save-gitlab-provider";
+
+type TabState =
+ | "github"
+ | "docker"
+ | "git"
+ | "drop"
+ | "gitlab"
+ | "bitbucket"
+ | "gitea";
+
+interface Props {
+ applicationId: string;
+}
+
+export const ShowProviderForm = ({ applicationId }: Props) => {
+ const { data: githubProviders, isLoading: isLoadingGithub } =
+ api.github.githubProviders.useQuery();
+ const { data: gitlabProviders, isLoading: isLoadingGitlab } =
+ api.gitlab.gitlabProviders.useQuery();
+ const { data: bitbucketProviders, isLoading: isLoadingBitbucket } =
+ api.bitbucket.bitbucketProviders.useQuery();
+ const { data: giteaProviders, isLoading: isLoadingGitea } =
+ api.gitea.giteaProviders.useQuery();
+
+ const { data: application } = api.application.one.useQuery({ applicationId });
+ const [tab, setSab] = useState(application?.sourceType || "github");
+
+ const isLoading =
+ isLoadingGithub || isLoadingGitlab || isLoadingBitbucket || isLoadingGitea;
+
+ if (isLoading) {
+ return (
+
+
+
+
+
Provider
+
+ Select the source of your code
+
+
+
+
+
+
+
+
+
+
+
+ Loading providers...
+
+
+
+
+ );
+ }
+
+ return (
+
+
+
+
+
Provider
+
+ Select the source of your code
+
+
+
+
+
+
+
+
+ {
+ setSab(e as TabState);
+ }}
+ >
+
+
+
+
+ Github
+
+
+
+ Gitlab
+
+
+
+ Bitbucket
+
+
+
+ Gitea
+
+
+
+ Docker
+
+
+
+ Git
+
+
+
+ Drop
+
+
+
+
+
+ {githubProviders && githubProviders?.length > 0 ? (
+
+ ) : (
+
+
+
+ To deploy using GitHub, you need to configure your account
+ first. Please, go to{" "}
+
+ Settings
+ {" "}
+ to do so.
+
+
+ )}
+
+
+ {gitlabProviders && gitlabProviders?.length > 0 ? (
+
+ ) : (
+
+
+
+ To deploy using GitLab, you need to configure your account
+ first. Please, go to{" "}
+
+ Settings
+ {" "}
+ to do so.
+
+
+ )}
+
+
+ {bitbucketProviders && bitbucketProviders?.length > 0 ? (
+
+ ) : (
+
+
+
+ To deploy using Bitbucket, you need to configure your account
+ first. Please, go to{" "}
+
+ Settings
+ {" "}
+ to do so.
+
+
+ )}
+
+
+ {giteaProviders && giteaProviders?.length > 0 ? (
+
+ ) : (
+
+
+
+ To deploy using Gitea, you need to configure your account
+ first. Please, go to{" "}
+
+ Settings
+ {" "}
+ to do so.
+
+
+ )}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/general/show.tsx b/data/apps/dokploy/components/dashboard/application/general/show.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c917d7ab7077f22e093c56b12a567b33face4118
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/general/show.tsx
@@ -0,0 +1,321 @@
+import { ShowBuildChooseForm } from "@/components/dashboard/application/build/show";
+import { ShowProviderForm } from "@/components/dashboard/application/general/generic/show";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+import {
+ Ban,
+ CheckCircle2,
+ Hammer,
+ RefreshCcw,
+ Rocket,
+ Terminal,
+} from "lucide-react";
+import { useRouter } from "next/router";
+import { toast } from "sonner";
+import { DockerTerminalModal } from "../../settings/web-server/docker-terminal-modal";
+interface Props {
+ applicationId: string;
+}
+
+export const ShowGeneralApplication = ({ applicationId }: Props) => {
+ const router = useRouter();
+ const { data, refetch } = api.application.one.useQuery(
+ {
+ applicationId,
+ },
+ { enabled: !!applicationId },
+ );
+ const { mutateAsync: update } = api.application.update.useMutation();
+ const { mutateAsync: start, isLoading: isStarting } =
+ api.application.start.useMutation();
+ const { mutateAsync: stop, isLoading: isStopping } =
+ api.application.stop.useMutation();
+
+ const { mutateAsync: deploy } = api.application.deploy.useMutation();
+
+ const { mutateAsync: reload, isLoading: isReloading } =
+ api.application.reload.useMutation();
+
+ const { mutateAsync: redeploy } = api.application.redeploy.useMutation();
+
+ return (
+ <>
+
+
+ Deploy Settings
+
+
+
+ {
+ await deploy({
+ applicationId: applicationId,
+ })
+ .then(() => {
+ toast.success("Application deployed successfully");
+ refetch();
+ router.push(
+ `/dashboard/project/${data?.projectId}/services/application/${applicationId}?tab=deployments`,
+ );
+ })
+ .catch(() => {
+ toast.error("Error deploying application");
+ });
+ }}
+ >
+
+
+
+
+
+ Deploy
+
+
+
+
+
+ Downloads the source code and performs a complete build
+
+
+
+
+
+
+ {
+ await reload({
+ applicationId: applicationId,
+ appName: data?.appName || "",
+ })
+ .then(() => {
+ toast.success("Application reloaded successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error reloading application");
+ });
+ }}
+ >
+
+
+
+
+
+ Reload
+
+
+
+
+ Reload the application without rebuilding it
+
+
+
+
+
+ {
+ await redeploy({
+ applicationId: applicationId,
+ })
+ .then(() => {
+ toast.success("Application rebuilt successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error rebuilding application");
+ });
+ }}
+ >
+
+
+
+
+
+ Rebuild
+
+
+
+
+
+ Only rebuilds the application without downloading new
+ code
+
+
+
+
+
+
+
+ {data?.applicationStatus === "idle" ? (
+ {
+ await start({
+ applicationId: applicationId,
+ })
+ .then(() => {
+ toast.success("Application started successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error starting application");
+ });
+ }}
+ >
+
+
+
+
+
+ Start
+
+
+
+
+
+ Start the application (requires a previous successful
+ build)
+
+
+
+
+
+
+ ) : (
+ {
+ await stop({
+ applicationId: applicationId,
+ })
+ .then(() => {
+ toast.success("Application stopped successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error stopping application");
+ });
+ }}
+ >
+
+
+
+
+
+ Stop
+
+
+
+
+ Stop the currently running application
+
+
+
+
+
+ )}
+
+
+
+
+ Open Terminal
+
+
+
+ Autodeploy
+ {
+ await update({
+ applicationId,
+ autoDeploy: enabled,
+ })
+ .then(async () => {
+ toast.success("Auto Deploy Updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error updating Auto Deploy");
+ });
+ }}
+ className="flex flex-row gap-2 items-center data-[state=checked]:bg-primary"
+ />
+
+
+
+ Clean Cache
+ {
+ await update({
+ applicationId,
+ cleanCache: enabled,
+ })
+ .then(async () => {
+ toast.success("Clean Cache Updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error updating Clean Cache");
+ });
+ }}
+ className="flex flex-row gap-2 items-center data-[state=checked]:bg-primary"
+ />
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/logs/show.tsx b/data/apps/dokploy/components/dashboard/application/logs/show.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..a73b99d25387d71bd7d236808ef81b93f46489b4
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/logs/show.tsx
@@ -0,0 +1,177 @@
+import { Badge } from "@/components/ui/badge";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { Loader2 } from "lucide-react";
+import dynamic from "next/dynamic";
+import { useEffect, useState } from "react";
+export const DockerLogs = dynamic(
+ () =>
+ import("@/components/dashboard/docker/logs/docker-logs-id").then(
+ (e) => e.DockerLogsId,
+ ),
+ {
+ ssr: false,
+ },
+);
+
+export const badgeStateColor = (state: string) => {
+ switch (state) {
+ case "running":
+ return "green";
+ case "exited":
+ case "shutdown":
+ return "red";
+ case "accepted":
+ case "created":
+ return "blue";
+ default:
+ return "default";
+ }
+};
+
+interface Props {
+ appName: string;
+ serverId?: string;
+}
+
+export const ShowDockerLogs = ({ appName, serverId }: Props) => {
+ const [containerId, setContainerId] = useState();
+ const [option, setOption] = useState<"swarm" | "native">("native");
+
+ const { data: services, isLoading: servicesLoading } =
+ api.docker.getServiceContainersByAppName.useQuery(
+ {
+ appName,
+ serverId,
+ },
+ {
+ enabled: !!appName && option === "swarm",
+ },
+ );
+
+ const { data: containers, isLoading: containersLoading } =
+ api.docker.getContainersByAppNameMatch.useQuery(
+ {
+ appName,
+ serverId,
+ },
+ {
+ enabled: !!appName && option === "native",
+ },
+ );
+
+ useEffect(() => {
+ if (option === "native") {
+ if (containers && containers?.length > 0) {
+ setContainerId(containers[0]?.containerId);
+ }
+ } else {
+ if (services && services?.length > 0) {
+ setContainerId(services[0]?.containerId);
+ }
+ }
+ }, [option, services, containers]);
+
+ const isLoading = option === "native" ? containersLoading : servicesLoading;
+ const containersLenght =
+ option === "native" ? containers?.length : services?.length;
+
+ return (
+
+
+ Logs
+
+ Watch the logs of the application in real time
+
+
+
+
+
+
Select a container to view logs
+
+
+ {option === "native" ? "Native" : "Swarm"}
+
+ {
+ setOption(checked ? "native" : "swarm");
+ }}
+ />
+
+
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+
+ )}
+
+
+
+ {option === "native" ? (
+
+ {containers?.map((container) => (
+
+ {container.name} ({container.containerId}){" "}
+
+ {container.state}
+
+
+ ))}
+
+ ) : (
+ <>
+ {services?.map((container) => (
+
+ {container.name} ({container.containerId}@{container.node}
+ )
+
+ {container.state}
+
+
+ ))}
+ >
+ )}
+
+ Containers ({containersLenght})
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/preview-deployments/add-preview-domain.tsx b/data/apps/dokploy/components/dashboard/application/preview-deployments/add-preview-domain.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..78cd55d7a2a9caf9b07670a75a129afdd8829be1
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/preview-deployments/add-preview-domain.tsx
@@ -0,0 +1,303 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input, NumberInput } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+
+import { domain } from "@/server/db/validations/domain";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Dices } from "lucide-react";
+import type z from "zod";
+
+type Domain = z.infer;
+
+interface Props {
+ previewDeploymentId: string;
+ domainId?: string;
+ children: React.ReactNode;
+}
+
+export const AddPreviewDomain = ({
+ previewDeploymentId,
+ domainId = "",
+ children,
+}: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const utils = api.useUtils();
+ const { data, refetch } = api.domain.one.useQuery(
+ {
+ domainId,
+ },
+ {
+ enabled: !!domainId,
+ },
+ );
+
+ const { data: previewDeployment } = api.previewDeployment.one.useQuery(
+ {
+ previewDeploymentId,
+ },
+ {
+ enabled: !!previewDeploymentId,
+ },
+ );
+
+ const { mutateAsync, isError, error, isLoading } = domainId
+ ? api.domain.update.useMutation()
+ : api.domain.create.useMutation();
+
+ const { mutateAsync: generateDomain, isLoading: isLoadingGenerate } =
+ api.domain.generateDomain.useMutation();
+
+ const form = useForm({
+ resolver: zodResolver(domain),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ ...data,
+ /* Convert null to undefined */
+ path: data?.path || undefined,
+ port: data?.port || undefined,
+ customCertResolver: data?.customCertResolver || undefined,
+ });
+ }
+
+ if (!domainId) {
+ form.reset({});
+ }
+ }, [form, form.reset, data, isLoading]);
+
+ const dictionary = {
+ success: domainId ? "Domain Updated" : "Domain Created",
+ error: domainId ? "Error updating the domain" : "Error creating the domain",
+ submit: domainId ? "Update" : "Create",
+ dialogDescription: domainId
+ ? "In this section you can edit a domain"
+ : "In this section you can add domains",
+ };
+
+ const onSubmit = async (data: Domain) => {
+ await mutateAsync({
+ domainId,
+ previewDeploymentId,
+ ...data,
+ })
+ .then(async () => {
+ toast.success(dictionary.success);
+ await utils.previewDeployment.all.invalidate({
+ applicationId: previewDeployment?.applicationId,
+ });
+
+ if (domainId) {
+ refetch();
+ }
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error(dictionary.error);
+ });
+ };
+ return (
+
+
+ {children}
+
+
+
+ Domain
+ {dictionary.dialogDescription}
+
+ {isError && {error?.message} }
+
+
+
+
+
+
(
+
+ Host
+
+
+
+
+
+
+
+ {
+ generateDomain({
+ appName: previewDeployment?.appName || "",
+ serverId:
+ previewDeployment?.application
+ ?.serverId || "",
+ })
+ .then((domain) => {
+ field.onChange(domain);
+ })
+ .catch((err) => {
+ toast.error(err.message);
+ });
+ }}
+ >
+
+
+
+
+ Generate traefik.me domain
+
+
+
+
+
+
+
+ )}
+ />
+
+ {
+ return (
+
+ Path
+
+
+
+
+
+ );
+ }}
+ />
+
+ {
+ return (
+
+ Container Port
+
+
+
+
+
+ );
+ }}
+ />
+
+ (
+
+
+ HTTPS
+
+ Automatically provision SSL Certificate.
+
+
+
+
+
+
+
+ )}
+ />
+
+ {form.getValues().https && (
+ (
+
+ Certificate Provider
+
+
+
+
+
+
+
+
+ None
+
+ Let's Encrypt
+
+
+
+
+
+ )}
+ />
+ )}
+
+
+
+
+
+
+ {dictionary.submit}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/preview-deployments/show-preview-deployments.tsx b/data/apps/dokploy/components/dashboard/application/preview-deployments/show-preview-deployments.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..bf93af71890af10301e52e5d297aa04ca025ad96
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/preview-deployments/show-preview-deployments.tsx
@@ -0,0 +1,239 @@
+import { GithubIcon } from "@/components/icons/data-tools-icons";
+import { DateTooltip } from "@/components/shared/date-tooltip";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { StatusTooltip } from "@/components/shared/status-tooltip";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import {
+ ExternalLink,
+ FileText,
+ GitPullRequest,
+ Loader2,
+ PenSquare,
+ RocketIcon,
+ Trash2,
+} from "lucide-react";
+import { toast } from "sonner";
+import { ShowModalLogs } from "../../settings/web-server/show-modal-logs";
+import { ShowDeploymentsModal } from "../deployments/show-deployments-modal";
+import { AddPreviewDomain } from "./add-preview-domain";
+import { ShowPreviewSettings } from "./show-preview-settings";
+
+interface Props {
+ applicationId: string;
+}
+
+export const ShowPreviewDeployments = ({ applicationId }: Props) => {
+ const { data } = api.application.one.useQuery({ applicationId });
+
+ const { mutateAsync: deletePreviewDeployment, isLoading } =
+ api.previewDeployment.delete.useMutation();
+
+ const {
+ data: previewDeployments,
+ refetch: refetchPreviewDeployments,
+ isLoading: isLoadingPreviewDeployments,
+ } = api.previewDeployment.all.useQuery(
+ { applicationId },
+ {
+ enabled: !!applicationId,
+ },
+ );
+
+ const handleDeletePreviewDeployment = async (previewDeploymentId: string) => {
+ deletePreviewDeployment({
+ previewDeploymentId: previewDeploymentId,
+ })
+ .then(() => {
+ refetchPreviewDeployments();
+ toast.success("Preview deployment deleted");
+ })
+ .catch((error) => {
+ toast.error(error.message);
+ });
+ };
+
+ return (
+
+
+
+ Preview Deployments
+ See all the preview deployments
+
+ {data?.isPreviewDeploymentsActive && (
+
+ )}
+
+
+ {data?.isPreviewDeploymentsActive ? (
+ <>
+
+
+ Preview deployments are a way to test your application before it
+ is deployed to production. It will create a new deployment for
+ each pull request you create.
+
+
+ {isLoadingPreviewDeployments ? (
+
+
+
+ Loading preview deployments...
+
+
+ ) : !previewDeployments?.length ? (
+
+
+
+ No preview deployments found
+
+
+ ) : (
+
+ {previewDeployments?.map((deployment) => {
+ const deploymentUrl = `${deployment.domain?.https ? "https" : "http"}://${deployment.domain?.host}${deployment.domain?.path || "/"}`;
+ const status = deployment.previewStatus;
+ return (
+
+
+
+
+
+
+
+
+
+ {deployment.pullRequestTitle}
+
+
+ {deployment.branch}
+
+
+
+
+
+
+
+
+
+
+
+
+ window.open(deploymentUrl, "_blank")
+ }
+ />
+
+
+
+
+
+ window.open(deployment.pullRequestURL, "_blank")
+ }
+ >
+
+ Pull Request
+
+
+
+
+ Logs
+
+
+
+
+
+
+
+
+
+
+
+ handleDeletePreviewDeployment(
+ deployment.previewDeploymentId,
+ )
+ }
+ >
+
+
+
+
+
+
+
+
+ );
+ })}
+
+ )}
+ >
+ ) : (
+
+
+
+ Preview deployments are disabled for this application, please
+ enable it
+
+
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/preview-deployments/show-preview-settings.tsx b/data/apps/dokploy/components/dashboard/application/preview-deployments/show-preview-settings.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..4c5068eee9a47e51ca2c24487bcfedf8bc599e09
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/preview-deployments/show-preview-settings.tsx
@@ -0,0 +1,381 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input, NumberInput } from "@/components/ui/input";
+import { Secrets } from "@/components/ui/secrets";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Settings2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const schema = z
+ .object({
+ env: z.string(),
+ buildArgs: z.string(),
+ wildcardDomain: z.string(),
+ port: z.number(),
+ previewLimit: z.number(),
+ previewHttps: z.boolean(),
+ previewPath: z.string(),
+ previewCertificateType: z.enum(["letsencrypt", "none", "custom"]),
+ previewCustomCertResolver: z.string().optional(),
+ })
+ .superRefine((input, ctx) => {
+ if (
+ input.previewCertificateType === "custom" &&
+ !input.previewCustomCertResolver
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["previewCustomCertResolver"],
+ message: "Required",
+ });
+ }
+ });
+
+type Schema = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const ShowPreviewSettings = ({ applicationId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [isEnabled, setIsEnabled] = useState(false);
+ const { mutateAsync: updateApplication, isLoading } =
+ api.application.update.useMutation();
+
+ const { data, refetch } = api.application.one.useQuery({ applicationId });
+
+ const form = useForm({
+ defaultValues: {
+ env: "",
+ wildcardDomain: "*.traefik.me",
+ port: 3000,
+ previewLimit: 3,
+ previewHttps: false,
+ previewPath: "/",
+ previewCertificateType: "none",
+ },
+ resolver: zodResolver(schema),
+ });
+
+ const previewHttps = form.watch("previewHttps");
+
+ useEffect(() => {
+ setIsEnabled(data?.isPreviewDeploymentsActive || false);
+ }, [data?.isPreviewDeploymentsActive]);
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ env: data.previewEnv || "",
+ buildArgs: data.previewBuildArgs || "",
+ wildcardDomain: data.previewWildcard || "*.traefik.me",
+ port: data.previewPort || 3000,
+ previewLimit: data.previewLimit || 3,
+ previewHttps: data.previewHttps || false,
+ previewPath: data.previewPath || "/",
+ previewCertificateType: data.previewCertificateType || "none",
+ previewCustomCertResolver: data.previewCustomCertResolver || "",
+ });
+ }
+ }, [data]);
+
+ const onSubmit = async (formData: Schema) => {
+ updateApplication({
+ previewEnv: formData.env,
+ previewBuildArgs: formData.buildArgs,
+ previewWildcard: formData.wildcardDomain,
+ previewPort: formData.port,
+ applicationId,
+ previewLimit: formData.previewLimit,
+ previewHttps: formData.previewHttps,
+ previewPath: formData.previewPath,
+ previewCertificateType: formData.previewCertificateType,
+ previewCustomCertResolver: formData.previewCustomCertResolver,
+ })
+ .then(() => {
+ toast.success("Preview Deployments settings updated");
+ })
+ .catch((error) => {
+ toast.error(error.message);
+ });
+ };
+ return (
+
+
+
+
+
+ Configure
+
+
+
+
+ Preview Deployment Settings
+
+ Adjust the settings for preview deployments of this application,
+ including environment variables, build options, and deployment
+ rules.
+
+
+
+
+
+
+
+
+
+
+ Enable preview deployments
+
+
+ Enable or disable preview deployments for this
+ application.
+
+
+
{
+ updateApplication({
+ isPreviewDeploymentsActive: checked,
+ applicationId,
+ })
+ .then(() => {
+ refetch();
+ toast.success(
+ checked
+ ? "Preview deployments enabled"
+ : "Preview deployments disabled",
+ );
+ })
+ .catch((error) => {
+ toast.error(error.message);
+ });
+ }}
+ />
+
+
+
+ (
+
+
+
+
+
+
+ )}
+ />
+ {data?.buildType === "dockerfile" && (
+
+ Available only at build-time. See documentation
+
+ here
+
+ .
+
+ }
+ placeholder="NPM_TOKEN=xyz"
+ />
+ )}
+
+
+
+
+ {
+ setIsOpen(false);
+ }}
+ >
+ Cancel
+
+
+ Save
+
+
+
+
+ {/* */}
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/schedules/handle-schedules.tsx b/data/apps/dokploy/components/dashboard/application/schedules/handle-schedules.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2d26d7a94e2c79428482476701b39e0d5d049b6a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/schedules/handle-schedules.tsx
@@ -0,0 +1,538 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ DatabaseZap,
+ Info,
+ PenBoxIcon,
+ PlusCircle,
+ RefreshCw,
+} from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import type { CacheType } from "../domains/handle-domain";
+
+export const commonCronExpressions = [
+ { label: "Every minute", value: "* * * * *" },
+ { label: "Every hour", value: "0 * * * *" },
+ { label: "Every day at midnight", value: "0 0 * * *" },
+ { label: "Every Sunday at midnight", value: "0 0 * * 0" },
+ { label: "Every month on the 1st at midnight", value: "0 0 1 * *" },
+ { label: "Every 15 minutes", value: "*/15 * * * *" },
+ { label: "Every weekday at midnight", value: "0 0 * * 1-5" },
+];
+
+const formSchema = z
+ .object({
+ name: z.string().min(1, "Name is required"),
+ cronExpression: z.string().min(1, "Cron expression is required"),
+ shellType: z.enum(["bash", "sh"]).default("bash"),
+ command: z.string(),
+ enabled: z.boolean().default(true),
+ serviceName: z.string(),
+ scheduleType: z.enum([
+ "application",
+ "compose",
+ "server",
+ "dokploy-server",
+ ]),
+ script: z.string(),
+ })
+ .superRefine((data, ctx) => {
+ if (data.scheduleType === "compose" && !data.serviceName) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Service name is required",
+ path: ["serviceName"],
+ });
+ }
+
+ if (
+ (data.scheduleType === "dokploy-server" ||
+ data.scheduleType === "server") &&
+ !data.script
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Script is required",
+ path: ["script"],
+ });
+ }
+
+ if (
+ (data.scheduleType === "application" ||
+ data.scheduleType === "compose") &&
+ !data.command
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Command is required",
+ path: ["command"],
+ });
+ }
+ });
+
+interface Props {
+ id?: string;
+ scheduleId?: string;
+ scheduleType?: "application" | "compose" | "server" | "dokploy-server";
+}
+
+export const HandleSchedules = ({ id, scheduleId, scheduleType }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [cacheType, setCacheType] = useState("cache");
+
+ const utils = api.useUtils();
+ const form = useForm>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ name: "",
+ cronExpression: "",
+ shellType: "bash",
+ command: "",
+ enabled: true,
+ serviceName: "",
+ scheduleType: scheduleType || "application",
+ script: "",
+ },
+ });
+
+ const scheduleTypeForm = form.watch("scheduleType");
+
+ const { data: schedule } = api.schedule.one.useQuery(
+ { scheduleId: scheduleId || "" },
+ { enabled: !!scheduleId },
+ );
+
+ const {
+ data: services,
+ isFetching: isLoadingServices,
+ error: errorServices,
+ refetch: refetchServices,
+ } = api.compose.loadServices.useQuery(
+ {
+ composeId: id || "",
+ type: cacheType,
+ },
+ {
+ retry: false,
+ refetchOnWindowFocus: false,
+ enabled: !!id && scheduleType === "compose",
+ },
+ );
+
+ useEffect(() => {
+ if (scheduleId && schedule) {
+ form.reset({
+ name: schedule.name,
+ cronExpression: schedule.cronExpression,
+ shellType: schedule.shellType,
+ command: schedule.command,
+ enabled: schedule.enabled,
+ serviceName: schedule.serviceName || "",
+ scheduleType: schedule.scheduleType,
+ script: schedule.script || "",
+ });
+ }
+ }, [form, schedule, scheduleId]);
+
+ const { mutateAsync, isLoading } = scheduleId
+ ? api.schedule.update.useMutation()
+ : api.schedule.create.useMutation();
+
+ const onSubmit = async (values: z.infer) => {
+ if (!id && !scheduleId) return;
+
+ await mutateAsync({
+ ...values,
+ scheduleId: scheduleId || "",
+ ...(scheduleType === "application" && {
+ applicationId: id || "",
+ }),
+ ...(scheduleType === "compose" && {
+ composeId: id || "",
+ }),
+ ...(scheduleType === "server" && {
+ serverId: id || "",
+ }),
+ ...(scheduleType === "dokploy-server" && {
+ userId: id || "",
+ }),
+ })
+ .then(() => {
+ toast.success(
+ `Schedule ${scheduleId ? "updated" : "created"} successfully`,
+ );
+ utils.schedule.list.invalidate({
+ id,
+ scheduleType,
+ });
+ setIsOpen(false);
+ })
+ .catch((error) => {
+ toast.error(
+ error instanceof Error ? error.message : "An unknown error occurred",
+ );
+ });
+ };
+
+ return (
+
+
+ {scheduleId ? (
+
+
+
+ ) : (
+
+
+ Add Schedule
+
+ )}
+
+
+
+ {scheduleId ? "Edit" : "Create"} Schedule
+
+
+
+ {scheduleTypeForm === "compose" && (
+
+ {errorServices && (
+
+ {errorServices?.message}
+
+ )}
+
(
+
+ Service Name
+
+
+
+
+
+
+
+
+
+ {services?.map((service, index) => (
+
+ {service}
+
+ ))}
+
+ Empty
+
+
+
+
+
+
+ {
+ if (cacheType === "fetch") {
+ refetchServices();
+ } else {
+ setCacheType("fetch");
+ }
+ }}
+ >
+
+
+
+
+
+ Fetch: Will clone the repository and load the
+ services
+
+
+
+
+
+
+
+ {
+ if (cacheType === "cache") {
+ refetchServices();
+ } else {
+ setCacheType("cache");
+ }
+ }}
+ >
+
+
+
+
+
+ Cache: If you previously deployed this compose,
+ it will read the services from the last
+ deployment/fetch from the repository
+
+
+
+
+
+
+
+
+ )}
+ />
+
+ )}
+
+ (
+
+
+ Task Name
+
+
+
+
+
+ A descriptive name for your scheduled task
+
+
+
+ )}
+ />
+
+ (
+
+
+ Schedule
+
+
+
+
+
+
+
+ Cron expression format: minute hour day month
+ weekday
+
+ Example: 0 0 * * * (daily at midnight)
+
+
+
+
+
+
{
+ field.onChange(value);
+ }}
+ >
+
+
+
+
+
+
+ {commonCronExpressions.map((expr) => (
+
+ {expr.label} ({expr.value})
+
+ ))}
+
+
+
+
+
+
+
+
+
+ Choose a predefined schedule or enter a custom cron
+ expression
+
+
+
+ )}
+ />
+
+ {(scheduleTypeForm === "application" ||
+ scheduleTypeForm === "compose") && (
+ <>
+ (
+
+
+ Shell Type
+
+
+
+
+
+
+
+
+ Bash
+ Sh
+
+
+
+ Choose the shell to execute your command
+
+
+
+ )}
+ />
+ (
+
+
+ Command
+
+
+
+
+
+ The command to execute in your container
+
+
+
+ )}
+ />
+ >
+ )}
+
+ {(scheduleTypeForm === "dokploy-server" ||
+ scheduleTypeForm === "server") && (
+ (
+
+ Script
+
+
+
+
+
+
+
+ )}
+ />
+ )}
+
+ (
+
+
+
+ Enabled
+
+
+ )}
+ />
+
+
+ {scheduleId ? "Update" : "Create"} Schedule
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/schedules/show-schedules.tsx b/data/apps/dokploy/components/dashboard/application/schedules/show-schedules.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..672fb5ee31c422278e0ee1d9816671e53c3fdb32
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/schedules/show-schedules.tsx
@@ -0,0 +1,239 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import {
+ ClipboardList,
+ Clock,
+ Loader2,
+ Play,
+ Terminal,
+ Trash2,
+} from "lucide-react";
+import { toast } from "sonner";
+import { ShowDeploymentsModal } from "../deployments/show-deployments-modal";
+import { HandleSchedules } from "./handle-schedules";
+
+interface Props {
+ id: string;
+ scheduleType?: "application" | "compose" | "server" | "dokploy-server";
+}
+
+export const ShowSchedules = ({ id, scheduleType = "application" }: Props) => {
+ const {
+ data: schedules,
+ isLoading: isLoadingSchedules,
+ refetch: refetchSchedules,
+ } = api.schedule.list.useQuery(
+ {
+ id: id || "",
+ scheduleType,
+ },
+ {
+ enabled: !!id,
+ },
+ );
+
+ const utils = api.useUtils();
+
+ const { mutateAsync: deleteSchedule, isLoading: isDeleting } =
+ api.schedule.delete.useMutation();
+
+ const { mutateAsync: runManually, isLoading } =
+ api.schedule.runManually.useMutation();
+
+ return (
+
+
+
+
+
+ Scheduled Tasks
+
+
+ Schedule tasks to run automatically at specified intervals.
+
+
+
+ {schedules && schedules.length > 0 && (
+
+ )}
+
+
+
+ {isLoadingSchedules ? (
+
+
+
+ Loading scheduled tasks...
+
+
+ ) : schedules && schedules.length > 0 ? (
+
+ {schedules.map((schedule) => {
+ const serverId =
+ schedule.serverId ||
+ schedule.application?.serverId ||
+ schedule.compose?.serverId;
+ return (
+
+
+
+
+
+
+
+
+ {schedule.name}
+
+
+ {schedule.enabled ? "Enabled" : "Disabled"}
+
+
+
+
+ Cron: {schedule.cronExpression}
+
+ {schedule.scheduleType !== "server" &&
+ schedule.scheduleType !== "dokploy-server" && (
+ <>
+
+ •
+
+
+ {schedule.shellType}
+
+ >
+ )}
+
+ {schedule.command && (
+
+
+
+ {schedule.command}
+
+
+ )}
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {
+ toast.success("Schedule run successfully");
+
+ await runManually({
+ scheduleId: schedule.scheduleId,
+ }).then(async () => {
+ await new Promise((resolve) =>
+ setTimeout(resolve, 1500),
+ );
+ refetchSchedules();
+ });
+ }}
+ >
+
+
+
+ Run Manual Schedule
+
+
+
+
+
+
{
+ await deleteSchedule({
+ scheduleId: schedule.scheduleId,
+ })
+ .then(() => {
+ utils.schedule.list.invalidate({
+ id,
+ scheduleType,
+ });
+ toast.success("Schedule deleted successfully");
+ })
+ .catch(() => {
+ toast.error("Error deleting schedule");
+ });
+ }}
+ >
+
+
+
+
+
+
+ );
+ })}
+
+ ) : (
+
+
+
+ No scheduled tasks
+
+
+ Create your first scheduled task to automate your workflows
+
+
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/application/update-application.tsx b/data/apps/dokploy/components/dashboard/application/update-application.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..934a596df01802c112e94c0f8c7bae55ac3f0cdd
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/application/update-application.tsx
@@ -0,0 +1,165 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const updateApplicationSchema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ description: z.string().optional(),
+});
+
+type UpdateApplication = z.infer;
+
+interface Props {
+ applicationId: string;
+}
+
+export const UpdateApplication = ({ applicationId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const utils = api.useUtils();
+ const { mutateAsync, error, isError, isLoading } =
+ api.application.update.useMutation();
+ const { data } = api.application.one.useQuery(
+ {
+ applicationId,
+ },
+ {
+ enabled: !!applicationId,
+ },
+ );
+ const form = useForm({
+ defaultValues: {
+ description: data?.description ?? "",
+ name: data?.name ?? "",
+ },
+ resolver: zodResolver(updateApplicationSchema),
+ });
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ description: data.description ?? "",
+ name: data.name,
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: UpdateApplication) => {
+ await mutateAsync({
+ name: formData.name,
+ applicationId: applicationId,
+ description: formData.description || "",
+ })
+ .then(() => {
+ toast.success("Application updated successfully");
+ utils.application.one.invalidate({
+ applicationId: applicationId,
+ });
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating the Application");
+ })
+ .finally(() => {});
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Modify Application
+ Update the application data
+
+ {isError && {error?.message} }
+
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+ Update
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/advanced/add-command.tsx b/data/apps/dokploy/components/dashboard/compose/advanced/add-command.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c5a34b3c13df0bac810bea05ee497f8be4216dc2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/advanced/add-command.tsx
@@ -0,0 +1,139 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+interface Props {
+ composeId: string;
+}
+
+const AddRedirectSchema = z.object({
+ command: z.string(),
+});
+
+type AddCommand = z.infer;
+
+export const AddCommandCompose = ({ composeId }: Props) => {
+ const { data } = api.compose.one.useQuery(
+ {
+ composeId,
+ },
+ { enabled: !!composeId },
+ );
+
+ const { data: defaultCommand, refetch } =
+ api.compose.getDefaultCommand.useQuery(
+ {
+ composeId,
+ },
+ { enabled: !!composeId },
+ );
+
+ const utils = api.useUtils();
+
+ const { mutateAsync, isLoading } = api.compose.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ command: "",
+ },
+ resolver: zodResolver(AddRedirectSchema),
+ });
+
+ useEffect(() => {
+ if (data?.command) {
+ form.reset({
+ command: data?.command || "",
+ });
+ }
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data?.command]);
+
+ const onSubmit = async (data: AddCommand) => {
+ await mutateAsync({
+ composeId,
+ command: data?.command,
+ })
+ .then(async () => {
+ toast.success("Command Updated");
+ refetch();
+ await utils.compose.one.invalidate({
+ composeId,
+ });
+ })
+ .catch(() => {
+ toast.error("Error updating the command");
+ });
+ };
+
+ return (
+
+
+
+ Run Command
+
+ Override a custom command to the compose file
+
+
+
+
+
+
+
+ Modifying the default command may affect deployment stability,
+ impacting logs and monitoring. Proceed carefully and test
+ thoroughly. By default, the command starts with{" "}
+ docker .
+
+
+ (
+
+ Command
+
+
+
+
+
+ Default Command ({defaultCommand})
+
+
+
+ )}
+ />
+
+
+
+ Save
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/delete-service.tsx b/data/apps/dokploy/components/dashboard/compose/delete-service.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..212b5ac73477f7a621c95bfd4142c9e5bd007388
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/delete-service.tsx
@@ -0,0 +1,226 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import type { ServiceType } from "@dokploy/server/db/schema";
+import { zodResolver } from "@hookform/resolvers/zod";
+import copy from "copy-to-clipboard";
+import { Copy, Trash2 } from "lucide-react";
+import { useRouter } from "next/router";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const deleteComposeSchema = z.object({
+ projectName: z.string().min(1, {
+ message: "Compose name is required",
+ }),
+ deleteVolumes: z.boolean(),
+});
+
+type DeleteCompose = z.infer;
+
+interface Props {
+ id: string;
+ type: ServiceType | "application";
+}
+
+export const DeleteService = ({ id, type }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ const queryMap = {
+ postgres: () =>
+ api.postgres.one.useQuery({ postgresId: id }, { enabled: !!id }),
+ redis: () => api.redis.one.useQuery({ redisId: id }, { enabled: !!id }),
+ mysql: () => api.mysql.one.useQuery({ mysqlId: id }, { enabled: !!id }),
+ mariadb: () =>
+ api.mariadb.one.useQuery({ mariadbId: id }, { enabled: !!id }),
+ application: () =>
+ api.application.one.useQuery({ applicationId: id }, { enabled: !!id }),
+ mongo: () => api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id }),
+ compose: () =>
+ api.compose.one.useQuery({ composeId: id }, { enabled: !!id }),
+ };
+ const { data } = queryMap[type]
+ ? queryMap[type]()
+ : api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id });
+
+ const mutationMap = {
+ postgres: () => api.postgres.remove.useMutation(),
+ redis: () => api.redis.remove.useMutation(),
+ mysql: () => api.mysql.remove.useMutation(),
+ mariadb: () => api.mariadb.remove.useMutation(),
+ application: () => api.application.delete.useMutation(),
+ mongo: () => api.mongo.remove.useMutation(),
+ compose: () => api.compose.delete.useMutation(),
+ };
+ const { mutateAsync, isLoading } = mutationMap[type]
+ ? mutationMap[type]()
+ : api.mongo.remove.useMutation();
+ const { push } = useRouter();
+ const form = useForm({
+ defaultValues: {
+ projectName: "",
+ deleteVolumes: false,
+ },
+ resolver: zodResolver(deleteComposeSchema),
+ });
+
+ const onSubmit = async (formData: DeleteCompose) => {
+ const expectedName = `${data?.name}/${data?.appName}`;
+ if (formData.projectName === expectedName) {
+ const { deleteVolumes } = formData;
+ await mutateAsync({
+ mongoId: id || "",
+ postgresId: id || "",
+ redisId: id || "",
+ mysqlId: id || "",
+ mariadbId: id || "",
+ applicationId: id || "",
+ composeId: id || "",
+ deleteVolumes,
+ })
+ .then((result) => {
+ push(`/dashboard/project/${result?.projectId}`);
+ toast.success("deleted successfully");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error deleting the service");
+ });
+ } else {
+ form.setError("projectName", {
+ message: `Project name must match "${expectedName}"`,
+ });
+ }
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Are you absolutely sure?
+
+ This action cannot be undone. This will permanently delete the
+ service. If you are sure please enter the service name to delete
+ this service.
+
+
+
+
+
+ (
+
+
+
+ To confirm, type{" "}
+ {
+ if (data?.name && data?.appName) {
+ copy(`${data.name}/${data.appName}`);
+ toast.success("Copied to clipboard. Be careful!");
+ }
+ }}
+ >
+ {data?.name}/{data?.appName}
+
+ {" "}
+ in the box below:
+
+
+
+
+
+
+
+ )}
+ />
+ {type === "compose" && (
+ (
+
+
+
+
+
+
+
+ Delete volumes associated with this compose
+
+
+
+
+ )}
+ />
+ )}
+
+
+
+
+ {
+ setIsOpen(false);
+ }}
+ >
+ Cancel
+
+
+ Confirm
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/actions.tsx b/data/apps/dokploy/components/dashboard/compose/general/actions.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..0a4433e7cb77430bd14cd256af62a855a75c4765
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/actions.tsx
@@ -0,0 +1,230 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+import { Ban, CheckCircle2, RefreshCcw, Rocket, Terminal } from "lucide-react";
+import { useRouter } from "next/router";
+import { toast } from "sonner";
+import { DockerTerminalModal } from "../../settings/web-server/docker-terminal-modal";
+
+interface Props {
+ composeId: string;
+}
+export const ComposeActions = ({ composeId }: Props) => {
+ const router = useRouter();
+ const { data, refetch } = api.compose.one.useQuery(
+ {
+ composeId,
+ },
+ { enabled: !!composeId },
+ );
+ const { mutateAsync: update } = api.compose.update.useMutation();
+ const { mutateAsync: deploy } = api.compose.deploy.useMutation();
+ const { mutateAsync: redeploy } = api.compose.redeploy.useMutation();
+ const { mutateAsync: start, isLoading: isStarting } =
+ api.compose.start.useMutation();
+ const { mutateAsync: stop, isLoading: isStopping } =
+ api.compose.stop.useMutation();
+ return (
+
+
+ {
+ await deploy({
+ composeId: composeId,
+ })
+ .then(() => {
+ toast.success("Compose deployed successfully");
+ refetch();
+ router.push(
+ `/dashboard/project/${data?.project.projectId}/services/compose/${composeId}?tab=deployments`,
+ );
+ })
+ .catch(() => {
+ toast.error("Error deploying compose");
+ });
+ }}
+ >
+
+
+
+
+
+ Deploy
+
+
+
+
+ Downloads the source code and performs a complete build
+
+
+
+
+
+ {
+ await redeploy({
+ composeId: composeId,
+ })
+ .then(() => {
+ toast.success("Compose reloaded successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error reloading compose");
+ });
+ }}
+ >
+
+
+
+
+
+ Reload
+
+
+
+
+ Reload the compose without rebuilding it
+
+
+
+
+
+ {data?.composeType === "docker-compose" &&
+ data?.composeStatus === "idle" ? (
+ {
+ await start({
+ composeId: composeId,
+ })
+ .then(() => {
+ toast.success("Compose started successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error starting compose");
+ });
+ }}
+ >
+
+
+
+
+
+ Start
+
+
+
+
+
+ Start the compose (requires a previous successful build)
+
+
+
+
+
+
+ ) : (
+ {
+ await stop({
+ composeId: composeId,
+ })
+ .then(() => {
+ toast.success("Compose stopped successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error stopping compose");
+ });
+ }}
+ >
+
+
+
+
+
+ Stop
+
+
+
+
+ Stop the currently running compose
+
+
+
+
+
+ )}
+
+
+
+
+ Open Terminal
+
+
+
+ Autodeploy
+ {
+ await update({
+ composeId,
+ autoDeploy: enabled,
+ })
+ .then(async () => {
+ toast.success("Auto Deploy Updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error updating Auto Deploy");
+ });
+ }}
+ className="flex flex-row gap-2 items-center data-[state=checked]:bg-primary"
+ />
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/compose-file-editor.tsx b/data/apps/dokploy/components/dashboard/compose/general/compose-file-editor.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..50f0f4ab50fab4e9858b1e4e17e97cfac6a4c8f1
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/compose-file-editor.tsx
@@ -0,0 +1,158 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormMessage,
+} from "@/components/ui/form";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import { validateAndFormatYAML } from "../../application/advanced/traefik/update-traefik-config";
+import { ShowUtilities } from "./show-utilities";
+
+interface Props {
+ composeId: string;
+}
+
+const AddComposeFile = z.object({
+ composeFile: z.string(),
+});
+
+type AddComposeFile = z.infer;
+
+export const ComposeFileEditor = ({ composeId }: Props) => {
+ const utils = api.useUtils();
+ const { data, refetch } = api.compose.one.useQuery(
+ {
+ composeId,
+ },
+ { enabled: !!composeId },
+ );
+
+ const { mutateAsync, isLoading } = api.compose.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ composeFile: "",
+ },
+ resolver: zodResolver(AddComposeFile),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ composeFile: data.composeFile || "",
+ });
+ }
+ }, [form, form.reset, data]);
+
+ const onSubmit = async (data: AddComposeFile) => {
+ const { valid, error } = validateAndFormatYAML(data.composeFile);
+ if (!valid) {
+ form.setError("composeFile", {
+ type: "manual",
+ message: error || "Invalid YAML",
+ });
+ return;
+ }
+
+ form.clearErrors("composeFile");
+ await mutateAsync({
+ composeId,
+ composeFile: data.composeFile,
+ sourceType: "raw",
+ })
+ .then(async () => {
+ toast.success("Compose config Updated");
+ refetch();
+ await utils.compose.getConvertedCompose.invalidate({
+ composeId,
+ });
+ })
+ .catch((_e) => {
+ toast.error("Error updating the Compose config");
+ });
+ };
+
+ // Add keyboard shortcut for Ctrl+S/Cmd+S
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if ((e.ctrlKey || e.metaKey) && e.key === "s" && !isLoading) {
+ e.preventDefault();
+ form.handleSubmit(onSubmit)();
+ }
+ };
+
+ document.addEventListener("keydown", handleKeyDown);
+ return () => {
+ document.removeEventListener("keydown", handleKeyDown);
+ };
+ }, [form, onSubmit, isLoading]);
+
+ return (
+ <>
+
+
+
+ (
+
+
+
+ {
+ field.onChange(value);
+ }}
+ />
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/generic/save-bitbucket-provider-compose.tsx b/data/apps/dokploy/components/dashboard/compose/general/generic/save-bitbucket-provider-compose.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..73d8cf1c6ce9ef9fe532d138c0ac6e8605670e9a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/generic/save-bitbucket-provider-compose.tsx
@@ -0,0 +1,506 @@
+import { BitbucketIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { CheckIcon, ChevronsUpDown, X } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const BitbucketProviderSchema = z.object({
+ composePath: z.string().min(1),
+ repository: z
+ .object({
+ repo: z.string().min(1, "Repo is required"),
+ owner: z.string().min(1, "Owner is required"),
+ })
+ .required(),
+ branch: z.string().min(1, "Branch is required"),
+ bitbucketId: z.string().min(1, "Bitbucket Provider is required"),
+ watchPaths: z.array(z.string()).optional(),
+ enableSubmodules: z.boolean().default(false),
+});
+
+type BitbucketProvider = z.infer;
+
+interface Props {
+ composeId: string;
+}
+
+export const SaveBitbucketProviderCompose = ({ composeId }: Props) => {
+ const { data: bitbucketProviders } =
+ api.bitbucket.bitbucketProviders.useQuery();
+ const { data, refetch } = api.compose.one.useQuery({ composeId });
+
+ const { mutateAsync, isLoading: isSavingBitbucketProvider } =
+ api.compose.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ composePath: "./docker-compose.yml",
+ repository: {
+ owner: "",
+ repo: "",
+ },
+ bitbucketId: "",
+ branch: "",
+ watchPaths: [],
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(BitbucketProviderSchema),
+ });
+
+ const repository = form.watch("repository");
+ const bitbucketId = form.watch("bitbucketId");
+
+ const {
+ data: repositories,
+ isLoading: isLoadingRepositories,
+ error,
+ } = api.bitbucket.getBitbucketRepositories.useQuery(
+ {
+ bitbucketId,
+ },
+ {
+ enabled: !!bitbucketId,
+ },
+ );
+
+ const {
+ data: branches,
+ fetchStatus,
+ status,
+ } = api.bitbucket.getBitbucketBranches.useQuery(
+ {
+ owner: repository?.owner,
+ repo: repository?.repo,
+ bitbucketId,
+ },
+ {
+ enabled: !!repository?.owner && !!repository?.repo && !!bitbucketId,
+ },
+ );
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ branch: data.bitbucketBranch || "",
+ repository: {
+ repo: data.bitbucketRepository || "",
+ owner: data.bitbucketOwner || "",
+ },
+ composePath: data.composePath,
+ bitbucketId: data.bitbucketId || "",
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules ?? false,
+ });
+ }
+ }, [form.reset, data?.composeId, form]);
+
+ const onSubmit = async (data: BitbucketProvider) => {
+ await mutateAsync({
+ bitbucketBranch: data.branch,
+ bitbucketRepository: data.repository.repo,
+ bitbucketOwner: data.repository.owner,
+ bitbucketId: data.bitbucketId,
+ composePath: data.composePath,
+ composeId,
+ sourceType: "bitbucket",
+ composeStatus: "idle",
+ watchPaths: data.watchPaths,
+ enableSubmodules: data.enableSubmodules,
+ })
+ .then(async () => {
+ toast.success("Service Provided Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the Bitbucket provider");
+ });
+ };
+
+ return (
+
+
+
+ {error && (
+ Repositories: {error.message}
+ )}
+
+
(
+
+ Bitbucket Account
+ {
+ field.onChange(value);
+ form.setValue("repository", {
+ owner: "",
+ repo: "",
+ });
+ form.setValue("branch", "");
+ }}
+ defaultValue={field.value}
+ value={field.value}
+ >
+
+
+
+
+
+
+ {bitbucketProviders?.map((bitbucketProvider) => (
+
+ {bitbucketProvider.gitProvider.name}
+
+ ))}
+
+
+
+
+ )}
+ />
+
+ (
+
+
+ Repository
+ {field.value.owner && field.value.repo && (
+
+
+ View Repository
+
+ )}
+
+
+
+
+
+ {isLoadingRepositories
+ ? "Loading...."
+ : field.value.owner
+ ? repositories?.find(
+ (repo) => repo.name === field.value.repo,
+ )?.name
+ : "Select repository"}
+
+
+
+
+
+
+
+
+ {isLoadingRepositories && (
+
+ Loading Repositories....
+
+ )}
+ No repositories found.
+
+
+ {repositories?.map((repo) => (
+ {
+ form.setValue("repository", {
+ owner: repo.owner.username as string,
+ repo: repo.name,
+ });
+ form.setValue("branch", "");
+ }}
+ >
+
+ {repo.name}
+
+ {repo.owner.username}
+
+
+
+
+ ))}
+
+
+
+
+
+ {form.formState.errors.repository && (
+
+ Repository is required
+
+ )}
+
+ )}
+ />
+ (
+
+ Branch
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching"
+ ? "Loading...."
+ : field.value
+ ? branches?.find(
+ (branch) => branch.name === field.value,
+ )?.name
+ : "Select branch"}
+
+
+
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching" && (
+
+ Loading Branches....
+
+ )}
+ {!repository?.owner && (
+
+ Select a repository
+
+ )}
+
+ No branch found.
+
+
+ {branches?.map((branch) => (
+ {
+ form.setValue("branch", branch.name);
+ }}
+ >
+ {branch.name}
+
+
+ ))}
+
+
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Compose Path
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
Watch Paths
+
+
+
+
+ ?
+
+
+
+
+ Add paths to watch for changes. When files in these
+ paths change, a new deployment will be triggered.
+
+
+
+
+
+
+ {field.value?.map((path, index) => (
+
+ {path}
+ {
+ const newPaths = [...(field.value || [])];
+ newPaths.splice(index, 1);
+ form.setValue("watchPaths", newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }
+ }}
+ />
+ {
+ const input = document.querySelector(
+ 'input[placeholder="Enter a path to watch (e.g., src/**, dist/*.js)"]',
+ ) as HTMLInputElement;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }}
+ >
+ Add
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+ Save
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/generic/save-git-provider-compose.tsx b/data/apps/dokploy/components/dashboard/compose/general/generic/save-git-provider-compose.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..fc90f4f1aa584e5e4808769c01fcbed7f2ac9fb5
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/generic/save-git-provider-compose.tsx
@@ -0,0 +1,328 @@
+import { GitIcon } from "@/components/icons/data-tools-icons";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { KeyRoundIcon, LockIcon, X } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const GitProviderSchema = z.object({
+ composePath: z.string().min(1),
+ repositoryURL: z.string().min(1, {
+ message: "Repository URL is required",
+ }),
+ branch: z.string().min(1, "Branch required"),
+ sshKey: z.string().optional(),
+ watchPaths: z.array(z.string()).optional(),
+ enableSubmodules: z.boolean().default(false),
+});
+
+type GitProvider = z.infer;
+
+interface Props {
+ composeId: string;
+}
+
+export const SaveGitProviderCompose = ({ composeId }: Props) => {
+ const { data, refetch } = api.compose.one.useQuery({ composeId });
+ const { data: sshKeys } = api.sshKey.all.useQuery();
+ const router = useRouter();
+
+ const { mutateAsync, isLoading } = api.compose.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ branch: "",
+ repositoryURL: "",
+ composePath: "./docker-compose.yml",
+ sshKey: undefined,
+ watchPaths: [],
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(GitProviderSchema),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ sshKey: data.customGitSSHKeyId || undefined,
+ branch: data.customGitBranch || "",
+ repositoryURL: data.customGitUrl || "",
+ composePath: data.composePath,
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules ?? false,
+ });
+ }
+ }, [form.reset, data, form]);
+
+ const onSubmit = async (values: GitProvider) => {
+ await mutateAsync({
+ customGitBranch: values.branch,
+ customGitUrl: values.repositoryURL,
+ customGitSSHKeyId: values.sshKey === "none" ? null : values.sshKey,
+ composeId,
+ sourceType: "git",
+ composePath: values.composePath,
+ composeStatus: "idle",
+ watchPaths: values.watchPaths || [],
+ enableSubmodules: values.enableSubmodules,
+ })
+ .then(async () => {
+ toast.success("Git Provider Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the Git provider");
+ });
+ };
+
+ return (
+
+
+
+
+
+ {sshKeys && sshKeys.length > 0 ? (
+
(
+
+
+ SSH Key
+
+
+
+
+
+
+
+
+
+ {sshKeys?.map((sshKey) => (
+
+ {sshKey.name}
+
+ ))}
+ None
+ Keys ({sshKeys?.length})
+
+
+
+
+
+ )}
+ />
+ ) : (
+ router.push("/dashboard/settings/ssh-keys")}
+ type="button"
+ >
+ Add SSH Key
+
+ )}
+
+
+ (
+
+ Branch
+
+
+
+
+
+ )}
+ />
+
+
+
(
+
+ Compose Path
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
Watch Paths
+
+
+
+
+ ?
+
+
+
+
+ Add paths to watch for changes. When files in these
+ paths change, a new deployment will be triggered. This
+ will work only when manual webhook is setup.
+
+
+
+
+
+
+ {field.value?.map((path, index) => (
+
+ {path}
+ {
+ const newPaths = [...(field.value || [])];
+ newPaths.splice(index, 1);
+ form.setValue("watchPaths", newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }
+ }}
+ />
+ {
+ const input = document.querySelector(
+ 'input[placeholder="Enter a path to watch (e.g., src/**, dist/*.js)"]',
+ ) as HTMLInputElement;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }}
+ >
+ Add
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+
+ Save{" "}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/generic/save-gitea-provider-compose.tsx b/data/apps/dokploy/components/dashboard/compose/general/generic/save-gitea-provider-compose.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..0b57b03d2424525a357c9a4eabbfe3a54843fdb8
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/generic/save-gitea-provider-compose.tsx
@@ -0,0 +1,503 @@
+import { GiteaIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import type { Repository } from "@/utils/gitea-utils";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { CheckIcon, ChevronsUpDown, Plus, X } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const GiteaProviderSchema = z.object({
+ composePath: z.string().min(1),
+ repository: z
+ .object({
+ repo: z.string().min(1, "Repo is required"),
+ owner: z.string().min(1, "Owner is required"),
+ })
+ .required(),
+ branch: z.string().min(1, "Branch is required"),
+ giteaId: z.string().min(1, "Gitea Provider is required"),
+ watchPaths: z.array(z.string()).optional(),
+ enableSubmodules: z.boolean().default(false),
+});
+
+type GiteaProvider = z.infer;
+
+interface Props {
+ composeId: string;
+}
+
+export const SaveGiteaProviderCompose = ({ composeId }: Props) => {
+ const { data: giteaProviders } = api.gitea.giteaProviders.useQuery();
+ const { data, refetch } = api.compose.one.useQuery({ composeId });
+ const { mutateAsync, isLoading: isSavingGiteaProvider } =
+ api.compose.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ composePath: "./docker-compose.yml",
+ repository: {
+ owner: "",
+ repo: "",
+ },
+ giteaId: "",
+ branch: "",
+ watchPaths: [],
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(GiteaProviderSchema),
+ });
+
+ const repository = form.watch("repository");
+ const giteaId = form.watch("giteaId");
+
+ const { data: giteaUrl } = api.gitea.getGiteaUrl.useQuery(
+ { giteaId },
+ {
+ enabled: !!giteaId,
+ },
+ );
+
+ const {
+ data: repositories,
+ isLoading: isLoadingRepositories,
+ error,
+ } = api.gitea.getGiteaRepositories.useQuery(
+ {
+ giteaId,
+ },
+ {
+ enabled: !!giteaId,
+ },
+ );
+
+ const {
+ data: branches,
+ fetchStatus,
+ status,
+ } = api.gitea.getGiteaBranches.useQuery(
+ {
+ owner: repository?.owner,
+ repositoryName: repository?.repo,
+ giteaId: giteaId,
+ },
+ {
+ enabled: !!repository?.owner && !!repository?.repo && !!giteaId,
+ },
+ );
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ branch: data.giteaBranch || "",
+ repository: {
+ repo: data.giteaRepository || "",
+ owner: data.giteaOwner || "",
+ },
+ composePath: data.composePath || "./docker-compose.yml",
+ giteaId: data.giteaId || "",
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules ?? false,
+ });
+ }
+ }, [form.reset, data?.composeId, form]);
+
+ const onSubmit = async (data: GiteaProvider) => {
+ await mutateAsync({
+ giteaBranch: data.branch,
+ giteaRepository: data.repository.repo,
+ giteaOwner: data.repository.owner,
+ composePath: data.composePath,
+ giteaId: data.giteaId,
+ composeId,
+ sourceType: "gitea",
+ composeStatus: "idle",
+ watchPaths: data.watchPaths,
+ enableSubmodules: data.enableSubmodules,
+ } as any)
+ .then(async () => {
+ toast.success("Service Provider Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the Gitea provider");
+ });
+ };
+
+ return (
+
+
+
+ {error && {error?.message} }
+
+
+
(
+
+ Gitea Account
+ {
+ field.onChange(value);
+ form.setValue("repository", {
+ owner: "",
+ repo: "",
+ });
+ form.setValue("branch", "");
+ }}
+ defaultValue={field.value}
+ value={field.value}
+ >
+
+
+
+
+
+
+ {giteaProviders?.map((giteaProvider) => (
+
+ {giteaProvider.gitProvider.name}
+
+ ))}
+
+
+
+
+ )}
+ />
+
+ (
+
+
+ Repository
+ {field.value.owner && field.value.repo && (
+
+
+ View Repository
+
+ )}
+
+
+
+
+
+ {isLoadingRepositories
+ ? "Loading...."
+ : field.value.owner
+ ? repositories?.find(
+ (repo) => repo.name === field.value.repo,
+ )?.name
+ : "Select repository"}
+
+
+
+
+
+
+
+ {isLoadingRepositories && (
+
+ Loading Repositories....
+
+ )}
+ No repositories found.
+
+
+ {repositories?.map((repo) => (
+ {
+ form.setValue("repository", {
+ owner: repo.owner.username,
+ repo: repo.name,
+ });
+ form.setValue("branch", "");
+ }}
+ >
+
+ {repo.name}
+
+ {repo.owner.username}
+
+
+
+
+ ))}
+
+
+
+
+
+ {form.formState.errors.repository && (
+
+ Repository is required
+
+ )}
+
+ )}
+ />
+
+ (
+
+ Branch
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching"
+ ? "Loading...."
+ : field.value
+ ? branches?.find(
+ (branch) => branch.name === field.value,
+ )?.name
+ : "Select branch"}
+
+
+
+
+
+
+
+ No branches found.
+
+
+ {branches?.map((branch) => (
+
+ form.setValue("branch", branch.name)
+ }
+ >
+
+ {branch.name}
+
+
+
+ ))}
+
+
+
+
+
+ {form.formState.errors.branch && (
+
+ Branch is required
+
+ )}
+
+ )}
+ />
+
+ (
+
+ Compose Path
+
+
+
+
+
+ )}
+ />
+
+ (
+
+
+
Watch Paths
+
+
+
+
+ ?
+
+
+
+
+ Add paths to watch for changes. When files in these
+ paths change, a new deployment will be triggered.
+
+
+
+
+
+
+ {field.value?.map((path, index) => (
+
+ {path}
+ {
+ const newPaths = [...(field.value || [])];
+ newPaths.splice(index, 1);
+ form.setValue("watchPaths", newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+
{
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }
+ }}
+ />
+
{
+ const input = document.querySelector(
+ 'input[placeholder*="Enter a path"]',
+ ) as HTMLInputElement;
+ const path = input.value.trim();
+ if (path) {
+ field.onChange([...(field.value || []), path]);
+ input.value = "";
+ }
+ }}
+ >
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+
+ Save
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/generic/save-github-provider-compose.tsx b/data/apps/dokploy/components/dashboard/compose/general/generic/save-github-provider-compose.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5b2019fe336dc8bd0abb02b0b43525160efe9aa7
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/generic/save-github-provider-compose.tsx
@@ -0,0 +1,547 @@
+import { GithubIcon } from "@/components/icons/data-tools-icons";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { CheckIcon, ChevronsUpDown, HelpCircle, X } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const GithubProviderSchema = z.object({
+ composePath: z.string().min(1),
+ repository: z
+ .object({
+ repo: z.string().min(1, "Repo is required"),
+ owner: z.string().min(1, "Owner is required"),
+ })
+ .required(),
+ branch: z.string().min(1, "Branch is required"),
+ githubId: z.string().min(1, "Github Provider is required"),
+ watchPaths: z.array(z.string()).optional(),
+ triggerType: z.enum(["push", "tag"]).default("push"),
+ enableSubmodules: z.boolean().default(false),
+});
+
+type GithubProvider = z.infer;
+
+interface Props {
+ composeId: string;
+}
+
+export const SaveGithubProviderCompose = ({ composeId }: Props) => {
+ const { data: githubProviders } = api.github.githubProviders.useQuery();
+ const { data, refetch } = api.compose.one.useQuery({ composeId });
+
+ const { mutateAsync, isLoading: isSavingGithubProvider } =
+ api.compose.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ composePath: "./docker-compose.yml",
+ repository: {
+ owner: "",
+ repo: "",
+ },
+ githubId: "",
+ branch: "",
+ watchPaths: [],
+ triggerType: "push",
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(GithubProviderSchema),
+ });
+
+ const repository = form.watch("repository");
+ const githubId = form.watch("githubId");
+ const triggerType = form.watch("triggerType");
+ const { data: repositories, isLoading: isLoadingRepositories } =
+ api.github.getGithubRepositories.useQuery(
+ {
+ githubId,
+ },
+ {
+ enabled: !!githubId,
+ },
+ );
+
+ const {
+ data: branches,
+ fetchStatus,
+ status,
+ } = api.github.getGithubBranches.useQuery(
+ {
+ owner: repository?.owner,
+ repo: repository?.repo,
+ githubId,
+ },
+ {
+ enabled: !!repository?.owner && !!repository?.repo && !!githubId,
+ },
+ );
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ branch: data.branch || "",
+ repository: {
+ repo: data.repository || "",
+ owner: data.owner || "",
+ },
+ composePath: data.composePath,
+ githubId: data.githubId || "",
+ watchPaths: data.watchPaths || [],
+ triggerType: data.triggerType || "push",
+ enableSubmodules: data.enableSubmodules ?? false,
+ });
+ }
+ }, [form.reset, data?.composeId, form]);
+
+ const onSubmit = async (data: GithubProvider) => {
+ await mutateAsync({
+ branch: data.branch,
+ repository: data.repository.repo,
+ composeId,
+ owner: data.repository.owner,
+ composePath: data.composePath,
+ githubId: data.githubId,
+ sourceType: "github",
+ composeStatus: "idle",
+ watchPaths: data.watchPaths,
+ enableSubmodules: data.enableSubmodules,
+ triggerType: data.triggerType,
+ })
+ .then(async () => {
+ toast.success("Service Provided Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the Github provider");
+ });
+ };
+
+ return (
+
+
+
+
+
(
+
+ Github Account
+ {
+ field.onChange(value);
+ form.setValue("repository", {
+ owner: "",
+ repo: "",
+ });
+ form.setValue("branch", "");
+ }}
+ defaultValue={field.value}
+ value={field.value}
+ >
+
+
+
+
+
+
+ {githubProviders?.map((githubProvider) => (
+
+ {githubProvider.gitProvider.name}
+
+ ))}
+
+
+
+
+ )}
+ />
+ (
+
+
+ Repository
+ {field.value.owner && field.value.repo && (
+
+
+ View Repository
+
+ )}
+
+
+
+
+
+ {isLoadingRepositories
+ ? "Loading...."
+ : field.value.owner
+ ? repositories?.find(
+ (repo) => repo.name === field.value.repo,
+ )?.name
+ : "Select repository"}
+
+
+
+
+
+
+
+
+ {isLoadingRepositories && (
+
+ Loading Repositories....
+
+ )}
+ No repositories found.
+
+
+ {repositories?.map((repo) => (
+ {
+ form.setValue("repository", {
+ owner: repo.owner.login as string,
+ repo: repo.name,
+ });
+ form.setValue("branch", "");
+ }}
+ >
+
+ {repo.name}
+
+ {repo.owner.login}
+
+
+
+
+ ))}
+
+
+
+
+
+ {form.formState.errors.repository && (
+
+ Repository is required
+
+ )}
+
+ )}
+ />
+ (
+
+ Branch
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching"
+ ? "Loading...."
+ : field.value
+ ? branches?.find(
+ (branch) => branch.name === field.value,
+ )?.name
+ : "Select branch"}
+
+
+
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching" && (
+
+ Loading Branches....
+
+ )}
+ {!repository?.owner && (
+
+ Select a repository
+
+ )}
+
+ No branch found.
+
+
+ {branches?.map((branch) => (
+ {
+ form.setValue("branch", branch.name);
+ }}
+ >
+ {branch.name}
+
+
+ ))}
+
+
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Compose Path
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
Trigger Type
+
+
+
+
+
+
+
+ Choose when to trigger deployments: on push to the
+ selected branch or when a new tag is created.
+
+
+
+
+
+
+
+
+
+
+
+
+ On Push
+ On Tag
+
+
+
+
+ )}
+ />
+ {triggerType === "push" && (
+ (
+
+
+
Watch Paths
+
+
+
+
+ ?
+
+
+
+
+ Add paths to watch for changes. When files in
+ these paths change, a new deployment will be
+ triggered.
+
+
+
+
+
+
+ {field.value?.map((path, index) => (
+
+ {path}
+ {
+ const newPaths = [...(field.value || [])];
+ newPaths.splice(index, 1);
+ form.setValue("watchPaths", newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [
+ ...(field.value || []),
+ value,
+ ];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }
+ }}
+ />
+ {
+ const input = document.querySelector(
+ 'input[placeholder="Enter a path to watch (e.g., src/**, dist/*.js)"]',
+ ) as HTMLInputElement;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }}
+ >
+ Add
+
+
+
+
+
+ )}
+ />
+ )}
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+ Save
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/generic/save-gitlab-provider-compose.tsx b/data/apps/dokploy/components/dashboard/compose/general/generic/save-gitlab-provider-compose.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c630cd71e91f573810bb07267557e677b7d92a20
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/generic/save-gitlab-provider-compose.tsx
@@ -0,0 +1,522 @@
+import { GitlabIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { CheckIcon, ChevronsUpDown, X } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const GitlabProviderSchema = z.object({
+ composePath: z.string().min(1),
+ repository: z
+ .object({
+ repo: z.string().min(1, "Repo is required"),
+ owner: z.string().min(1, "Owner is required"),
+ id: z.number().nullable(),
+ gitlabPathNamespace: z.string().min(1),
+ })
+ .required(),
+ branch: z.string().min(1, "Branch is required"),
+ gitlabId: z.string().min(1, "Gitlab Provider is required"),
+ watchPaths: z.array(z.string()).optional(),
+ enableSubmodules: z.boolean().default(false),
+});
+
+type GitlabProvider = z.infer;
+
+interface Props {
+ composeId: string;
+}
+
+export const SaveGitlabProviderCompose = ({ composeId }: Props) => {
+ const { data: gitlabProviders } = api.gitlab.gitlabProviders.useQuery();
+ const { data, refetch } = api.compose.one.useQuery({ composeId });
+
+ const { mutateAsync, isLoading: isSavingGitlabProvider } =
+ api.compose.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ composePath: "./docker-compose.yml",
+ repository: {
+ owner: "",
+ repo: "",
+ gitlabPathNamespace: "",
+ id: null,
+ },
+ gitlabId: "",
+ branch: "",
+ watchPaths: [],
+ enableSubmodules: false,
+ },
+ resolver: zodResolver(GitlabProviderSchema),
+ });
+
+ const repository = form.watch("repository");
+ const gitlabId = form.watch("gitlabId");
+
+ const {
+ data: repositories,
+ isLoading: isLoadingRepositories,
+ error,
+ } = api.gitlab.getGitlabRepositories.useQuery(
+ {
+ gitlabId,
+ },
+ {
+ enabled: !!gitlabId,
+ },
+ );
+
+ const {
+ data: branches,
+ fetchStatus,
+ status,
+ } = api.gitlab.getGitlabBranches.useQuery(
+ {
+ owner: repository?.owner,
+ repo: repository?.repo,
+ id: repository?.id || 0,
+ gitlabId: gitlabId,
+ },
+ {
+ enabled: !!repository?.owner && !!repository?.repo && !!gitlabId,
+ },
+ );
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ branch: data.gitlabBranch || "",
+ repository: {
+ repo: data.gitlabRepository || "",
+ owner: data.gitlabOwner || "",
+ id: data.gitlabProjectId,
+ gitlabPathNamespace: data.gitlabPathNamespace || "",
+ },
+ composePath: data.composePath,
+ gitlabId: data.gitlabId || "",
+ watchPaths: data.watchPaths || [],
+ enableSubmodules: data.enableSubmodules ?? false,
+ });
+ }
+ }, [form.reset, data?.composeId, form]);
+
+ const onSubmit = async (data: GitlabProvider) => {
+ await mutateAsync({
+ gitlabBranch: data.branch,
+ gitlabRepository: data.repository.repo,
+ gitlabOwner: data.repository.owner,
+ composePath: data.composePath,
+ gitlabId: data.gitlabId,
+ composeId,
+ gitlabProjectId: data.repository.id,
+ gitlabPathNamespace: data.repository.gitlabPathNamespace,
+ sourceType: "gitlab",
+ composeStatus: "idle",
+ watchPaths: data.watchPaths,
+ enableSubmodules: data.enableSubmodules,
+ })
+ .then(async () => {
+ toast.success("Service Provided Saved");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the Gitlab provider");
+ });
+ };
+
+ return (
+
+
+
+ {error && {error?.message} }
+
+
(
+
+ Gitlab Account
+ {
+ field.onChange(value);
+ form.setValue("repository", {
+ owner: "",
+ repo: "",
+ gitlabPathNamespace: "",
+ id: null,
+ });
+ form.setValue("branch", "");
+ }}
+ defaultValue={field.value}
+ value={field.value}
+ >
+
+
+
+
+
+
+ {gitlabProviders?.map((gitlabProvider) => (
+
+ {gitlabProvider.gitProvider.name}
+
+ ))}
+
+
+
+
+ )}
+ />
+ (
+
+
+ Repository
+ {field.value.owner && field.value.repo && (
+
+
+ View Repository
+
+ )}
+
+
+
+
+
+ {isLoadingRepositories
+ ? "Loading...."
+ : field.value.owner
+ ? repositories?.find(
+ (repo) => repo.name === field.value.repo,
+ )?.name
+ : "Select repository"}
+
+
+
+
+
+
+
+
+ {isLoadingRepositories && (
+
+ Loading Repositories....
+
+ )}
+ No repositories found.
+
+
+ {repositories && repositories.length === 0 && (
+
+ No repositories found.
+
+ )}
+ {repositories?.map((repo) => {
+ return (
+ {
+ form.setValue("repository", {
+ owner: repo.owner.username as string,
+ repo: repo.name,
+ id: repo.id,
+ gitlabPathNamespace: repo.url,
+ });
+ form.setValue("branch", "");
+ }}
+ >
+
+ {repo.name}
+
+ {repo.owner.username}
+
+
+
+
+ );
+ })}
+
+
+
+
+
+ {form.formState.errors.repository && (
+
+ Repository is required
+
+ )}
+
+ )}
+ />
+ (
+
+ Branch
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching"
+ ? "Loading...."
+ : field.value
+ ? branches?.find(
+ (branch) => branch.name === field.value,
+ )?.name
+ : "Select branch"}
+
+
+
+
+
+
+
+ {status === "loading" && fetchStatus === "fetching" && (
+
+ Loading Branches....
+
+ )}
+ {!repository?.owner && (
+
+ Select a repository
+
+ )}
+
+ No branch found.
+
+
+ {branches?.map((branch) => (
+ {
+ form.setValue("branch", branch.name);
+ }}
+ >
+ {branch.name}
+
+
+ ))}
+
+
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Compose Path
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
Watch Paths
+
+
+
+
+ ?
+
+
+
+
+ Add paths to watch for changes. When files in these
+ paths change, a new deployment will be triggered.
+
+
+
+
+
+
+ {field.value?.map((path, index) => (
+
+ {path}
+ {
+ const newPaths = [...(field.value || [])];
+ newPaths.splice(index, 1);
+ form.setValue("watchPaths", newPaths);
+ }}
+ />
+
+ ))}
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const input = e.currentTarget;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }
+ }}
+ />
+ {
+ const input = document.querySelector(
+ 'input[placeholder="Enter a path to watch (e.g., src/**, dist/*.js)"]',
+ ) as HTMLInputElement;
+ const value = input.value.trim();
+ if (value) {
+ const newPaths = [...(field.value || []), value];
+ form.setValue("watchPaths", newPaths);
+ input.value = "";
+ }
+ }}
+ >
+ Add
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
+
+ Enable Submodules
+
+ )}
+ />
+
+
+
+ Save
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/generic/show.tsx b/data/apps/dokploy/components/dashboard/compose/general/generic/show.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..afdfbfba4ae080a401f7e422a9200033436ba476
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/generic/show.tsx
@@ -0,0 +1,232 @@
+import {
+ BitbucketIcon,
+ GitIcon,
+ GiteaIcon,
+ GithubIcon,
+ GitlabIcon,
+} from "@/components/icons/data-tools-icons";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { api } from "@/utils/api";
+import { CodeIcon, GitBranch, Loader2 } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { ComposeFileEditor } from "../compose-file-editor";
+import { ShowConvertedCompose } from "../show-converted-compose";
+import { SaveBitbucketProviderCompose } from "./save-bitbucket-provider-compose";
+import { SaveGitProviderCompose } from "./save-git-provider-compose";
+import { SaveGiteaProviderCompose } from "./save-gitea-provider-compose";
+import { SaveGithubProviderCompose } from "./save-github-provider-compose";
+import { SaveGitlabProviderCompose } from "./save-gitlab-provider-compose";
+
+type TabState = "github" | "git" | "raw" | "gitlab" | "bitbucket" | "gitea";
+interface Props {
+ composeId: string;
+}
+
+export const ShowProviderFormCompose = ({ composeId }: Props) => {
+ const { data: githubProviders, isLoading: isLoadingGithub } =
+ api.github.githubProviders.useQuery();
+ const { data: gitlabProviders, isLoading: isLoadingGitlab } =
+ api.gitlab.gitlabProviders.useQuery();
+ const { data: bitbucketProviders, isLoading: isLoadingBitbucket } =
+ api.bitbucket.bitbucketProviders.useQuery();
+ const { data: giteaProviders, isLoading: isLoadingGitea } =
+ api.gitea.giteaProviders.useQuery();
+
+ const { data: compose } = api.compose.one.useQuery({ composeId });
+ const [tab, setSab] = useState(compose?.sourceType || "github");
+
+ const isLoading =
+ isLoadingGithub || isLoadingGitlab || isLoadingBitbucket || isLoadingGitea;
+
+ if (isLoading) {
+ return (
+
+
+
+
+
Provider
+
+ Select the source of your code
+
+
+
+
+
+
+
+
+
+
+
+ Loading providers...
+
+
+
+
+ );
+ }
+
+ return (
+
+
+
+
+
Provider
+
+ Select the source of your code
+
+
+
+
+
+
+
+
+
+ {
+ setSab(e as TabState);
+ }}
+ >
+
+
+
+
+ GitHub
+
+
+
+ GitLab
+
+
+
+ Bitbucket
+
+
+ Gitea
+
+
+
+ Git
+
+
+
+ Raw
+
+
+
+
+
+ {githubProviders && githubProviders?.length > 0 ? (
+
+ ) : (
+
+
+
+ To deploy using GitHub, you need to configure your account
+ first. Please, go to{" "}
+
+ Settings
+ {" "}
+ to do so.
+
+
+ )}
+
+
+ {gitlabProviders && gitlabProviders?.length > 0 ? (
+
+ ) : (
+
+
+
+ To deploy using GitLab, you need to configure your account
+ first. Please, go to{" "}
+
+ Settings
+ {" "}
+ to do so.
+
+
+ )}
+
+
+ {bitbucketProviders && bitbucketProviders?.length > 0 ? (
+
+ ) : (
+
+
+
+ To deploy using Bitbucket, you need to configure your account
+ first. Please, go to{" "}
+
+ Settings
+ {" "}
+ to do so.
+
+
+ )}
+
+
+ {giteaProviders && giteaProviders?.length > 0 ? (
+
+ ) : (
+
+
+
+ To deploy using Gitea, you need to configure your account
+ first. Please, go to{" "}
+
+ Settings
+ {" "}
+ to do so.
+
+
+ )}
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/isolated-deployment.tsx b/data/apps/dokploy/components/dashboard/compose/general/isolated-deployment.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..d76f79021d50ffb38d47fb91885d01a5caa6fca6
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/isolated-deployment.tsx
@@ -0,0 +1,188 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+} from "@/components/ui/form";
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertTriangle } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+interface Props {
+ composeId: string;
+}
+
+const schema = z.object({
+ isolatedDeployment: z.boolean().optional(),
+});
+
+type Schema = z.infer;
+
+export const IsolatedDeployment = ({ composeId }: Props) => {
+ const utils = api.useUtils();
+ const [compose, setCompose] = useState("");
+ const { mutateAsync, error, isError } =
+ api.compose.isolatedDeployment.useMutation();
+
+ const { mutateAsync: updateCompose } = api.compose.update.useMutation();
+
+ const { data, refetch } = api.compose.one.useQuery(
+ { composeId },
+ { enabled: !!composeId },
+ );
+
+ console.log(data);
+
+ const form = useForm({
+ defaultValues: {
+ isolatedDeployment: false,
+ },
+ resolver: zodResolver(schema),
+ });
+
+ useEffect(() => {
+ randomizeCompose();
+ if (data) {
+ form.reset({
+ isolatedDeployment: data?.isolatedDeployment || false,
+ });
+ }
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data]);
+
+ const onSubmit = async (formData: Schema) => {
+ await updateCompose({
+ composeId,
+ isolatedDeployment: formData?.isolatedDeployment || false,
+ })
+ .then(async (_data) => {
+ await randomizeCompose();
+ await refetch();
+ toast.success("Compose updated");
+ })
+ .catch(() => {
+ toast.error("Error updating the compose");
+ });
+ };
+
+ const randomizeCompose = async () => {
+ await mutateAsync({
+ composeId,
+ suffix: data?.appName || "",
+ }).then(async (data) => {
+ await utils.project.all.invalidate();
+ setCompose(data);
+ });
+ };
+
+ return (
+ <>
+
+ Isolate Deployment
+
+ Use this option to isolate the deployment of this compose file.
+
+
+
+
+ This feature creates an isolated environment for your deployment by
+ adding unique prefixes to all resources. It establishes a dedicated
+ network based on your compose file's name, ensuring your services run
+ in isolation. This prevents conflicts when running multiple instances
+ of the same template or services with identical names.
+
+
+
+
+ Resources that will be isolated:
+
+
+ Docker volumes
+ Docker networks
+
+
+
+
+ {isError && {error?.message} }
+
+
+ {isError && (
+
+
+
+ {error?.message}
+
+
+ )}
+
+
+
+
(
+
+
+
+ Enable Isolated Deployment ({data?.appName})
+
+
+ Enable isolated deployment to the compose file.
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ Save
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/randomize-compose.tsx b/data/apps/dokploy/components/dashboard/compose/general/randomize-compose.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5ac67e0c880ff4bef90e1f9e8a951aca39cab48a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/randomize-compose.tsx
@@ -0,0 +1,213 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertTriangle } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+interface Props {
+ composeId: string;
+}
+
+const schema = z.object({
+ suffix: z.string(),
+ randomize: z.boolean().optional(),
+});
+
+type Schema = z.infer;
+
+export const RandomizeCompose = ({ composeId }: Props) => {
+ const utils = api.useUtils();
+ const [compose, setCompose] = useState("");
+ const [_isOpen, _setIsOpen] = useState(false);
+ const { mutateAsync, error, isError } =
+ api.compose.randomizeCompose.useMutation();
+
+ const { mutateAsync: updateCompose } = api.compose.update.useMutation();
+
+ const { data, refetch } = api.compose.one.useQuery(
+ { composeId },
+ { enabled: !!composeId },
+ );
+
+ const form = useForm({
+ defaultValues: {
+ suffix: "",
+ randomize: false,
+ },
+ resolver: zodResolver(schema),
+ });
+
+ const suffix = form.watch("suffix");
+
+ useEffect(() => {
+ randomizeCompose();
+ if (data) {
+ form.reset({
+ suffix: data?.suffix || "",
+ randomize: data?.randomize || false,
+ });
+ }
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data]);
+
+ const onSubmit = async (formData: Schema) => {
+ await updateCompose({
+ composeId,
+ suffix: formData?.suffix || "",
+ randomize: formData?.randomize || false,
+ })
+ .then(async (_data) => {
+ await randomizeCompose();
+ await refetch();
+ toast.success("Compose updated");
+ })
+ .catch(() => {
+ toast.error("Error randomizing the compose");
+ });
+ };
+
+ const randomizeCompose = async () => {
+ await mutateAsync({
+ composeId,
+ suffix,
+ }).then(async (data) => {
+ await utils.project.all.invalidate();
+ setCompose(data);
+ });
+ };
+
+ return (
+
+
+ Randomize Compose (Experimental)
+
+ Use this in case you want to deploy the same compose file and you have
+ conflicts with some property like volumes, networks, etc.
+
+
+
+
+ This will randomize the compose file and will add a suffix to the
+ property to avoid conflicts
+
+
+ volumes
+ networks
+ services
+ configs
+ secrets
+
+
+ When you activate this option, we will include a env `COMPOSE_PREFIX`
+ variable to the compose file so you can use it in your compose file.
+
+
+ {isError &&
{error?.message} }
+
+
+ {isError && (
+
+
+
+ {error?.message}
+
+
+ )}
+
+
+
+
+
+
+ Save
+
+ {
+ await randomizeCompose();
+ }}
+ className="lg:w-fit"
+ >
+ Random
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/show-converted-compose.tsx b/data/apps/dokploy/components/dashboard/compose/general/show-converted-compose.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..77f331bdd5c921f5872476fba8bf254e477002f9
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/show-converted-compose.tsx
@@ -0,0 +1,116 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { api } from "@/utils/api";
+import { Loader2, Puzzle, RefreshCw } from "lucide-react";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+
+interface Props {
+ composeId: string;
+}
+
+export const ShowConvertedCompose = ({ composeId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const {
+ data: compose,
+ error,
+ isError,
+ refetch,
+ } = api.compose.getConvertedCompose.useQuery(
+ { composeId },
+ {
+ retry: false,
+ },
+ );
+
+ const { mutateAsync, isLoading } = api.compose.fetchSourceType.useMutation();
+
+ useEffect(() => {
+ if (isOpen) {
+ mutateAsync({ composeId })
+ .then(() => {
+ refetch();
+ })
+ .catch((_err) => {});
+ }
+ }, [isOpen]);
+
+ return (
+
+
+
+
+ Preview Compose
+
+
+
+
+ Converted Compose
+
+ Preview your docker-compose file with added domains. Note: At least
+ one domain must be specified for this conversion to take effect.
+
+
+ {isError && {error?.message} }
+
+
+ Preview your docker-compose file with added domains. Note: At least
+ one domain must be specified for this conversion to take effect.
+
+ {isLoading ? (
+
+
+
+ ) : compose?.length === 5 ? (
+
+
+
+ No converted compose data available.
+
+
+ ) : (
+ <>
+
+ {
+ mutateAsync({ composeId })
+ .then(() => {
+ refetch();
+ toast.success("Fetched source type");
+ })
+ .catch((err) => {
+ toast.error("Error fetching source type", {
+ description: err.message,
+ });
+ });
+ }}
+ >
+ Refresh
+
+
+
+
+
+
+ >
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/show-utilities.tsx b/data/apps/dokploy/components/dashboard/compose/general/show-utilities.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..214102ce988d4b1287e4f485d4a1c3a623daf422
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/show-utilities.tsx
@@ -0,0 +1,46 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { useState } from "react";
+import { IsolatedDeployment } from "./isolated-deployment";
+import { RandomizeCompose } from "./randomize-compose";
+
+interface Props {
+ composeId: string;
+}
+
+export const ShowUtilities = ({ composeId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+
+
+ Show Utilities
+
+
+
+ Utilities
+ Modify the application data
+
+
+
+ Isolated Deployment
+ Randomize Compose
+
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/general/show.tsx b/data/apps/dokploy/components/dashboard/compose/general/show.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..71752525c50b579d48d5b3e9f61f8db1b8a2dc04
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/general/show.tsx
@@ -0,0 +1,46 @@
+import { Badge } from "@/components/ui/badge";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { ComposeActions } from "./actions";
+import { ShowProviderFormCompose } from "./generic/show";
+interface Props {
+ composeId: string;
+}
+
+export const ShowGeneralCompose = ({ composeId }: Props) => {
+ const { data } = api.compose.one.useQuery(
+ { composeId },
+ {
+ enabled: !!composeId,
+ },
+ );
+
+ return (
+ <>
+
+
+
+ Deploy Settings
+
+ {data?.composeType === "docker-compose" ? "Compose" : "Stack"}
+
+
+
+
+ Create a compose file to deploy your compose
+
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/logs/show-stack.tsx b/data/apps/dokploy/components/dashboard/compose/logs/show-stack.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..d166f933f3d210fd645079e281ee3da9c0f3a9f3
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/logs/show-stack.tsx
@@ -0,0 +1,165 @@
+import { badgeStateColor } from "@/components/dashboard/application/logs/show";
+import { Badge } from "@/components/ui/badge";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { Loader2 } from "lucide-react";
+import dynamic from "next/dynamic";
+import { useEffect, useState } from "react";
+export const DockerLogs = dynamic(
+ () =>
+ import("@/components/dashboard/docker/logs/docker-logs-id").then(
+ (e) => e.DockerLogsId,
+ ),
+ {
+ ssr: false,
+ },
+);
+
+interface Props {
+ appName: string;
+ serverId?: string;
+}
+
+badgeStateColor;
+
+export const ShowDockerLogsStack = ({ appName, serverId }: Props) => {
+ const [option, setOption] = useState<"swarm" | "native">("native");
+ const [containerId, setContainerId] = useState();
+
+ const { data: services, isLoading: servicesLoading } =
+ api.docker.getStackContainersByAppName.useQuery(
+ {
+ appName,
+ serverId,
+ },
+ {
+ enabled: !!appName && option === "swarm",
+ },
+ );
+
+ const { data: containers, isLoading: containersLoading } =
+ api.docker.getContainersByAppNameMatch.useQuery(
+ {
+ appName,
+ appType: "stack",
+ serverId,
+ },
+ {
+ enabled: !!appName && option === "native",
+ },
+ );
+
+ useEffect(() => {
+ if (option === "native") {
+ if (containers && containers?.length > 0) {
+ setContainerId(containers[0]?.containerId);
+ }
+ } else {
+ if (services && services?.length > 0) {
+ setContainerId(services[0]?.containerId);
+ }
+ }
+ }, [option, services, containers]);
+
+ const isLoading = option === "native" ? containersLoading : servicesLoading;
+ const containersLenght =
+ option === "native" ? containers?.length : services?.length;
+
+ return (
+
+
+ Logs
+
+ Watch the logs of the application in real time
+
+
+
+
+
+
Select a container to view logs
+
+
+ {option === "native" ? "Native" : "Swarm"}
+
+ {
+ setOption(checked ? "native" : "swarm");
+ }}
+ />
+
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+
+ )}
+
+
+
+ {option === "native" ? (
+
+ {containers?.map((container) => (
+
+ {container.name} ({container.containerId}){" "}
+
+ {container.state}
+
+
+ ))}
+
+ ) : (
+ <>
+ {services?.map((container) => (
+
+ {container.name} ({container.containerId}@{container.node}
+ )
+
+ {container.state}
+
+
+ ))}
+ >
+ )}
+
+ Containers ({containersLenght})
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/logs/show.tsx b/data/apps/dokploy/components/dashboard/compose/logs/show.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..571190549e2a634fc92832918c70e3c2f6b4e3af
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/logs/show.tsx
@@ -0,0 +1,110 @@
+import { badgeStateColor } from "@/components/dashboard/application/logs/show";
+import { Badge } from "@/components/ui/badge";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { Loader2 } from "lucide-react";
+import dynamic from "next/dynamic";
+import { useEffect, useState } from "react";
+export const DockerLogs = dynamic(
+ () =>
+ import("@/components/dashboard/docker/logs/docker-logs-id").then(
+ (e) => e.DockerLogsId,
+ ),
+ {
+ ssr: false,
+ },
+);
+
+interface Props {
+ appName: string;
+ serverId?: string;
+ appType: "stack" | "docker-compose";
+}
+
+export const ShowDockerLogsCompose = ({
+ appName,
+ appType,
+ serverId,
+}: Props) => {
+ const { data, isLoading } = api.docker.getContainersByAppNameMatch.useQuery(
+ {
+ appName,
+ appType,
+ serverId,
+ },
+ {
+ enabled: !!appName,
+ },
+ );
+ const [containerId, setContainerId] = useState();
+
+ useEffect(() => {
+ if (data && data?.length > 0) {
+ setContainerId(data[0]?.containerId);
+ }
+ }, [data]);
+
+ return (
+
+
+ Logs
+
+ Watch the logs of the application in real time
+
+
+
+
+ Select a container to view logs
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+
+ )}
+
+
+
+ {data?.map((container) => (
+
+ {container.name} ({container.containerId}){" "}
+
+ {container.state}
+
+
+ ))}
+ Containers ({data?.length})
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/compose/update-compose.tsx b/data/apps/dokploy/components/dashboard/compose/update-compose.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c896186018313b1be2186f365c149b88a6d7e128
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/compose/update-compose.tsx
@@ -0,0 +1,165 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const updateComposeSchema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ description: z.string().optional(),
+});
+
+type UpdateCompose = z.infer;
+
+interface Props {
+ composeId: string;
+}
+
+export const UpdateCompose = ({ composeId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const utils = api.useUtils();
+ const { mutateAsync, error, isError, isLoading } =
+ api.compose.update.useMutation();
+ const { data } = api.compose.one.useQuery(
+ {
+ composeId,
+ },
+ {
+ enabled: !!composeId,
+ },
+ );
+ const form = useForm({
+ defaultValues: {
+ description: data?.description ?? "",
+ name: data?.name ?? "",
+ },
+ resolver: zodResolver(updateComposeSchema),
+ });
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ description: data.description ?? "",
+ name: data.name,
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: UpdateCompose) => {
+ await mutateAsync({
+ name: formData.name,
+ composeId: composeId,
+ description: formData.description || "",
+ })
+ .then(() => {
+ toast.success("Compose updated successfully");
+ utils.compose.one.invalidate({
+ composeId: composeId,
+ });
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating the Compose");
+ })
+ .finally(() => {});
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Modify Compose
+ Update the compose data
+
+ {isError && {error?.message} }
+
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+ Update
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/database/backups/handle-backup.tsx b/data/apps/dokploy/components/dashboard/database/backups/handle-backup.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..ca2cd27fbbac68c87e7caf386328a2ba11c2bb87
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/database/backups/handle-backup.tsx
@@ -0,0 +1,828 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ DatabaseZap,
+ Info,
+ PenBoxIcon,
+ PlusIcon,
+ RefreshCw,
+} from "lucide-react";
+import { CheckIcon, ChevronsUpDown } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import { commonCronExpressions } from "../../application/schedules/handle-schedules";
+
+type CacheType = "cache" | "fetch";
+
+type DatabaseType = "postgres" | "mariadb" | "mysql" | "mongo" | "web-server";
+
+const Schema = z
+ .object({
+ destinationId: z.string().min(1, "Destination required"),
+ schedule: z.string().min(1, "Schedule (Cron) required"),
+ prefix: z.string().min(1, "Prefix required"),
+ enabled: z.boolean(),
+ database: z.string().min(1, "Database required"),
+ keepLatestCount: z.coerce.number().optional(),
+ serviceName: z.string().nullable(),
+ databaseType: z
+ .enum(["postgres", "mariadb", "mysql", "mongo", "web-server"])
+ .optional(),
+ backupType: z.enum(["database", "compose"]),
+ metadata: z
+ .object({
+ postgres: z
+ .object({
+ databaseUser: z.string(),
+ })
+ .optional(),
+ mariadb: z
+ .object({
+ databaseUser: z.string(),
+ databasePassword: z.string(),
+ })
+ .optional(),
+ mongo: z
+ .object({
+ databaseUser: z.string(),
+ databasePassword: z.string(),
+ })
+ .optional(),
+ mysql: z
+ .object({
+ databaseRootPassword: z.string(),
+ })
+ .optional(),
+ })
+ .optional(),
+ })
+ .superRefine((data, ctx) => {
+ if (data.backupType === "compose" && !data.databaseType) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database type is required for compose backups",
+ path: ["databaseType"],
+ });
+ }
+
+ if (data.backupType === "compose" && !data.serviceName) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Service name is required for compose backups",
+ path: ["serviceName"],
+ });
+ }
+
+ if (data.backupType === "compose" && data.databaseType) {
+ if (data.databaseType === "postgres") {
+ if (!data.metadata?.postgres?.databaseUser) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database user is required for PostgreSQL",
+ path: ["metadata", "postgres", "databaseUser"],
+ });
+ }
+ } else if (data.databaseType === "mariadb") {
+ if (!data.metadata?.mariadb?.databaseUser) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database user is required for MariaDB",
+ path: ["metadata", "mariadb", "databaseUser"],
+ });
+ }
+ if (!data.metadata?.mariadb?.databasePassword) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database password is required for MariaDB",
+ path: ["metadata", "mariadb", "databasePassword"],
+ });
+ }
+ } else if (data.databaseType === "mongo") {
+ if (!data.metadata?.mongo?.databaseUser) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database user is required for MongoDB",
+ path: ["metadata", "mongo", "databaseUser"],
+ });
+ }
+ if (!data.metadata?.mongo?.databasePassword) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database password is required for MongoDB",
+ path: ["metadata", "mongo", "databasePassword"],
+ });
+ }
+ } else if (data.databaseType === "mysql") {
+ if (!data.metadata?.mysql?.databaseRootPassword) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Root password is required for MySQL",
+ path: ["metadata", "mysql", "databaseRootPassword"],
+ });
+ }
+ }
+ }
+ });
+
+interface Props {
+ id?: string;
+ backupId?: string;
+ databaseType?: DatabaseType;
+ refetch: () => void;
+ backupType: "database" | "compose";
+}
+
+export const HandleBackup = ({
+ id,
+ backupId,
+ databaseType = "postgres",
+ refetch,
+ backupType = "database",
+}: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ const { data, isLoading } = api.destination.all.useQuery();
+ const { data: backup } = api.backup.one.useQuery(
+ {
+ backupId: backupId ?? "",
+ },
+ {
+ enabled: !!backupId,
+ },
+ );
+ const [cacheType, setCacheType] = useState("cache");
+ const { mutateAsync: createBackup, isLoading: isCreatingPostgresBackup } =
+ backupId
+ ? api.backup.update.useMutation()
+ : api.backup.create.useMutation();
+
+ const form = useForm>({
+ defaultValues: {
+ database: databaseType === "web-server" ? "dokploy" : "",
+ destinationId: "",
+ enabled: true,
+ prefix: "/",
+ schedule: "",
+ keepLatestCount: undefined,
+ serviceName: null,
+ databaseType: backupType === "compose" ? undefined : databaseType,
+ backupType: backupType,
+ metadata: {},
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ const {
+ data: services,
+ isFetching: isLoadingServices,
+ error: errorServices,
+ refetch: refetchServices,
+ } = api.compose.loadServices.useQuery(
+ {
+ composeId: backup?.composeId ?? id ?? "",
+ type: cacheType,
+ },
+ {
+ retry: false,
+ refetchOnWindowFocus: false,
+ enabled: backupType === "compose" && !!backup?.composeId && !!id,
+ },
+ );
+
+ useEffect(() => {
+ form.reset({
+ database: backup?.database
+ ? backup?.database
+ : databaseType === "web-server"
+ ? "dokploy"
+ : "",
+ destinationId: backup?.destinationId ?? "",
+ enabled: backup?.enabled ?? true,
+ prefix: backup?.prefix ?? "/",
+ schedule: backup?.schedule ?? "",
+ keepLatestCount: backup?.keepLatestCount ?? undefined,
+ serviceName: backup?.serviceName ?? null,
+ databaseType: backup?.databaseType ?? databaseType,
+ backupType: backup?.backupType ?? backupType,
+ metadata: backup?.metadata ?? {},
+ });
+ }, [form, form.reset, backupId, backup]);
+
+ const onSubmit = async (data: z.infer) => {
+ const getDatabaseId =
+ backupType === "compose"
+ ? {
+ composeId: id,
+ }
+ : databaseType === "postgres"
+ ? {
+ postgresId: id,
+ }
+ : databaseType === "mariadb"
+ ? {
+ mariadbId: id,
+ }
+ : databaseType === "mysql"
+ ? {
+ mysqlId: id,
+ }
+ : databaseType === "mongo"
+ ? {
+ mongoId: id,
+ }
+ : databaseType === "web-server"
+ ? {
+ userId: id,
+ }
+ : undefined;
+
+ await createBackup({
+ destinationId: data.destinationId,
+ prefix: data.prefix,
+ schedule: data.schedule,
+ enabled: data.enabled,
+ database: data.database,
+ keepLatestCount: data.keepLatestCount ?? null,
+ databaseType: data.databaseType || databaseType,
+ serviceName: data.serviceName,
+ ...getDatabaseId,
+ backupId: backupId ?? "",
+ backupType,
+ metadata: data.metadata,
+ })
+ .then(async () => {
+ toast.success(`Backup ${backupId ? "Updated" : "Created"}`);
+ refetch();
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error(`Error ${backupId ? "updating" : "creating"} a backup`);
+ });
+ };
+
+ return (
+
+
+ {backupId ? (
+
+
+
+ ) : (
+
+
+ {backupId ? "Update Backup" : "Create Backup"}
+
+ )}
+
+
+
+
+ {backupId ? "Update Backup" : "Create Backup"}
+
+
+ {backupId ? "Update a backup" : "Add a new backup"}
+
+
+
+
+
+
+
+
+ {backupId ? "Update" : "Create"}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/database/backups/restore-backup.tsx b/data/apps/dokploy/components/dashboard/database/backups/restore-backup.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..7617b510ed648c71361605afec9718c284acd735
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/database/backups/restore-backup.tsx
@@ -0,0 +1,818 @@
+import { DrawerLogs } from "@/components/shared/drawer-logs";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import copy from "copy-to-clipboard";
+import { debounce } from "lodash";
+import {
+ CheckIcon,
+ ChevronsUpDown,
+ Copy,
+ DatabaseZap,
+ RefreshCw,
+ RotateCcw,
+} from "lucide-react";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import type { ServiceType } from "../../application/advanced/show-resources";
+import { type LogLine, parseLogs } from "../../docker/logs/utils";
+
+type DatabaseType =
+ | Exclude
+ | "web-server";
+
+interface Props {
+ id: string;
+ databaseType?: DatabaseType;
+ serverId?: string | null;
+ backupType?: "database" | "compose";
+}
+
+const RestoreBackupSchema = z
+ .object({
+ destinationId: z
+ .string({
+ required_error: "Please select a destination",
+ })
+ .min(1, {
+ message: "Destination is required",
+ }),
+ backupFile: z
+ .string({
+ required_error: "Please select a backup file",
+ })
+ .min(1, {
+ message: "Backup file is required",
+ }),
+ databaseName: z
+ .string({
+ required_error: "Please enter a database name",
+ })
+ .min(1, {
+ message: "Database name is required",
+ }),
+ databaseType: z
+ .enum(["postgres", "mariadb", "mysql", "mongo", "web-server"])
+ .optional(),
+ backupType: z.enum(["database", "compose"]).default("database"),
+ metadata: z
+ .object({
+ postgres: z
+ .object({
+ databaseUser: z.string(),
+ })
+ .optional(),
+ mariadb: z
+ .object({
+ databaseUser: z.string(),
+ databasePassword: z.string(),
+ })
+ .optional(),
+ mongo: z
+ .object({
+ databaseUser: z.string(),
+ databasePassword: z.string(),
+ })
+ .optional(),
+ mysql: z
+ .object({
+ databaseRootPassword: z.string(),
+ })
+ .optional(),
+ serviceName: z.string().optional(),
+ })
+ .optional(),
+ })
+ .superRefine((data, ctx) => {
+ if (data.backupType === "compose" && !data.databaseType) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database type is required for compose backups",
+ path: ["databaseType"],
+ });
+ }
+
+ if (data.backupType === "compose" && !data.metadata?.serviceName) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Service name is required for compose backups",
+ path: ["metadata", "serviceName"],
+ });
+ }
+
+ if (data.backupType === "compose" && data.databaseType) {
+ if (data.databaseType === "postgres") {
+ if (!data.metadata?.postgres?.databaseUser) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database user is required for PostgreSQL",
+ path: ["metadata", "postgres", "databaseUser"],
+ });
+ }
+ } else if (data.databaseType === "mariadb") {
+ if (!data.metadata?.mariadb?.databaseUser) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database user is required for MariaDB",
+ path: ["metadata", "mariadb", "databaseUser"],
+ });
+ }
+ if (!data.metadata?.mariadb?.databasePassword) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database password is required for MariaDB",
+ path: ["metadata", "mariadb", "databasePassword"],
+ });
+ }
+ } else if (data.databaseType === "mongo") {
+ if (!data.metadata?.mongo?.databaseUser) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database user is required for MongoDB",
+ path: ["metadata", "mongo", "databaseUser"],
+ });
+ }
+ if (!data.metadata?.mongo?.databasePassword) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Database password is required for MongoDB",
+ path: ["metadata", "mongo", "databasePassword"],
+ });
+ }
+ } else if (data.databaseType === "mysql") {
+ if (!data.metadata?.mysql?.databaseRootPassword) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Root password is required for MySQL",
+ path: ["metadata", "mysql", "databaseRootPassword"],
+ });
+ }
+ }
+ }
+ });
+
+const formatBytes = (bytes: number): string => {
+ if (bytes === 0) return "0 Bytes";
+ const k = 1024;
+ const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
+};
+
+export const RestoreBackup = ({
+ id,
+ databaseType,
+ serverId,
+ backupType = "database",
+}: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [search, setSearch] = useState("");
+ const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");
+
+ const { data: destinations = [] } = api.destination.all.useQuery();
+
+ const form = useForm>({
+ defaultValues: {
+ destinationId: "",
+ backupFile: "",
+ databaseName: databaseType === "web-server" ? "dokploy" : "",
+ databaseType:
+ backupType === "compose" ? ("postgres" as DatabaseType) : databaseType,
+ backupType: backupType,
+ metadata: {},
+ },
+ resolver: zodResolver(RestoreBackupSchema),
+ });
+
+ const destionationId = form.watch("destinationId");
+ const currentDatabaseType = form.watch("databaseType");
+ const metadata = form.watch("metadata");
+
+ const debouncedSetSearch = debounce((value: string) => {
+ setDebouncedSearchTerm(value);
+ }, 350);
+
+ const handleSearchChange = (value: string) => {
+ setSearch(value);
+ debouncedSetSearch(value);
+ };
+
+ const { data: files = [], isLoading } = api.backup.listBackupFiles.useQuery(
+ {
+ destinationId: destionationId,
+ search: debouncedSearchTerm,
+ serverId: serverId ?? "",
+ },
+ {
+ enabled: isOpen && !!destionationId,
+ },
+ );
+
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [filteredLogs, setFilteredLogs] = useState([]);
+ const [isDeploying, setIsDeploying] = useState(false);
+
+ api.backup.restoreBackupWithLogs.useSubscription(
+ {
+ databaseId: id,
+ databaseType: currentDatabaseType as DatabaseType,
+ databaseName: form.watch("databaseName"),
+ backupFile: form.watch("backupFile"),
+ destinationId: form.watch("destinationId"),
+ backupType: backupType,
+ metadata: metadata,
+ },
+ {
+ enabled: isDeploying,
+ onData(log) {
+ if (!isDrawerOpen) {
+ setIsDrawerOpen(true);
+ }
+
+ if (log === "Restore completed successfully!") {
+ setIsDeploying(false);
+ }
+ const parsedLogs = parseLogs(log);
+ setFilteredLogs((prev) => [...prev, ...parsedLogs]);
+ },
+ onError(error) {
+ console.error("Restore logs error:", error);
+ setIsDeploying(false);
+ },
+ },
+ );
+
+ const onSubmit = async (data: z.infer) => {
+ if (backupType === "compose" && !data.databaseType) {
+ toast.error("Please select a database type");
+ return;
+ }
+ console.log({ data });
+ setIsDeploying(true);
+ };
+
+ const [cacheType, setCacheType] = useState<"fetch" | "cache">("cache");
+ const {
+ data: services = [],
+ isLoading: isLoadingServices,
+ refetch: refetchServices,
+ } = api.compose.loadServices.useQuery(
+ {
+ composeId: id,
+ type: cacheType,
+ },
+ {
+ retry: false,
+ refetchOnWindowFocus: false,
+ enabled: backupType === "compose",
+ },
+ );
+
+ return (
+
+
+
+
+ Restore Backup
+
+
+
+
+
+
+ Restore Backup
+
+
+ Select a destination and search for backup files
+
+
+
+
+
+ (
+
+ Destination
+
+
+
+
+ {field.value
+ ? destinations.find(
+ (d) => d.destinationId === field.value,
+ )?.name
+ : "Select Destination"}
+
+
+
+
+
+
+
+ No destinations found.
+
+
+ {destinations.map((destination) => (
+ {
+ form.setValue(
+ "destinationId",
+ destination.destinationId,
+ );
+ }}
+ >
+ {destination.name}
+
+
+ ))}
+
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+
+ Search Backup Files
+ {field.value && (
+
+ {field.value}
+ {
+ e.stopPropagation();
+ e.preventDefault();
+ copy(field.value);
+ toast.success("Backup file copied to clipboard");
+ }}
+ />
+
+ )}
+
+
+
+
+
+ {field.value || "Search and select a backup file"}
+
+
+
+
+
+
+
+ {isLoading ? (
+
+ Loading backup files...
+
+ ) : files.length === 0 && search ? (
+
+ No backup files found for "{search}"
+
+ ) : files.length === 0 ? (
+
+ No backup files available
+
+ ) : (
+
+
+ {files?.map((file) => (
+ {
+ form.setValue("backupFile", file.Path);
+ if (file.IsDir) {
+ setSearch(`${file.Path}/`);
+ setDebouncedSearchTerm(`${file.Path}/`);
+ } else {
+ setSearch(file.Path);
+ setDebouncedSearchTerm(file.Path);
+ }
+ }}
+ >
+
+
+
+ {file.Path}
+
+
+
+
+
+
+ Size: {formatBytes(file.Size)}
+
+ {file.IsDir && (
+
+ Directory
+
+ )}
+ {file.Hashes?.MD5 && (
+ MD5: {file.Hashes.MD5}
+ )}
+
+
+
+ ))}
+
+
+ )}
+
+
+
+
+
+ )}
+ />
+ (
+
+ Database Name
+
+
+
+
+
+ )}
+ />
+
+ {backupType === "compose" && (
+ <>
+ (
+
+ Database Type
+ {
+ field.onChange(value);
+ form.setValue("metadata", {});
+ }}
+ >
+
+
+
+
+ PostgreSQL
+ MariaDB
+ MongoDB
+ MySQL
+
+
+
+
+ )}
+ />
+
+ (
+
+ Service Name
+
+
+
+
+
+
+
+
+
+ {services?.map((service, index) => (
+
+ {service}
+
+ ))}
+ {(!services || services.length === 0) && (
+
+ Empty
+
+ )}
+
+
+
+
+
+ {
+ if (cacheType === "fetch") {
+ refetchServices();
+ } else {
+ setCacheType("fetch");
+ }
+ }}
+ >
+
+
+
+
+
+ Fetch: Will clone the repository and load the
+ services
+
+
+
+
+
+
+
+ {
+ if (cacheType === "cache") {
+ refetchServices();
+ } else {
+ setCacheType("cache");
+ }
+ }}
+ >
+
+
+
+
+
+ Cache: If you previously deployed this compose,
+ it will read the services from the last
+ deployment/fetch from the repository
+
+
+
+
+
+
+
+
+ )}
+ />
+
+ {currentDatabaseType === "postgres" && (
+ (
+
+ Database User
+
+
+
+
+
+ )}
+ />
+ )}
+
+ {currentDatabaseType === "mariadb" && (
+ <>
+ (
+
+ Database User
+
+
+
+
+
+ )}
+ />
+ (
+
+ Database Password
+
+
+
+
+
+ )}
+ />
+ >
+ )}
+
+ {currentDatabaseType === "mongo" && (
+ <>
+ (
+
+ Database User
+
+
+
+
+
+ )}
+ />
+ (
+
+ Database Password
+
+
+
+
+
+ )}
+ />
+ >
+ )}
+
+ {currentDatabaseType === "mysql" && (
+ (
+
+ Root Password
+
+
+
+
+
+ )}
+ />
+ )}
+ >
+ )}
+
+
+
+ Restore
+
+
+
+
+
+ {
+ setIsDrawerOpen(false);
+ setFilteredLogs([]);
+ setIsDeploying(false);
+ // refetch();
+ }}
+ filteredLogs={filteredLogs}
+ />
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/database/backups/show-backups.tsx b/data/apps/dokploy/components/dashboard/database/backups/show-backups.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..28ee68a9cebfa3307fc1945a2f6e5d77efb7dbea
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/database/backups/show-backups.tsx
@@ -0,0 +1,381 @@
+import {
+ MariadbIcon,
+ MongodbIcon,
+ MysqlIcon,
+ PostgresqlIcon,
+} from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import {
+ ClipboardList,
+ Database,
+ DatabaseBackup,
+ Play,
+ Trash2,
+} from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import type { ServiceType } from "../../application/advanced/show-resources";
+import { ShowDeploymentsModal } from "../../application/deployments/show-deployments-modal";
+import { HandleBackup } from "./handle-backup";
+import { RestoreBackup } from "./restore-backup";
+
+interface Props {
+ id: string;
+ databaseType?: Exclude | "web-server";
+ backupType?: "database" | "compose";
+}
+export const ShowBackups = ({
+ id,
+ databaseType,
+ backupType = "database",
+}: Props) => {
+ const [activeManualBackup, setActiveManualBackup] = useState<
+ string | undefined
+ >();
+ const queryMap =
+ backupType === "database"
+ ? {
+ postgres: () =>
+ api.postgres.one.useQuery({ postgresId: id }, { enabled: !!id }),
+ mysql: () =>
+ api.mysql.one.useQuery({ mysqlId: id }, { enabled: !!id }),
+ mariadb: () =>
+ api.mariadb.one.useQuery({ mariadbId: id }, { enabled: !!id }),
+ mongo: () =>
+ api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id }),
+ "web-server": () => api.user.getBackups.useQuery(),
+ }
+ : {
+ compose: () =>
+ api.compose.one.useQuery({ composeId: id }, { enabled: !!id }),
+ };
+ const { data } = api.destination.all.useQuery();
+ const key = backupType === "database" ? databaseType : "compose";
+ const query = queryMap[key as keyof typeof queryMap];
+ const { data: postgres, refetch } = query
+ ? query()
+ : api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id });
+
+ const mutationMap =
+ backupType === "database"
+ ? {
+ postgres: api.backup.manualBackupPostgres.useMutation(),
+ mysql: api.backup.manualBackupMySql.useMutation(),
+ mariadb: api.backup.manualBackupMariadb.useMutation(),
+ mongo: api.backup.manualBackupMongo.useMutation(),
+ "web-server": api.backup.manualBackupWebServer.useMutation(),
+ }
+ : {
+ compose: api.backup.manualBackupCompose.useMutation(),
+ };
+
+ const mutation = mutationMap[key as keyof typeof mutationMap];
+
+ const { mutateAsync: manualBackup, isLoading: isManualBackup } = mutation
+ ? mutation
+ : api.backup.manualBackupMongo.useMutation();
+
+ const { mutateAsync: deleteBackup, isLoading: isRemoving } =
+ api.backup.remove.useMutation();
+
+ return (
+
+
+
+
+
+ Backups
+
+
+ Add backups to your database to save the data to a different
+ provider.
+
+
+
+ {postgres && postgres?.backups?.length > 0 && (
+
+ {databaseType !== "web-server" && (
+
+ )}
+
+
+ )}
+
+
+ {data?.length === 0 ? (
+
+
+
+ To create a backup it is required to set at least 1 provider.
+ Please, go to{" "}
+
+ S3 Destinations
+ {" "}
+ to do so.
+
+
+ ) : (
+
+ {postgres?.backups.length === 0 ? (
+
+
+
+ No backups configured
+
+
+
+
+
+
+ ) : (
+
+ {backupType === "compose" && (
+
+ Make sure the compose is running before creating a backup.
+
+ )}
+
+ {postgres?.backups.map((backup) => {
+ const serverId =
+ "serverId" in postgres ? postgres.serverId : undefined;
+
+ return (
+
+
+
+
+ {backup.backupType === "compose" && (
+
+ {backup.databaseType === "postgres" && (
+
+ )}
+ {backup.databaseType === "mysql" && (
+
+ )}
+ {backup.databaseType === "mariadb" && (
+
+ )}
+ {backup.databaseType === "mongo" && (
+
+ )}
+
+ )}
+
+ {backup.backupType === "compose" && (
+
+
+ {backup.serviceName}
+
+
+ {backup.databaseType}
+
+
+ )}
+
+
+
+ {backup.enabled ? "Active" : "Inactive"}
+
+
+
+
+
+
+
+
+ Destination
+
+
+ {backup.destination.name}
+
+
+
+
+
+ Database
+
+
+ {backup.database}
+
+
+
+
+
+ Schedule
+
+
+ {backup.schedule}
+
+
+
+
+
+ Prefix Storage
+
+
+ {backup.prefix}
+
+
+
+
+
+ Keep Latest
+
+
+ {backup.keepLatestCount || "All"}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {
+ setActiveManualBackup(backup.backupId);
+ await manualBackup({
+ backupId: backup.backupId as string,
+ })
+ .then(async () => {
+ toast.success(
+ "Manual Backup Successful",
+ );
+ })
+ .catch(() => {
+ toast.error(
+ "Error creating the manual backup",
+ );
+ });
+ setActiveManualBackup(undefined);
+ }}
+ >
+
+
+
+
+ Run Manual Backup
+
+
+
+
+
+
{
+ await deleteBackup({
+ backupId: backup.backupId,
+ })
+ .then(() => {
+ refetch();
+ toast.success(
+ "Backup deleted successfully",
+ );
+ })
+ .catch(() => {
+ toast.error("Error deleting backup");
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ );
+ })}
+
+
+ )}
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/docker/config/show-container-config.tsx b/data/apps/dokploy/components/dashboard/docker/config/show-container-config.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..1f1591c9d0deb5d56c12ca70ec5fb9c6ad0e0e5c
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/config/show-container-config.tsx
@@ -0,0 +1,61 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { api } from "@/utils/api";
+
+interface Props {
+ containerId: string;
+ serverId?: string;
+}
+
+export const ShowContainerConfig = ({ containerId, serverId }: Props) => {
+ const { data } = api.docker.getConfig.useQuery(
+ {
+ containerId,
+ serverId,
+ },
+ {
+ enabled: !!containerId,
+ },
+ );
+ return (
+
+
+ e.preventDefault()}
+ >
+ View Config
+
+
+
+
+ Container Config
+
+ See in detail the config of this container
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/docker/logs/docker-logs-id.tsx b/data/apps/dokploy/components/dashboard/docker/logs/docker-logs-id.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..611af355ed5cf930e1198e6f7008a64ad56b8153
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/logs/docker-logs-id.tsx
@@ -0,0 +1,302 @@
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { Download as DownloadIcon, Loader2 } from "lucide-react";
+import React, { useEffect, useRef } from "react";
+import { LineCountFilter } from "./line-count-filter";
+import { SinceLogsFilter, type TimeFilter } from "./since-logs-filter";
+import { StatusLogsFilter } from "./status-logs-filter";
+import { TerminalLine } from "./terminal-line";
+import { type LogLine, getLogType, parseLogs } from "./utils";
+
+interface Props {
+ containerId: string;
+ serverId?: string | null;
+ runType: "swarm" | "native";
+}
+
+export const priorities = [
+ {
+ label: "Info",
+ value: "info",
+ },
+ {
+ label: "Success",
+ value: "success",
+ },
+ {
+ label: "Warning",
+ value: "warning",
+ },
+ {
+ label: "Debug",
+ value: "debug",
+ },
+ {
+ label: "Error",
+ value: "error",
+ },
+];
+
+export const DockerLogsId: React.FC = ({
+ containerId,
+ serverId,
+ runType,
+}) => {
+ const { data } = api.docker.getConfig.useQuery(
+ {
+ containerId,
+ serverId: serverId ?? undefined,
+ },
+ {
+ enabled: !!containerId,
+ },
+ );
+
+ const [rawLogs, setRawLogs] = React.useState("");
+ const [filteredLogs, setFilteredLogs] = React.useState([]);
+ const [autoScroll, setAutoScroll] = React.useState(true);
+ const [lines, setLines] = React.useState(100);
+ const [search, setSearch] = React.useState("");
+ const [showTimestamp, setShowTimestamp] = React.useState(true);
+ const [since, setSince] = React.useState("all");
+ const [typeFilter, setTypeFilter] = React.useState([]);
+ const scrollRef = useRef(null);
+ const [isLoading, setIsLoading] = React.useState(false);
+
+ const scrollToBottom = () => {
+ if (autoScroll && scrollRef.current) {
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ }
+ };
+
+ const handleScroll = () => {
+ if (!scrollRef.current) return;
+
+ const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;
+ const isAtBottom = Math.abs(scrollHeight - scrollTop - clientHeight) < 10;
+ setAutoScroll(isAtBottom);
+ };
+
+ const handleSearch = (e: React.ChangeEvent) => {
+ setSearch(e.target.value || "");
+ };
+
+ const handleLines = (lines: number) => {
+ setRawLogs("");
+ setFilteredLogs([]);
+ setLines(lines);
+ };
+
+ const handleSince = (value: TimeFilter) => {
+ setRawLogs("");
+ setFilteredLogs([]);
+ setSince(value);
+ };
+
+ useEffect(() => {
+ if (!containerId) return;
+
+ let isCurrentConnection = true;
+ let noDataTimeout: NodeJS.Timeout;
+ setIsLoading(true);
+ setRawLogs("");
+ setFilteredLogs([]);
+
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ const params = new globalThis.URLSearchParams({
+ containerId,
+ tail: lines.toString(),
+ since,
+ search,
+ runType,
+ });
+
+ if (serverId) {
+ params.append("serverId", serverId);
+ }
+
+ const wsUrl = `${protocol}//${
+ window.location.host
+ }/docker-container-logs?${params.toString()}`;
+ const ws = new WebSocket(wsUrl);
+
+ const resetNoDataTimeout = () => {
+ if (noDataTimeout) clearTimeout(noDataTimeout);
+ noDataTimeout = setTimeout(() => {
+ if (isCurrentConnection) {
+ setIsLoading(false);
+ }
+ }, 2000); // Wait 2 seconds for data before showing "No logs found"
+ };
+
+ ws.onopen = () => {
+ if (!isCurrentConnection) {
+ ws.close();
+ return;
+ }
+ resetNoDataTimeout();
+ };
+
+ ws.onmessage = (e) => {
+ if (!isCurrentConnection) return;
+ setRawLogs((prev) => {
+ const updated = prev + e.data;
+ const splitLines = updated.split("\n");
+ if (splitLines.length > lines) {
+ return splitLines.slice(-lines).join("\n");
+ }
+ return updated;
+ });
+ setIsLoading(false);
+ if (noDataTimeout) clearTimeout(noDataTimeout);
+ };
+
+ ws.onerror = (error) => {
+ if (!isCurrentConnection) return;
+ console.error("WebSocket error:", error);
+ setIsLoading(false);
+ if (noDataTimeout) clearTimeout(noDataTimeout);
+ };
+
+ ws.onclose = (e) => {
+ if (!isCurrentConnection) return;
+ console.log("WebSocket closed:", e.reason);
+ setIsLoading(false);
+ if (noDataTimeout) clearTimeout(noDataTimeout);
+ };
+
+ return () => {
+ isCurrentConnection = false;
+ if (noDataTimeout) clearTimeout(noDataTimeout);
+ if (ws.readyState === WebSocket.OPEN) {
+ ws.close();
+ }
+ };
+ }, [containerId, serverId, lines, search, since]);
+
+ const handleDownload = () => {
+ const logContent = filteredLogs
+ .map(
+ ({ timestamp, message }: { timestamp: Date | null; message: string }) =>
+ `${timestamp?.toISOString() || "No timestamp"} ${message}`,
+ )
+ .join("\n");
+
+ const blob = new Blob([logContent], { type: "text/plain" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ const appName = data.Name.replace("/", "") || "app";
+ const isoDate = new Date().toISOString();
+ a.href = url;
+ a.download = `${appName}-${isoDate.slice(0, 10).replace(/-/g, "")}_${isoDate
+ .slice(11, 19)
+ .replace(/:/g, "")}.log.txt`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ };
+
+ const handleFilter = (logs: LogLine[]) => {
+ return logs.filter((log) => {
+ const logType = getLogType(log.message).type;
+
+ if (typeFilter.length === 0) {
+ return true;
+ }
+
+ return typeFilter.includes(logType);
+ });
+ };
+
+ useEffect(() => {
+ setRawLogs("");
+ setFilteredLogs([]);
+ }, [containerId]);
+
+ useEffect(() => {
+ const logs = parseLogs(rawLogs);
+ const filtered = handleFilter(logs);
+ setFilteredLogs(filtered);
+ }, [rawLogs, search, lines, since, typeFilter]);
+
+ useEffect(() => {
+ scrollToBottom();
+
+ if (autoScroll && scrollRef.current) {
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ }
+ }, [filteredLogs, autoScroll]);
+
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Download logs
+
+
+
+ {filteredLogs.length > 0 ? (
+ filteredLogs.map((filteredLog: LogLine, index: number) => (
+
+ ))
+ ) : isLoading ? (
+
+
+
+ ) : (
+
+ No logs found
+
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/docker/logs/line-count-filter.tsx b/data/apps/dokploy/components/dashboard/docker/logs/line-count-filter.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..dd7b63af5b201bde03d7abf25d0285e0daefc68e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/logs/line-count-filter.tsx
@@ -0,0 +1,173 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Separator } from "@/components/ui/separator";
+import { cn } from "@/lib/utils";
+import { Command as CommandPrimitive } from "cmdk";
+import { debounce } from "lodash";
+import { CheckIcon, Hash } from "lucide-react";
+import React, { useCallback, useRef } from "react";
+
+const lineCountOptions = [
+ { label: "100 lines", value: 100 },
+ { label: "300 lines", value: 300 },
+ { label: "500 lines", value: 500 },
+ { label: "1000 lines", value: 1000 },
+ { label: "5000 lines", value: 5000 },
+] as const;
+
+interface LineCountFilterProps {
+ value: number;
+ onValueChange: (value: number) => void;
+ title?: string;
+}
+
+export function LineCountFilter({
+ value,
+ onValueChange,
+ title = "Limit to",
+}: LineCountFilterProps) {
+ const [open, setOpen] = React.useState(false);
+ const [inputValue, setInputValue] = React.useState("");
+ const pendingValueRef = useRef(null);
+
+ const isPresetValue = lineCountOptions.some(
+ (option) => option.value === value,
+ );
+
+ const debouncedValueChange = useCallback(
+ debounce((numValue: number) => {
+ if (numValue > 0 && numValue !== value) {
+ onValueChange(numValue);
+ pendingValueRef.current = null;
+ }
+ }, 500),
+ [onValueChange, value],
+ );
+
+ const handleInputChange = (input: string) => {
+ setInputValue(input);
+
+ // Extract numbers from input and convert
+ const numValue = Number.parseInt(input.replace(/[^0-9]/g, ""));
+ if (!Number.isNaN(numValue)) {
+ pendingValueRef.current = numValue;
+ debouncedValueChange(numValue);
+ }
+ };
+
+ const handleSelect = (selectedValue: string) => {
+ const preset = lineCountOptions.find((opt) => opt.label === selectedValue);
+ if (preset) {
+ if (preset.value !== value) {
+ onValueChange(preset.value);
+ }
+ setInputValue("");
+ setOpen(false);
+ return;
+ }
+
+ const numValue = Number.parseInt(selectedValue);
+ if (
+ !Number.isNaN(numValue) &&
+ numValue > 0 &&
+ numValue !== value &&
+ numValue !== pendingValueRef.current
+ ) {
+ onValueChange(numValue);
+ setInputValue("");
+ setOpen(false);
+ }
+ };
+
+ React.useEffect(() => {
+ return () => {
+ debouncedValueChange.cancel();
+ };
+ }, [debouncedValueChange]);
+
+ const displayValue = isPresetValue
+ ? lineCountOptions.find((option) => option.value === value)?.label
+ : `${value} lines`;
+
+ return (
+
+
+
+ {title}
+
+
+
+ {displayValue}
+
+
+
+
+
+
+
+
+ {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const numValue = Number.parseInt(
+ inputValue.replace(/[^0-9]/g, ""),
+ );
+ if (
+ !Number.isNaN(numValue) &&
+ numValue > 0 &&
+ numValue !== value &&
+ numValue !== pendingValueRef.current
+ ) {
+ handleSelect(inputValue);
+ }
+ }
+ }}
+ />
+
+
+
+ {lineCountOptions.map((option) => {
+ const isSelected = value === option.value;
+ return (
+ handleSelect(option.label)}
+ className="relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 aria-selected:bg-accent aria-selected:text-accent-foreground"
+ >
+
+
+
+ {option.label}
+
+ );
+ })}
+
+
+
+
+
+ );
+}
+
+export default LineCountFilter;
diff --git a/data/apps/dokploy/components/dashboard/docker/logs/show-docker-modal-logs.tsx b/data/apps/dokploy/components/dashboard/docker/logs/show-docker-modal-logs.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..619b25d0cf35d60530e4407e19f7eb343c6c6b07
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/logs/show-docker-modal-logs.tsx
@@ -0,0 +1,58 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import dynamic from "next/dynamic";
+import type React from "react";
+export const DockerLogsId = dynamic(
+ () =>
+ import("@/components/dashboard/docker/logs/docker-logs-id").then(
+ (e) => e.DockerLogsId,
+ ),
+ {
+ ssr: false,
+ },
+);
+
+interface Props {
+ containerId: string;
+ children?: React.ReactNode;
+ serverId?: string | null;
+}
+
+export const ShowDockerModalLogs = ({
+ containerId,
+ children,
+ serverId,
+}: Props) => {
+ return (
+
+
+ e.preventDefault()}
+ >
+ {children}
+
+
+
+
+ View Logs
+ View the logs for {containerId}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/docker/logs/show-docker-modal-stack-logs.tsx b/data/apps/dokploy/components/dashboard/docker/logs/show-docker-modal-stack-logs.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..36719bb07350e7d45f4c5167f29bab7ec2ccdbd7
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/logs/show-docker-modal-stack-logs.tsx
@@ -0,0 +1,58 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import dynamic from "next/dynamic";
+import type React from "react";
+export const DockerLogsId = dynamic(
+ () =>
+ import("@/components/dashboard/docker/logs/docker-logs-id").then(
+ (e) => e.DockerLogsId,
+ ),
+ {
+ ssr: false,
+ },
+);
+
+interface Props {
+ containerId: string;
+ children?: React.ReactNode;
+ serverId?: string | null;
+}
+
+export const ShowDockerModalStackLogs = ({
+ containerId,
+ children,
+ serverId,
+}: Props) => {
+ return (
+
+
+ e.preventDefault()}
+ >
+ {children}
+
+
+
+
+ View Logs
+ View the logs for {containerId}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/docker/logs/since-logs-filter.tsx b/data/apps/dokploy/components/dashboard/docker/logs/since-logs-filter.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..44f2cdfc32e218a793cf540ecaf488101c5c6b6f
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/logs/since-logs-filter.tsx
@@ -0,0 +1,124 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandGroup,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Separator } from "@/components/ui/separator";
+import { Switch } from "@/components/ui/switch";
+import { cn } from "@/lib/utils";
+import { CheckIcon } from "lucide-react";
+
+export type TimeFilter = "all" | "1h" | "6h" | "24h" | "168h" | "720h";
+
+const timeRanges: Array<{ label: string; value: TimeFilter }> = [
+ {
+ label: "All time",
+ value: "all",
+ },
+ {
+ label: "Last hour",
+ value: "1h",
+ },
+ {
+ label: "Last 6 hours",
+ value: "6h",
+ },
+ {
+ label: "Last 24 hours",
+ value: "24h",
+ },
+ {
+ label: "Last 7 days",
+ value: "168h",
+ },
+ {
+ label: "Last 30 days",
+ value: "720h",
+ },
+] as const;
+
+interface SinceLogsFilterProps {
+ value: TimeFilter;
+ onValueChange: (value: TimeFilter) => void;
+ showTimestamp: boolean;
+ onTimestampChange: (show: boolean) => void;
+ title?: string;
+}
+
+export function SinceLogsFilter({
+ value,
+ onValueChange,
+ showTimestamp,
+ onTimestampChange,
+ title = "Time range",
+}: SinceLogsFilterProps) {
+ const selectedLabel =
+ timeRanges.find((range) => range.value === value)?.label ??
+ "Select time range";
+
+ return (
+
+
+
+ {title}
+
+
+
+ {selectedLabel}
+
+
+
+
+
+
+
+
+ {timeRanges.map((range) => {
+ const isSelected = value === range.value;
+ return (
+ {
+ if (!isSelected) {
+ onValueChange(range.value);
+ }
+ }}
+ >
+
+
+
+ {range.label}
+
+ );
+ })}
+
+
+
+
+
+ Show timestamps
+
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/docker/logs/status-logs-filter.tsx b/data/apps/dokploy/components/dashboard/docker/logs/status-logs-filter.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..3ef11517abe27908bb729e00bb0f8e11d61634dd
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/logs/status-logs-filter.tsx
@@ -0,0 +1,170 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandGroup,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Separator } from "@/components/ui/separator";
+import { cn } from "@/lib/utils";
+import { CheckIcon } from "lucide-react";
+import type React from "react";
+
+interface StatusLogsFilterProps {
+ value?: string[];
+ setValue?: (value: string[]) => void;
+ title?: string;
+ options: {
+ label: string;
+ value: string;
+ icon?: React.ComponentType<{ className?: string }>;
+ }[];
+}
+
+export function StatusLogsFilter({
+ value = [],
+ setValue,
+ title,
+ options,
+}: StatusLogsFilterProps) {
+ const selectedValues = new Set(value as string[]);
+ const allSelected = selectedValues.size === 0;
+
+ const getSelectedBadges = () => {
+ if (allSelected) {
+ return (
+
+ All
+
+ );
+ }
+
+ if (selectedValues.size >= 1) {
+ const selected = options.find((opt) => selectedValues.has(opt.value));
+ return (
+ <>
+
+ {selected?.label}
+
+ {selectedValues.size > 1 && (
+
+ +{selectedValues.size - 1}
+
+ )}
+ >
+ );
+ }
+
+ return null;
+ };
+
+ return (
+
+
+
+ {title}
+
+ {getSelectedBadges()}
+
+
+
+
+
+
+ {
+ setValue?.([]); // Empty array means "All"
+ }}
+ >
+
+
+
+ All
+
+ {options.map((option) => {
+ const isSelected = selectedValues.has(option.value);
+ return (
+ {
+ const newValues = new Set(selectedValues);
+ if (isSelected) {
+ newValues.delete(option.value);
+ } else {
+ newValues.add(option.value);
+ }
+ setValue?.(Array.from(newValues));
+ }}
+ >
+
+
+
+ {option.icon && (
+
+ )}
+
+ {option.label}
+
+
+ );
+ })}
+
+
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/docker/logs/terminal-line.tsx b/data/apps/dokploy/components/dashboard/docker/logs/terminal-line.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..48ec4557be14b2af890ed46a2f5eec606df9e9e9
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/logs/terminal-line.tsx
@@ -0,0 +1,127 @@
+import { Badge } from "@/components/ui/badge";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipPortal,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { FancyAnsi } from "fancy-ansi";
+import { escapeRegExp } from "lodash";
+import { type LogLine, getLogType } from "./utils";
+
+interface LogLineProps {
+ log: LogLine;
+ noTimestamp?: boolean;
+ searchTerm?: string;
+}
+
+const fancyAnsi = new FancyAnsi();
+
+export function TerminalLine({ log, noTimestamp, searchTerm }: LogLineProps) {
+ const { timestamp, message, rawTimestamp } = log;
+ const { type, variant, color } = getLogType(message);
+
+ const formattedTime = timestamp
+ ? timestamp.toLocaleString([], {
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ year: "2-digit",
+ second: "2-digit",
+ })
+ : "--- No time found ---";
+
+ const highlightMessage = (text: string, term: string) => {
+ if (!term) {
+ return (
+
+ );
+ }
+
+ const htmlContent = fancyAnsi.toHtml(text);
+ const searchRegex = new RegExp(`(${escapeRegExp(term)})`, "gi");
+
+ const modifiedContent = htmlContent.replace(
+ searchRegex,
+ (match) =>
+ `${match} `,
+ );
+
+ return (
+
+ );
+ };
+
+ const tooltip = (color: string, timestamp: string | null) => {
+ const square = (
+
+ );
+ return timestamp ? (
+
+
+ {square}
+
+
+
+
{timestamp}
+
+
+
+
+
+ ) : (
+ square
+ );
+ };
+
+ return (
+
+ {" "}
+
+ {/* Icon to expand the log item maybe implement a colapsible later */}
+ {/* */}
+ {tooltip(color, rawTimestamp)}
+ {!noTimestamp && (
+
+ {formattedTime}
+
+ )}
+
+
+ {type}
+
+
+
+ {highlightMessage(message, searchTerm || "")}
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/docker/logs/utils.ts b/data/apps/dokploy/components/dashboard/docker/logs/utils.ts
new file mode 100644
index 0000000000000000000000000000000000000000..5e97edfe255b31054be970f468bf6b3c8e06c6c1
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/logs/utils.ts
@@ -0,0 +1,144 @@
+export type LogType = "error" | "warning" | "success" | "info" | "debug";
+export type LogVariant = "red" | "yellow" | "green" | "blue" | "orange";
+
+export interface LogLine {
+ rawTimestamp: string | null;
+ timestamp: Date | null;
+ message: string;
+}
+
+interface LogStyle {
+ type: LogType;
+ variant: LogVariant;
+ color: string;
+}
+
+const LOG_STYLES: Record = {
+ error: {
+ type: "error",
+ variant: "red",
+ color: "bg-red-500/40",
+ },
+ warning: {
+ type: "warning",
+ variant: "orange",
+ color: "bg-orange-500/40",
+ },
+ debug: {
+ type: "debug",
+ variant: "yellow",
+ color: "bg-yellow-500/40",
+ },
+ success: {
+ type: "success",
+ variant: "green",
+ color: "bg-green-500/40",
+ },
+ info: {
+ type: "info",
+ variant: "blue",
+ color: "bg-blue-600/40",
+ },
+} as const;
+
+export function parseLogs(logString: string): LogLine[] {
+ // Regex to match the log line format
+ // Example of return :
+ // 1 2024-12-10T10:00:00.000Z The server is running on port 8080
+ // Should return :
+ // { timestamp: new Date("2024-12-10T10:00:00.000Z"),
+ // message: "The server is running on port 8080" }
+ const logRegex =
+ /^(?:(\d+)\s+)?(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z|\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3} UTC)?\s*(.*)$/;
+
+ return logString
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line !== "")
+ .map((line) => {
+ const match = line.match(logRegex);
+ if (!match) return null;
+
+ const [, , timestamp, message] = match;
+
+ if (!message?.trim()) return null;
+
+ return {
+ rawTimestamp: timestamp ?? null,
+ timestamp: timestamp ? new Date(timestamp.replace(" UTC", "Z")) : null,
+ message: message.trim(),
+ };
+ })
+ .filter((log) => log !== null);
+}
+
+// Detect log type based on message content
+export const getLogType = (message: string): LogStyle => {
+ const lowerMessage = message.toLowerCase();
+
+ if (
+ /(?:^|\s)(?:info|inf|information):?\s/i.test(lowerMessage) ||
+ /\[(?:info|information)\]/i.test(lowerMessage) ||
+ /\b(?:status|state|current|progress)\b:?\s/i.test(lowerMessage) ||
+ /\b(?:processing|executing|performing)\b/i.test(lowerMessage)
+ ) {
+ return LOG_STYLES.info;
+ }
+
+ if (
+ /(?:^|\s)(?:error|err):?\s/i.test(lowerMessage) ||
+ /\b(?:exception|failed|failure)\b/i.test(lowerMessage) ||
+ /(?:stack\s?trace):\s*$/i.test(lowerMessage) ||
+ /^\s*at\s+[\w.]+\s*\(?.+:\d+:\d+\)?/.test(lowerMessage) ||
+ /\b(?:uncaught|unhandled)\s+(?:exception|error)\b/i.test(lowerMessage) ||
+ /Error:\s.*(?:in|at)\s+.*:\d+(?::\d+)?/.test(lowerMessage) ||
+ /\b(?:errno|code):\s*(?:\d+|[A-Z_]+)\b/i.test(lowerMessage) ||
+ /\[(?:error|err|fatal)\]/i.test(lowerMessage) ||
+ /\b(?:crash|critical|fatal)\b/i.test(lowerMessage) ||
+ /\b(?:fail(?:ed|ure)?|broken|dead)\b/i.test(lowerMessage)
+ ) {
+ return LOG_STYLES.error;
+ }
+
+ if (
+ /(?:^|\s)(?:warning|warn):?\s/i.test(lowerMessage) ||
+ /\[(?:warn(?:ing)?|attention)\]/i.test(lowerMessage) ||
+ /(?:deprecated|obsolete)\s+(?:since|in|as\s+of)/i.test(lowerMessage) ||
+ /\b(?:caution|attention|notice):\s/i.test(lowerMessage) ||
+ /(?:might|may|could)\s+(?:not|cause|lead\s+to)/i.test(lowerMessage) ||
+ /(?:!+\s*(?:warning|caution|attention)\s*!+)/i.test(lowerMessage) ||
+ /\b(?:deprecated|obsolete)\b/i.test(lowerMessage) ||
+ /\b(?:unstable|experimental)\b/i.test(lowerMessage)
+ ) {
+ return LOG_STYLES.warning;
+ }
+
+ if (
+ /(?:successfully|complete[d]?)\s+(?:initialized|started|completed|created|done|deployed)/i.test(
+ lowerMessage,
+ ) ||
+ /\[(?:success|ok|done)\]/i.test(lowerMessage) ||
+ /(?:listening|running)\s+(?:on|at)\s+(?:port\s+)?\d+/i.test(lowerMessage) ||
+ /(?:connected|established|ready)\s+(?:to|for|on)/i.test(lowerMessage) ||
+ /\b(?:loaded|mounted|initialized)\s+successfully\b/i.test(lowerMessage) ||
+ /✓|√|✅|\[ok\]|done!/i.test(lowerMessage) ||
+ /\b(?:success(?:ful)?|completed|ready)\b/i.test(lowerMessage) ||
+ /\b(?:started|starting|active)\b/i.test(lowerMessage)
+ ) {
+ return LOG_STYLES.success;
+ }
+
+ if (
+ /(?:^|\s)(?:info|inf):?\s/i.test(lowerMessage) ||
+ /\[(info|log|debug|trace|server|db|api|http|request|response)\]/i.test(
+ lowerMessage,
+ ) ||
+ /\b(?:version|config|import|load|get|HTTP|PATCH|POST|debug)\b:?/i.test(
+ lowerMessage,
+ )
+ ) {
+ return LOG_STYLES.debug;
+ }
+
+ return LOG_STYLES.info;
+};
diff --git a/data/apps/dokploy/components/dashboard/docker/show/colums.tsx b/data/apps/dokploy/components/dashboard/docker/show/colums.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..1cf0200f2cb5c8b99b30bcdebd8fa4c02a329b31
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/show/colums.tsx
@@ -0,0 +1,137 @@
+import type { ColumnDef } from "@tanstack/react-table";
+import { ArrowUpDown, MoreHorizontal } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+
+import { Badge } from "@/components/ui/badge";
+import { ShowContainerConfig } from "../config/show-container-config";
+import { ShowDockerModalLogs } from "../logs/show-docker-modal-logs";
+import { DockerTerminalModal } from "../terminal/docker-terminal-modal";
+import type { Container } from "./show-containers";
+
+export const columns: ColumnDef[] = [
+ {
+ accessorKey: "name",
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Name
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("name")}
;
+ },
+ },
+ {
+ accessorKey: "state",
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ State
+
+
+ );
+ },
+ cell: ({ row }) => {
+ const value = row.getValue("state") as string;
+ return (
+
+
+ {value}
+
+
+ );
+ },
+ },
+ {
+ accessorKey: "status",
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Status
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("status")}
;
+ },
+ },
+ {
+ accessorKey: "image",
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Image
+
+
+ );
+ },
+ cell: ({ row }) => {row.getValue("image")}
,
+ },
+ {
+ id: "actions",
+ enableHiding: false,
+ cell: ({ row }) => {
+ const container = row.original;
+
+ return (
+
+
+
+ Open menu
+
+
+
+
+ Actions
+
+ View Logs
+
+
+
+ Terminal
+
+
+
+ );
+ },
+ },
+];
diff --git a/data/apps/dokploy/components/dashboard/docker/show/show-containers.tsx b/data/apps/dokploy/components/dashboard/docker/show/show-containers.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..024b00618b87b98e04e2c9706a3408ea95b32fea
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/show/show-containers.tsx
@@ -0,0 +1,240 @@
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { type RouterOutputs, api } from "@/utils/api";
+import {
+ type ColumnFiltersState,
+ type SortingState,
+ type VisibilityState,
+ flexRender,
+ getCoreRowModel,
+ getFilteredRowModel,
+ getPaginationRowModel,
+ getSortedRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import { ChevronDown, Container } from "lucide-react";
+import * as React from "react";
+import { columns } from "./colums";
+export type Container = NonNullable<
+ RouterOutputs["docker"]["getContainers"]
+>[0];
+
+interface Props {
+ serverId?: string;
+}
+
+export const ShowContainers = ({ serverId }: Props) => {
+ const { data, isLoading } = api.docker.getContainers.useQuery({
+ serverId,
+ });
+
+ const [sorting, setSorting] = React.useState([]);
+ const [columnFilters, setColumnFilters] = React.useState(
+ [],
+ );
+ const [columnVisibility, setColumnVisibility] =
+ React.useState({});
+ const [rowSelection, setRowSelection] = React.useState({});
+
+ const table = useReactTable({
+ data: data ?? [],
+ columns,
+ onSortingChange: setSorting,
+ onColumnFiltersChange: setColumnFilters,
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ getFilteredRowModel: getFilteredRowModel(),
+ onColumnVisibilityChange: setColumnVisibility,
+ onRowSelectionChange: setRowSelection,
+ state: {
+ sorting,
+ columnFilters,
+ columnVisibility,
+ rowSelection,
+ },
+ });
+
+ return (
+
+
+
+
+
+
+ Docker Containers
+
+
+ See all the containers of your dokploy server
+
+
+
+
+
+
+
+ table
+ .getColumn("name")
+ ?.setFilterValue(event.target.value)
+ }
+ className="md:max-w-sm"
+ />
+
+
+
+ Columns
+
+
+
+ {table
+ .getAllColumns()
+ .filter((column) => column.getCanHide())
+ .map((column) => {
+ return (
+
+ column.toggleVisibility(!!value)
+ }
+ >
+ {column.id}
+
+ );
+ })}
+
+
+
+
+ {isLoading ? (
+
+
+ Loading...
+
+
+ ) : data?.length === 0 ? (
+
+
+ No results.
+
+
+ ) : (
+
+
+ {table.getHeaderGroups().map((headerGroup) => (
+
+ {headerGroup.headers.map((header) => {
+ return (
+
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+
+ );
+ })}
+
+ ))}
+
+
+ {table?.getRowModel()?.rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+
+ {row.getVisibleCells().map((cell) => (
+
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+
+ ))}
+
+ ))
+ ) : (
+
+
+ {isLoading ? (
+
+
+ Loading...
+
+
+ ) : (
+ <>No results.>
+ )}
+
+
+ )}
+
+
+ )}
+
+ {data && data?.length > 0 && (
+
+
+ table.previousPage()}
+ disabled={!table.getCanPreviousPage()}
+ >
+ Previous
+
+ table.nextPage()}
+ disabled={!table.getCanNextPage()}
+ >
+ Next
+
+
+
+ )}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/docker/terminal/docker-terminal-modal.tsx b/data/apps/dokploy/components/dashboard/docker/terminal/docker-terminal-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..90aa2b406752eee734e20a240b63000332aa757f
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/terminal/docker-terminal-modal.tsx
@@ -0,0 +1,99 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import dynamic from "next/dynamic";
+import { useState } from "react";
+
+const Terminal = dynamic(
+ () => import("./docker-terminal").then((e) => e.DockerTerminal),
+ {
+ ssr: false,
+ },
+);
+
+interface Props {
+ containerId: string;
+ serverId?: string;
+ children?: React.ReactNode;
+}
+
+export const DockerTerminalModal = ({
+ children,
+ containerId,
+ serverId,
+}: Props) => {
+ const [mainDialogOpen, setMainDialogOpen] = useState(false);
+ const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
+
+ const handleMainDialogOpenChange = (open: boolean) => {
+ if (!open) {
+ setConfirmDialogOpen(true);
+ } else {
+ setMainDialogOpen(true);
+ }
+ };
+
+ const handleConfirm = () => {
+ setConfirmDialogOpen(false);
+ setMainDialogOpen(false);
+ };
+
+ const handleCancel = () => {
+ setConfirmDialogOpen(false);
+ };
+ return (
+
+
+ e.preventDefault()}
+ >
+ {children}
+
+
+ event.preventDefault()}
+ >
+
+ Docker Terminal
+
+ Easy way to access to docker container
+
+
+
+
+
+ event.preventDefault()}>
+
+
+ Are you sure you want to close the terminal?
+
+
+ By clicking the confirm button, the terminal will be closed.
+
+
+
+
+ Cancel
+
+ Confirm
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx b/data/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..bf14680a46356ebd52c9fb8c809c4bcf44e5819b
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx
@@ -0,0 +1,76 @@
+import { Terminal } from "@xterm/xterm";
+import React, { useEffect, useRef } from "react";
+import { FitAddon } from "xterm-addon-fit";
+import "@xterm/xterm/css/xterm.css";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { AttachAddon } from "@xterm/addon-attach";
+import { useTheme } from "next-themes";
+
+interface Props {
+ id: string;
+ containerId: string;
+ serverId?: string;
+}
+
+export const DockerTerminal: React.FC = ({
+ id,
+ containerId,
+ serverId,
+}) => {
+ const termRef = useRef(null);
+ const [activeWay, setActiveWay] = React.useState("bash");
+ const { resolvedTheme } = useTheme();
+ useEffect(() => {
+ const container = document.getElementById(id);
+ if (container) {
+ container.innerHTML = "";
+ }
+ const term = new Terminal({
+ cursorBlink: true,
+ lineHeight: 1.4,
+ convertEol: true,
+ theme: {
+ cursor: resolvedTheme === "light" ? "#000000" : "transparent",
+ background: "rgba(0, 0, 0, 0)",
+ foreground: "currentColor",
+ },
+ });
+ const addonFit = new FitAddon();
+
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+
+ const wsUrl = `${protocol}//${window.location.host}/docker-container-terminal?containerId=${containerId}&activeWay=${activeWay}${serverId ? `&serverId=${serverId}` : ""}`;
+
+ const ws = new WebSocket(wsUrl);
+
+ const addonAttach = new AttachAddon(ws);
+ // @ts-ignore
+ term.open(termRef.current);
+ // @ts-ignore
+ term.loadAddon(addonFit);
+ term.loadAddon(addonAttach);
+ addonFit.fit();
+ return () => {
+ ws.readyState === WebSocket.OPEN && ws.close();
+ };
+ }, [containerId, activeWay, id]);
+
+ return (
+
+
+
+ Select way to connect to {containerId}
+
+
+
+ Bash
+ /bin/sh
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/file-system/show-traefik-file.tsx b/data/apps/dokploy/components/dashboard/file-system/show-traefik-file.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..fb5fe8f5c2f90aad4624f0d390aa9cc44a6ed83d
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/file-system/show-traefik-file.tsx
@@ -0,0 +1,170 @@
+import { Button } from "@/components/ui/button";
+
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Loader2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import { validateAndFormatYAML } from "../application/advanced/traefik/update-traefik-config";
+
+const UpdateServerMiddlewareConfigSchema = z.object({
+ traefikConfig: z.string(),
+});
+
+type UpdateServerMiddlewareConfig = z.infer<
+ typeof UpdateServerMiddlewareConfigSchema
+>;
+
+interface Props {
+ path: string;
+ serverId?: string;
+}
+
+export const ShowTraefikFile = ({ path, serverId }: Props) => {
+ const {
+ data,
+ refetch,
+ isLoading: isLoadingFile,
+ } = api.settings.readTraefikFile.useQuery(
+ {
+ path,
+ serverId,
+ },
+ {
+ enabled: !!path,
+ },
+ );
+ const [canEdit, setCanEdit] = useState(true);
+
+ const { mutateAsync, isLoading, error, isError } =
+ api.settings.updateTraefikFile.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ traefikConfig: "",
+ },
+ disabled: canEdit,
+ resolver: zodResolver(UpdateServerMiddlewareConfigSchema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ traefikConfig: data || "",
+ });
+ }, [form, form.reset, data]);
+
+ const onSubmit = async (data: UpdateServerMiddlewareConfig) => {
+ const { valid, error } = validateAndFormatYAML(data.traefikConfig);
+ if (!valid) {
+ form.setError("traefikConfig", {
+ type: "manual",
+ message: error || "Invalid YAML",
+ });
+ return;
+ }
+ form.clearErrors("traefikConfig");
+ await mutateAsync({
+ traefikConfig: data.traefikConfig,
+ path,
+ serverId,
+ })
+ .then(async () => {
+ toast.success("Traefik config Updated");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error updating the Traefik config");
+ });
+ };
+
+ return (
+
+ {isError &&
{error?.message} }
+
+
+
+ {isLoadingFile ? (
+
+
+ Loading...
+
+
+
+ ) : (
+
(
+
+ Traefik config
+
+ {path}
+
+
+
+
+
+
+
+
+
+ {
+ setCanEdit(!canEdit);
+ }}
+ >
+ {canEdit ? "Unlock" : "Lock"}
+
+
+
+ )}
+ />
+ )}
+
+
+
+ Update
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/file-system/show-traefik-system.tsx b/data/apps/dokploy/components/dashboard/file-system/show-traefik-system.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c9272f293a427cfc8724fd8c0090cd0050213d60
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/file-system/show-traefik-system.tsx
@@ -0,0 +1,109 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Tree } from "@/components/ui/file-tree";
+import { api } from "@/utils/api";
+import { FileIcon, Folder, Loader2, Workflow } from "lucide-react";
+import React from "react";
+import { ShowTraefikFile } from "./show-traefik-file";
+
+interface Props {
+ serverId?: string;
+}
+export const ShowTraefikSystem = ({ serverId }: Props) => {
+ const [file, setFile] = React.useState(null);
+
+ const {
+ data: directories,
+ isLoading,
+ error,
+ isError,
+ } = api.settings.readDirectories.useQuery(
+ {
+ serverId,
+ },
+ {
+ retry: 2,
+ },
+ );
+
+ return (
+
+
+
+
+
+
+ Traefik File System
+
+
+ Manage all the files and directories in {"'/etc/dokploy/traefik'"}
+ .
+
+
+
+ Adding invalid configuration to existing files, can break your
+ Traefik instance, preventing access to your applications.
+
+
+
+
+
+ {isError && (
+
+ {error?.message}
+
+ )}
+ {isLoading && (
+
+
+ Loading...
+
+
+
+ )}
+ {directories?.length === 0 && (
+
+
+ No directories or files detected in{" "}
+ {"'/etc/dokploy/traefik'"}
+
+
+
+ )}
+ {directories && directories?.length > 0 && (
+ <>
+
setFile(item?.id || null)}
+ folderIcon={Folder}
+ itemIcon={Workflow}
+ />
+
+ {file ? (
+
+ ) : (
+
+
+ No file selected
+
+
+
+ )}
+
+ >
+ )}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/impersonation/impersonation-bar.tsx b/data/apps/dokploy/components/dashboard/impersonation/impersonation-bar.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8a9f55c9029df9c85068e657a93ca111147c7787
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/impersonation/impersonation-bar.tsx
@@ -0,0 +1,454 @@
+"use client";
+
+import { Logo } from "@/components/shared/logo";
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { authClient } from "@/lib/auth-client";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import copy from "copy-to-clipboard";
+import { format } from "date-fns";
+import {
+ Building2,
+ Calendar,
+ CheckIcon,
+ ChevronsUpDown,
+ Copy,
+ CreditCard,
+ Fingerprint,
+ Key,
+ Server,
+ Settings2,
+ Shield,
+ UserIcon,
+ XIcon,
+} from "lucide-react";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+
+type User = typeof authClient.$Infer.Session.user;
+
+export const ImpersonationBar = () => {
+ const [users, setUsers] = useState([]);
+ const [selectedUser, setSelectedUser] = useState(null);
+ const [isImpersonating, setIsImpersonating] = useState(false);
+ const [open, setOpen] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+ const [showBar, setShowBar] = useState(false);
+ const { data } = api.user.get.useQuery();
+
+ const fetchUsers = async (search?: string) => {
+ try {
+ const session = await authClient.getSession();
+ if (session?.data?.session?.impersonatedBy) {
+ return;
+ }
+ setIsLoading(true);
+ const response = await authClient.admin.listUsers({
+ query: {
+ limit: 30,
+ ...(search && {
+ searchField: "email",
+ searchOperator: "contains",
+ searchValue: search,
+ }),
+ },
+ });
+
+ const filteredUsers = response.data?.users.filter(
+ // @ts-ignore
+ (user) => user.allowImpersonation && data?.user?.email !== user.email,
+ );
+
+ if (!response.error) {
+ // @ts-ignore
+ setUsers(filteredUsers || []);
+ }
+ } catch (error) {
+ console.error("Error fetching users:", error);
+ toast.error("Error loading users");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleImpersonate = async () => {
+ if (!selectedUser) return;
+
+ try {
+ await authClient.admin.impersonateUser({
+ userId: selectedUser.id,
+ });
+ setIsImpersonating(true);
+ setOpen(false);
+
+ toast.success("Successfully impersonating user", {
+ description: `You are now viewing as ${selectedUser.name || selectedUser.email}`,
+ });
+ window.location.reload();
+ } catch (error) {
+ console.error("Error impersonating user:", error);
+ toast.error("Error impersonating user");
+ }
+ };
+
+ const handleStopImpersonating = async () => {
+ try {
+ await authClient.admin.stopImpersonating();
+ setIsImpersonating(false);
+ setSelectedUser(null);
+ setShowBar(false);
+ toast.success("Stopped impersonating user");
+ window.location.reload();
+ } catch (error) {
+ console.error("Error stopping impersonation:", error);
+ toast.error("Error stopping impersonation");
+ }
+ };
+
+ useEffect(() => {
+ const checkImpersonation = async () => {
+ try {
+ const session = await authClient.getSession();
+ if (session?.data?.session?.impersonatedBy) {
+ setIsImpersonating(true);
+ setShowBar(true);
+ // setSelectedUser(data);
+ }
+ } catch (error) {
+ console.error("Error checking impersonation status:", error);
+ }
+ };
+
+ checkImpersonation();
+ fetchUsers();
+ }, []);
+
+ return (
+
+ <>
+
+
+ setShowBar(!showBar)}
+ >
+
+
+
+
+ {isImpersonating ? "Impersonation Controls" : "User Impersonation"}
+
+
+
+
+
+
+ {!isImpersonating ? (
+
+
+
+
+ {selectedUser ? (
+
+
+
+
+ {selectedUser.name || ""}
+
+
+ {selectedUser.email}
+
+
+
+ ) : (
+ <>
+
+ Select user to impersonate
+ >
+ )}
+
+
+
+
+
+ {
+ fetchUsers(search);
+ }}
+ className="h-9"
+ />
+ {isLoading ? (
+
+ Loading users...
+
+ ) : (
+ <>
+ No users found.
+
+
+ {users.map((user) => (
+ {
+ setSelectedUser(user);
+ setOpen(false);
+ }}
+ >
+
+
+
+
+ {user.name || ""}
+
+
+ {user.email} • {user.role}
+
+
+
+
+
+ ))}
+
+
+ >
+ )}
+
+
+
+
+
+ Impersonate
+
+
+ ) : (
+
+
+
+
+
+ {data?.user?.name?.slice(0, 2).toUpperCase() || "U"}
+
+
+
+
+
+
+ Impersonating
+
+
+ {data?.user?.name || ""}
+
+
+
+
+
+ {data?.user?.email} • {data?.role}
+
+
+
+
+ ID: {data?.user?.id?.slice(0, 8)}
+ {
+ if (data?.id) {
+ copy(data.id);
+ toast.success("ID copied to clipboard");
+ }
+ }}
+ >
+
+
+
+
+
+
+
+ Org: {data?.organizationId?.slice(0, 8)}
+ {
+ if (data?.organizationId) {
+ copy(data.organizationId);
+ toast.success(
+ "Organization ID copied to clipboard",
+ );
+ }
+ }}
+ >
+
+
+
+
+ {data?.user?.stripeCustomerId && (
+
+
+
+ Customer:
+ {data?.user?.stripeCustomerId?.slice(0, 8)}
+ {
+ copy(data?.user?.stripeCustomerId || "");
+ toast.success(
+ "Stripe Customer ID copied to clipboard",
+ );
+ }}
+ >
+
+
+
+
+ )}
+ {data?.user?.stripeSubscriptionId && (
+
+
+
+ Sub: {data?.user?.stripeSubscriptionId?.slice(0, 8)}
+ {
+ copy(data.user.stripeSubscriptionId || "");
+ toast.success(
+ "Stripe Subscription ID copied to clipboard",
+ );
+ }}
+ >
+
+
+
+
+ )}
+ {data?.user?.serversQuantity !== undefined && (
+
+
+ Servers: {data.user.serversQuantity}
+
+ )}
+ {data?.createdAt && (
+
+
+ Created:{" "}
+ {format(new Date(data.createdAt), "MMM d, yyyy")}
+
+ )}
+
+
+
+
+
+ 2FA{" "}
+ {data?.user?.twoFactorEnabled
+ ? "Enabled"
+ : "Disabled"}
+
+
+
+
+ Two-Factor Authentication Status
+
+
+
+
+
+
+
+ Stop Impersonating
+
+
+ )}
+
+
+ >
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mariadb/general/show-external-mariadb-credentials.tsx b/data/apps/dokploy/components/dashboard/mariadb/general/show-external-mariadb-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c00af42be8798e08c51ebe35d79ce5affef1364c
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mariadb/general/show-external-mariadb-credentials.tsx
@@ -0,0 +1,175 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const DockerProviderSchema = z.object({
+ externalPort: z.preprocess((a) => {
+ if (a !== null) {
+ const parsed = Number.parseInt(z.string().parse(a), 10);
+ return Number.isNaN(parsed) ? null : parsed;
+ }
+ return null;
+ }, z
+ .number()
+ .gte(0, "Range must be 0 - 65535")
+ .lte(65535, "Range must be 0 - 65535")
+ .nullable()),
+});
+
+type DockerProvider = z.infer;
+
+interface Props {
+ mariadbId: string;
+}
+export const ShowExternalMariadbCredentials = ({ mariadbId }: Props) => {
+ const { data: ip } = api.settings.getIp.useQuery();
+ const { data, refetch } = api.mariadb.one.useQuery({ mariadbId });
+ const { mutateAsync, isLoading } = api.mariadb.saveExternalPort.useMutation();
+ const [connectionUrl, setConnectionUrl] = useState("");
+ const getIp = data?.server?.ipAddress || ip;
+ const form = useForm({
+ defaultValues: {},
+ resolver: zodResolver(DockerProviderSchema),
+ });
+
+ useEffect(() => {
+ if (data?.externalPort) {
+ form.reset({
+ externalPort: data.externalPort,
+ });
+ }
+ }, [form.reset, data, form]);
+
+ const onSubmit = async (values: DockerProvider) => {
+ await mutateAsync({
+ externalPort: values.externalPort,
+ mariadbId,
+ })
+ .then(async () => {
+ toast.success("External Port updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the external port");
+ });
+ };
+
+ useEffect(() => {
+ const buildConnectionUrl = () => {
+ const port = form.watch("externalPort") || data?.externalPort;
+
+ return `mariadb://${data?.databaseUser}:${data?.databasePassword}@${getIp}:${port}/${data?.databaseName}`;
+ };
+
+ setConnectionUrl(buildConnectionUrl());
+ }, [
+ data?.appName,
+ data?.externalPort,
+ data?.databasePassword,
+ form,
+ data?.databaseName,
+ data?.databaseUser,
+ getIp,
+ ]);
+ return (
+ <>
+
+
+
+ External Credentials
+
+ In order to make the database reachable trought internet is
+ required to set a port, make sure the port is not used by another
+ application or database
+
+
+
+ {!getIp && (
+
+ You need to set an IP address in your{" "}
+
+ {data?.serverId
+ ? "Remote Servers -> Server -> Edit Server -> Update IP Address"
+ : "Web Server -> Server -> Update Server IP"}
+ {" "}
+ to fix the database url connection.
+
+ )}
+
+
+
+
+ {
+ return (
+
+ External Port (Internet)
+
+
+
+
+
+ );
+ }}
+ />
+
+
+ {!!data?.externalPort && (
+
+
+ {/* jdbc:mariadb://5.161.59.207:3306/pixel-calculate?user=mariadb&password=HdVXfq6hM7W7F1 */}
+ External Host
+
+
+
+ )}
+
+
+
+ Save
+
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mariadb/general/show-general-mariadb.tsx b/data/apps/dokploy/components/dashboard/mariadb/general/show-general-mariadb.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2f8bab77be681d05d865db983c25632a901d46ec
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mariadb/general/show-general-mariadb.tsx
@@ -0,0 +1,268 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { DrawerLogs } from "@/components/shared/drawer-logs";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+import { Ban, CheckCircle2, RefreshCcw, Rocket, Terminal } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { type LogLine, parseLogs } from "../../docker/logs/utils";
+import { DockerTerminalModal } from "../../settings/web-server/docker-terminal-modal";
+
+interface Props {
+ mariadbId: string;
+}
+
+export const ShowGeneralMariadb = ({ mariadbId }: Props) => {
+ const { data, refetch } = api.mariadb.one.useQuery(
+ {
+ mariadbId,
+ },
+ { enabled: !!mariadbId },
+ );
+
+ const { mutateAsync: reload, isLoading: isReloading } =
+ api.mariadb.reload.useMutation();
+
+ const { mutateAsync: start, isLoading: isStarting } =
+ api.mariadb.start.useMutation();
+
+ const { mutateAsync: stop, isLoading: isStopping } =
+ api.mariadb.stop.useMutation();
+
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [filteredLogs, setFilteredLogs] = useState([]);
+ const [isDeploying, setIsDeploying] = useState(false);
+ api.mariadb.deployWithLogs.useSubscription(
+ {
+ mariadbId: mariadbId,
+ },
+ {
+ enabled: isDeploying,
+ onData(log) {
+ if (!isDrawerOpen) {
+ setIsDrawerOpen(true);
+ }
+
+ if (log === "Deployment completed successfully!") {
+ setIsDeploying(false);
+ }
+ const parsedLogs = parseLogs(log);
+ setFilteredLogs((prev) => [...prev, ...parsedLogs]);
+ },
+ onError(error) {
+ console.error("Deployment logs error:", error);
+ setIsDeploying(false);
+ },
+ },
+ );
+
+ return (
+ <>
+
+
+
+ Deploy Settings
+
+
+
+ {
+ setIsDeploying(true);
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ refetch();
+ }}
+ >
+
+
+
+
+
+ Deploy
+
+
+
+
+ Downloads and sets up the MariaDB database
+
+
+
+
+
+
+
+ {
+ await reload({
+ mariadbId: mariadbId,
+ appName: data?.appName || "",
+ })
+ .then(() => {
+ toast.success("Mariadb reloaded successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error reloading Mariadb");
+ });
+ }}
+ >
+
+
+
+
+
+ Reload
+
+
+
+
+ Restart the MariaDB service without rebuilding
+
+
+
+
+
+
+ {data?.applicationStatus === "idle" ? (
+
+ {
+ await start({
+ mariadbId: mariadbId,
+ })
+ .then(() => {
+ toast.success("Mariadb started successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error starting Mariadb");
+ });
+ }}
+ >
+
+
+
+
+
+ Start
+
+
+
+
+
+ Start the MariaDB database (requires a previous
+ successful setup)
+
+
+
+
+
+
+
+ ) : (
+
+ {
+ await stop({
+ mariadbId: mariadbId,
+ })
+ .then(() => {
+ toast.success("Mariadb stopped successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error stopping Mariadb");
+ });
+ }}
+ >
+
+
+
+
+
+ Stop
+
+
+
+
+ Stop the currently running MariaDB database
+
+
+
+
+
+
+ )}
+
+
+
+
+
+
+ Open Terminal
+
+
+
+
+ Open a terminal to the MariaDB container
+
+
+
+
+
+
+
+
{
+ setIsDrawerOpen(false);
+ setFilteredLogs([]);
+ setIsDeploying(false);
+ refetch();
+ }}
+ filteredLogs={filteredLogs}
+ />
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mariadb/general/show-internal-mariadb-credentials.tsx b/data/apps/dokploy/components/dashboard/mariadb/general/show-internal-mariadb-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..17026926933e7860064e60a103cab8e00b5257e4
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mariadb/general/show-internal-mariadb-credentials.tsx
@@ -0,0 +1,70 @@
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+
+interface Props {
+ mariadbId: string;
+}
+export const ShowInternalMariadbCredentials = ({ mariadbId }: Props) => {
+ const { data } = api.mariadb.one.useQuery({ mariadbId });
+ return (
+ <>
+
+
+
+ Internal Credentials
+
+
+
+
+ User
+
+
+
+ Database Name
+
+
+
+
+
+ Internal Port (Container)
+
+
+
+
+ Internal Host
+
+
+
+
+ Internal Connection URL
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mariadb/update-mariadb.tsx b/data/apps/dokploy/components/dashboard/mariadb/update-mariadb.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..64705b693b993b73f2607e88377d23db2093580e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mariadb/update-mariadb.tsx
@@ -0,0 +1,163 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const updateMariadbSchema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ description: z.string().optional(),
+});
+
+type UpdateMariadb = z.infer;
+
+interface Props {
+ mariadbId: string;
+}
+
+export const UpdateMariadb = ({ mariadbId }: Props) => {
+ const utils = api.useUtils();
+ const { mutateAsync, error, isError, isLoading } =
+ api.mariadb.update.useMutation();
+ const { data } = api.mariadb.one.useQuery(
+ {
+ mariadbId,
+ },
+ {
+ enabled: !!mariadbId,
+ },
+ );
+ const form = useForm({
+ defaultValues: {
+ description: data?.description ?? "",
+ name: data?.name ?? "",
+ },
+ resolver: zodResolver(updateMariadbSchema),
+ });
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ description: data.description ?? "",
+ name: data.name,
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: UpdateMariadb) => {
+ await mutateAsync({
+ name: formData.name,
+ mariadbId: mariadbId,
+ description: formData.description || "",
+ })
+ .then(() => {
+ toast.success("MariaDB updated successfully");
+ utils.mariadb.one.invalidate({
+ mariadbId: mariadbId,
+ });
+ })
+ .catch(() => {
+ toast.error("Error updating the Mariadb");
+ })
+ .finally(() => {});
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Modify MariaDB
+ Update the MariaDB data
+
+ {isError && {error?.message} }
+
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+ Update
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mongo/general/show-external-mongo-credentials.tsx b/data/apps/dokploy/components/dashboard/mongo/general/show-external-mongo-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..75772bfdf294ca628e7489d9afc4c43eab407ca4
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mongo/general/show-external-mongo-credentials.tsx
@@ -0,0 +1,174 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const DockerProviderSchema = z.object({
+ externalPort: z.preprocess((a) => {
+ if (a !== null) {
+ const parsed = Number.parseInt(z.string().parse(a), 10);
+ return Number.isNaN(parsed) ? null : parsed;
+ }
+ return null;
+ }, z
+ .number()
+ .gte(0, "Range must be 0 - 65535")
+ .lte(65535, "Range must be 0 - 65535")
+ .nullable()),
+});
+
+type DockerProvider = z.infer;
+
+interface Props {
+ mongoId: string;
+}
+export const ShowExternalMongoCredentials = ({ mongoId }: Props) => {
+ const { data: ip } = api.settings.getIp.useQuery();
+ const { data, refetch } = api.mongo.one.useQuery({ mongoId });
+ const { mutateAsync, isLoading } = api.mongo.saveExternalPort.useMutation();
+ const [connectionUrl, setConnectionUrl] = useState("");
+ const getIp = data?.server?.ipAddress || ip;
+ const form = useForm({
+ defaultValues: {},
+ resolver: zodResolver(DockerProviderSchema),
+ });
+
+ useEffect(() => {
+ if (data?.externalPort) {
+ form.reset({
+ externalPort: data.externalPort,
+ });
+ }
+ }, [form.reset, data, form]);
+
+ const onSubmit = async (values: DockerProvider) => {
+ await mutateAsync({
+ externalPort: values.externalPort,
+ mongoId,
+ })
+ .then(async () => {
+ toast.success("External Port updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the external port");
+ });
+ };
+
+ useEffect(() => {
+ const buildConnectionUrl = () => {
+ const port = form.watch("externalPort") || data?.externalPort;
+
+ return `mongodb://${data?.databaseUser}:${data?.databasePassword}@${getIp}:${port}`;
+ };
+
+ setConnectionUrl(buildConnectionUrl());
+ }, [
+ data?.appName,
+ data?.externalPort,
+ data?.databasePassword,
+ form,
+ data?.databaseUser,
+ getIp,
+ ]);
+
+ return (
+ <>
+
+
+
+ External Credentials
+
+ In order to make the database reachable trought internet is
+ required to set a port, make sure the port is not used by another
+ application or database
+
+
+
+ {!getIp && (
+
+ You need to set an IP address in your{" "}
+
+ {data?.serverId
+ ? "Remote Servers -> Server -> Edit Server -> Update IP Address"
+ : "Web Server -> Server -> Update Server IP"}
+ {" "}
+ to fix the database url connection.
+
+ )}
+
+
+
+
+ {
+ return (
+
+ External Port (Internet)
+
+
+
+
+
+ );
+ }}
+ />
+
+
+ {!!data?.externalPort && (
+
+ )}
+
+
+
+ Save
+
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mongo/general/show-general-mongo.tsx b/data/apps/dokploy/components/dashboard/mongo/general/show-general-mongo.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..fdc28adc3fe1ae8c552e53960473f1e23c254944
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mongo/general/show-general-mongo.tsx
@@ -0,0 +1,261 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { DrawerLogs } from "@/components/shared/drawer-logs";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+import { Ban, CheckCircle2, RefreshCcw, Rocket, Terminal } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { type LogLine, parseLogs } from "../../docker/logs/utils";
+import { DockerTerminalModal } from "../../settings/web-server/docker-terminal-modal";
+interface Props {
+ mongoId: string;
+}
+
+export const ShowGeneralMongo = ({ mongoId }: Props) => {
+ const { data, refetch } = api.mongo.one.useQuery(
+ {
+ mongoId,
+ },
+ { enabled: !!mongoId },
+ );
+
+ const { mutateAsync: reload, isLoading: isReloading } =
+ api.mongo.reload.useMutation();
+
+ const { mutateAsync: start, isLoading: isStarting } =
+ api.mongo.start.useMutation();
+
+ const { mutateAsync: stop, isLoading: isStopping } =
+ api.mongo.stop.useMutation();
+
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [filteredLogs, setFilteredLogs] = useState([]);
+ const [isDeploying, setIsDeploying] = useState(false);
+ api.mongo.deployWithLogs.useSubscription(
+ {
+ mongoId: mongoId,
+ },
+ {
+ enabled: isDeploying,
+ onData(log) {
+ if (!isDrawerOpen) {
+ setIsDrawerOpen(true);
+ }
+
+ if (log === "Deployment completed successfully!") {
+ setIsDeploying(false);
+ }
+
+ const parsedLogs = parseLogs(log);
+ setFilteredLogs((prev) => [...prev, ...parsedLogs]);
+ },
+ onError(error) {
+ console.error("Deployment logs error:", error);
+ setIsDeploying(false);
+ },
+ },
+ );
+ return (
+ <>
+
+
+
+ Deploy Settings
+
+
+
+ {
+ setIsDeploying(true);
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ refetch();
+ }}
+ >
+
+
+
+
+
+ Deploy
+
+
+
+
+ Downloads and sets up the MongoDB database
+
+
+
+
+
+ {
+ await reload({
+ mongoId: mongoId,
+ appName: data?.appName || "",
+ })
+ .then(() => {
+ toast.success("Mongo reloaded successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error reloading Mongo");
+ });
+ }}
+ >
+
+
+
+
+
+ Reload
+
+
+
+
+ Restart the MongoDB service without rebuilding
+
+
+
+
+
+ {data?.applicationStatus === "idle" ? (
+ {
+ await start({
+ mongoId: mongoId,
+ })
+ .then(() => {
+ toast.success("Mongo started successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error starting Mongo");
+ });
+ }}
+ >
+
+
+
+
+
+ Start
+
+
+
+
+
+ Start the MongoDB database (requires a previous
+ successful setup)
+
+
+
+
+
+
+ ) : (
+ {
+ await stop({
+ mongoId: mongoId,
+ })
+ .then(() => {
+ toast.success("Mongo stopped successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error stopping Mongo");
+ });
+ }}
+ >
+
+
+
+
+
+ Stop
+
+
+
+
+ Stop the currently running MongoDB database
+
+
+
+
+
+ )}
+
+
+
+
+
+
+
+ Open Terminal
+
+
+
+
+ Open a terminal to the MongoDB container
+
+
+
+
+
+
+
+
{
+ setIsDrawerOpen(false);
+ setFilteredLogs([]);
+ setIsDeploying(false);
+ refetch();
+ }}
+ filteredLogs={filteredLogs}
+ />
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mongo/general/show-internal-mongo-credentials.tsx b/data/apps/dokploy/components/dashboard/mongo/general/show-internal-mongo-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e66ea8c36a0c9cc933fb7c1d3fbe1163d393b3e0
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mongo/general/show-internal-mongo-credentials.tsx
@@ -0,0 +1,59 @@
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+
+interface Props {
+ mongoId: string;
+}
+export const ShowInternalMongoCredentials = ({ mongoId }: Props) => {
+ const { data } = api.mongo.one.useQuery({ mongoId });
+ return (
+ <>
+
+
+
+ Internal Credentials
+
+
+
+
+ User
+
+
+
+
+
+
+ Internal Port (Container)
+
+
+
+
+ Internal Host
+
+
+
+
+ Internal Connection URL
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mongo/update-mongo.tsx b/data/apps/dokploy/components/dashboard/mongo/update-mongo.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..d42f406f0ec524ea2bfe23f0d4cc2a92cc55eea2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mongo/update-mongo.tsx
@@ -0,0 +1,165 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const updateMongoSchema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ description: z.string().optional(),
+});
+
+type UpdateMongo = z.infer;
+
+interface Props {
+ mongoId: string;
+}
+
+export const UpdateMongo = ({ mongoId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const utils = api.useUtils();
+ const { mutateAsync, error, isError, isLoading } =
+ api.mongo.update.useMutation();
+ const { data } = api.mongo.one.useQuery(
+ {
+ mongoId,
+ },
+ {
+ enabled: !!mongoId,
+ },
+ );
+ const form = useForm({
+ defaultValues: {
+ description: data?.description ?? "",
+ name: data?.name ?? "",
+ },
+ resolver: zodResolver(updateMongoSchema),
+ });
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ description: data.description ?? "",
+ name: data.name,
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: UpdateMongo) => {
+ await mutateAsync({
+ name: formData.name,
+ mongoId: mongoId,
+ description: formData.description || "",
+ })
+ .then(() => {
+ toast.success("Mongo updated successfully");
+ utils.mongo.one.invalidate({
+ mongoId: mongoId,
+ });
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating mongo database");
+ })
+ .finally(() => {});
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Modify MongoDB
+ Update the MongoDB data
+
+ {isError && {error?.message} }
+
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+ Update
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-block-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-block-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..718ddafa47bba33f387ccca564026dd1dce17873
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-block-chart.tsx
@@ -0,0 +1,103 @@
+import { format } from "date-fns";
+import {
+ Area,
+ AreaChart,
+ CartesianGrid,
+ Legend,
+ ResponsiveContainer,
+ Tooltip,
+ YAxis,
+} from "recharts";
+import type { DockerStatsJSON } from "./show-free-container-monitoring";
+
+interface Props {
+ acummulativeData: DockerStatsJSON["block"];
+}
+
+export const DockerBlockChart = ({ acummulativeData }: Props) => {
+ const transformedData = acummulativeData.map((item, index) => {
+ return {
+ time: item.time,
+ name: `Point ${index + 1}`,
+ readMb: item.value.readMb,
+ writeMb: item.value.writeMb,
+ };
+ });
+
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {/* @ts-ignore */}
+ } />
+
+
+
+
+
+
+ );
+};
+interface CustomTooltipProps {
+ active: boolean;
+ payload?: {
+ color?: string;
+ dataKey?: string;
+ value?: number;
+ payload: {
+ time: string;
+ readMb: number;
+ writeMb: number;
+ };
+ }[];
+}
+
+const CustomTooltip = ({ active, payload }: CustomTooltipProps) => {
+ if (active && payload && payload.length && payload[0]) {
+ return (
+
+ {payload[0].payload.time && (
+
{`Date: ${format(new Date(payload[0].payload.time), "PPpp")}`}
+ )}
+
{`Read ${payload[0].payload.readMb} `}
+
{`Write: ${payload[0].payload.writeMb} `}
+
+ );
+ }
+
+ return null;
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-cpu-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-cpu-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c24a636383bd9a8c2520cc608de00ddda2b9d9f4
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-cpu-chart.tsx
@@ -0,0 +1,87 @@
+import { format } from "date-fns";
+import {
+ Area,
+ AreaChart,
+ CartesianGrid,
+ Legend,
+ ResponsiveContainer,
+ Tooltip,
+ YAxis,
+} from "recharts";
+import type { DockerStatsJSON } from "./show-free-container-monitoring";
+
+interface Props {
+ acummulativeData: DockerStatsJSON["cpu"];
+}
+
+export const DockerCpuChart = ({ acummulativeData }: Props) => {
+ const transformedData = acummulativeData.map((item, index) => {
+ return {
+ name: `Point ${index + 1}`,
+ time: item.time,
+ usage: item.value.toString().split("%")[0],
+ };
+ });
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ {/* @ts-ignore */}
+ } />
+
+
+
+
+
+ );
+};
+
+interface CustomTooltipProps {
+ active: boolean;
+ payload?: {
+ color?: string;
+ dataKey?: string;
+ value?: number;
+ payload: {
+ time: string;
+ usage: number;
+ };
+ }[];
+}
+
+const CustomTooltip = ({ active, payload }: CustomTooltipProps) => {
+ if (active && payload && payload.length && payload[0]) {
+ return (
+
+ {payload[0].payload.time && (
+
{`Date: ${format(new Date(payload[0].payload.time), "PPpp")}`}
+ )}
+
{`CPU Usage: ${payload[0].payload.usage}%`}
+
+ );
+ }
+
+ return null;
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-disk-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-disk-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5fe62154c33d1d701246eecdb187aeaa62d8c712
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-disk-chart.tsx
@@ -0,0 +1,105 @@
+import { format } from "date-fns";
+import {
+ Area,
+ AreaChart,
+ CartesianGrid,
+ Legend,
+ ResponsiveContainer,
+ Tooltip,
+ YAxis,
+} from "recharts";
+import type { DockerStatsJSON } from "./show-free-container-monitoring";
+
+interface Props {
+ acummulativeData: DockerStatsJSON["disk"];
+ diskTotal: number;
+}
+
+export const DockerDiskChart = ({ acummulativeData, diskTotal }: Props) => {
+ const transformedData = acummulativeData.map((item, index) => {
+ return {
+ time: item.time,
+ name: `Point ${index + 1}`,
+ usedGb: +item.value.diskUsage,
+ totalGb: +item.value.diskTotal,
+ freeGb: item.value.diskFree,
+ };
+ });
+
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {/* @ts-ignore */}
+ } />
+
+
+
+
+
+
+ );
+};
+interface CustomTooltipProps {
+ active: boolean;
+ payload?: {
+ color?: string;
+ dataKey?: string;
+ value?: number;
+ payload: {
+ time: string;
+ usedGb: number;
+ freeGb: number;
+ totalGb: number;
+ };
+ }[];
+}
+
+const CustomTooltip = ({ active, payload }: CustomTooltipProps) => {
+ if (active && payload && payload.length && payload[0]) {
+ return (
+
+
{`Date: ${format(new Date(payload[0].payload.time), "PPpp")}`}
+
{`Disk usage: ${payload[0].payload.usedGb} GB`}
+
{`Disk free: ${payload[0].payload.freeGb} GB`}
+
{`Total disk: ${payload[0].payload.totalGb} GB`}
+
+ );
+ }
+
+ return null;
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-memory-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-memory-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..82a1ff3d55abb71b0567b8c341194dd0e2ee7f4e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-memory-chart.tsx
@@ -0,0 +1,92 @@
+import { format } from "date-fns";
+import {
+ Area,
+ AreaChart,
+ CartesianGrid,
+ Legend,
+ ResponsiveContainer,
+ Tooltip,
+ YAxis,
+} from "recharts";
+import type { DockerStatsJSON } from "./show-free-container-monitoring";
+import { convertMemoryToBytes } from "./show-free-container-monitoring";
+interface Props {
+ acummulativeData: DockerStatsJSON["memory"];
+ memoryLimitGB: number;
+}
+
+export const DockerMemoryChart = ({
+ acummulativeData,
+ memoryLimitGB,
+}: Props) => {
+ const transformedData = acummulativeData.map((item, index) => {
+ return {
+ time: item.time,
+ name: `Point ${index + 1}`,
+ // @ts-ignore
+ usage: (convertMemoryToBytes(item.value.used) / 1024 ** 3).toFixed(2),
+ };
+ });
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ {/* @ts-ignore */}
+ } />
+
+
+
+
+
+ );
+};
+interface CustomTooltipProps {
+ active: boolean;
+ payload?: {
+ color?: string;
+ dataKey?: string;
+ value?: number;
+ payload: {
+ time: string;
+ usage: number;
+ };
+ }[];
+}
+
+const CustomTooltip = ({ active, payload }: CustomTooltipProps) => {
+ if (active && payload && payload.length && payload[0] && payload[0].payload) {
+ return (
+
+ {payload[0].payload.time && (
+
{`Date: ${format(new Date(payload[0].payload.time), "PPpp")}`}
+ )}
+
+
{`Memory usage: ${payload[0].payload.usage} GB`}
+
+ );
+ }
+
+ return null;
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-network-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-network-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..cd6b7dfde506df1fd239d3fc10dc518bc38f19c6
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/free/container/docker-network-chart.tsx
@@ -0,0 +1,98 @@
+import { format } from "date-fns";
+import {
+ Area,
+ AreaChart,
+ CartesianGrid,
+ Legend,
+ ResponsiveContainer,
+ Tooltip,
+ YAxis,
+} from "recharts";
+import type { DockerStatsJSON } from "./show-free-container-monitoring";
+interface Props {
+ acummulativeData: DockerStatsJSON["network"];
+}
+
+export const DockerNetworkChart = ({ acummulativeData }: Props) => {
+ const transformedData = acummulativeData.map((item, index) => {
+ return {
+ time: item.time,
+ name: `Point ${index + 1}`,
+ inMB: item.value.inputMb,
+ outMB: item.value.outputMb,
+ };
+ });
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ {/* @ts-ignore */}
+ } />
+
+
+
+
+
+
+ );
+};
+
+interface CustomTooltipProps {
+ active: boolean;
+ payload?: {
+ color?: string;
+ dataKey?: string;
+ value?: number;
+ payload: {
+ time: string;
+ inMB: number;
+ outMB: number;
+ };
+ }[];
+}
+
+const CustomTooltip = ({ active, payload }: CustomTooltipProps) => {
+ if (active && payload && payload.length && payload[0]) {
+ return (
+
+ {payload[0].payload.time && (
+
{`Date: ${format(new Date(payload[0].payload.time), "PPpp")}`}
+ )}
+
{`In Usage: ${payload[0].payload.inMB} `}
+
{`Out Usage: ${payload[0].payload.outMB} `}
+
+ );
+ }
+
+ return null;
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/free/container/show-free-compose-monitoring.tsx b/data/apps/dokploy/components/dashboard/monitoring/free/container/show-free-compose-monitoring.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..84510154c407563f1ff9df1a1400f57c9462e9bb
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/free/container/show-free-compose-monitoring.tsx
@@ -0,0 +1,130 @@
+import { badgeStateColor } from "@/components/dashboard/application/logs/show";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { Loader2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import { ContainerFreeMonitoring } from "./show-free-container-monitoring";
+
+interface Props {
+ appName: string;
+ serverId?: string;
+ appType: "stack" | "docker-compose";
+}
+
+export const ComposeFreeMonitoring = ({
+ appName,
+ appType = "stack",
+ serverId,
+}: Props) => {
+ const { data, isLoading } = api.docker.getContainersByAppNameMatch.useQuery(
+ {
+ appName: appName,
+ appType,
+ serverId,
+ },
+ {
+ enabled: !!appName,
+ },
+ );
+
+ const [containerAppName, setContainerAppName] = useState<
+ string | undefined
+ >();
+
+ const [containerId, setContainerId] = useState();
+
+ const { mutateAsync: restart, isLoading: isRestarting } =
+ api.docker.restartContainer.useMutation();
+
+ useEffect(() => {
+ if (data && data?.length > 0) {
+ setContainerAppName(data[0]?.name);
+ setContainerId(data[0]?.containerId);
+ }
+ }, [data]);
+
+ return (
+ <>
+
+ Monitoring
+ Watch the usage of your compose
+
+
+ Select a container to watch the monitoring
+
+
{
+ setContainerAppName(value);
+ setContainerId(
+ data?.find((container) => container.name === value)
+ ?.containerId,
+ );
+ }}
+ value={containerAppName}
+ >
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+
+ )}
+
+
+
+ {data?.map((container) => (
+
+ {container.name} ({container.containerId}){" "}
+
+ {container.state}
+
+
+ ))}
+ Containers ({data?.length})
+
+
+
+
{
+ if (!containerId) return;
+ toast.success(`Restarting container ${containerAppName}`);
+ await restart({ containerId }).then(() => {
+ toast.success("Container restarted");
+ });
+ }}
+ >
+ Restart
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/free/container/show-free-container-monitoring.tsx b/data/apps/dokploy/components/dashboard/monitoring/free/container/show-free-container-monitoring.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..117fae388368e1344a127cbb03e6fa4cadff60e1
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/free/container/show-free-container-monitoring.tsx
@@ -0,0 +1,310 @@
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Progress } from "@/components/ui/progress";
+import { api } from "@/utils/api";
+import { useEffect, useState } from "react";
+import { DockerBlockChart } from "./docker-block-chart";
+import { DockerCpuChart } from "./docker-cpu-chart";
+import { DockerDiskChart } from "./docker-disk-chart";
+import { DockerMemoryChart } from "./docker-memory-chart";
+import { DockerNetworkChart } from "./docker-network-chart";
+
+const defaultData = {
+ cpu: {
+ value: 0,
+ time: "",
+ },
+ memory: {
+ value: {
+ used: 0,
+ total: 0,
+ },
+ time: "",
+ },
+ block: {
+ value: {
+ readMb: 0,
+ writeMb: 0,
+ },
+ time: "",
+ },
+ network: {
+ value: {
+ inputMb: 0,
+ outputMb: 0,
+ },
+ time: "",
+ },
+ disk: {
+ value: { diskTotal: 0, diskUsage: 0, diskUsedPercentage: 0, diskFree: 0 },
+ time: "",
+ },
+};
+
+interface Props {
+ appName: string;
+ appType?: "application" | "stack" | "docker-compose";
+}
+export interface DockerStats {
+ cpu: {
+ value: number;
+ time: string;
+ };
+ memory: {
+ value: {
+ used: number;
+ total: number;
+ };
+ time: string;
+ };
+ block: {
+ value: {
+ readMb: number;
+ writeMb: number;
+ };
+ time: string;
+ };
+ network: {
+ value: {
+ inputMb: number;
+ outputMb: number;
+ };
+ time: string;
+ };
+ disk: {
+ value: {
+ diskTotal: number;
+ diskUsage: number;
+ diskUsedPercentage: number;
+ diskFree: number;
+ };
+
+ time: string;
+ };
+}
+
+export type DockerStatsJSON = {
+ cpu: DockerStats["cpu"][];
+ memory: DockerStats["memory"][];
+ block: DockerStats["block"][];
+ network: DockerStats["network"][];
+ disk: DockerStats["disk"][];
+};
+
+export const convertMemoryToBytes = (
+ memoryString: string | undefined,
+): number => {
+ if (!memoryString || typeof memoryString !== "string") {
+ return 0;
+ }
+
+ const value = Number.parseFloat(memoryString) || 0;
+ const unit = memoryString.replace(/[0-9.]/g, "").trim();
+
+ switch (unit) {
+ case "KiB":
+ return value * 1024;
+ case "MiB":
+ return value * 1024 * 1024;
+ case "GiB":
+ return value * 1024 * 1024 * 1024;
+ case "TiB":
+ return value * 1024 * 1024 * 1024 * 1024;
+ default:
+ return value;
+ }
+};
+
+export const ContainerFreeMonitoring = ({
+ appName,
+ appType = "application",
+}: Props) => {
+ const { data } = api.application.readAppMonitoring.useQuery(
+ { appName },
+ {
+ refetchOnWindowFocus: false,
+ },
+ );
+ const [acummulativeData, setAcummulativeData] = useState({
+ cpu: [],
+ memory: [],
+ block: [],
+ network: [],
+ disk: [],
+ });
+ const [currentData, setCurrentData] = useState(defaultData);
+
+ useEffect(() => {
+ setCurrentData(defaultData);
+
+ setAcummulativeData({
+ cpu: [],
+ memory: [],
+ block: [],
+ network: [],
+ disk: [],
+ });
+ }, [appName]);
+
+ useEffect(() => {
+ if (!data) return;
+
+ setCurrentData({
+ cpu: data.cpu[data.cpu.length - 1] ?? currentData.cpu,
+ memory: data.memory[data.memory.length - 1] ?? currentData.memory,
+ block: data.block[data.block.length - 1] ?? currentData.block,
+ network: data.network[data.network.length - 1] ?? currentData.network,
+ disk: data.disk[data.disk.length - 1] ?? currentData.disk,
+ });
+ setAcummulativeData({
+ block: data?.block || [],
+ cpu: data?.cpu || [],
+ disk: data?.disk || [],
+ memory: data?.memory || [],
+ network: data?.network || [],
+ });
+ }, [data]);
+
+ useEffect(() => {
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ const wsUrl = `${protocol}//${window.location.host}/listen-docker-stats-monitoring?appName=${appName}&appType=${appType}`;
+ const ws = new WebSocket(wsUrl);
+
+ ws.onmessage = (e) => {
+ const value = JSON.parse(e.data);
+ if (!value) return;
+
+ const data = {
+ cpu: value.data.cpu ?? currentData.cpu,
+ memory: value.data.memory ?? currentData.memory,
+ block: value.data.block ?? currentData.block,
+ disk: value.data.disk ?? currentData.disk,
+ network: value.data.network ?? currentData.network,
+ };
+
+ setCurrentData(data);
+
+ setAcummulativeData((prevData) => ({
+ cpu: [...prevData.cpu, data.cpu],
+ memory: [...prevData.memory, data.memory],
+ block: [...prevData.block, data.block],
+ network: [...prevData.network, data.network],
+ disk: [...prevData.disk, data.disk],
+ }));
+ };
+
+ ws.onclose = (e) => {
+ console.log(e.reason);
+ };
+
+ return () => ws.close();
+ }, [appName]);
+
+ return (
+
+
+
+
+
+
+ CPU Usage
+
+
+
+
+ Used: {currentData.cpu.value}
+
+
+
+
+
+
+
+
+ Memory Usage
+
+
+
+
+ {`Used: ${currentData.memory.value.used} / Limit: ${currentData.memory.value.total} `}
+
+
+
+
+
+
+ {appName === "dokploy" && (
+
+
+ Disk Space
+
+
+
+
+ {`Used: ${currentData.disk.value.diskUsage} GB / Limit: ${currentData.disk.value.diskTotal} GB`}
+
+
+
+
+
+
+ )}
+
+
+
+ Block I/O
+
+
+
+
+ {`Read: ${currentData.block.value.readMb} / Write: ${currentData.block.value.writeMb} `}
+
+
+
+
+
+
+
+ Network I/O
+
+
+
+
+ {`In MB: ${currentData.network.value.inputMb} / Out MB: ${currentData.network.value.outputMb} `}
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-block-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-block-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..12af6b91db7997dc2225689fc45987426e19b9f8
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-block-chart.tsx
@@ -0,0 +1,181 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ type ChartConfig,
+ ChartContainer,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+} from "@/components/ui/chart";
+import { formatTimestamp } from "@/lib/utils";
+import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
+
+interface ContainerMetric {
+ timestamp: string;
+ BlockIO: {
+ read: number;
+ write: number;
+ readUnit: string;
+ writeUnit: string;
+ };
+}
+
+interface Props {
+ data: ContainerMetric[];
+}
+
+const chartConfig = {
+ read: {
+ label: "Read",
+ color: "hsl(217, 91%, 60%)", // Azul brillante
+ },
+ write: {
+ label: "Write",
+ color: "hsl(142, 71%, 45%)", // Verde brillante
+ },
+} satisfies ChartConfig;
+
+export const ContainerBlockChart = ({ data }: Props) => {
+ const formattedData = data.map((metric) => ({
+ timestamp: metric.timestamp,
+ read: metric.BlockIO.read,
+ write: metric.BlockIO.write,
+ readUnit: metric.BlockIO.readUnit,
+ writeUnit: metric.BlockIO.writeUnit,
+ }));
+
+ const latestData = formattedData[formattedData.length - 1] || {
+ timestamp: "",
+ read: 0,
+ write: 0,
+ readUnit: "B",
+ writeUnit: "B",
+ };
+
+ return (
+
+
+ Block I/O
+
+ Read: {latestData.read}
+ {latestData.readUnit} / Write: {latestData.write}
+ {latestData.writeUnit}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ formatTimestamp(value)}
+ />
+
+ {
+ if (active && payload && payload.length) {
+ const data = payload?.[0]?.payload;
+ return (
+
+
+
+
+ Time
+
+
+ {formatTimestamp(label)}
+
+
+
+
+ Read
+
+
+ {data.read}
+ {data.readUnit}
+
+
+
+
+ Write
+
+
+ {data.write}
+ {data.writeUnit}
+
+
+
+
+ );
+ }
+ return null;
+ }}
+ />
+
+
+ }
+ verticalAlign="bottom"
+ align="center"
+ />
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-cpu-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-cpu-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..445e03e12aed778b0ca2bc8eaf5881368b47fd87
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-cpu-chart.tsx
@@ -0,0 +1,128 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ type ChartConfig,
+ ChartContainer,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+} from "@/components/ui/chart";
+import { formatTimestamp } from "@/lib/utils";
+import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
+
+interface ContainerMetric {
+ timestamp: string;
+ CPU: number;
+}
+
+interface Props {
+ data: ContainerMetric[];
+}
+
+const chartConfig = {
+ cpu: {
+ label: "CPU",
+ color: "hsl(var(--chart-1))",
+ },
+} satisfies ChartConfig;
+
+export const ContainerCPUChart = ({ data }: Props) => {
+ const formattedData = data.map((metric) => ({
+ timestamp: metric.timestamp,
+ cpu: metric.CPU,
+ }));
+
+ const latestData = formattedData[formattedData.length - 1] || {
+ timestamp: "",
+ cpu: 0,
+ };
+
+ return (
+
+
+ CPU
+ CPU Usage: {latestData.cpu}%
+
+
+
+
+
+
+
+
+
+
+
+ formatTimestamp(value)}
+ />
+ `${value}%`} domain={[0, 100]} />
+ {
+ if (active && payload && payload.length) {
+ const data = payload?.[0]?.payload;
+ return (
+
+
+
+
+ Time
+
+
+ {formatTimestamp(label)}
+
+
+
+
+ CPU
+
+ {data.cpu}%
+
+
+
+ );
+ }
+ return null;
+ }}
+ />
+
+ }
+ verticalAlign="bottom"
+ align="center"
+ />
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-memory-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-memory-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..4da864285892e4a44230630e236161c8bda8e0d0
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-memory-chart.tsx
@@ -0,0 +1,149 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ type ChartConfig,
+ ChartContainer,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+} from "@/components/ui/chart";
+import { formatTimestamp } from "@/lib/utils";
+import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
+
+interface ContainerMetric {
+ timestamp: string;
+ Memory: {
+ percentage: number;
+ used: number;
+ total: number;
+ usedUnit: string;
+ totalUnit: string;
+ };
+}
+
+interface Props {
+ data: ContainerMetric[];
+}
+
+const chartConfig = {
+ memory: {
+ label: "Memory",
+ color: "hsl(var(--chart-2))",
+ },
+} satisfies ChartConfig;
+
+const formatMemoryValue = (value: number) => {
+ return value.toLocaleString("en-US", {
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 2,
+ });
+};
+
+export const ContainerMemoryChart = ({ data }: Props) => {
+ const formattedData = data.map((metric) => ({
+ timestamp: metric.timestamp,
+ memory: metric.Memory.percentage,
+ usage: `${formatMemoryValue(metric.Memory.used)}${metric.Memory.usedUnit} / ${formatMemoryValue(metric.Memory.total)}${metric.Memory.totalUnit}`,
+ }));
+
+ const latestData = formattedData[formattedData.length - 1] || {
+ timestamp: "",
+ memory: 0,
+ usage: "0 / 0 B",
+ };
+
+ return (
+
+
+ Memory
+ Memory Usage: {latestData.usage}
+
+
+
+
+
+
+
+
+
+
+
+ formatTimestamp(value)}
+ />
+ `${value}%`} domain={[0, 100]} />
+ {
+ if (active && payload && payload.length) {
+ const data = payload?.[0]?.payload;
+ return (
+
+
+
+
+ Time
+
+
+ {formatTimestamp(label)}
+
+
+
+
+ Memory
+
+ {data.memory}%
+
+
+
+ Usage
+
+ {data.usage}
+
+
+
+ );
+ }
+ return null;
+ }}
+ />
+
+ }
+ verticalAlign="bottom"
+ align="center"
+ />
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-network-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-network-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..d51e896876a57bfadf8946b12a353fcd588ddead
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/container/container-network-chart.tsx
@@ -0,0 +1,186 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ type ChartConfig,
+ ChartContainer,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+} from "@/components/ui/chart";
+import { formatTimestamp } from "@/lib/utils";
+import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
+
+interface ContainerMetric {
+ timestamp: string;
+ Network: {
+ input: number;
+ output: number;
+ inputUnit: string;
+ outputUnit: string;
+ };
+}
+
+interface Props {
+ data: ContainerMetric[];
+}
+
+interface FormattedMetric {
+ timestamp: string;
+ input: number;
+ output: number;
+ inputUnit: string;
+ outputUnit: string;
+}
+
+const chartConfig = {
+ input: {
+ label: "Input",
+ color: "hsl(var(--chart-3))",
+ },
+ output: {
+ label: "Output",
+ color: "hsl(var(--chart-4))",
+ },
+} satisfies ChartConfig;
+
+export const ContainerNetworkChart = ({ data }: Props) => {
+ const formattedData: FormattedMetric[] = data.map((metric) => ({
+ timestamp: metric.timestamp,
+ input: metric.Network.input,
+ output: metric.Network.output,
+ inputUnit: metric.Network.inputUnit,
+ outputUnit: metric.Network.outputUnit,
+ }));
+
+ const latestData = formattedData[formattedData.length - 1] || {
+ input: 0,
+ output: 0,
+ inputUnit: "B",
+ outputUnit: "B",
+ };
+
+ return (
+
+
+ Network I/O
+
+ Input: {latestData.input}
+ {latestData.inputUnit} / Output: {latestData.output}
+ {latestData.outputUnit}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ formatTimestamp(value)}
+ />
+
+ {
+ if (active && payload && payload.length) {
+ const data = payload?.[0]?.payload;
+ return (
+
+
+
+
+ Time
+
+
+ {formatTimestamp(label)}
+
+
+
+
+ Input
+
+
+ {data.input}
+ {data.inputUnit}
+
+
+
+
+ Output
+
+
+ {data.output}
+ {data.outputUnit}
+
+
+
+
+ );
+ }
+ return null;
+ }}
+ />
+
+
+ }
+ verticalAlign="bottom"
+ align="center"
+ />
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/container/show-paid-compose-monitoring.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/container/show-paid-compose-monitoring.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..4ca461c2153e097273933c7fc06f36752175d461
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/container/show-paid-compose-monitoring.tsx
@@ -0,0 +1,140 @@
+import { badgeStateColor } from "@/components/dashboard/application/logs/show";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { Loader2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import { ContainerPaidMonitoring } from "./show-paid-container-monitoring";
+
+interface Props {
+ appName: string;
+ serverId?: string;
+ appType: "stack" | "docker-compose";
+ baseUrl: string;
+ token: string;
+}
+
+export const ComposePaidMonitoring = ({
+ appName,
+ appType = "stack",
+ serverId,
+ baseUrl,
+ token,
+}: Props) => {
+ const { data, isLoading } = api.docker.getContainersByAppNameMatch.useQuery(
+ {
+ appName: appName,
+ appType,
+ serverId,
+ },
+ {
+ enabled: !!appName,
+ },
+ );
+
+ const [containerAppName, setContainerAppName] = useState(
+ "",
+ );
+
+ const [containerId, setContainerId] = useState();
+
+ const { mutateAsync: restart, isLoading: isRestarting } =
+ api.docker.restartContainer.useMutation();
+
+ useEffect(() => {
+ if (data && data?.length > 0) {
+ setContainerAppName(data[0]?.name);
+ setContainerId(data[0]?.containerId);
+ }
+ }, [data]);
+
+ return (
+
+
+
+ Monitoring
+ Watch the usage of your compose
+
+
+ Select a container to watch the monitoring
+
+
{
+ setContainerAppName(value);
+ setContainerId(
+ data?.find((container) => container.name === value)
+ ?.containerId,
+ );
+ }}
+ value={containerAppName}
+ >
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+
+ )}
+
+
+
+ {data?.map((container) => (
+
+ {container.name} ({container.containerId}){" "}
+
+ {container.state}
+
+
+ ))}
+ Containers ({data?.length})
+
+
+
+
{
+ if (!containerId) return;
+ toast.success(`Restarting container ${containerAppName}`);
+ await restart({ containerId }).then(() => {
+ toast.success("Container restarted");
+ });
+ }}
+ >
+ Restart
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/container/show-paid-container-monitoring.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/container/show-paid-container-monitoring.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..3b189c2ac69208db1a900fd3b2e6717dad7a9f80
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/container/show-paid-container-monitoring.tsx
@@ -0,0 +1,258 @@
+import { Card } from "@/components/ui/card";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { Cpu, HardDrive, Loader2, MemoryStick, Network } from "lucide-react";
+import { useEffect, useState } from "react";
+import { ContainerBlockChart } from "./container-block-chart";
+import { ContainerCPUChart } from "./container-cpu-chart";
+import { ContainerMemoryChart } from "./container-memory-chart";
+import { ContainerNetworkChart } from "./container-network-chart";
+
+const REFRESH_INTERVALS = {
+ "5000": "5 Seconds",
+ "10000": "10 Seconds",
+ "20000": "20 Seconds",
+ "30000": "30 Seconds",
+} as const;
+
+const DATA_POINTS_OPTIONS = {
+ "50": "50 points",
+ "200": "200 points",
+ "500": "500 points",
+ "800": "800 points",
+ "1200": "1200 points",
+ "1600": "1600 points",
+ "2000": "2000 points",
+ all: "All points",
+} as const;
+
+interface ContainerMetric {
+ timestamp: string;
+ CPU: number;
+ Memory: {
+ percentage: number;
+ used: number;
+ total: number;
+ unit: string;
+ usedUnit: string;
+ totalUnit: string;
+ };
+ Network: {
+ input: number;
+ output: number;
+ inputUnit: string;
+ outputUnit: string;
+ };
+ BlockIO: {
+ read: number;
+ write: number;
+ readUnit: string;
+ writeUnit: string;
+ };
+ Container: string;
+ ID: string;
+ Name: string;
+}
+
+interface Props {
+ appName: string;
+ baseUrl: string;
+ token: string;
+}
+
+export const ContainerPaidMonitoring = ({ appName, baseUrl, token }: Props) => {
+ const [historicalData, setHistoricalData] = useState([]);
+ const [metrics, setMetrics] = useState(
+ {} as ContainerMetric,
+ );
+ const [dataPoints, setDataPoints] =
+ useState("50");
+ const [refreshInterval, setRefreshInterval] = useState("5000");
+
+ const {
+ data,
+ isLoading,
+ error: queryError,
+ } = api.user.getContainerMetrics.useQuery(
+ {
+ url: baseUrl,
+ token,
+ dataPoints,
+ appName,
+ },
+ {
+ refetchInterval:
+ dataPoints === "all" ? undefined : Number.parseInt(refreshInterval),
+ enabled: !!appName,
+ },
+ );
+
+ useEffect(() => {
+ if (!data) return;
+
+ // @ts-ignore
+ setHistoricalData(data);
+ // @ts-ignore
+ setMetrics(data[data.length - 1]);
+ }, [data]);
+
+ if (isLoading) {
+ return (
+
+
+
+ );
+ }
+
+ if (queryError) {
+ return (
+
+
+
+ Error fetching metrics for{" "}
+ {appName}
+
+
+ {queryError instanceof Error
+ ? queryError.message
+ : "Failed to fetch metrics, Please check your monitoring Instance is Configured correctly."}
+
+
URL: {baseUrl}
+
+
+ );
+ }
+
+ return (
+ <>
+
+
+ Container Monitoring
+
+
+
+ Data points:
+
+ setDataPoints(value)
+ }
+ >
+
+
+
+
+ {Object.entries(DATA_POINTS_OPTIONS).map(([value, label]) => (
+
+ {label}
+
+ ))}
+
+
+
+
+
+
+ Refresh interval:
+
+
+ setRefreshInterval(value)
+ }
+ >
+
+
+
+
+ {Object.entries(REFRESH_INTERVALS).map(([value, label]) => (
+
+ {label}
+
+ ))}
+
+
+
+
+
+
+ {/* Stats Cards */}
+
+
+
+
+
CPU Usage
+
+ {metrics.CPU}%
+
+
+
+
+
+
Memory Usage
+
+
+ {metrics?.Memory?.percentage}%
+
+
+ {metrics?.Memory?.used} {metrics?.Memory?.unit} /{" "}
+ {metrics?.Memory?.total} {metrics?.Memory?.unit}
+
+
+
+
+
+
+
Network I/O
+
+
+ {metrics?.Network?.input} {metrics?.Network?.inputUnit} /{" "}
+ {metrics?.Network?.output} {metrics?.Network?.outputUnit}
+
+
+
+
+
+
+
Block I/O
+
+
+ {metrics?.BlockIO?.read} {metrics?.BlockIO?.readUnit} /{" "}
+ {metrics?.BlockIO?.write} {metrics?.BlockIO?.writeUnit}
+
+
+
+
+ {/* Container Information */}
+
+ Container Information
+
+
+
+ Container ID
+
+
{metrics.ID}
+
+
+
Name
+
{metrics.Name}
+
+
+
+
+ {/* Charts Grid */}
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/servers/cpu-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/cpu-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8c9602ee22834a056d8202d84ac344f1e537217e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/cpu-chart.tsx
@@ -0,0 +1,115 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ type ChartConfig,
+ ChartContainer,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+} from "@/components/ui/chart";
+import { formatTimestamp } from "@/lib/utils";
+import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
+
+interface CPUChartProps {
+ data: any[];
+}
+
+const chartConfig = {
+ cpu: {
+ label: "CPU",
+ color: "hsl(var(--chart-1))",
+ },
+} satisfies ChartConfig;
+
+export function CPUChart({ data }: CPUChartProps) {
+ const latestData = data[data.length - 1] || {};
+
+ return (
+
+
+ CPU
+ CPU Usage: {latestData.cpu}%
+
+
+
+
+
+
+
+
+
+
+
+ formatTimestamp(value)}
+ />
+ `${value}%`} domain={[0, 100]} />
+ {
+ if (active && payload && payload.length) {
+ const data = payload?.[0]?.payload;
+ return (
+
+
+
+
+ Time
+
+
+ {formatTimestamp(label)}
+
+
+
+
+ CPU
+
+ {data.cpu}%
+
+
+
+ );
+ }
+ return null;
+ }}
+ />
+
+ }
+ verticalAlign="bottom"
+ align="center"
+ />
+
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/servers/disk-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/disk-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..3a81526cc7780e19449081a82cafa80fe09d79b0
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/disk-chart.tsx
@@ -0,0 +1,120 @@
+import { HardDrive } from "lucide-react";
+import {
+ Label,
+ PolarGrid,
+ PolarRadiusAxis,
+ RadialBar,
+ RadialBarChart,
+} from "recharts";
+
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { type ChartConfig, ChartContainer } from "@/components/ui/chart";
+
+interface RadialChartProps {
+ data: any;
+}
+
+export function DiskChart({ data }: RadialChartProps) {
+ const diskUsed = Number.parseFloat(data.diskUsed || 0);
+ const totalDiskGB = Number.parseFloat(data.totalDisk || 0);
+ const usedDiskGB = (totalDiskGB * diskUsed) / 100;
+
+ const chartData = [
+ {
+ disk: 25,
+ fill: "hsl(var(--chart-2))",
+ },
+ ];
+
+ const chartConfig = {
+ disk: {
+ label: "Disk",
+ color: "hsl(var(--chart-2))",
+ },
+ } satisfies ChartConfig;
+
+ const endAngle = (diskUsed * 360) / 100;
+
+ return (
+
+
+ Disk
+ Storage Space
+
+
+
+
+
+
+
+ {
+ if (viewBox && "cx" in viewBox && "cy" in viewBox) {
+ return (
+
+
+ {diskUsed.toFixed(1)}%
+
+
+ Used
+
+
+ );
+ }
+ }}
+ />
+
+
+
+
+
+
+ {usedDiskGB.toFixed(1)} GB used
+
+
+ Of {totalDiskGB.toFixed(1)} GB total
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/servers/memory-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/memory-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..f4079c46d4439bf1b7c9fee36aed55d5050e2488
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/memory-chart.tsx
@@ -0,0 +1,128 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ type ChartConfig,
+ ChartContainer,
+ ChartTooltip,
+} from "@/components/ui/chart";
+import { formatTimestamp } from "@/lib/utils";
+import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
+
+interface MemoryChartProps {
+ data: any[];
+}
+
+const chartConfig = {
+ Memory: {
+ label: "Memory",
+ color: "hsl(var(--chart-2))",
+ },
+} satisfies ChartConfig;
+
+export function MemoryChart({ data }: MemoryChartProps) {
+ const latestData = data[data.length - 1] || {};
+
+ return (
+
+
+ Memory
+
+ Memory Usage: {latestData.memUsedGB} GB of {latestData.memTotal} GB (
+ {latestData.memUsed}%)
+
+
+
+
+
+
+
+
+
+
+
+
+ formatTimestamp(value)}
+ />
+ `${value}%`}
+ domain={[0, 100]}
+ />
+ `${value.toFixed(1)} GB`}
+ domain={[
+ 0,
+ Math.ceil(Number.parseFloat(latestData.memTotal || "0")),
+ ]}
+ />
+ {
+ if (active && payload && payload.length) {
+ const data = payload?.[0]?.payload;
+ return (
+
+
+
+
+ Time
+
+
+ {formatTimestamp(label)}
+
+
+
+
+ Memory
+
+
+ {data.memUsed}% ({data.memUsedGB} GB)
+
+
+
+
+ );
+ }
+ return null;
+ }}
+ />
+
+
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/servers/network-chart.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/network-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..b84af0952d972a53674085cee6d42310ebec64b1
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/network-chart.tsx
@@ -0,0 +1,145 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ type ChartConfig,
+ ChartContainer,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+} from "@/components/ui/chart";
+import { formatTimestamp } from "@/lib/utils";
+import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
+
+interface NetworkChartProps {
+ data: any[];
+}
+
+const chartConfig = {
+ networkIn: {
+ label: "Network In",
+ color: "hsl(var(--chart-3))",
+ },
+ networkOut: {
+ label: "Network Out",
+ color: "hsl(var(--chart-4))",
+ },
+} satisfies ChartConfig;
+
+export function NetworkChart({ data }: NetworkChartProps) {
+ const latestData = data[data.length - 1] || {};
+
+ return (
+
+
+ Network
+
+ Network Traffic: ↑ {latestData.networkOut} KB/s ↓{" "}
+ {latestData.networkIn} KB/s
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ formatTimestamp(value)}
+ />
+ `${value} KB/s`} />
+ {
+ if (active && payload && payload.length) {
+ const data = payload?.[0]?.payload;
+ return (
+
+
+
+
+ Time
+
+
+ {formatTimestamp(label)}
+
+
+
+
+ Network
+
+
+ ↑ {data.networkOut} KB/s
+ ↓ {data.networkIn} KB/s
+
+
+
+
+ );
+ }
+ return null;
+ }}
+ />
+
+
+ }
+ verticalAlign="bottom"
+ align="center"
+ />
+
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/monitoring/paid/servers/show-paid-monitoring.tsx b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/show-paid-monitoring.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e92ce03fc4408f14614f1d047a033f0945c087e8
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/monitoring/paid/servers/show-paid-monitoring.tsx
@@ -0,0 +1,275 @@
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { Clock, Cpu, HardDrive, Loader2, MemoryStick } from "lucide-react";
+import { useEffect, useState } from "react";
+import { CPUChart } from "./cpu-chart";
+import { DiskChart } from "./disk-chart";
+import { MemoryChart } from "./memory-chart";
+import { NetworkChart } from "./network-chart";
+
+const REFRESH_INTERVALS = {
+ "5000": "5 Seconds",
+ "10000": "10 Seconds",
+ "20000": "20 Seconds",
+ "30000": "30 Seconds",
+} as const;
+
+const DATA_POINTS_OPTIONS = {
+ "50": "50 points",
+ "200": "200 points",
+ "500": "500 points",
+ "800": "800 points",
+ "1200": "1200 points",
+ "1600": "1600 points",
+ "2000": "2000 points",
+ all: "All points",
+} as const;
+
+interface SystemMetrics {
+ cpu: string;
+ cpuModel: string;
+ cpuCores: number;
+ cpuPhysicalCores: number;
+ cpuSpeed: number;
+ os: string;
+ distro: string;
+ kernel: string;
+ arch: string;
+ memUsed: string;
+ memUsedGB: string;
+ memTotal: string;
+ uptime: number;
+ diskUsed: string;
+ totalDisk: string;
+ networkIn: string;
+ networkOut: string;
+ timestamp: string;
+}
+
+interface Props {
+ BASE_URL?: string;
+ token?: string;
+}
+
+export const ShowPaidMonitoring = ({
+ BASE_URL = process.env.NEXT_PUBLIC_METRICS_URL ||
+ "http://localhost:3001/metrics",
+ token = process.env.NEXT_PUBLIC_METRICS_TOKEN || "my-token",
+}: Props) => {
+ const [historicalData, setHistoricalData] = useState([]);
+ const [metrics, setMetrics] = useState({} as SystemMetrics);
+ const [dataPoints, setDataPoints] =
+ useState("50");
+ const [refreshInterval, setRefreshInterval] = useState("5000");
+
+ const {
+ data,
+ isLoading,
+ error: queryError,
+ } = api.server.getServerMetrics.useQuery(
+ {
+ url: BASE_URL,
+ token,
+ dataPoints,
+ },
+ {
+ refetchInterval:
+ dataPoints === "all" ? undefined : Number.parseInt(refreshInterval),
+ enabled: true,
+ },
+ );
+
+ useEffect(() => {
+ if (!data) return;
+
+ const formattedData = data.map((metric: SystemMetrics) => ({
+ timestamp: metric.timestamp,
+ cpu: Number.parseFloat(metric.cpu),
+ cpuModel: metric.cpuModel,
+ cpuCores: metric.cpuCores,
+ cpuPhysicalCores: metric.cpuPhysicalCores,
+ cpuSpeed: metric.cpuSpeed,
+ os: metric.os,
+ distro: metric.distro,
+ kernel: metric.kernel,
+ arch: metric.arch,
+ memUsed: Number.parseFloat(metric.memUsed),
+ memUsedGB: Number.parseFloat(metric.memUsedGB),
+ memTotal: Number.parseFloat(metric.memTotal),
+ networkIn: Number.parseFloat(metric.networkIn),
+ networkOut: Number.parseFloat(metric.networkOut),
+ diskUsed: Number.parseFloat(metric.diskUsed),
+ totalDisk: Number.parseFloat(metric.totalDisk),
+ uptime: metric.uptime,
+ }));
+
+ // @ts-ignore
+ setHistoricalData(formattedData);
+ // @ts-ignore
+ setMetrics(formattedData[formattedData.length - 1] || {});
+ }, [data]);
+
+ const formatUptime = (seconds: number): string => {
+ const days = Math.floor(seconds / (24 * 60 * 60));
+ const hours = Math.floor((seconds % (24 * 60 * 60)) / (60 * 60));
+ const minutes = Math.floor((seconds % (60 * 60)) / 60);
+
+ return `${days}d ${hours}h ${minutes}m`;
+ };
+
+ if (isLoading) {
+ return (
+
+
+
+ );
+ }
+
+ if (queryError) {
+ return (
+
+
+
+ Error fetching metrics{" "}
+
+
+ {queryError instanceof Error
+ ? queryError.message
+ : "Failed to fetch metrics, Please check your monitoring Instance is Configured correctly."}
+
+
URL: {BASE_URL}
+
+
+ );
+ }
+
+ return (
+
+
+
System Monitoring
+
+
+ Data points:
+
+ setDataPoints(value)
+ }
+ >
+
+
+
+
+ {Object.entries(DATA_POINTS_OPTIONS).map(([value, label]) => (
+
+ {label}
+
+ ))}
+
+
+
+
+
+
+ Refresh interval:
+
+
+ setRefreshInterval(value)
+ }
+ >
+
+
+
+
+ {Object.entries(REFRESH_INTERVALS).map(([value, label]) => (
+
+ {label}
+
+ ))}
+
+
+
+
+
+
+ {/* Stats Cards */}
+
+
+
+
+
Uptime
+
+
+ {formatUptime(metrics.uptime || 0)}
+
+
+
+
+
+
+
CPU Usage
+
+
{metrics.cpu}%
+
+
+
+
+
+
Memory Usage
+
+
+ {metrics.memUsedGB} GB / {metrics.memTotal} GB
+
+
+
+
+
+
+
Disk Usage
+
+
{metrics.diskUsed}%
+
+
+
+ {/* System Information */}
+
+
System Information
+
+
+
CPU
+
{metrics.cpuModel}
+
+ {metrics.cpuPhysicalCores} Physical Cores ({metrics.cpuCores}{" "}
+ Threads) @ {metrics.cpuSpeed}GHz
+
+
+
+
+ Operating System
+
+
{metrics.distro}
+
+ Kernel: {metrics.kernel} ({metrics.arch})
+
+
+
+
+
+ {/* Charts Grid */}
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mysql/general/show-external-mysql-credentials.tsx b/data/apps/dokploy/components/dashboard/mysql/general/show-external-mysql-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..73f99b7d073c62b1ccc7d7821cf3443bb72d35f7
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mysql/general/show-external-mysql-credentials.tsx
@@ -0,0 +1,174 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const DockerProviderSchema = z.object({
+ externalPort: z.preprocess((a) => {
+ if (a !== null) {
+ const parsed = Number.parseInt(z.string().parse(a), 10);
+ return Number.isNaN(parsed) ? null : parsed;
+ }
+ return null;
+ }, z
+ .number()
+ .gte(0, "Range must be 0 - 65535")
+ .lte(65535, "Range must be 0 - 65535")
+ .nullable()),
+});
+
+type DockerProvider = z.infer;
+
+interface Props {
+ mysqlId: string;
+}
+export const ShowExternalMysqlCredentials = ({ mysqlId }: Props) => {
+ const { data: ip } = api.settings.getIp.useQuery();
+ const { data, refetch } = api.mysql.one.useQuery({ mysqlId });
+ const { mutateAsync, isLoading } = api.mysql.saveExternalPort.useMutation();
+ const [connectionUrl, setConnectionUrl] = useState("");
+ const getIp = data?.server?.ipAddress || ip;
+ const form = useForm({
+ defaultValues: {},
+ resolver: zodResolver(DockerProviderSchema),
+ });
+
+ useEffect(() => {
+ if (data?.externalPort) {
+ form.reset({
+ externalPort: data.externalPort,
+ });
+ }
+ }, [form.reset, data, form]);
+
+ const onSubmit = async (values: DockerProvider) => {
+ await mutateAsync({
+ externalPort: values.externalPort,
+ mysqlId,
+ })
+ .then(async () => {
+ toast.success("External Port updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the external port");
+ });
+ };
+
+ useEffect(() => {
+ const buildConnectionUrl = () => {
+ const port = form.watch("externalPort") || data?.externalPort;
+
+ return `mysql://${data?.databaseUser}:${data?.databasePassword}@${getIp}:${port}/${data?.databaseName}`;
+ };
+
+ setConnectionUrl(buildConnectionUrl());
+ }, [
+ data?.appName,
+ data?.externalPort,
+ data?.databasePassword,
+ data?.databaseName,
+ data?.databaseUser,
+ form,
+ getIp,
+ ]);
+ return (
+ <>
+
+
+
+ External Credentials
+
+ In order to make the database reachable trought internet is
+ required to set a port, make sure the port is not used by another
+ application or database
+
+
+
+ {!getIp && (
+
+ You need to set an IP address in your{" "}
+
+ {data?.serverId
+ ? "Remote Servers -> Server -> Edit Server -> Update IP Address"
+ : "Web Server -> Server -> Update Server IP"}
+ {" "}
+ to fix the database url connection.
+
+ )}
+
+
+
+
+ {
+ return (
+
+ External Port (Internet)
+
+
+
+
+
+ );
+ }}
+ />
+
+
+ {!!data?.externalPort && (
+
+ )}
+
+
+
+ Save
+
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mysql/general/show-general-mysql.tsx b/data/apps/dokploy/components/dashboard/mysql/general/show-general-mysql.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..590127fa7967969b851fd4af22a48498a1d52f3d
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mysql/general/show-general-mysql.tsx
@@ -0,0 +1,259 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { DrawerLogs } from "@/components/shared/drawer-logs";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+import { Ban, CheckCircle2, RefreshCcw, Rocket, Terminal } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { type LogLine, parseLogs } from "../../docker/logs/utils";
+import { DockerTerminalModal } from "../../settings/web-server/docker-terminal-modal";
+interface Props {
+ mysqlId: string;
+}
+
+export const ShowGeneralMysql = ({ mysqlId }: Props) => {
+ const { data, refetch } = api.mysql.one.useQuery(
+ {
+ mysqlId,
+ },
+ { enabled: !!mysqlId },
+ );
+
+ const { mutateAsync: reload, isLoading: isReloading } =
+ api.mysql.reload.useMutation();
+ const { mutateAsync: start, isLoading: isStarting } =
+ api.mysql.start.useMutation();
+
+ const { mutateAsync: stop, isLoading: isStopping } =
+ api.mysql.stop.useMutation();
+
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [filteredLogs, setFilteredLogs] = useState([]);
+ const [isDeploying, setIsDeploying] = useState(false);
+ api.mysql.deployWithLogs.useSubscription(
+ {
+ mysqlId: mysqlId,
+ },
+ {
+ enabled: isDeploying,
+ onData(log) {
+ if (!isDrawerOpen) {
+ setIsDrawerOpen(true);
+ }
+
+ if (log === "Deployment completed successfully!") {
+ setIsDeploying(false);
+ }
+ const parsedLogs = parseLogs(log);
+ setFilteredLogs((prev) => [...prev, ...parsedLogs]);
+ },
+ onError(error) {
+ console.error("Deployment logs error:", error);
+ setIsDeploying(false);
+ },
+ },
+ );
+ return (
+ <>
+
+
+
+ Deploy Settings
+
+
+
+ {
+ setIsDeploying(true);
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ refetch();
+ }}
+ >
+
+
+
+
+
+ Deploy
+
+
+
+
+ Downloads and sets up the MySQL database
+
+
+
+
+
+ {
+ await reload({
+ mysqlId: mysqlId,
+ appName: data?.appName || "",
+ })
+ .then(() => {
+ toast.success("MySQL reloaded successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error reloading MySQL");
+ });
+ }}
+ >
+
+
+
+
+
+ Reload
+
+
+
+
+ Restart the MySQL service without rebuilding
+
+
+
+
+
+ {data?.applicationStatus === "idle" ? (
+ {
+ await start({
+ mysqlId: mysqlId,
+ })
+ .then(() => {
+ toast.success("MySQL started successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error starting MySQL");
+ });
+ }}
+ >
+
+
+
+
+
+ Start
+
+
+
+
+
+ Start the MySQL database (requires a previous
+ successful setup)
+
+
+
+
+
+
+ ) : (
+ {
+ await stop({
+ mysqlId: mysqlId,
+ })
+ .then(() => {
+ toast.success("MySQL stopped successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error stopping MySQL");
+ });
+ }}
+ >
+
+
+
+
+
+ Stop
+
+
+
+
+ Stop the currently running MySQL database
+
+
+
+
+
+ )}
+
+
+
+
+
+
+
+ Open Terminal
+
+
+
+
+ Open a terminal to the MySQL container
+
+
+
+
+
+
+
+
{
+ setIsDrawerOpen(false);
+ setFilteredLogs([]);
+ setIsDeploying(false);
+ refetch();
+ }}
+ filteredLogs={filteredLogs}
+ />
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mysql/general/show-internal-mysql-credentials.tsx b/data/apps/dokploy/components/dashboard/mysql/general/show-internal-mysql-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..3f1872371f35ad2945ff9063d2246b81e94f1ebb
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mysql/general/show-internal-mysql-credentials.tsx
@@ -0,0 +1,70 @@
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+
+interface Props {
+ mysqlId: string;
+}
+export const ShowInternalMysqlCredentials = ({ mysqlId }: Props) => {
+ const { data } = api.mysql.one.useQuery({ mysqlId });
+ return (
+ <>
+
+
+
+ Internal Credentials
+
+
+
+
+ User
+
+
+
+ Database Name
+
+
+
+
+
+ Internal Port (Container)
+
+
+
+
+ Internal Host
+
+
+
+
+ Internal Connection URL
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/mysql/update-mysql.tsx b/data/apps/dokploy/components/dashboard/mysql/update-mysql.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..ec3c1b4544997165677bf351503d76a20cc964ee
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/mysql/update-mysql.tsx
@@ -0,0 +1,163 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const updateMysqlSchema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ description: z.string().optional(),
+});
+
+type UpdateMysql = z.infer;
+
+interface Props {
+ mysqlId: string;
+}
+
+export const UpdateMysql = ({ mysqlId }: Props) => {
+ const utils = api.useUtils();
+ const { mutateAsync, error, isError, isLoading } =
+ api.mysql.update.useMutation();
+ const { data } = api.mysql.one.useQuery(
+ {
+ mysqlId,
+ },
+ {
+ enabled: !!mysqlId,
+ },
+ );
+ const form = useForm({
+ defaultValues: {
+ description: data?.description ?? "",
+ name: data?.name ?? "",
+ },
+ resolver: zodResolver(updateMysqlSchema),
+ });
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ description: data.description ?? "",
+ name: data.name,
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: UpdateMysql) => {
+ await mutateAsync({
+ name: formData.name,
+ mysqlId: mysqlId,
+ description: formData.description || "",
+ })
+ .then(() => {
+ toast.success("MySQL updated successfully");
+ utils.mysql.one.invalidate({
+ mysqlId: mysqlId,
+ });
+ })
+ .catch(() => {
+ toast.error("Error updating MySQL");
+ })
+ .finally(() => {});
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Modify MySQL
+ Update the MySQL data
+
+ {isError && {error?.message} }
+
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+ Update
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/organization/handle-organization.tsx b/data/apps/dokploy/components/dashboard/organization/handle-organization.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..014c37df185449bb4f1adbc75f33faf5edfcb05b
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/organization/handle-organization.tsx
@@ -0,0 +1,182 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon, Plus } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const organizationSchema = z.object({
+ name: z.string().min(1, {
+ message: "Organization name is required",
+ }),
+ logo: z.string().optional(),
+});
+
+type OrganizationFormValues = z.infer;
+
+interface Props {
+ organizationId?: string;
+ children?: React.ReactNode;
+}
+
+export function AddOrganization({ organizationId }: Props) {
+ const [open, setOpen] = useState(false);
+ const utils = api.useUtils();
+ const { data: organization } = api.organization.one.useQuery(
+ {
+ organizationId: organizationId ?? "",
+ },
+ {
+ enabled: !!organizationId,
+ },
+ );
+ const { mutateAsync, isLoading } = organizationId
+ ? api.organization.update.useMutation()
+ : api.organization.create.useMutation();
+
+ const form = useForm({
+ resolver: zodResolver(organizationSchema),
+ defaultValues: {
+ name: "",
+ logo: "",
+ },
+ });
+
+ useEffect(() => {
+ if (organization) {
+ form.reset({
+ name: organization.name,
+ logo: organization.logo || "",
+ });
+ }
+ }, [organization, form]);
+
+ const onSubmit = async (values: OrganizationFormValues) => {
+ await mutateAsync({
+ name: values.name,
+ logo: values.logo,
+ organizationId: organizationId ?? "",
+ })
+ .then(() => {
+ form.reset();
+ toast.success(
+ `Organization ${organizationId ? "updated" : "created"} successfully`,
+ );
+ utils.organization.all.invalidate();
+ setOpen(false);
+ })
+ .catch((error) => {
+ console.error(error);
+ toast.error(
+ `Failed to ${organizationId ? "update" : "create"} organization`,
+ );
+ });
+ };
+
+ return (
+
+
+ {organizationId ? (
+ e.preventDefault()}
+ >
+
+
+ ) : (
+ e.preventDefault()}
+ >
+
+
+ Add organization
+
+
+ )}
+
+
+
+
+ {organizationId ? "Update organization" : "Add organization"}
+
+
+ {organizationId
+ ? "Update the organization name and logo"
+ : "Create a new organization to manage your projects."}
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+ )}
+ />
+ (
+
+ Logo URL
+
+
+
+
+
+ )}
+ />
+
+
+ {organizationId ? "Update organization" : "Create organization"}
+
+
+
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/postgres/advanced/show-custom-command.tsx b/data/apps/dokploy/components/dashboard/postgres/advanced/show-custom-command.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..40e84844fa5b3463690b8b2383863881640786ea
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/postgres/advanced/show-custom-command.tsx
@@ -0,0 +1,150 @@
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import type { ServiceType } from "../../application/advanced/show-resources";
+
+const addDockerImage = z.object({
+ dockerImage: z.string().min(1, "Docker image is required"),
+ command: z.string(),
+});
+
+interface Props {
+ id: string;
+ type: Exclude;
+}
+
+type AddDockerImage = z.infer;
+export const ShowCustomCommand = ({ id, type }: Props) => {
+ const queryMap = {
+ postgres: () =>
+ api.postgres.one.useQuery({ postgresId: id }, { enabled: !!id }),
+ redis: () => api.redis.one.useQuery({ redisId: id }, { enabled: !!id }),
+ mysql: () => api.mysql.one.useQuery({ mysqlId: id }, { enabled: !!id }),
+ mariadb: () =>
+ api.mariadb.one.useQuery({ mariadbId: id }, { enabled: !!id }),
+ application: () =>
+ api.application.one.useQuery({ applicationId: id }, { enabled: !!id }),
+ mongo: () => api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id }),
+ };
+ const { data, refetch } = queryMap[type]
+ ? queryMap[type]()
+ : api.mongo.one.useQuery({ mongoId: id }, { enabled: !!id });
+
+ const mutationMap = {
+ postgres: () => api.postgres.update.useMutation(),
+ redis: () => api.redis.update.useMutation(),
+ mysql: () => api.mysql.update.useMutation(),
+ mariadb: () => api.mariadb.update.useMutation(),
+ application: () => api.application.update.useMutation(),
+ mongo: () => api.mongo.update.useMutation(),
+ };
+
+ const { mutateAsync } = mutationMap[type]
+ ? mutationMap[type]()
+ : api.mongo.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ dockerImage: "",
+ command: "",
+ },
+ resolver: zodResolver(addDockerImage),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ dockerImage: data.dockerImage,
+ command: data.command || "",
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: AddDockerImage) => {
+ await mutateAsync({
+ mongoId: id || "",
+ postgresId: id || "",
+ redisId: id || "",
+ mysqlId: id || "",
+ mariadbId: id || "",
+ dockerImage: formData?.dockerImage,
+ command: formData?.command,
+ })
+ .then(async () => {
+ toast.success("Custom Command Updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error updating the custom command");
+ });
+ };
+ return (
+ <>
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/postgres/general/show-external-postgres-credentials.tsx b/data/apps/dokploy/components/dashboard/postgres/general/show-external-postgres-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..444fa0ceec430497f3106a5bb4f04edcf1733f21
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/postgres/general/show-external-postgres-credentials.tsx
@@ -0,0 +1,176 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const DockerProviderSchema = z.object({
+ externalPort: z.preprocess((a) => {
+ if (a !== null) {
+ const parsed = Number.parseInt(z.string().parse(a), 10);
+ return Number.isNaN(parsed) ? null : parsed;
+ }
+ return null;
+ }, z
+ .number()
+ .gte(0, "Range must be 0 - 65535")
+ .lte(65535, "Range must be 0 - 65535")
+ .nullable()),
+});
+
+type DockerProvider = z.infer;
+
+interface Props {
+ postgresId: string;
+}
+export const ShowExternalPostgresCredentials = ({ postgresId }: Props) => {
+ const { data: ip } = api.settings.getIp.useQuery();
+ const { data, refetch } = api.postgres.one.useQuery({ postgresId });
+ const { mutateAsync, isLoading } =
+ api.postgres.saveExternalPort.useMutation();
+ const getIp = data?.server?.ipAddress || ip;
+ const [connectionUrl, setConnectionUrl] = useState("");
+
+ const form = useForm({
+ defaultValues: {},
+ resolver: zodResolver(DockerProviderSchema),
+ });
+
+ useEffect(() => {
+ if (data?.externalPort) {
+ form.reset({
+ externalPort: data.externalPort,
+ });
+ }
+ }, [form.reset, data, form]);
+
+ const onSubmit = async (values: DockerProvider) => {
+ await mutateAsync({
+ externalPort: values.externalPort,
+ postgresId,
+ })
+ .then(async () => {
+ toast.success("External Port updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the external port");
+ });
+ };
+
+ useEffect(() => {
+ const buildConnectionUrl = () => {
+ const port = form.watch("externalPort") || data?.externalPort;
+
+ return `postgresql://${data?.databaseUser}:${data?.databasePassword}@${getIp}:${port}/${data?.databaseName}`;
+ };
+
+ setConnectionUrl(buildConnectionUrl());
+ }, [
+ data?.appName,
+ data?.externalPort,
+ data?.databasePassword,
+ form,
+ data?.databaseName,
+ getIp,
+ ]);
+
+ return (
+ <>
+
+
+
+ External Credentials
+
+ In order to make the database reachable trought internet is
+ required to set a port, make sure the port is not used by another
+ application or database
+
+
+
+ {!getIp && (
+
+ You need to set an IP address in your{" "}
+
+ {data?.serverId
+ ? "Remote Servers -> Server -> Edit Server -> Update IP Address"
+ : "Web Server -> Server -> Update Server IP"}
+ {" "}
+ to fix the database url connection.
+
+ )}
+
+
+
+
+ {
+ return (
+
+ External Port (Internet)
+
+
+
+
+
+ );
+ }}
+ />
+
+
+ {!!data?.externalPort && (
+
+ )}
+
+
+
+ Save
+
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/postgres/general/show-general-postgres.tsx b/data/apps/dokploy/components/dashboard/postgres/general/show-general-postgres.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..fec51b5a2a01bc1c15f0fd110f11d31d87a4d56e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/postgres/general/show-general-postgres.tsx
@@ -0,0 +1,262 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { DrawerLogs } from "@/components/shared/drawer-logs";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+import { Ban, CheckCircle2, RefreshCcw, Rocket, Terminal } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { type LogLine, parseLogs } from "../../docker/logs/utils";
+import { DockerTerminalModal } from "../../settings/web-server/docker-terminal-modal";
+
+interface Props {
+ postgresId: string;
+}
+
+export const ShowGeneralPostgres = ({ postgresId }: Props) => {
+ const { data, refetch } = api.postgres.one.useQuery(
+ {
+ postgresId: postgresId,
+ },
+ { enabled: !!postgresId },
+ );
+
+ const { mutateAsync: reload, isLoading: isReloading } =
+ api.postgres.reload.useMutation();
+
+ const { mutateAsync: stop, isLoading: isStopping } =
+ api.postgres.stop.useMutation();
+
+ const { mutateAsync: start, isLoading: isStarting } =
+ api.postgres.start.useMutation();
+
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [filteredLogs, setFilteredLogs] = useState([]);
+ const [isDeploying, setIsDeploying] = useState(false);
+ api.postgres.deployWithLogs.useSubscription(
+ {
+ postgresId: postgresId,
+ },
+ {
+ enabled: isDeploying,
+ onData(log) {
+ if (!isDrawerOpen) {
+ setIsDrawerOpen(true);
+ }
+
+ if (log === "Deployment completed successfully!") {
+ setIsDeploying(false);
+ }
+ const parsedLogs = parseLogs(log);
+ setFilteredLogs((prev) => [...prev, ...parsedLogs]);
+ },
+ onError(error) {
+ console.error("Deployment logs error:", error);
+ setIsDeploying(false);
+ },
+ },
+ );
+
+ return (
+ <>
+
+
+
+ Deploy Settings
+
+
+
+ {
+ setIsDeploying(true);
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ refetch();
+ }}
+ >
+
+
+
+
+
+ Deploy
+
+
+
+
+ Downloads and sets up the PostgreSQL database
+
+
+
+
+
+ {
+ await reload({
+ postgresId: postgresId,
+ appName: data?.appName || "",
+ })
+ .then(() => {
+ toast.success("PostgreSQL reloaded successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error reloading PostgreSQL");
+ });
+ }}
+ >
+
+
+
+
+
+ Reload
+
+
+
+
+ Restart the PostgreSQL service without rebuilding
+
+
+
+
+
+ {data?.applicationStatus === "idle" ? (
+ {
+ await start({
+ postgresId: postgresId,
+ })
+ .then(() => {
+ toast.success("PostgreSQL started successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error starting PostgreSQL");
+ });
+ }}
+ >
+
+
+
+
+
+ Start
+
+
+
+
+
+ Start the PostgreSQL database (requires a previous
+ successful setup)
+
+
+
+
+
+
+ ) : (
+ {
+ await stop({
+ postgresId: postgresId,
+ })
+ .then(() => {
+ toast.success("PostgreSQL stopped successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error stopping PostgreSQL");
+ });
+ }}
+ >
+
+
+
+
+
+ Stop
+
+
+
+
+ Stop the currently running PostgreSQL database
+
+
+
+
+
+ )}
+
+
+
+
+
+
+
+ Open Terminal
+
+
+
+
+ Open a terminal to the PostgreSQL container
+
+
+
+
+
+
+
+
{
+ setIsDrawerOpen(false);
+ setFilteredLogs([]);
+ setIsDeploying(false);
+ refetch();
+ }}
+ filteredLogs={filteredLogs}
+ />
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/postgres/general/show-internal-postgres-credentials.tsx b/data/apps/dokploy/components/dashboard/postgres/general/show-internal-postgres-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..545150f871a63ef7b2ac5e7dada1a6f018e95ba7
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/postgres/general/show-internal-postgres-credentials.tsx
@@ -0,0 +1,62 @@
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+
+interface Props {
+ postgresId: string;
+}
+export const ShowInternalPostgresCredentials = ({ postgresId }: Props) => {
+ const { data } = api.postgres.one.useQuery({ postgresId });
+ return (
+ <>
+
+
+
+ Internal Credentials
+
+
+
+
+ User
+
+
+
+ Database Name
+
+
+
+
+ Internal Port (Container)
+
+
+
+
+ Internal Host
+
+
+
+
+ Internal Connection URL
+
+
+
+
+
+
+ >
+ );
+};
+// ReplyError: MISCONF Redis is configured to save RDB snapshots, but it's currently unable to persist to disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-w
diff --git a/data/apps/dokploy/components/dashboard/postgres/update-postgres.tsx b/data/apps/dokploy/components/dashboard/postgres/update-postgres.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..f70cd8c90d275291d08c956d8cf4a5309e3cb7b9
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/postgres/update-postgres.tsx
@@ -0,0 +1,166 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBox } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const updatePostgresSchema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ description: z.string().optional(),
+});
+
+type UpdatePostgres = z.infer;
+
+interface Props {
+ postgresId: string;
+}
+
+export const UpdatePostgres = ({ postgresId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const utils = api.useUtils();
+ const { mutateAsync, error, isError, isLoading } =
+ api.postgres.update.useMutation();
+ const { data } = api.postgres.one.useQuery(
+ {
+ postgresId,
+ },
+ {
+ enabled: !!postgresId,
+ },
+ );
+ const form = useForm({
+ defaultValues: {
+ description: data?.description ?? "",
+ name: data?.name ?? "",
+ },
+ resolver: zodResolver(updatePostgresSchema),
+ });
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ description: data.description ?? "",
+ name: data.name,
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: UpdatePostgres) => {
+ await mutateAsync({
+ name: formData.name,
+ postgresId: postgresId,
+ description: formData.description || "",
+ })
+ .then(() => {
+ toast.success("Postgres updated successfully");
+ utils.postgres.one.invalidate({
+ postgresId: postgresId,
+ });
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating Postgres");
+ })
+ .finally(() => {});
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Modify Postgres
+ Update the Postgres data
+
+ {isError && {error?.message} }
+
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+ Update
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/project/add-ai-assistant.tsx b/data/apps/dokploy/components/dashboard/project/add-ai-assistant.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2bb47618edce65a2fd8cdfc35ce39025c68e6df2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/add-ai-assistant.tsx
@@ -0,0 +1,10 @@
+import { TemplateGenerator } from "@/components/dashboard/project/ai/template-generator";
+
+interface Props {
+ projectId: string;
+ projectName?: string;
+}
+
+export const AddAiAssistant = ({ projectId }: Props) => {
+ return ;
+};
diff --git a/data/apps/dokploy/components/dashboard/project/add-application.tsx b/data/apps/dokploy/components/dashboard/project/add-application.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c93de25198875db6c28c671ffac3b4f6e7e6238e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/add-application.tsx
@@ -0,0 +1,256 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Textarea } from "@/components/ui/textarea";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { slugify } from "@/lib/slug";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Folder, HelpCircle } from "lucide-react";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const AddTemplateSchema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ appName: z
+ .string()
+ .min(1, {
+ message: "App name is required",
+ })
+ .regex(/^[a-z](?!.*--)([a-z0-9-]*[a-z])?$/, {
+ message:
+ "App name supports lowercase letters, numbers, '-' and can only start and end letters, and does not support continuous '-'",
+ }),
+ description: z.string().optional(),
+ serverId: z.string().optional(),
+});
+
+type AddTemplate = z.infer;
+
+interface Props {
+ projectId: string;
+ projectName?: string;
+}
+
+export const AddApplication = ({ projectId, projectName }: Props) => {
+ const utils = api.useUtils();
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const [visible, setVisible] = useState(false);
+ const slug = slugify(projectName);
+ const { data: servers } = api.server.withSSHKey.useQuery();
+
+ const { mutateAsync, isLoading, error, isError } =
+ api.application.create.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ name: "",
+ appName: `${slug}-`,
+ description: "",
+ },
+ resolver: zodResolver(AddTemplateSchema),
+ });
+
+ const onSubmit = async (data: AddTemplate) => {
+ await mutateAsync({
+ name: data.name,
+ appName: data.appName,
+ description: data.description,
+ projectId,
+ serverId: data.serverId,
+ })
+ .then(async () => {
+ toast.success("Service Created");
+ form.reset();
+ setVisible(false);
+ await utils.project.one.invalidate({
+ projectId,
+ });
+ })
+ .catch((_e) => {
+ toast.error("Error creating the service");
+ });
+ };
+
+ return (
+
+
+ e.preventDefault()}
+ >
+
+ Application
+
+
+
+
+ Create
+
+ Assign a name and description to your application
+
+
+ {isError && {error?.message} }
+
+
+ (
+
+ Name
+
+ {
+ const val = e.target.value?.trim() || "";
+ const serviceName = slugify(val);
+ form.setValue("appName", `${slug}-${serviceName}`);
+ field.onChange(val);
+ }}
+ />
+
+
+
+ )}
+ />
+ (
+
+
+
+
+
+ Select a Server {!isCloud ? "(Optional)" : ""}
+
+
+
+
+
+ If no server is selected, the application will be
+ deployed on the server where the user is logged in.
+
+
+
+
+
+
+
+
+
+
+
+ {servers?.map((server) => (
+
+
+ {server.name}
+
+ {server.ipAddress}
+
+
+
+ ))}
+ Servers ({servers?.length})
+
+
+
+
+
+ )}
+ />
+ (
+
+ App Name
+
+
+
+
+
+ )}
+ />
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ Create
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/project/add-compose.tsx b/data/apps/dokploy/components/dashboard/project/add-compose.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5f2bb137fa61038230434efab54c47dfb5c932fe
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/add-compose.tsx
@@ -0,0 +1,290 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Textarea } from "@/components/ui/textarea";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { slugify } from "@/lib/slug";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { CircuitBoard, HelpCircle } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const AddComposeSchema = z.object({
+ composeType: z.enum(["docker-compose", "stack"]).optional(),
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ appName: z
+ .string()
+ .min(1, {
+ message: "App name is required",
+ })
+ .regex(/^[a-z](?!.*--)([a-z0-9-]*[a-z])?$/, {
+ message:
+ "App name supports lowercase letters, numbers, '-' and can only start and end letters, and does not support continuous '-'",
+ }),
+ description: z.string().optional(),
+ serverId: z.string().optional(),
+});
+
+type AddCompose = z.infer;
+
+interface Props {
+ projectId: string;
+ projectName?: string;
+}
+
+export const AddCompose = ({ projectId, projectName }: Props) => {
+ const utils = api.useUtils();
+ const [visible, setVisible] = useState(false);
+ const slug = slugify(projectName);
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const { data: servers } = api.server.withSSHKey.useQuery();
+ const { mutateAsync, isLoading, error, isError } =
+ api.compose.create.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ name: "",
+ description: "",
+ composeType: "docker-compose",
+ appName: `${slug}-`,
+ },
+ resolver: zodResolver(AddComposeSchema),
+ });
+
+ useEffect(() => {
+ form.reset();
+ }, [form, form.reset, form.formState.isSubmitSuccessful]);
+
+ const onSubmit = async (data: AddCompose) => {
+ await mutateAsync({
+ name: data.name,
+ description: data.description,
+ projectId,
+ composeType: data.composeType,
+ appName: data.appName,
+ serverId: data.serverId,
+ })
+ .then(async () => {
+ toast.success("Compose Created");
+ setVisible(false);
+ await utils.project.one.invalidate({
+ projectId,
+ });
+ })
+ .catch(() => {
+ toast.error("Error creating the compose");
+ });
+ };
+
+ return (
+
+
+ e.preventDefault()}
+ >
+
+ Compose
+
+
+
+
+ Create Compose
+
+ Assign a name and description to your compose
+
+
+ {isError && {error?.message} }
+
+
+
+
+ (
+
+ Name
+
+ {
+ const val = e.target.value?.trim() || "";
+ const serviceName = slugify(val);
+ form.setValue("appName", `${slug}-${serviceName}`);
+ field.onChange(val);
+ }}
+ />
+
+
+
+ )}
+ />
+
+ (
+
+
+
+
+
+ Select a Server {!isCloud ? "(Optional)" : ""}
+
+
+
+
+
+ If no server is selected, the application will be
+ deployed on the server where the user is logged in.
+
+
+
+
+
+
+
+
+
+
+
+ {servers?.map((server) => (
+
+
+ {server.name}
+
+ {server.ipAddress}
+
+
+
+ ))}
+ Servers ({servers?.length})
+
+
+
+
+
+ )}
+ />
+ (
+
+ App Name
+
+
+
+
+
+ )}
+ />
+ (
+
+ Compose Type
+
+
+
+
+
+
+
+
+ Docker Compose
+
+ Stack
+
+
+
+
+ )}
+ />
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ Create
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/project/add-database.tsx b/data/apps/dokploy/components/dashboard/project/add-database.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2420e603fc5270539301bbc095b7366bb6c27807
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/add-database.tsx
@@ -0,0 +1,586 @@
+import {
+ MariadbIcon,
+ MongodbIcon,
+ MysqlIcon,
+ PostgresqlIcon,
+ RedisIcon,
+} from "@/components/icons/data-tools-icons";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import { slugify } from "@/lib/slug";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertTriangle, Database } from "lucide-react";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+type DbType = typeof mySchema._type.type;
+
+const dockerImageDefaultPlaceholder: Record = {
+ mongo: "mongo:6",
+ mariadb: "mariadb:11",
+ mysql: "mysql:8",
+ postgres: "postgres:15",
+ redis: "redis:7",
+};
+
+const databasesUserDefaultPlaceholder: Record<
+ Exclude,
+ string
+> = {
+ mongo: "mongo",
+ mariadb: "mariadb",
+ mysql: "mysql",
+ postgres: "postgres",
+};
+
+const baseDatabaseSchema = z.object({
+ name: z.string().min(1, "Name required"),
+ appName: z
+ .string()
+ .min(1, {
+ message: "App name is required",
+ })
+ .regex(/^[a-z](?!.*--)([a-z0-9-]*[a-z])?$/, {
+ message:
+ "App name supports lowercase letters, numbers, '-' and can only start and end letters, and does not support continuous '-'",
+ }),
+ databasePassword: z.string(),
+ dockerImage: z.string(),
+ description: z.string().nullable(),
+ serverId: z.string().nullable(),
+});
+
+const mySchema = z.discriminatedUnion("type", [
+ z
+ .object({
+ type: z.literal("postgres"),
+ databaseName: z.string().default("postgres"),
+ databaseUser: z.string().default("postgres"),
+ })
+ .merge(baseDatabaseSchema),
+ z
+ .object({
+ type: z.literal("mongo"),
+ databaseUser: z.string().default("mongo"),
+ replicaSets: z.boolean().default(false),
+ })
+ .merge(baseDatabaseSchema),
+ z
+ .object({
+ type: z.literal("redis"),
+ })
+ .merge(baseDatabaseSchema),
+ z
+ .object({
+ type: z.literal("mysql"),
+ databaseRootPassword: z.string().default(""),
+ databaseUser: z.string().default("mysql"),
+ databaseName: z.string().default("mysql"),
+ })
+ .merge(baseDatabaseSchema),
+ z
+ .object({
+ type: z.literal("mariadb"),
+ dockerImage: z.string().default("mariadb:4"),
+ databaseRootPassword: z.string().default(""),
+ databaseUser: z.string().default("mariadb"),
+ databaseName: z.string().default("mariadb"),
+ })
+ .merge(baseDatabaseSchema),
+]);
+
+const databasesMap = {
+ postgres: {
+ icon: ,
+ label: "PostgreSQL",
+ },
+ mongo: {
+ icon: ,
+ label: "MongoDB",
+ },
+ mariadb: {
+ icon: ,
+ label: "MariaDB",
+ },
+ mysql: {
+ icon: ,
+ label: "MySQL",
+ },
+ redis: {
+ icon: ,
+ label: "Redis",
+ },
+};
+
+type AddDatabase = z.infer;
+
+interface Props {
+ projectId: string;
+ projectName?: string;
+}
+
+export const AddDatabase = ({ projectId, projectName }: Props) => {
+ const utils = api.useUtils();
+ const [visible, setVisible] = useState(false);
+ const slug = slugify(projectName);
+ const { data: servers } = api.server.withSSHKey.useQuery();
+ const postgresMutation = api.postgres.create.useMutation();
+ const mongoMutation = api.mongo.create.useMutation();
+ const redisMutation = api.redis.create.useMutation();
+ const mariadbMutation = api.mariadb.create.useMutation();
+ const mysqlMutation = api.mysql.create.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ type: "postgres",
+ dockerImage: "",
+ name: "",
+ appName: `${slug}-`,
+ databasePassword: "",
+ description: "",
+ databaseName: "",
+ databaseUser: "",
+ serverId: null,
+ },
+ resolver: zodResolver(mySchema),
+ });
+ const type = form.watch("type");
+ const activeMutation = {
+ postgres: postgresMutation,
+ mongo: mongoMutation,
+ redis: redisMutation,
+ mariadb: mariadbMutation,
+ mysql: mysqlMutation,
+ };
+
+ const onSubmit = async (data: AddDatabase) => {
+ const defaultDockerImage =
+ data.dockerImage || dockerImageDefaultPlaceholder[data.type];
+
+ let promise: Promise | null = null;
+ const commonParams = {
+ name: data.name,
+ appName: data.appName,
+ dockerImage: defaultDockerImage,
+ projectId,
+ serverId: data.serverId,
+ description: data.description,
+ };
+
+ if (data.type === "postgres") {
+ promise = postgresMutation.mutateAsync({
+ ...commonParams,
+ databasePassword: data.databasePassword,
+ databaseName: data.databaseName || "postgres",
+
+ databaseUser:
+ data.databaseUser || databasesUserDefaultPlaceholder[data.type],
+ serverId: data.serverId,
+ });
+ } else if (data.type === "mongo") {
+ promise = mongoMutation.mutateAsync({
+ ...commonParams,
+ databasePassword: data.databasePassword,
+ databaseUser:
+ data.databaseUser || databasesUserDefaultPlaceholder[data.type],
+ serverId: data.serverId,
+ replicaSets: data.replicaSets,
+ });
+ } else if (data.type === "redis") {
+ promise = redisMutation.mutateAsync({
+ ...commonParams,
+ databasePassword: data.databasePassword,
+ serverId: data.serverId,
+ projectId,
+ });
+ } else if (data.type === "mariadb") {
+ promise = mariadbMutation.mutateAsync({
+ ...commonParams,
+ databasePassword: data.databasePassword,
+ databaseRootPassword: data.databaseRootPassword,
+ databaseName: data.databaseName || "mariadb",
+ databaseUser:
+ data.databaseUser || databasesUserDefaultPlaceholder[data.type],
+ serverId: data.serverId,
+ });
+ } else if (data.type === "mysql") {
+ promise = mysqlMutation.mutateAsync({
+ ...commonParams,
+ databasePassword: data.databasePassword,
+ databaseName: data.databaseName || "mysql",
+ databaseUser:
+ data.databaseUser || databasesUserDefaultPlaceholder[data.type],
+ databaseRootPassword: data.databaseRootPassword,
+ serverId: data.serverId,
+ });
+ }
+
+ if (promise) {
+ await promise
+ .then(async () => {
+ toast.success("Database Created");
+ form.reset({
+ type: "postgres",
+ dockerImage: "",
+ name: "",
+ appName: `${projectName}-`,
+ databasePassword: "",
+ description: "",
+ databaseName: "",
+ databaseUser: "",
+ });
+ setVisible(false);
+ await utils.project.one.invalidate({
+ projectId,
+ });
+ })
+ .catch(() => {
+ toast.error("Error creating a database");
+ });
+ }
+ };
+ return (
+
+
+ e.preventDefault()}
+ >
+
+ Database
+
+
+
+
+ Databases
+
+
+
+
+ (
+
+
+ Select a database
+
+
+
+ {Object.entries(databasesMap).map(([key, value]) => (
+
+
+
+
+
+ {value.icon}
+ {value.label}
+
+
+
+
+ ))}
+
+
+
+ {activeMutation[field.value].isError && (
+
+
+
+ {activeMutation[field.value].error?.message}
+
+
+ )}
+
+ )}
+ />
+
+
+ Fill the next fields.
+
+
+
+
+
+
+
+ Create
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/project/add-template.tsx b/data/apps/dokploy/components/dashboard/project/add-template.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8e9de54d9428292a98ec71c5ffd0ea967400a722
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/add-template.tsx
@@ -0,0 +1,524 @@
+import { GithubIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import {
+ BookText,
+ CheckIcon,
+ ChevronsUpDown,
+ Globe,
+ HelpCircle,
+ LayoutGrid,
+ List,
+ Loader2,
+ PuzzleIcon,
+ SearchIcon,
+} from "lucide-react";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+
+const TEMPLATE_BASE_URL_KEY = "dokploy_template_base_url";
+
+interface Props {
+ projectId: string;
+ baseUrl?: string;
+}
+
+export const AddTemplate = ({ projectId, baseUrl }: Props) => {
+ const [query, setQuery] = useState("");
+ const [open, setOpen] = useState(false);
+ const [viewMode, setViewMode] = useState<"detailed" | "icon">("detailed");
+ const [selectedTags, setSelectedTags] = useState([]);
+ const [customBaseUrl, setCustomBaseUrl] = useState(() => {
+ // Try to get from props first, then localStorage
+ if (baseUrl) return baseUrl;
+ if (typeof window !== "undefined") {
+ return localStorage.getItem(TEMPLATE_BASE_URL_KEY) || undefined;
+ }
+ return undefined;
+ });
+
+ // Save to localStorage when customBaseUrl changes
+ useEffect(() => {
+ if (customBaseUrl) {
+ localStorage.setItem(TEMPLATE_BASE_URL_KEY, customBaseUrl);
+ } else {
+ localStorage.removeItem(TEMPLATE_BASE_URL_KEY);
+ }
+ }, [customBaseUrl]);
+
+ const {
+ data,
+ isLoading: isLoadingTemplates,
+ error: errorTemplates,
+ isError: isErrorTemplates,
+ } = api.compose.templates.useQuery(
+ { baseUrl: customBaseUrl },
+ {
+ enabled: open,
+ },
+ );
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const { data: servers } = api.server.withSSHKey.useQuery();
+ const { data: tags, isLoading: isLoadingTags } = api.compose.getTags.useQuery(
+ { baseUrl: customBaseUrl },
+ {
+ enabled: open,
+ },
+ );
+ const utils = api.useUtils();
+
+ const [serverId, setServerId] = useState(undefined);
+ const { mutateAsync, isLoading, error, isError } =
+ api.compose.deployTemplate.useMutation();
+
+ const templates =
+ data?.filter((template) => {
+ const matchesTags =
+ selectedTags.length === 0 ||
+ template.tags.some((tag) => selectedTags.includes(tag));
+ const matchesQuery =
+ query === "" ||
+ template.name.toLowerCase().includes(query.toLowerCase()) ||
+ template.description.toLowerCase().includes(query.toLowerCase());
+ return matchesTags && matchesQuery;
+ }) || [];
+
+ return (
+
+
+ e.preventDefault()}
+ >
+
+ Template
+
+
+
+
+
+
+
+ Create from Template
+
+ Create an open source application from a template
+
+
+
+
+ {selectedTags.length > 0 && (
+
+ {selectedTags.map((tag) => (
+
+ setSelectedTags(selectedTags.filter((t) => t !== tag))
+ }
+ >
+ {tag} ×
+
+ ))}
+
+ )}
+
+
+
+
+
+ {isError && (
+
+ {error?.message}
+
+ )}
+
+ {isErrorTemplates && (
+
+ {errorTemplates?.message}
+
+ )}
+
+ {isLoadingTemplates ? (
+
+
+
+ Loading templates...
+
+
+ ) : templates.length === 0 ? (
+
+
+
+ No templates found
+
+
+ ) : (
+
+ {templates?.map((template) => (
+
+
+ {template?.version}
+
+
+
+
+
+ {template?.name}
+
+ {viewMode === "detailed" &&
+ template?.tags?.length > 0 && (
+
+ {template?.tags?.map((tag) => (
+
+ {tag}
+
+ ))}
+
+ )}
+
+
+
+ {/* Template Content */}
+ {viewMode === "detailed" && (
+
+
+ {template?.description}
+
+
+ )}
+
+ {/* Create Button */}
+
+ {viewMode === "detailed" && (
+
+ {template?.links?.github && (
+
+
+
+ )}
+ {template?.links?.website && (
+
+
+
+ )}
+ {template?.links?.docs && (
+
+
+
+ )}
+
+ )}
+
+
+
+ Create
+
+
+
+
+
+ Are you absolutely sure?
+
+
+ This will create an application from the{" "}
+ {template?.name} template and add it to your
+ project.
+
+
+
+
+
+
+
+ Select a Server{" "}
+ {!isCloud ? "(Optional)" : ""}
+
+
+
+
+
+ If no server is selected, the application
+ will be deployed on the server where the
+ user is logged in.
+
+
+
+
+
+ {
+ setServerId(e);
+ }}
+ >
+
+
+
+
+
+ {servers?.map((server) => (
+
+
+ {server.name}
+
+ {server.ipAddress}
+
+
+
+ ))}
+
+ Servers ({servers?.length})
+
+
+
+
+
+
+
+ Cancel
+ {
+ const promise = mutateAsync({
+ projectId,
+ serverId: serverId || undefined,
+ id: template.id,
+ baseUrl: customBaseUrl,
+ });
+ toast.promise(promise, {
+ loading: "Setting up...",
+ success: () => {
+ utils.project.one.invalidate({
+ projectId,
+ });
+ setOpen(false);
+ return `${template.name} template created successfully`;
+ },
+ error: () => {
+ return `An error occurred deploying ${template.name} template`;
+ },
+ });
+ }}
+ >
+ Confirm
+
+
+
+
+
+
+ ))}
+
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/project/ai/step-one.tsx b/data/apps/dokploy/components/dashboard/project/ai/step-one.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e2a6795fe4658b18d409f465b7e589ad84c82c57
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/ai/step-one.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+
+const examples = [
+ "Make a personal blog",
+ "Add a photo studio portfolio",
+ "Create a personal ad blocker",
+ "Build a social media dashboard",
+ "Sendgrid service opensource analogue",
+];
+
+export const StepOne = ({ setTemplateInfo, templateInfo }: any) => {
+ // Get servers from the API
+ const { data: servers } = api.server.withSSHKey.useQuery();
+
+ const handleExampleClick = (example: string) => {
+ setTemplateInfo({ ...templateInfo, userInput: example });
+ };
+ return (
+
+
+
+
Step 1: Describe Your Needs
+
+ Describe your template needs
+
+ setTemplateInfo({ ...templateInfo, userInput: e.target.value })
+ }
+ className="min-h-[100px]"
+ />
+
+
+
+
+ Select the server where you want to deploy (optional)
+
+ {
+ const server = servers?.find((s) => s.serverId === value);
+ if (server) {
+ setTemplateInfo({
+ ...templateInfo,
+ server: server,
+ });
+ }
+ }}
+ >
+
+
+
+
+
+ {servers?.map((server) => (
+
+ {server.name}
+
+ ))}
+ Servers ({servers?.length})
+
+
+
+
+
+
+
Examples:
+
+ {examples.map((example, index) => (
+ handleExampleClick(example)}
+ >
+ {example}
+
+ ))}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/project/ai/step-three.tsx b/data/apps/dokploy/components/dashboard/project/ai/step-three.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8aa014e30f51893fce02e89a6d2c71bff9c3298e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/ai/step-three.tsx
@@ -0,0 +1,109 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import ReactMarkdown from "react-markdown";
+import type { StepProps } from "./step-two";
+
+export const StepThree = ({ templateInfo }: StepProps) => {
+ return (
+
+
+
+
Step 3: Review and Finalize
+
+
+
Name
+
+ {templateInfo?.details?.name}
+
+
+
+
Description
+
+ {templateInfo?.details?.description}
+
+
+
+
Server
+
+ {templateInfo?.server?.name || "Dokploy Server"}
+
+
+
+
Docker Compose
+
+
+
+
Environment Variables
+
+ {templateInfo?.details?.envVariables.map(
+ (
+ env: {
+ name: string;
+ value: string;
+ },
+ index: number,
+ ) => (
+
+
+ {env.name}
+
+ :
+
+ {env.value}
+
+
+ ),
+ )}
+
+
+
+
Domains
+
+ {templateInfo?.details?.domains.map(
+ (
+ domain: {
+ host: string;
+ port: number;
+ serviceName: string;
+ },
+ index: number,
+ ) => (
+
+
+ {domain.host}
+
+ :
+
+ {domain.port} - {domain.serviceName}
+
+
+ ),
+ )}
+
+
+
+
Configuration Files
+
+ {templateInfo?.details?.configFiles.map((file, index) => (
+
+
+ {file.filePath}
+
+ :
+
+ {file.content}
+
+
+ ))}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/project/ai/step-two.tsx b/data/apps/dokploy/components/dashboard/project/ai/step-two.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..14a929fce4d74e1230e32cb77b02964a8cbbea7e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/ai/step-two.tsx
@@ -0,0 +1,530 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@/components/ui/accordion";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { api } from "@/utils/api";
+import { Bot, Eye, EyeOff, PlusCircle, Trash2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import ReactMarkdown from "react-markdown";
+import { toast } from "sonner";
+import type { TemplateInfo } from "./template-generator";
+
+export interface StepProps {
+ stepper?: any;
+ templateInfo: TemplateInfo;
+ setTemplateInfo: React.Dispatch>;
+}
+
+export const StepTwo = ({ templateInfo, setTemplateInfo }: StepProps) => {
+ const suggestions = templateInfo.suggestions || [];
+ const selectedVariant = templateInfo.details;
+ const [showValues, setShowValues] = useState>({});
+
+ const { mutateAsync, isLoading, error, isError } =
+ api.ai.suggest.useMutation();
+
+ useEffect(() => {
+ if (suggestions?.length > 0) {
+ return;
+ }
+ mutateAsync({
+ aiId: templateInfo.aiId,
+ serverId: templateInfo.server?.serverId || "",
+ input: templateInfo.userInput,
+ })
+ .then((data) => {
+ setTemplateInfo({
+ ...templateInfo,
+ suggestions: data,
+ });
+ })
+ .catch((error) => {
+ toast.error("Error generating suggestions", {
+ description: error.message,
+ });
+ });
+ }, [templateInfo.userInput]);
+
+ const toggleShowValue = (name: string) => {
+ setShowValues((prev) => ({ ...prev, [name]: !prev[name] }));
+ };
+
+ const handleEnvVariableChange = (
+ index: number,
+ field: "name" | "value",
+ value: string,
+ ) => {
+ if (!selectedVariant) return;
+
+ const updatedEnvVariables = [...selectedVariant.envVariables];
+ // @ts-ignore
+ updatedEnvVariables[index] = {
+ ...updatedEnvVariables[index],
+ [field]: value,
+ };
+
+ setTemplateInfo({
+ ...templateInfo,
+ ...(templateInfo.details && {
+ details: {
+ ...templateInfo.details,
+ envVariables: updatedEnvVariables,
+ },
+ }),
+ });
+ };
+
+ const removeEnvVariable = (index: number) => {
+ if (!selectedVariant) return;
+
+ const updatedEnvVariables = selectedVariant.envVariables.filter(
+ (_, i) => i !== index,
+ );
+
+ setTemplateInfo({
+ ...templateInfo,
+ ...(templateInfo.details && {
+ details: {
+ ...templateInfo.details,
+ envVariables: updatedEnvVariables,
+ },
+ }),
+ });
+ };
+
+ const handleDomainChange = (
+ index: number,
+ field: "host" | "port" | "serviceName",
+ value: string | number,
+ ) => {
+ if (!selectedVariant) return;
+
+ const updatedDomains = [...selectedVariant.domains];
+ // @ts-ignore
+ updatedDomains[index] = {
+ ...updatedDomains[index],
+ [field]: value,
+ };
+
+ setTemplateInfo({
+ ...templateInfo,
+ ...(templateInfo.details && {
+ details: {
+ ...templateInfo.details,
+ domains: updatedDomains,
+ },
+ }),
+ });
+ };
+
+ const removeDomain = (index: number) => {
+ if (!selectedVariant) return;
+
+ const updatedDomains = selectedVariant.domains.filter(
+ (_, i) => i !== index,
+ );
+
+ setTemplateInfo({
+ ...templateInfo,
+ ...(templateInfo.details && {
+ details: {
+ ...templateInfo.details,
+ domains: updatedDomains,
+ },
+ }),
+ });
+ };
+
+ const addEnvVariable = () => {
+ if (!selectedVariant) return;
+
+ setTemplateInfo({
+ ...templateInfo,
+
+ ...(templateInfo.details && {
+ details: {
+ ...templateInfo.details,
+ envVariables: [
+ ...selectedVariant.envVariables,
+ { name: "", value: "" },
+ ],
+ },
+ }),
+ });
+ };
+
+ const addDomain = () => {
+ if (!selectedVariant) return;
+
+ setTemplateInfo({
+ ...templateInfo,
+ ...(templateInfo.details && {
+ details: {
+ ...templateInfo.details,
+ domains: [
+ ...selectedVariant.domains,
+ { host: "", port: 80, serviceName: "" },
+ ],
+ },
+ }),
+ });
+ };
+ if (isError) {
+ return (
+
+
+
Error
+
+ {error?.message || "Error generating suggestions"}
+
+
+ );
+ }
+ if (isLoading) {
+ return (
+
+
+
+ AI is processing your request
+
+
+ Generating template suggestions based on your input...
+
+
{templateInfo.userInput}
+
+ );
+ }
+
+ return (
+
+
+
+
Step 2: Choose a Variant
+ {!selectedVariant && (
+
+
Based on your input, we suggest the following variants:
+
{
+ const element = suggestions?.find((s) => s?.id === value);
+ setTemplateInfo({
+ ...templateInfo,
+ details: element,
+ });
+ }}
+ className="space-y-4"
+ >
+ {suggestions?.map((suggestion) => (
+
+
+
+
+ {suggestion?.name}
+
+
+ {suggestion?.shortDescription}
+
+
+
+ ))}
+
+
+ )}
+ {selectedVariant && (
+ <>
+
+
{selectedVariant?.name}
+
+ {selectedVariant?.shortDescription}
+
+
+
+
+
+ Description
+
+
+
+ {selectedVariant?.description}
+
+
+
+
+
+ Docker Compose
+
+ {
+ setTemplateInfo({
+ ...templateInfo,
+ ...(templateInfo?.details && {
+ details: {
+ ...templateInfo.details,
+ dockerCompose: value,
+ },
+ }),
+ });
+ }}
+ />
+
+
+
+ Environment Variables
+
+
+
+ {selectedVariant?.envVariables.map((env, index) => (
+
+ ))}
+
+
+ Add Variable
+
+
+
+
+
+
+ Domains
+
+
+
+ {selectedVariant?.domains.map((domain, index) => (
+
+
+ handleDomainChange(
+ index,
+ "host",
+ e.target.value,
+ )
+ }
+ placeholder="Domain Host"
+ className="flex-1"
+ />
+
+ handleDomainChange(
+ index,
+ "port",
+ Number.parseInt(e.target.value),
+ )
+ }
+ placeholder="Port"
+ className="w-24"
+ />
+
+ handleDomainChange(
+ index,
+ "serviceName",
+ e.target.value,
+ )
+ }
+ placeholder="Service Name"
+ className="flex-1"
+ />
+ removeDomain(index)}
+ >
+
+
+
+ ))}
+
+
+ Add Domain
+
+
+
+
+
+
+ Configuration Files
+
+
+
+ {selectedVariant?.configFiles?.length > 0 ? (
+ <>
+
+ This template requires the following
+ configuration files to be mounted:
+
+ {selectedVariant.configFiles.map(
+ (config, index) => (
+
+
+
+
+ {config.filePath}
+
+
+ Will be mounted as: ../files
+ {config.filePath}
+
+
+
+
{
+ if (!selectedVariant?.configFiles)
+ return;
+ const updatedConfigFiles = [
+ ...selectedVariant.configFiles,
+ ];
+ updatedConfigFiles[index] = {
+ filePath: config.filePath,
+ content: value,
+ };
+ setTemplateInfo({
+ ...templateInfo,
+ ...(templateInfo.details && {
+ details: {
+ ...templateInfo.details,
+ configFiles: updatedConfigFiles,
+ },
+ }),
+ });
+ }}
+ />
+
+ ),
+ )}
+ >
+ ) : (
+
+
+ This template doesn't require any configuration
+ files.
+
+
+ All necessary configurations are handled through
+ environment variables.
+
+
+ )}
+
+
+
+
+
+
+ >
+ )}
+
+
+
+
+ {selectedVariant && (
+ {
+ const { details, ...rest } = templateInfo;
+ setTemplateInfo(rest);
+ }}
+ variant="outline"
+ >
+ Change Variant
+
+ )}
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/project/ai/template-generator.tsx b/data/apps/dokploy/components/dashboard/project/ai/template-generator.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..7fad2e35d27fbc81a665a518350c154dcb280b0c
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/ai/template-generator.tsx
@@ -0,0 +1,338 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Separator } from "@/components/ui/separator";
+import { api } from "@/utils/api";
+import { defineStepper } from "@stepperize/react";
+import { Bot } from "lucide-react";
+import Link from "next/link";
+import React, { useState } from "react";
+import { toast } from "sonner";
+import { StepOne } from "./step-one";
+import { StepThree } from "./step-three";
+import { StepTwo } from "./step-two";
+
+interface EnvVariable {
+ name: string;
+ value: string;
+}
+
+interface Domain {
+ host: string;
+ port: number;
+ serviceName: string;
+}
+
+interface Details {
+ name: string;
+ id: string;
+ description: string;
+ dockerCompose: string;
+ envVariables: EnvVariable[];
+ shortDescription: string;
+ domains: Domain[];
+ configFiles: Mount[];
+}
+
+interface Mount {
+ filePath: string;
+ content: string;
+}
+
+export interface TemplateInfo {
+ userInput: string;
+ details?: Details | null;
+ suggestions?: Details[];
+ server?: {
+ serverId: string;
+ name: string;
+ };
+ aiId: string;
+}
+
+const defaultTemplateInfo: TemplateInfo = {
+ aiId: "",
+ userInput: "",
+ server: undefined,
+ details: null,
+ suggestions: [],
+};
+
+export const { useStepper, steps, Scoped } = defineStepper(
+ {
+ id: "needs",
+ title: "Describe your needs",
+ },
+ {
+ id: "variant",
+ title: "Choose a Variant",
+ },
+ {
+ id: "review",
+ title: "Review and Finalize",
+ },
+);
+
+interface Props {
+ projectId: string;
+ projectName?: string;
+}
+
+export const TemplateGenerator = ({ projectId }: Props) => {
+ const [open, setOpen] = useState(false);
+ const stepper = useStepper();
+ const { data: aiSettings } = api.ai.getAll.useQuery();
+ const { mutateAsync } = api.ai.deploy.useMutation();
+ const [templateInfo, setTemplateInfo] =
+ useState(defaultTemplateInfo);
+ const utils = api.useUtils();
+
+ const haveAtleasOneProviderEnabled = aiSettings?.some(
+ (ai) => ai.isEnabled === true,
+ );
+
+ const isDisabled = () => {
+ if (stepper.current.id === "needs") {
+ return !templateInfo.aiId || !templateInfo.userInput;
+ }
+
+ if (stepper.current.id === "variant") {
+ return !templateInfo?.details?.id;
+ }
+
+ return false;
+ };
+
+ const onSubmit = async () => {
+ await mutateAsync({
+ projectId,
+ id: templateInfo.details?.id || "",
+ name: templateInfo?.details?.name || "",
+ description: templateInfo?.details?.shortDescription || "",
+ dockerCompose: templateInfo?.details?.dockerCompose || "",
+ envVariables: (templateInfo?.details?.envVariables || [])
+ .map((env: any) => `${env.name}=${env.value}`)
+ .join("\n"),
+ domains: templateInfo?.details?.domains || [],
+ ...(templateInfo.server?.serverId && {
+ serverId: templateInfo.server?.serverId || "",
+ }),
+ configFiles: templateInfo?.details?.configFiles || [],
+ })
+ .then(async () => {
+ toast.success("Compose Created");
+ setOpen(false);
+ await utils.project.one.invalidate({
+ projectId,
+ });
+ })
+ .catch(() => {
+ toast.error("Error creating the compose");
+ });
+ };
+
+ return (
+
+
+ e.preventDefault()}
+ >
+
+ AI Assistant
+
+
+
+
+ AI Assistant
+
+ Create a custom template based on your needs
+
+
+
+
+
Steps
+
+
+ Step {stepper.current.index + 1} of {steps.length}
+
+
+
+
+
+
+
+ {stepper.all.map((step, index, array) => (
+
+
+
+ {index + 1}
+
+ {step.title}
+
+ {index < array.length - 1 && (
+
+ )}
+
+ ))}
+
+
+ {stepper.switch({
+ needs: () => (
+ <>
+ {!haveAtleasOneProviderEnabled && (
+
+
+ AI features are not enabled
+
+ To use AI-powered template generation, please{" "}
+
+ enable AI in your settings
+
+ .
+
+
+
+ )}
+
+ {haveAtleasOneProviderEnabled &&
+ aiSettings &&
+ aiSettings?.length > 0 && (
+
+
+
+ Select AI Provider
+
+
+ setTemplateInfo((prev) => ({
+ ...prev,
+ aiId: value,
+ }))
+ }
+ >
+
+
+
+
+ {aiSettings.map((ai) => (
+
+ {ai.name} ({ai.model})
+
+ ))}
+
+
+
+ {templateInfo.aiId && (
+
+ )}
+
+ )}
+ >
+ ),
+ variant: () => (
+
+ ),
+ review: () => (
+
+ ),
+ })}
+
+
+
+
+
+
+ Back
+
+ {
+ if (stepper.current.id === "needs") {
+ setTemplateInfo((prev) => ({
+ ...prev,
+ suggestions: [],
+ details: null,
+ }));
+ }
+
+ if (stepper.isLast) {
+ await onSubmit();
+ return;
+ }
+ stepper.next();
+ // if (stepper.isLast) {
+ // // setIsOpen(false);
+ // // push("/dashboard/projects");
+ // } else {
+ // stepper.next();
+ // }
+ }}
+ >
+ {stepper.isLast ? "Create" : "Next"}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/project/duplicate-project.tsx b/data/apps/dokploy/components/dashboard/project/duplicate-project.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..ffcfeba87660be24f0da0d0c62c579c7c9824ca2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/project/duplicate-project.tsx
@@ -0,0 +1,208 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { api } from "@/utils/api";
+import { Copy, Loader2 } from "lucide-react";
+import { useRouter } from "next/router";
+import { useState } from "react";
+import { toast } from "sonner";
+
+export type Services = {
+ appName: string;
+ serverId?: string | null;
+ name: string;
+ type:
+ | "mariadb"
+ | "application"
+ | "postgres"
+ | "mysql"
+ | "mongo"
+ | "redis"
+ | "compose";
+ description?: string | null;
+ id: string;
+ createdAt: string;
+ status?: "idle" | "running" | "done" | "error";
+};
+
+interface DuplicateProjectProps {
+ projectId: string;
+ services: Services[];
+ selectedServiceIds: string[];
+}
+
+export const DuplicateProject = ({
+ projectId,
+ services,
+ selectedServiceIds,
+}: DuplicateProjectProps) => {
+ const [open, setOpen] = useState(false);
+ const [name, setName] = useState("");
+ const [description, setDescription] = useState("");
+ const [duplicateType, setDuplicateType] = useState("new-project"); // "new-project" or "same-project"
+ const utils = api.useUtils();
+ const router = useRouter();
+
+ const selectedServices = services.filter((service) =>
+ selectedServiceIds.includes(service.id),
+ );
+
+ const { mutateAsync: duplicateProject, isLoading } =
+ api.project.duplicate.useMutation({
+ onSuccess: async (newProject) => {
+ await utils.project.all.invalidate();
+ toast.success(
+ duplicateType === "new-project"
+ ? "Project duplicated successfully"
+ : "Services duplicated successfully",
+ );
+ setOpen(false);
+ if (duplicateType === "new-project") {
+ router.push(`/dashboard/project/${newProject.projectId}`);
+ }
+ },
+ onError: (error) => {
+ toast.error(error.message);
+ },
+ });
+
+ const handleDuplicate = async () => {
+ if (duplicateType === "new-project" && !name) {
+ toast.error("Project name is required");
+ return;
+ }
+
+ await duplicateProject({
+ sourceProjectId: projectId,
+ name,
+ description,
+ includeServices: true,
+ selectedServices: selectedServices.map((service) => ({
+ id: service.id,
+ type: service.type,
+ })),
+ duplicateInSameProject: duplicateType === "same-project",
+ });
+ };
+
+ return (
+ {
+ setOpen(isOpen);
+ if (!isOpen) {
+ // Reset form when closing
+ setName("");
+ setDescription("");
+ setDuplicateType("new-project");
+ }
+ }}
+ >
+
+
+
+ Duplicate
+
+
+
+
+ Duplicate Services
+
+ Choose where to duplicate the selected services
+
+
+
+
+
+
Duplicate to
+
+
+
+ New project
+
+
+
+ Same project
+
+
+
+
+ {duplicateType === "new-project" && (
+ <>
+
+ Name
+ setName(e.target.value)}
+ placeholder="New project name"
+ />
+
+
+
+ Description
+ setDescription(e.target.value)}
+ placeholder="Project description (optional)"
+ />
+
+ >
+ )}
+
+
+
Selected services to duplicate
+
+ {selectedServices.map((service) => (
+
+
+ {service.name} ({service.type})
+
+
+ ))}
+
+
+
+
+
+ setOpen(false)}
+ disabled={isLoading}
+ >
+ Cancel
+
+
+ {isLoading ? (
+ <>
+
+ {duplicateType === "new-project"
+ ? "Duplicating project..."
+ : "Duplicating services..."}
+ >
+ ) : duplicateType === "new-project" ? (
+ "Duplicate project"
+ ) : (
+ "Duplicate services"
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/projects/handle-project.tsx b/data/apps/dokploy/components/dashboard/projects/handle-project.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..ddc1303e469d66397cad20f49879aaca3d9ef36a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/projects/handle-project.tsx
@@ -0,0 +1,197 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PlusIcon, SquarePen } from "lucide-react";
+import { useRouter } from "next/router";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const AddProjectSchema = z.object({
+ name: z
+ .string()
+ .min(1, "Project name is required")
+ .refine(
+ (name) => {
+ const trimmedName = name.trim();
+ const validNameRegex =
+ /^[\p{L}\p{N}_-][\p{L}\p{N}\s_-]*[\p{L}\p{N}_-]$/u;
+ return validNameRegex.test(trimmedName);
+ },
+ {
+ message:
+ "Project name must start and end with a letter, number, hyphen or underscore. Spaces are allowed in between.",
+ },
+ )
+ .refine((name) => !/^\d/.test(name.trim()), {
+ message: "Project name cannot start with a number",
+ })
+ .transform((name) => name.trim()),
+ description: z.string().optional(),
+});
+
+type AddProject = z.infer;
+
+interface Props {
+ projectId?: string;
+}
+
+export const HandleProject = ({ projectId }: Props) => {
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+
+ const { mutateAsync, error, isError } = projectId
+ ? api.project.update.useMutation()
+ : api.project.create.useMutation();
+
+ const { data, refetch } = api.project.one.useQuery(
+ {
+ projectId: projectId || "",
+ },
+ {
+ enabled: !!projectId,
+ },
+ );
+ const router = useRouter();
+ const form = useForm({
+ defaultValues: {
+ description: "",
+ name: "",
+ },
+ resolver: zodResolver(AddProjectSchema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ description: data?.description ?? "",
+ name: data?.name ?? "",
+ });
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data]);
+
+ const onSubmit = async (data: AddProject) => {
+ await mutateAsync({
+ name: data.name,
+ description: data.description,
+ projectId: projectId || "",
+ })
+ .then(async (data) => {
+ await utils.project.all.invalidate();
+ toast.success(projectId ? "Project Updated" : "Project Created");
+ setIsOpen(false);
+ if (!projectId) {
+ router.push(`/dashboard/project/${data?.projectId}`);
+ } else {
+ refetch();
+ }
+ })
+ .catch(() => {
+ toast.error(
+ projectId ? "Error updating a project" : "Error creating a project",
+ );
+ });
+ };
+
+ return (
+
+
+ {projectId ? (
+ e.preventDefault()}
+ >
+
+ Update
+
+ ) : (
+
+
+ Create Project
+
+ )}
+
+
+
+ {projectId ? "Update" : "Add a"} project
+ The home of something big!
+
+ {isError && {error?.message} }
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+
+
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ {projectId ? "Update" : "Create"}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/projects/project-environment.tsx b/data/apps/dokploy/components/dashboard/projects/project-environment.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e43d1af87145d80c9a387ddd51421877f2c06384
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/projects/project-environment.tsx
@@ -0,0 +1,154 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { FileIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const updateProjectSchema = z.object({
+ env: z.string().optional(),
+});
+
+type UpdateProject = z.infer;
+
+interface Props {
+ projectId: string;
+ children?: React.ReactNode;
+}
+
+export const ProjectEnvironment = ({ projectId, children }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const utils = api.useUtils();
+ const { mutateAsync, error, isError, isLoading } =
+ api.project.update.useMutation();
+ const { data } = api.project.one.useQuery(
+ {
+ projectId,
+ },
+ {
+ enabled: !!projectId,
+ },
+ );
+
+ const form = useForm({
+ defaultValues: {
+ env: data?.env ?? "",
+ },
+ resolver: zodResolver(updateProjectSchema),
+ });
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ env: data.env ?? "",
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: UpdateProject) => {
+ await mutateAsync({
+ env: formData.env || "",
+ projectId: projectId,
+ })
+ .then(() => {
+ toast.success("Project env updated successfully");
+ utils.project.all.invalidate();
+ })
+ .catch(() => {
+ toast.error("Error updating the env");
+ })
+ .finally(() => {});
+ };
+
+ return (
+
+
+ {children ?? (
+ e.preventDefault()}
+ >
+
+ Project Environment
+
+ )}
+
+
+
+ Project Environment
+
+ Update the env Environment variables that are accessible to all
+ services of this project.
+
+
+ {isError && {error?.message} }
+
+ Use this syntax to reference project-level variables in your service
+ environments: DATABASE_URL=${"{{project.DATABASE_URL}}"}
+
+
+
+
+
+ (
+
+ Environment variables
+
+
+
+
+
+
+
+
+ )}
+ />
+
+
+ Update
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/projects/show.tsx b/data/apps/dokploy/components/dashboard/projects/show.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..03ebe7a85f78a23f9b8da7c411e7ff8fd89a9dbb
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/projects/show.tsx
@@ -0,0 +1,393 @@
+import { BreadcrumbSidebar } from "@/components/shared/breadcrumb-sidebar";
+import { DateTooltip } from "@/components/shared/date-tooltip";
+import { StatusTooltip } from "@/components/shared/status-tooltip";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import {
+ AlertTriangle,
+ BookIcon,
+ ExternalLinkIcon,
+ FolderInput,
+ Loader2,
+ MoreHorizontalIcon,
+ Search,
+ TrashIcon,
+} from "lucide-react";
+import Link from "next/link";
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+import { HandleProject } from "./handle-project";
+import { ProjectEnvironment } from "./project-environment";
+
+export const ShowProjects = () => {
+ const utils = api.useUtils();
+ const { data, isLoading } = api.project.all.useQuery();
+ const { data: auth } = api.user.get.useQuery();
+ const { mutateAsync } = api.project.remove.useMutation();
+ const [searchQuery, setSearchQuery] = useState("");
+
+ const filteredProjects = useMemo(() => {
+ if (!data) return [];
+ return data.filter(
+ (project) =>
+ project.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ project.description?.toLowerCase().includes(searchQuery.toLowerCase()),
+ );
+ }, [data, searchQuery]);
+
+ return (
+ <>
+
+
+
+
+
+
+
+
+ Projects
+
+
+ Create and manage your projects
+
+
+
+ {(auth?.role === "owner" || auth?.canCreateProjects) && (
+
+
+
+ )}
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+
+ setSearchQuery(e.target.value)}
+ className="pr-10"
+ />
+
+
+ {filteredProjects?.length === 0 && (
+
+
+
+ No projects found
+
+
+ )}
+
+ {filteredProjects?.map((project) => {
+ const emptyServices =
+ project?.mariadb.length === 0 &&
+ project?.mongo.length === 0 &&
+ project?.mysql.length === 0 &&
+ project?.postgres.length === 0 &&
+ project?.redis.length === 0 &&
+ project?.applications.length === 0 &&
+ project?.compose.length === 0;
+
+ const totalServices =
+ project?.mariadb.length +
+ project?.mongo.length +
+ project?.mysql.length +
+ project?.postgres.length +
+ project?.redis.length +
+ project?.applications.length +
+ project?.compose.length;
+
+ return (
+
+
+
+ {project.applications.length > 0 ||
+ project.compose.length > 0 ? (
+
+
+
+
+
+
+ e.stopPropagation()}
+ >
+ {project.applications.length > 0 && (
+
+
+ Applications
+
+ {project.applications.map((app) => (
+
+
+
+
+ {app.name}
+
+
+
+ {app.domains.map((domain) => (
+
+
+
+ {domain.host}
+
+
+
+
+ ))}
+
+
+ ))}
+
+ )}
+ {project.compose.length > 0 && (
+
+
+ Compose
+
+ {project.compose.map((comp) => (
+
+
+
+
+ {comp.name}
+
+
+
+ {comp.domains.map((domain) => (
+
+
+
+ {domain.host}
+
+
+
+
+ ))}
+
+
+ ))}
+
+ )}
+
+
+ ) : null}
+
+
+
+
+
+
+ {project.name}
+
+
+
+
+ {project.description}
+
+
+
+
+
+
+
+
+
+ e.stopPropagation()}
+ >
+
+ Actions
+
+ e.stopPropagation()}
+ >
+
+
+ e.stopPropagation()}
+ >
+
+
+
+ e.stopPropagation()}
+ >
+ {(auth?.role === "owner" ||
+ auth?.canDeleteProjects) && (
+
+
+
+ e.preventDefault()
+ }
+ >
+
+ Delete
+
+
+
+
+
+ Are you sure to delete this
+ project?
+
+ {!emptyServices ? (
+
+
+
+ You have active
+ services, please delete
+ them first
+
+
+ ) : (
+
+ This action cannot be
+ undone
+
+ )}
+
+
+
+ Cancel
+
+ {
+ await mutateAsync({
+ projectId:
+ project.projectId,
+ })
+ .then(() => {
+ toast.success(
+ "Project deleted successfully",
+ );
+ })
+ .catch(() => {
+ toast.error(
+ "Error deleting this project",
+ );
+ })
+ .finally(() => {
+ utils.project.all.invalidate();
+ });
+ }}
+ >
+ Delete
+
+
+
+
+ )}
+
+
+
+
+
+
+
+
+
+ Created
+
+
+ {totalServices}{" "}
+ {totalServices === 1
+ ? "service"
+ : "services"}
+
+
+
+
+
+
+ );
+ })}
+
+ >
+ )}
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/redis/general/show-external-redis-credentials.tsx b/data/apps/dokploy/components/dashboard/redis/general/show-external-redis-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..46cb09530b081bda3122d5276a6399a132206612
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/redis/general/show-external-redis-credentials.tsx
@@ -0,0 +1,168 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const DockerProviderSchema = z.object({
+ externalPort: z.preprocess((a) => {
+ if (a !== null) {
+ const parsed = Number.parseInt(z.string().parse(a), 10);
+ return Number.isNaN(parsed) ? null : parsed;
+ }
+ return null;
+ }, z
+ .number()
+ .gte(0, "Range must be 0 - 65535")
+ .lte(65535, "Range must be 0 - 65535")
+ .nullable()),
+});
+
+type DockerProvider = z.infer;
+
+interface Props {
+ redisId: string;
+}
+export const ShowExternalRedisCredentials = ({ redisId }: Props) => {
+ const { data: ip } = api.settings.getIp.useQuery();
+ const { data, refetch } = api.redis.one.useQuery({ redisId });
+ const { mutateAsync, isLoading } = api.redis.saveExternalPort.useMutation();
+ const [connectionUrl, setConnectionUrl] = useState("");
+ const getIp = data?.server?.ipAddress || ip;
+
+ const form = useForm({
+ defaultValues: {},
+ resolver: zodResolver(DockerProviderSchema),
+ });
+
+ useEffect(() => {
+ if (data?.externalPort) {
+ form.reset({
+ externalPort: data.externalPort,
+ });
+ }
+ }, [form.reset, data, form]);
+
+ const onSubmit = async (values: DockerProvider) => {
+ await mutateAsync({
+ externalPort: values.externalPort,
+ redisId,
+ })
+ .then(async () => {
+ toast.success("External Port updated");
+ await refetch();
+ })
+ .catch(() => {
+ toast.error("Error saving the external port");
+ });
+ };
+
+ useEffect(() => {
+ const buildConnectionUrl = () => {
+ const _hostname = window.location.hostname;
+ const port = form.watch("externalPort") || data?.externalPort;
+
+ return `redis://default:${data?.databasePassword}@${getIp}:${port}`;
+ };
+
+ setConnectionUrl(buildConnectionUrl());
+ }, [data?.appName, data?.externalPort, data?.databasePassword, form, getIp]);
+ return (
+ <>
+
+
+
+ External Credentials
+
+ In order to make the database reachable trought internet is
+ required to set a port, make sure the port is not used by another
+ application or database
+
+
+
+ {!getIp && (
+
+ You need to set an IP address in your{" "}
+
+ {data?.serverId
+ ? "Remote Servers -> Server -> Edit Server -> Update IP Address"
+ : "Web Server -> Server -> Update Server IP"}
+ {" "}
+ to fix the database url connection.
+
+ )}
+
+
+
+
+ {
+ return (
+
+ External Port (Internet)
+
+
+
+
+
+ );
+ }}
+ />
+
+
+ {!!data?.externalPort && (
+
+ )}
+
+
+
+ Save
+
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/redis/general/show-general-redis.tsx b/data/apps/dokploy/components/dashboard/redis/general/show-general-redis.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..59a123bd903c95b851d40355ac0f159b90d88ab3
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/redis/general/show-general-redis.tsx
@@ -0,0 +1,261 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { DrawerLogs } from "@/components/shared/drawer-logs";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+import { Ban, CheckCircle2, RefreshCcw, Rocket, Terminal } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { type LogLine, parseLogs } from "../../docker/logs/utils";
+import { DockerTerminalModal } from "../../settings/web-server/docker-terminal-modal";
+
+interface Props {
+ redisId: string;
+}
+
+export const ShowGeneralRedis = ({ redisId }: Props) => {
+ const { data, refetch } = api.redis.one.useQuery(
+ {
+ redisId,
+ },
+ { enabled: !!redisId },
+ );
+
+ const { mutateAsync: reload, isLoading: isReloading } =
+ api.redis.reload.useMutation();
+ const { mutateAsync: start, isLoading: isStarting } =
+ api.redis.start.useMutation();
+
+ const { mutateAsync: stop, isLoading: isStopping } =
+ api.redis.stop.useMutation();
+
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [filteredLogs, setFilteredLogs] = useState([]);
+ const [isDeploying, setIsDeploying] = useState(false);
+ api.redis.deployWithLogs.useSubscription(
+ {
+ redisId: redisId,
+ },
+ {
+ enabled: isDeploying,
+ onData(log) {
+ if (!isDrawerOpen) {
+ setIsDrawerOpen(true);
+ }
+
+ if (log === "Deployment completed successfully!") {
+ setIsDeploying(false);
+ }
+ const parsedLogs = parseLogs(log);
+ setFilteredLogs((prev) => [...prev, ...parsedLogs]);
+ },
+ onError(error) {
+ console.error("Deployment logs error:", error);
+ setIsDeploying(false);
+ },
+ },
+ );
+
+ return (
+ <>
+
+
+
+ Deploy Settings
+
+
+
+ {
+ setIsDeploying(true);
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ refetch();
+ }}
+ >
+
+
+
+
+
+ Deploy
+
+
+
+
+ Downloads and sets up the Redis database
+
+
+
+
+
+ {
+ await reload({
+ redisId: redisId,
+ appName: data?.appName || "",
+ })
+ .then(() => {
+ toast.success("Redis reloaded successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error reloading Redis");
+ });
+ }}
+ >
+
+
+
+
+
+ Reload
+
+
+
+
+ Restart the Redis service without rebuilding
+
+
+
+
+
+ {data?.applicationStatus === "idle" ? (
+ {
+ await start({
+ redisId: redisId,
+ })
+ .then(() => {
+ toast.success("Redis started successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error starting Redis");
+ });
+ }}
+ >
+
+
+
+
+
+ Start
+
+
+
+
+
+ Start the Redis database (requires a previous
+ successful setup)
+
+
+
+
+
+
+ ) : (
+ {
+ await stop({
+ redisId: redisId,
+ })
+ .then(() => {
+ toast.success("Redis stopped successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error stopping Redis");
+ });
+ }}
+ >
+
+
+
+
+
+ Stop
+
+
+
+
+ Stop the currently running Redis database
+
+
+
+
+
+ )}
+
+
+
+
+
+
+
+ Open Terminal
+
+
+
+
+ Open a terminal to the Redis container
+
+
+
+
+
+
+
+
{
+ setIsDrawerOpen(false);
+ setFilteredLogs([]);
+ setIsDeploying(false);
+ refetch();
+ }}
+ filteredLogs={filteredLogs}
+ />
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/redis/general/show-internal-redis-credentials.tsx b/data/apps/dokploy/components/dashboard/redis/general/show-internal-redis-credentials.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..47ad0df0b73032d5703780d33cc4c29d60bb2fd6
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/redis/general/show-internal-redis-credentials.tsx
@@ -0,0 +1,57 @@
+import { ToggleVisibilityInput } from "@/components/shared/toggle-visibility-input";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+
+interface Props {
+ redisId: string;
+}
+export const ShowInternalRedisCredentials = ({ redisId }: Props) => {
+ const { data } = api.redis.one.useQuery({ redisId });
+ return (
+ <>
+
+
+
+ Internal Credentials
+
+
+
+
+ User
+
+
+
+
+ Internal Port (Container)
+
+
+
+
+ Internal Host
+
+
+
+
+ Internal Connection URL
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/redis/update-redis.tsx b/data/apps/dokploy/components/dashboard/redis/update-redis.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8d720703ea9468d9454be34daabb5e72b01664b0
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/redis/update-redis.tsx
@@ -0,0 +1,163 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const updateRedisSchema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ description: z.string().optional(),
+});
+
+type UpdateRedis = z.infer;
+
+interface Props {
+ redisId: string;
+}
+
+export const UpdateRedis = ({ redisId }: Props) => {
+ const utils = api.useUtils();
+ const { mutateAsync, error, isError, isLoading } =
+ api.redis.update.useMutation();
+ const { data } = api.redis.one.useQuery(
+ {
+ redisId,
+ },
+ {
+ enabled: !!redisId,
+ },
+ );
+ const form = useForm({
+ defaultValues: {
+ description: data?.description ?? "",
+ name: data?.name ?? "",
+ },
+ resolver: zodResolver(updateRedisSchema),
+ });
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ description: data.description ?? "",
+ name: data.name,
+ });
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (formData: UpdateRedis) => {
+ await mutateAsync({
+ name: formData.name,
+ redisId: redisId,
+ description: formData.description || "",
+ })
+ .then(() => {
+ toast.success("Redis updated successfully");
+ utils.redis.one.invalidate({
+ redisId: redisId,
+ });
+ })
+ .catch(() => {
+ toast.error("Error updating Redis");
+ })
+ .finally(() => {});
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Modify Redis
+ Update the redis data
+
+ {isError && {error?.message} }
+
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+
+
+ Update
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/requests/columns.tsx b/data/apps/dokploy/components/dashboard/requests/columns.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2c0391f801d3acbc8f489d33f70a2e7601254767
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/requests/columns.tsx
@@ -0,0 +1,97 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import type { ColumnDef } from "@tanstack/react-table";
+import { format } from "date-fns";
+import { ArrowUpDown } from "lucide-react";
+import type { LogEntry } from "./show-requests";
+
+export const getStatusColor = (status: number) => {
+ if (status >= 100 && status < 200) {
+ return "outline";
+ }
+ if (status >= 200 && status < 300) {
+ return "default";
+ }
+ if (status >= 300 && status < 400) {
+ return "outline";
+ }
+ if (status >= 400 && status < 500) {
+ return "destructive";
+ }
+ return "destructive";
+};
+
+export const columns: ColumnDef[] = [
+ {
+ accessorKey: "level",
+ header: () => {
+ return Level ;
+ },
+ cell: ({ row }) => {
+ return {row.original.level}
;
+ },
+ },
+ {
+ accessorKey: "RequestPath",
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Message
+
+
+ );
+ },
+ cell: ({ row }) => {
+ const log = row.original;
+ return (
+
+
+ {log.RequestMethod}{" "}
+
+ {log.RequestAddr}
+
+ {log.RequestPath.length > 100
+ ? `${log.RequestPath.slice(0, 82)}...`
+ : log.RequestPath}
+
+
+
+ Status: {log.OriginStatus}
+
+
+ Exec Time: {`${log.Duration / 1000000000}s`}
+
+ IP: {log.ClientAddr}
+
+
+ );
+ },
+ },
+ {
+ accessorKey: "time",
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Time
+
+
+ );
+ },
+ cell: ({ row }) => {
+ const log = row.original;
+ return (
+
+
+ {format(new Date(log.StartUTC), "yyyy-MM-dd HH:mm:ss")}
+
+
+ );
+ },
+ },
+];
diff --git a/data/apps/dokploy/components/dashboard/requests/request-distribution-chart.tsx b/data/apps/dokploy/components/dashboard/requests/request-distribution-chart.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..cf4b4ded465be1ed4474c9d985afc1746f4a7ff6
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/requests/request-distribution-chart.tsx
@@ -0,0 +1,99 @@
+import {
+ type ChartConfig,
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+} from "@/components/ui/chart";
+import { api } from "@/utils/api";
+import {
+ Area,
+ AreaChart,
+ CartesianGrid,
+ ResponsiveContainer,
+ XAxis,
+ YAxis,
+} from "recharts";
+
+export interface RequestDistributionChartProps {
+ dateRange?: {
+ from: Date | undefined;
+ to: Date | undefined;
+ };
+}
+
+const chartConfig = {
+ views: {
+ label: "Page Views",
+ },
+ count: {
+ label: "Count",
+ color: "hsl(var(--chart-1))",
+ },
+} satisfies ChartConfig;
+
+export const RequestDistributionChart = ({
+ dateRange,
+}: RequestDistributionChartProps) => {
+ const { data: stats } = api.settings.readStats.useQuery(
+ {
+ dateRange: dateRange
+ ? {
+ start: dateRange.from?.toISOString(),
+ end: dateRange.to?.toISOString(),
+ }
+ : undefined,
+ },
+ {
+ refetchInterval: 1333,
+ },
+ );
+
+ return (
+
+
+
+
+
+ new Date(value).toLocaleTimeString([], {
+ hour: "2-digit",
+ minute: "2-digit",
+ })
+ }
+ />
+
+ }
+ labelFormatter={(value) =>
+ new Date(value).toLocaleString([], {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ })
+ }
+ />
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/requests/requests-table.tsx b/data/apps/dokploy/components/dashboard/requests/requests-table.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..3f6fe6e3396e1447e3b01750898b074de4e9a00f
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/requests/requests-table.tsx
@@ -0,0 +1,384 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { api } from "@/utils/api";
+import {
+ type ColumnFiltersState,
+ type PaginationState,
+ type SortingState,
+ type VisibilityState,
+ flexRender,
+ getCoreRowModel,
+ getFilteredRowModel,
+ getSortedRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import copy from "copy-to-clipboard";
+import {
+ CheckCircle2Icon,
+ ChevronDown,
+ Copy,
+ Download,
+ Globe,
+ InfoIcon,
+ Server,
+ TrendingUpIcon,
+} from "lucide-react";
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+import { columns, getStatusColor } from "./columns";
+import type { LogEntry } from "./show-requests";
+import { DataTableFacetedFilter } from "./status-request-filter";
+
+export const priorities = [
+ {
+ label: "100 - 199",
+ value: "info",
+ icon: InfoIcon,
+ },
+ {
+ label: "200 - 299",
+ value: "success",
+ icon: CheckCircle2Icon,
+ },
+ {
+ label: "300 - 399",
+ value: "redirect",
+ icon: TrendingUpIcon,
+ },
+ {
+ label: "400 - 499",
+ value: "client",
+ icon: Globe,
+ },
+ {
+ label: "500 - 599",
+ value: "server",
+ icon: Server,
+ },
+];
+
+export interface RequestsTableProps {
+ dateRange?: {
+ from: Date | undefined;
+ to: Date | undefined;
+ };
+}
+
+export const RequestsTable = ({ dateRange }: RequestsTableProps) => {
+ const [statusFilter, setStatusFilter] = useState([]);
+ const [search, setSearch] = useState("");
+ const [selectedRow, setSelectedRow] = useState();
+ const [sorting, setSorting] = useState([]);
+ const [columnVisibility, setColumnVisibility] = useState({});
+ const [rowSelection, setRowSelection] = useState({});
+ const [columnFilters, setColumnFilters] = useState([]);
+ const [pagination, setPagination] = useState({
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ const { data: statsLogs } = api.settings.readStatsLogs.useQuery(
+ {
+ sort: sorting[0],
+ page: pagination,
+ search,
+ status: statusFilter,
+ dateRange: dateRange
+ ? {
+ start: dateRange.from?.toISOString(),
+ end: dateRange.to?.toISOString(),
+ }
+ : undefined,
+ },
+ {
+ refetchInterval: 1333,
+ },
+ );
+
+ const pageCount = useMemo(() => {
+ if (statsLogs?.totalCount) {
+ return Math.ceil(statsLogs.totalCount / pagination.pageSize);
+ }
+ return -1;
+ }, [statsLogs?.totalCount, pagination.pageSize]);
+
+ const table = useReactTable({
+ data: statsLogs?.data ?? [],
+ columns,
+ onPaginationChange: setPagination,
+ onSortingChange: setSorting,
+ pageCount: pageCount,
+ onColumnFiltersChange: setColumnFilters,
+ getCoreRowModel: getCoreRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ getFilteredRowModel: getFilteredRowModel(),
+ onColumnVisibilityChange: setColumnVisibility,
+ onRowSelectionChange: setRowSelection,
+ manualPagination: true,
+ state: {
+ pagination,
+ sorting,
+ columnFilters,
+ columnVisibility,
+ rowSelection,
+ },
+ });
+
+ const formatValue = (key: string, value: any) => {
+ if (typeof value === "object" && value !== null) {
+ return JSON.stringify(value, null, 2);
+ }
+ if (key === "Duration" || key === "OriginDuration" || key === "Overhead") {
+ return `${value / 1000000000} s`;
+ }
+ if (key === "level") {
+ return {value} ;
+ }
+ if (key === "RequestMethod") {
+ return {value} ;
+ }
+ if (key === "DownstreamStatus" || key === "OriginStatus") {
+ return {value} ;
+ }
+ return value;
+ };
+
+ return (
+ <>
+
+
+
+
+ setSearch(event.target.value)}
+ className="md:max-w-sm"
+ />
+
+
+
+
+ Columns
+
+
+
+ {table
+ .getAllColumns()
+ .filter((column) => column.getCanHide())
+ .map((column) => {
+ return (
+
+ column.toggleVisibility(!!value)
+ }
+ >
+ {column.id}
+
+ );
+ })}
+
+
+
+
+
+
+ {table.getHeaderGroups().map((headerGroup) => (
+
+ {headerGroup.headers.map((header) => {
+ return (
+
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+
+ );
+ })}
+
+ ))}
+
+
+ {table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ {
+ setSelectedRow(row.original);
+ }}
+ data-state={row.getIsSelected() && "selected"}
+ >
+ {row.getVisibleCells().map((cell) => (
+
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+
+ ))}
+
+ ))
+ ) : (
+
+
+ {statsLogs?.data.length === 0 && (
+
+
+ No results.
+
+
+ )}
+
+
+ )}
+
+
+
+
+ {statsLogs?.totalCount && (
+
+ Showing{" "}
+ {Math.min(
+ pagination.pageIndex * pagination.pageSize + 1,
+ statsLogs.totalCount,
+ )}{" "}
+ to{" "}
+ {Math.min(
+ (pagination.pageIndex + 1) * pagination.pageSize,
+ statsLogs.totalCount,
+ )}{" "}
+ of {statsLogs.totalCount} entries
+
+ )}
+
+ table.previousPage()}
+ disabled={!table.getCanPreviousPage()}
+ >
+ Previous
+
+ table.nextPage()}
+ disabled={!table.getCanNextPage()}
+ >
+ Next
+
+
+
+
+
+
+ setSelectedRow(undefined)}
+ >
+
+
+ Request log
+
+ Details of the request log entry.
+
+
+
+
+
+
+ {Object.entries(selectedRow || {}).map(([key, value]) => (
+
+ {key}
+
+ {key === "RequestAddr" ? (
+
+ {value}
+ {
+ copy(value);
+ toast.success("Copied to clipboard");
+ }}
+ className="h-4 w-4 text-muted-foreground cursor-pointer"
+ />
+
+ ) : (
+ formatValue(key, value)
+ )}
+
+
+ ))}
+
+
+
+
+
+ {
+ const logs = JSON.stringify(selectedRow, null, 2);
+ const element = document.createElement("a");
+ element.setAttribute(
+ "href",
+ `data:text/plain;charset=utf-8,${encodeURIComponent(logs)}`,
+ );
+ element.setAttribute("download", "logs.json");
+
+ element.style.display = "none";
+ document.body.appendChild(element);
+
+ element.click();
+
+ document.body.removeChild(element);
+ }}
+ >
+
+ Download as JSON
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/requests/show-requests.tsx b/data/apps/dokploy/components/dashboard/requests/show-requests.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..aad4f011f340a28741a96f58ebe5014ed00af285
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/requests/show-requests.tsx
@@ -0,0 +1,248 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import { Calendar } from "@/components/ui/calendar";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { type RouterOutputs, api } from "@/utils/api";
+import { format } from "date-fns";
+import {
+ AlertCircle,
+ ArrowDownUp,
+ Calendar as CalendarIcon,
+ InfoIcon,
+} from "lucide-react";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import { RequestDistributionChart } from "./request-distribution-chart";
+import { RequestsTable } from "./requests-table";
+
+export type LogEntry = NonNullable<
+ RouterOutputs["settings"]["readStatsLogs"]["data"]
+>[0];
+
+export const ShowRequests = () => {
+ const { data: isActive, refetch } =
+ api.settings.haveActivateRequests.useQuery();
+ const { mutateAsync: toggleRequests } =
+ api.settings.toggleRequests.useMutation();
+
+ const { data: logCleanupStatus } =
+ api.settings.getLogCleanupStatus.useQuery();
+ const { mutateAsync: updateLogCleanup } =
+ api.settings.updateLogCleanup.useMutation();
+ const [cronExpression, setCronExpression] = useState(null);
+ const [dateRange, setDateRange] = useState<{
+ from: Date | undefined;
+ to: Date | undefined;
+ }>({
+ from: undefined,
+ to: undefined,
+ });
+
+ useEffect(() => {
+ if (logCleanupStatus) {
+ setCronExpression(logCleanupStatus.cronExpression || "0 0 * * *");
+ }
+ }, [logCleanupStatus]);
+
+ return (
+ <>
+
+
+
+
+
+
+ Requests
+
+
+ See all the incoming requests that pass trough Traefik
+
+
+
+ When you activate, you need to reload traefik to apply the
+ changes, you can reload traefik in{" "}
+
+ Settings
+
+
+
+
+
+
+
+
+ Log Cleanup Schedule
+
+
+
+
+
+
+
+
+ At the scheduled time, the cleanup job will keep
+ only the last 1000 entries in the access log file
+ and signal Traefik to reopen its log files. The
+ default schedule is daily at midnight (0 0 * * *).
+
+
+
+
+
+
+ setCronExpression(e.target.value)}
+ className="max-w-60"
+ required
+ />
+ {
+ if (!cronExpression?.trim()) {
+ toast.error("Please enter a valid cron expression");
+ return;
+ }
+ try {
+ await updateLogCleanup({
+ cronExpression: cronExpression,
+ });
+ toast.success("Log cleanup schedule updated");
+ } catch (error) {
+ toast.error(
+ `Failed to update log cleanup schedule: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+ }}
+ >
+ Update Schedule
+
+
+
+
{
+ await toggleRequests({ enable: !isActive })
+ .then(() => {
+ refetch();
+ toast.success(
+ `Requests ${isActive ? "deactivated" : "activated"}`,
+ );
+ })
+ .catch((err) => {
+ toast.error(err.message);
+ });
+ }}
+ >
+ {isActive ? "Deactivate" : "Activate"}
+
+
+
+ {isActive ? (
+ <>
+
+ {(dateRange.from || dateRange.to) && (
+
+ setDateRange({ from: undefined, to: undefined })
+ }
+ className="px-3"
+ >
+ Clear dates
+
+ )}
+
+
+
+
+ {dateRange.from ? (
+ dateRange.to ? (
+ <>
+ {format(dateRange.from, "LLL dd, y")} -{" "}
+ {format(dateRange.to, "LLL dd, y")}
+ >
+ ) : (
+ format(dateRange.from, "LLL dd, y")
+ )
+ ) : (
+ Pick a date range
+ )}
+
+
+
+ {
+ setDateRange({
+ from: range?.from,
+ to: range?.to,
+ });
+ }}
+ numberOfMonths={2}
+ />
+
+
+
+
+
+ >
+ ) : (
+
+
+
+
+ Requests are not activated
+
+
+ Activate requests to see incoming traffic statistics and
+ monitor your application's usage. After activation, you'll
+ need to reload Traefik for the changes to take effect.
+
+
+
+ )}
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/requests/status-request-filter.tsx b/data/apps/dokploy/components/dashboard/requests/status-request-filter.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2dd8f05941d5c5743e0ed922842b09187a45c97e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/requests/status-request-filter.tsx
@@ -0,0 +1,138 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Separator } from "@/components/ui/separator";
+import { cn } from "@/lib/utils";
+import { CheckIcon, PlusCircle } from "lucide-react";
+
+interface DataTableFacetedFilterProps {
+ value?: string[];
+ setValue?: (value: string[]) => void;
+ title?: string;
+ options: {
+ label: string;
+ value: string;
+ icon?: React.ComponentType<{ className?: string }>;
+ }[];
+}
+
+export function DataTableFacetedFilter({
+ value = [],
+ setValue,
+ title,
+ options,
+}: DataTableFacetedFilterProps) {
+ const selectedValues = new Set(value as string[]);
+
+ return (
+
+
+
+
+ {title}
+ {selectedValues?.size > 0 && (
+ <>
+
+
+ {selectedValues.size}
+
+
+ {selectedValues.size > 2 ? (
+
+ {selectedValues.size} selected
+
+ ) : (
+ options
+ .filter((option) => selectedValues.has(option.value))
+ .map((option) => (
+
+ {option.label}
+
+ ))
+ )}
+
+ >
+ )}
+
+
+
+
+
+
+ No results found.
+
+ {options.map((option) => {
+ const isSelected = selectedValues.has(option.value);
+ return (
+ {
+ if (isSelected) {
+ selectedValues.delete(option.value);
+ } else {
+ selectedValues.add(option.value);
+ }
+ const filterValues = Array.from(selectedValues);
+ setValue?.(filterValues.length ? filterValues : []);
+ }}
+ >
+
+
+
+ {option.icon && (
+
+ )}
+ {option.label}
+
+ );
+ })}
+
+ {selectedValues.size > 0 && (
+ <>
+
+
+ setValue?.([])}
+ className="justify-center text-center"
+ >
+ Clear filters
+
+
+ >
+ )}
+
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/search-command.tsx b/data/apps/dokploy/components/dashboard/search-command.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..b36703036ab29f9fd7ea76b10a28bfbb5a5391ca
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/search-command.tsx
@@ -0,0 +1,187 @@
+"use client";
+
+import {
+ MariadbIcon,
+ MongodbIcon,
+ MysqlIcon,
+ PostgresqlIcon,
+ RedisIcon,
+} from "@/components/icons/data-tools-icons";
+import {
+ CommandDialog,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@/components/ui/command";
+import { authClient } from "@/lib/auth-client";
+import {
+ type Services,
+ extractServices,
+} from "@/pages/dashboard/project/[projectId]";
+import { api } from "@/utils/api";
+import { BookIcon, CircuitBoard, GlobeIcon } from "lucide-react";
+import { useRouter } from "next/router";
+import React from "react";
+import { StatusTooltip } from "../shared/status-tooltip";
+
+export const SearchCommand = () => {
+ const router = useRouter();
+ const [open, setOpen] = React.useState(false);
+ const [search, setSearch] = React.useState("");
+ const { data: session } = authClient.useSession();
+ const { data } = api.project.all.useQuery(undefined, {
+ enabled: !!session,
+ });
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+
+ React.useEffect(() => {
+ const down = (e: KeyboardEvent) => {
+ if (e.key === "j" && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ setOpen((open) => !open);
+ }
+ };
+
+ document.addEventListener("keydown", down);
+ return () => document.removeEventListener("keydown", down);
+ }, []);
+
+ return (
+
+
+
+
+
+ No projects added yet. Click on Create project.
+
+
+
+ {data?.map((project) => (
+ {
+ router.push(`/dashboard/project/${project.projectId}`);
+ setOpen(false);
+ }}
+ >
+
+ {project.name}
+
+ ))}
+
+
+
+
+
+ {data?.map((project) => {
+ const applications: Services[] = extractServices(project);
+ return applications.map((application) => (
+ {
+ router.push(
+ `/dashboard/project/${project.projectId}/services/${application.type}/${application.id}`,
+ );
+ setOpen(false);
+ }}
+ >
+ {application.type === "postgres" && (
+
+ )}
+ {application.type === "redis" && (
+
+ )}
+ {application.type === "mariadb" && (
+
+ )}
+ {application.type === "mongo" && (
+
+ )}
+ {application.type === "mysql" && (
+
+ )}
+ {application.type === "application" && (
+
+ )}
+ {application.type === "compose" && (
+
+ )}
+
+ {project.name} / {application.name}{" "}
+ {application.id}
+
+
+
+
+
+ ));
+ })}
+
+
+
+
+ {
+ router.push("/dashboard/projects");
+ setOpen(false);
+ }}
+ >
+ Projects
+
+ {!isCloud && (
+ <>
+ {
+ router.push("/dashboard/monitoring");
+ setOpen(false);
+ }}
+ >
+ Monitoring
+
+ {
+ router.push("/dashboard/traefik");
+ setOpen(false);
+ }}
+ >
+ Traefik
+
+ {
+ router.push("/dashboard/docker");
+ setOpen(false);
+ }}
+ >
+ Docker
+
+ {
+ router.push("/dashboard/requests");
+ setOpen(false);
+ }}
+ >
+ Requests
+
+ >
+ )}
+ {
+ router.push("/dashboard/settings/server");
+ setOpen(false);
+ }}
+ >
+ Settings
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/ai-form.tsx b/data/apps/dokploy/components/dashboard/settings/ai-form.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..b1923918e5edd2832ba51b02c1ab89b7cef2c8df
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/ai-form.tsx
@@ -0,0 +1,106 @@
+"use client";
+
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { BotIcon, Loader2, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { HandleAi } from "./handle-ai";
+
+export const AiForm = () => {
+ const { data: aiConfigs, refetch, isLoading } = api.ai.getAll.useQuery();
+ const { mutateAsync, isLoading: isRemoving } = api.ai.delete.useMutation();
+
+ return (
+
+
+
+
+
+
+
+ AI Settings
+
+ Manage your AI configurations
+
+ {aiConfigs && aiConfigs?.length > 0 && }
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {aiConfigs?.length === 0 ? (
+
+
+
+ You don't have any AI configurations
+
+
+
+ ) : (
+
+ {aiConfigs?.map((config) => (
+
+
+
+
+ {config.name}
+
+ {config.model}
+
+
+
+ {
+ await mutateAsync({
+ aiId: config.aiId,
+ })
+ .then(() => {
+ toast.success("AI deleted successfully");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error deleting AI");
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/api/add-api-key.tsx b/data/apps/dokploy/components/dashboard/settings/api/add-api-key.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..568b86e942cb8d8a9136d428f9e28d9ce193b34f
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/api/add-api-key.tsx
@@ -0,0 +1,473 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import copy from "copy-to-clipboard";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const formSchema = z.object({
+ name: z.string().min(1, "Name is required"),
+ prefix: z.string().optional(),
+ expiresIn: z.number().nullable(),
+ organizationId: z.string().min(1, "Organization is required"),
+ // Rate limiting fields
+ rateLimitEnabled: z.boolean().optional(),
+ rateLimitTimeWindow: z.number().nullable(),
+ rateLimitMax: z.number().nullable(),
+ // Request limiting fields
+ remaining: z.number().nullable().optional(),
+ refillAmount: z.number().nullable().optional(),
+ refillInterval: z.number().nullable().optional(),
+});
+
+type FormValues = z.infer;
+
+const EXPIRATION_OPTIONS = [
+ { label: "Never", value: "0" },
+ { label: "1 day", value: String(60 * 60 * 24) },
+ { label: "7 days", value: String(60 * 60 * 24 * 7) },
+ { label: "30 days", value: String(60 * 60 * 24 * 30) },
+ { label: "90 days", value: String(60 * 60 * 24 * 90) },
+ { label: "1 year", value: String(60 * 60 * 24 * 365) },
+];
+
+const TIME_WINDOW_OPTIONS = [
+ { label: "1 minute", value: String(60 * 1000) },
+ { label: "5 minutes", value: String(5 * 60 * 1000) },
+ { label: "15 minutes", value: String(15 * 60 * 1000) },
+ { label: "30 minutes", value: String(30 * 60 * 1000) },
+ { label: "1 hour", value: String(60 * 60 * 1000) },
+ { label: "1 day", value: String(24 * 60 * 60 * 1000) },
+];
+
+const REFILL_INTERVAL_OPTIONS = [
+ { label: "1 hour", value: String(60 * 60 * 1000) },
+ { label: "6 hours", value: String(6 * 60 * 60 * 1000) },
+ { label: "12 hours", value: String(12 * 60 * 60 * 1000) },
+ { label: "1 day", value: String(24 * 60 * 60 * 1000) },
+ { label: "7 days", value: String(7 * 24 * 60 * 60 * 1000) },
+ { label: "30 days", value: String(30 * 24 * 60 * 60 * 1000) },
+];
+
+export const AddApiKey = () => {
+ const [open, setOpen] = useState(false);
+ const [showSuccessModal, setShowSuccessModal] = useState(false);
+ const [newApiKey, setNewApiKey] = useState("");
+ const { refetch } = api.user.get.useQuery();
+ const { data: organizations } = api.organization.all.useQuery();
+ const createApiKey = api.user.createApiKey.useMutation({
+ onSuccess: (data) => {
+ if (!data) return;
+
+ setNewApiKey(data.key);
+ setOpen(false);
+ setShowSuccessModal(true);
+ form.reset();
+ void refetch();
+ },
+ onError: () => {
+ toast.error("Failed to generate API key");
+ },
+ });
+
+ const form = useForm({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ name: "",
+ prefix: "",
+ expiresIn: null,
+ organizationId: "",
+ rateLimitEnabled: false,
+ rateLimitTimeWindow: null,
+ rateLimitMax: null,
+ remaining: null,
+ refillAmount: null,
+ refillInterval: null,
+ },
+ });
+
+ const rateLimitEnabled = form.watch("rateLimitEnabled");
+
+ const onSubmit = async (values: FormValues) => {
+ createApiKey.mutate({
+ name: values.name,
+ expiresIn: values.expiresIn || undefined,
+ prefix: values.prefix || undefined,
+ metadata: {
+ organizationId: values.organizationId,
+ },
+ // Rate limiting
+ rateLimitEnabled: values.rateLimitEnabled,
+ rateLimitTimeWindow: values.rateLimitTimeWindow || undefined,
+ rateLimitMax: values.rateLimitMax || undefined,
+ // Request limiting
+ remaining: values.remaining || undefined,
+ refillAmount: values.refillAmount || undefined,
+ refillInterval: values.refillInterval || undefined,
+ });
+ };
+
+ return (
+ <>
+
+
+ Generate New Key
+
+
+
+ Generate API Key
+
+ Create a new API key for accessing the API. You can set an
+ expiration date and a custom prefix for better organization.
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+ )}
+ />
+ (
+
+ Prefix
+
+
+
+
+
+ )}
+ />
+ (
+
+ Expiration
+
+ field.onChange(Number.parseInt(value, 10))
+ }
+ >
+
+
+
+
+
+
+ {EXPIRATION_OPTIONS.map((option) => (
+
+ {option.label}
+
+ ))}
+
+
+
+
+ )}
+ />
+ (
+
+ Organization
+
+
+
+
+
+
+
+ {organizations?.map((org) => (
+
+ {org.name}
+
+ ))}
+
+
+
+
+ )}
+ />
+
+ {/* Rate Limiting Section */}
+
+
Rate Limiting
+
(
+
+
+ Enable Rate Limiting
+
+ Limit the number of requests within a time window
+
+
+
+
+
+
+ )}
+ />
+
+ {rateLimitEnabled && (
+ <>
+ (
+
+ Time Window
+
+ field.onChange(Number.parseInt(value, 10))
+ }
+ >
+
+
+
+
+
+
+ {TIME_WINDOW_OPTIONS.map((option) => (
+
+ {option.label}
+
+ ))}
+
+
+
+ The duration in which requests are counted
+
+
+
+ )}
+ />
+ (
+
+ Maximum Requests
+
+
+ field.onChange(
+ e.target.value
+ ? Number.parseInt(e.target.value, 10)
+ : null,
+ )
+ }
+ />
+
+
+ Maximum number of requests allowed within the time
+ window
+
+
+
+ )}
+ />
+ >
+ )}
+
+
+ {/* Request Limiting Section */}
+
+
Request Limiting
+ (
+
+ Total Request Limit
+
+
+ field.onChange(
+ e.target.value
+ ? Number.parseInt(e.target.value, 10)
+ : null,
+ )
+ }
+ />
+
+
+ Total number of requests allowed (leave empty for
+ unlimited)
+
+
+
+ )}
+ />
+
+ (
+
+ Refill Amount
+
+
+ field.onChange(
+ e.target.value
+ ? Number.parseInt(e.target.value, 10)
+ : null,
+ )
+ }
+ />
+
+
+ Number of requests to add on each refill
+
+
+
+ )}
+ />
+
+ (
+
+ Refill Interval
+
+ field.onChange(Number.parseInt(value, 10))
+ }
+ >
+
+
+
+
+
+
+ {REFILL_INTERVAL_OPTIONS.map((option) => (
+
+ {option.label}
+
+ ))}
+
+
+
+ How often to refill the request limit
+
+
+
+ )}
+ />
+
+
+
+ setOpen(false)}
+ >
+ Cancel
+
+ Generate
+
+
+
+
+
+
+
+
+
+ API Key Generated Successfully
+
+ Please copy your API key now. You won't be able to see it again!
+
+
+
+
+
+ {
+ copy(newApiKey);
+ toast.success("API key copied to clipboard");
+ }}
+ >
+ Copy to Clipboard
+
+ setShowSuccessModal(false)}
+ >
+ Close
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/api/show-api-keys.tsx b/data/apps/dokploy/components/dashboard/settings/api/show-api-keys.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..743542ad05f53b8c110e7b5e6480d8bbe259178e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/api/show-api-keys.tsx
@@ -0,0 +1,142 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { formatDistanceToNow } from "date-fns";
+import { Clock, ExternalLinkIcon, KeyIcon, Tag, Trash2 } from "lucide-react";
+import Link from "next/link";
+import { toast } from "sonner";
+import { AddApiKey } from "./add-api-key";
+
+export const ShowApiKeys = () => {
+ const { data, refetch } = api.user.get.useQuery();
+ const { mutateAsync: deleteApiKey, isLoading: isLoadingDelete } =
+ api.user.deleteApiKey.useMutation();
+
+ return (
+
+
+
+
+
+
+
+ API/CLI Keys
+
+
+ Generate and manage API keys to access the API/CLI
+
+
+
+
+ Swagger API:
+
+
+ View
+
+
+
+
+
+
+ {data?.user.apiKeys && data.user.apiKeys.length > 0 ? (
+ data.user.apiKeys.map((apiKey) => (
+
+
+
+
{apiKey.name}
+
+
+
+ Created{" "}
+ {formatDistanceToNow(new Date(apiKey.createdAt))}{" "}
+ ago
+
+ {apiKey.prefix && (
+
+
+ {apiKey.prefix}
+
+ )}
+ {apiKey.expiresAt && (
+
+
+ Expires in{" "}
+ {formatDistanceToNow(
+ new Date(apiKey.expiresAt),
+ )}{" "}
+
+ )}
+
+
+
{
+ try {
+ await deleteApiKey({
+ apiKeyId: apiKey.id,
+ });
+ await refetch();
+ toast.success("API key deleted successfully");
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Error deleting API key",
+ );
+ }
+ }}
+ >
+
+
+
+
+
+
+ ))
+ ) : (
+
+
+
+ No API keys found
+
+
+ )}
+
+
+ {/* Generate new API key */}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/billing/show-billing.tsx b/data/apps/dokploy/components/dashboard/settings/billing/show-billing.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2c20bb81dc366ef2c015be8d50c24c5110ef27d1
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/billing/show-billing.tsx
@@ -0,0 +1,324 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { NumberInput } from "@/components/ui/input";
+import { Progress } from "@/components/ui/progress";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { loadStripe } from "@stripe/stripe-js";
+import clsx from "clsx";
+import {
+ AlertTriangle,
+ CheckIcon,
+ CreditCard,
+ Loader2,
+ MinusIcon,
+ PlusIcon,
+} from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+
+const stripePromise = loadStripe(
+ process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
+);
+
+export const calculatePrice = (count: number, isAnnual = false) => {
+ if (isAnnual) {
+ if (count <= 1) return 45.9;
+ return 35.7 * count;
+ }
+ if (count <= 1) return 4.5;
+ return count * 3.5;
+};
+export const ShowBilling = () => {
+ const { data: servers } = api.server.count.useQuery();
+ const { data: admin } = api.user.get.useQuery();
+ const { data, isLoading } = api.stripe.getProducts.useQuery();
+ const { mutateAsync: createCheckoutSession } =
+ api.stripe.createCheckoutSession.useMutation();
+
+ const { mutateAsync: createCustomerPortalSession } =
+ api.stripe.createCustomerPortalSession.useMutation();
+
+ const [serverQuantity, setServerQuantity] = useState(3);
+ const [isAnnual, setIsAnnual] = useState(false);
+
+ const handleCheckout = async (productId: string) => {
+ const stripe = await stripePromise;
+ if (data && data.subscriptions.length === 0) {
+ createCheckoutSession({
+ productId,
+ serverQuantity: serverQuantity,
+ isAnnual,
+ }).then(async (session) => {
+ await stripe?.redirectToCheckout({
+ sessionId: session.sessionId,
+ });
+ });
+ }
+ };
+ const products = data?.products.filter((product) => {
+ // @ts-ignore
+ const interval = product?.default_price?.recurring?.interval;
+ return isAnnual ? interval === "year" : interval === "month";
+ });
+
+ const maxServers = admin?.user.serversQuantity ?? 1;
+ const percentage = ((servers ?? 0) / maxServers) * 100;
+ const safePercentage = Math.min(percentage, 100);
+
+ return (
+
+
+
+
+
+
+ Billing
+
+ Manage your subscription
+
+
+
+
setIsAnnual(e === "annual")}
+ >
+
+ Monthly
+ Annual
+
+
+ {admin?.user.stripeSubscriptionId && (
+
+
Servers Plan
+
+ You have {servers} server on your plan of{" "}
+ {admin?.user.serversQuantity} servers
+
+
+ {admin && admin.user.serversQuantity! <= (servers ?? 0) && (
+
+
+
+ You have reached the maximum number of servers you can
+ create, please upgrade your plan to add more servers.
+
+
+ )}
+
+ )}
+
+
+ Need Help? We are here to help you.
+
+
+ Join to our Discord server and we will help you.
+
+
+
+
+
+
+ Join Discord
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {products?.map((product) => {
+ const featured = true;
+ return (
+
+
+ {isAnnual && (
+
+ Recommended 🚀
+
+ )}
+ {isAnnual ? (
+
+
+ ${" "}
+ {calculatePrice(
+ serverQuantity,
+ isAnnual,
+ ).toFixed(2)}{" "}
+ USD
+
+ |
+
+ ${" "}
+ {(
+ calculatePrice(serverQuantity, isAnnual) / 12
+ ).toFixed(2)}{" "}
+ / Month USD
+
+
+ ) : (
+
+ ${" "}
+ {calculatePrice(serverQuantity, isAnnual).toFixed(
+ 2,
+ )}{" "}
+ USD
+
+ )}
+
+ {product.name}
+
+
+ {product.description}
+
+
+
+ {[
+ "All the features of Dokploy",
+ "Unlimited deployments",
+ "Self-hosted on your own infrastructure",
+ "Full access to all deployment features",
+ "Dokploy integration",
+ "Backups",
+ "All Incoming features",
+ ].map((feature) => (
+
+
+ {feature}
+
+ ))}
+
+
+
+
+ {serverQuantity} Servers
+
+
+
+
+
{
+ if (serverQuantity <= 1) return;
+
+ setServerQuantity(serverQuantity - 1);
+ }}
+ >
+
+
+
{
+ setServerQuantity(
+ e.target.value as unknown as number,
+ );
+ }}
+ />
+
+ {
+ setServerQuantity(serverQuantity + 1);
+ }}
+ >
+
+
+
+
0
+ ? "justify-between"
+ : "justify-end",
+ "flex flex-row items-center gap-2 mt-4",
+ )}
+ >
+ {admin?.user.stripeCustomerId && (
+
{
+ const session =
+ await createCustomerPortalSession();
+
+ window.open(session.url);
+ }}
+ >
+ Manage Subscription
+
+ )}
+
+ {data?.subscriptions?.length === 0 && (
+
+ {
+ handleCheckout(product.id);
+ }}
+ disabled={serverQuantity < 1}
+ >
+ Subscribe
+
+
+ )}
+
+
+
+
+ );
+ })}
+ >
+ )}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/billing/show-welcome-dokploy.tsx b/data/apps/dokploy/components/dashboard/settings/billing/show-welcome-dokploy.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..64362b25c7547f7468832546d75ad5849234253e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/billing/show-welcome-dokploy.tsx
@@ -0,0 +1,61 @@
+import { ShowBilling } from "@/components/dashboard/settings/billing/show-billing";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { api } from "@/utils/api";
+import { useEffect, useState } from "react";
+
+export const ShowWelcomeDokploy = () => {
+ const { data } = api.user.get.useQuery();
+ const [open, setOpen] = useState(false);
+
+ const { data: isCloud, isLoading } = api.settings.isCloud.useQuery();
+
+ if (!isCloud || data?.role !== "admin") {
+ return null;
+ }
+
+ useEffect(() => {
+ if (
+ !isLoading &&
+ isCloud &&
+ !localStorage.getItem("hasSeenCloudWelcomeModal") &&
+ data?.role === "owner"
+ ) {
+ setOpen(true);
+ }
+ }, [isCloud, isLoading]);
+
+ const handleClose = (isOpen: boolean) => {
+ if (data?.role === "owner") {
+ setOpen(isOpen);
+ if (!isOpen) {
+ localStorage.setItem("hasSeenCloudWelcomeModal", "true"); // Establece el flag al cerrar el modal
+ }
+ }
+ };
+
+ return (
+ <>
+
+
+
+
+ Welcome to Dokploy Cloud 🎉
+
+
+ Unlock powerful features to streamline your deployments and manage
+ projects effortlessly.
+
+
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/certificates/add-certificate.tsx b/data/apps/dokploy/components/dashboard/settings/certificates/add-certificate.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..58cad7910fe6b97edd2687cc926f4a5d4a07c5f6
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/certificates/add-certificate.tsx
@@ -0,0 +1,238 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Textarea } from "@/components/ui/textarea";
+import {
+ Tooltip,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { HelpCircle, PlusIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const certificateDataHolder =
+ "-----BEGIN CERTIFICATE-----\nMIIFRDCCAyygAwIBAgIUEPOR47ys6VDwMVB9tYoeEka83uQwDQYJKoZIhvcNAQELBQAwGTEXMBUGA1UEAwwObWktZG9taW5pby5jb20wHhcNMjQwMzExMDQyNzU3WhcN\n------END CERTIFICATE-----";
+
+const privateKeyDataHolder =
+ "-----BEGIN PRIVATE KEY-----\nMIIFRDCCAyygAwIBAgIUEPOR47ys6VDwMVB9tYoeEka83uQwDQYJKoZIhvcNAQELBQAwGTEXMBUGA1UEAwwObWktZG9taW5pby5jb20wHhcNMjQwMzExMDQyNzU3WhcN\n-----END PRIVATE KEY-----";
+
+const addCertificate = z.object({
+ name: z.string().min(1, "Name is required"),
+ certificateData: z.string().min(1, "Certificate data is required"),
+ privateKey: z.string().min(1, "Private key is required"),
+ autoRenew: z.boolean().optional(),
+ serverId: z.string().optional(),
+});
+
+type AddCertificate = z.infer;
+
+export const AddCertificate = () => {
+ const [open, setOpen] = useState(false);
+ const utils = api.useUtils();
+
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const { mutateAsync, isError, error, isLoading } =
+ api.certificates.create.useMutation();
+ const { data: servers } = api.server.withSSHKey.useQuery();
+
+ const form = useForm({
+ defaultValues: {
+ name: "",
+ certificateData: "",
+ privateKey: "",
+ autoRenew: false,
+ },
+ resolver: zodResolver(addCertificate),
+ });
+ useEffect(() => {
+ form.reset();
+ }, [form, form.formState.isSubmitSuccessful, form.reset]);
+
+ const onSubmit = async (data: AddCertificate) => {
+ await mutateAsync({
+ name: data.name,
+ certificateData: data.certificateData,
+ privateKey: data.privateKey,
+ autoRenew: data.autoRenew,
+ serverId: data.serverId,
+ organizationId: "",
+ })
+ .then(async () => {
+ toast.success("Certificate Created");
+ await utils.certificates.all.invalidate();
+ setOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error creating the Certificate");
+ });
+ };
+ return (
+
+
+
+ {" "}
+
+ Add Certificate
+
+
+
+
+ Add New Certificate
+
+ Upload or generate a certificate to secure your application
+
+
+ {isError && {error?.message} }
+
+
+
+ {
+ return (
+
+ Certificate Name
+
+
+
+
+
+ );
+ }}
+ />
+ (
+
+
+ Certificate Data
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Private Key
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+
+
+
+ Select a Server {!isCloud && "(Optional)"}
+
+
+
+
+
+
+
+
+
+
+
+
+ {servers?.map((server) => (
+
+
+ {server.name}
+
+ {server.ipAddress}
+
+
+
+ ))}
+ Servers ({servers?.length})
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ Create
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/certificates/show-certificates.tsx b/data/apps/dokploy/components/dashboard/settings/certificates/show-certificates.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..b80c7b5496d8528b116308c17a88744166a36867
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/certificates/show-certificates.tsx
@@ -0,0 +1,154 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { AlertCircle, Link, Loader2, ShieldCheck, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { AddCertificate } from "./add-certificate";
+import { getCertificateChainInfo, getExpirationStatus } from "./utils";
+
+export const ShowCertificates = () => {
+ const { mutateAsync, isLoading: isRemoving } =
+ api.certificates.remove.useMutation();
+ const { data, isLoading, refetch } = api.certificates.all.useQuery();
+
+ return (
+
+
+
+
+
+
+ Certificates
+
+
+ Create certificates in the Traefik directory
+
+
+
+ Certificates are created in the Traefik directory. Traefik uses
+ these certificates to secure your applications. Using invalid
+ certificates can break your Traefik instance, preventing access to
+ your applications.
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {data?.length === 0 ? (
+
+
+
+ You don't have any certificates created
+
+
+
+ ) : (
+
+
+ {data?.map((certificate, index) => {
+ const expiration = getExpirationStatus(
+ certificate.certificateData,
+ );
+ const chainInfo = getCertificateChainInfo(
+ certificate.certificateData,
+ );
+ return (
+
+
+
+
+
+ {index + 1}. {certificate.name}
+
+ {chainInfo.isChain && (
+
+
+
+ Chain ({chainInfo.count})
+
+
+ )}
+
+ {expiration.status !== "valid" && (
+
+ )}
+ {expiration.message}
+ {certificate.autoRenew &&
+ expiration.status !== "valid" && (
+
+ (Auto-renewal enabled)
+
+ )}
+
+
+
+
+
+ {
+ await mutateAsync({
+ certificateId: certificate.certificateId,
+ })
+ .then(() => {
+ toast.success(
+ "Certificate deleted successfully",
+ );
+ refetch();
+ })
+ .catch(() => {
+ toast.error(
+ "Error deleting certificate",
+ );
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ );
+ })}
+
+
+
+
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/certificates/utils.ts b/data/apps/dokploy/components/dashboard/settings/certificates/utils.ts
new file mode 100644
index 0000000000000000000000000000000000000000..80f332d8d25d32bc79f2689b20b6e8452657c57d
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/certificates/utils.ts
@@ -0,0 +1,142 @@
+export const extractExpirationDate = (certData: string): Date | null => {
+ try {
+ const match = certData.match(
+ /-----BEGIN CERTIFICATE-----\s*([^-]+)\s*-----END CERTIFICATE-----/,
+ );
+ if (!match?.[1]) return null;
+
+ const base64Cert = match[1].replace(/\s/g, "");
+ const binaryStr = window.atob(base64Cert);
+ const bytes = new Uint8Array(binaryStr.length);
+
+ for (let i = 0; i < binaryStr.length; i++) {
+ bytes[i] = binaryStr.charCodeAt(i);
+ }
+
+ // ASN.1 tag for UTCTime is 0x17, GeneralizedTime is 0x18
+ // We need to find the second occurrence of either tag as it's the "not after" (expiration) date
+ let dateFound = false;
+ for (let i = 0; i < bytes.length - 2; i++) {
+ // Look for sequence containing validity period (0x30)
+ if (bytes[i] === 0x30) {
+ // Check next bytes for UTCTime or GeneralizedTime
+ let j = i + 1;
+ while (j < bytes.length - 2) {
+ if (bytes[j] === 0x17 || bytes[j] === 0x18) {
+ const dateType = bytes[j];
+ const dateLength = bytes[j + 1];
+ if (typeof dateLength === "undefined") break;
+
+ if (!dateFound) {
+ // Skip "not before" date
+ dateFound = true;
+ j += dateLength + 2;
+ continue;
+ }
+
+ // Found "not after" date
+ let dateStr = "";
+ for (let k = 0; k < dateLength; k++) {
+ const charCode = bytes[j + 2 + k];
+ if (typeof charCode === "undefined") continue;
+ dateStr += String.fromCharCode(charCode);
+ }
+
+ if (dateType === 0x17) {
+ // UTCTime (YYMMDDhhmmssZ)
+ const year = Number.parseInt(dateStr.slice(0, 2));
+ const fullYear = year >= 50 ? 1900 + year : 2000 + year;
+ return new Date(
+ Date.UTC(
+ fullYear,
+ Number.parseInt(dateStr.slice(2, 4)) - 1,
+ Number.parseInt(dateStr.slice(4, 6)),
+ Number.parseInt(dateStr.slice(6, 8)),
+ Number.parseInt(dateStr.slice(8, 10)),
+ Number.parseInt(dateStr.slice(10, 12)),
+ ),
+ );
+ }
+
+ // GeneralizedTime (YYYYMMDDhhmmssZ)
+ return new Date(
+ Date.UTC(
+ Number.parseInt(dateStr.slice(0, 4)),
+ Number.parseInt(dateStr.slice(4, 6)) - 1,
+ Number.parseInt(dateStr.slice(6, 8)),
+ Number.parseInt(dateStr.slice(8, 10)),
+ Number.parseInt(dateStr.slice(10, 12)),
+ Number.parseInt(dateStr.slice(12, 14)),
+ ),
+ );
+ }
+ j++;
+ }
+ }
+ }
+ return null;
+ } catch (error) {
+ console.error("Error parsing certificate:", error);
+ return null;
+ }
+};
+
+export const getExpirationStatus = (certData: string) => {
+ const expirationDate = extractExpirationDate(certData);
+
+ if (!expirationDate)
+ return {
+ status: "unknown" as const,
+ className: "text-muted-foreground",
+ message: "Could not determine expiration",
+ };
+
+ const now = new Date();
+ const daysUntilExpiration = Math.ceil(
+ (expirationDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24),
+ );
+
+ if (daysUntilExpiration < 0) {
+ return {
+ status: "expired" as const,
+ className: "text-red-500",
+ message: `Expired on ${expirationDate.toLocaleDateString([], {
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ })}`,
+ };
+ }
+
+ if (daysUntilExpiration <= 30) {
+ return {
+ status: "warning" as const,
+ className: "text-yellow-500",
+ message: `Expires in ${daysUntilExpiration} days`,
+ };
+ }
+
+ return {
+ status: "valid" as const,
+ className: "text-muted-foreground",
+ message: `Expires ${expirationDate.toLocaleDateString([], {
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ })}`,
+ };
+};
+
+export const getCertificateChainInfo = (certData: string) => {
+ const certCount = (certData.match(/-----BEGIN CERTIFICATE-----/g) || [])
+ .length;
+ return certCount > 1
+ ? {
+ isChain: true,
+ count: certCount,
+ }
+ : {
+ isChain: false,
+ count: 1,
+ };
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/cluster/nodes/add-node.tsx b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/add-node.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..63fb17ddad90f2b55c337ea9f72683e97e1a03b6
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/add-node.tsx
@@ -0,0 +1,75 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { ExternalLink, PlusIcon } from "lucide-react";
+import Link from "next/link";
+import { AddManager } from "./manager/add-manager";
+import { AddWorker } from "./workers/add-worker";
+
+interface Props {
+ serverId?: string;
+}
+
+export const AddNode = ({ serverId }: Props) => {
+ return (
+
+
+
+
+ Add Node
+
+
+
+
+ Add Node
+
+ Follow the steps to add a new node to your cluster, before you start
+ using this feature, you need to understand how docker swarm works.{" "}
+
+ Docker Swarm
+
+
+
+ Architecture
+
+
+
+ Make sure you use the same architecture as the node you are
+ adding.
+
+
+
+
+
+
+ Worker
+ Manager
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/cluster/nodes/manager/add-manager.tsx b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/manager/add-manager.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..bb2064d4ea57cfa8ac039f2a59565dc443d23d46
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/manager/add-manager.tsx
@@ -0,0 +1,80 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CardContent } from "@/components/ui/card";
+import {
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { api } from "@/utils/api";
+import copy from "copy-to-clipboard";
+import { CopyIcon, Loader2 } from "lucide-react";
+import { toast } from "sonner";
+
+interface Props {
+ serverId?: string;
+}
+
+export const AddManager = ({ serverId }: Props) => {
+ const { data, isLoading, error, isError } = api.cluster.addManager.useQuery({
+ serverId,
+ });
+
+ return (
+ <>
+
+
+ Add a new manager
+ Add a new manager
+
+ {isError && {error?.message} }
+ {isLoading ? (
+
+ ) : (
+ <>
+
+
+ 1. Go to your new server and run the following command
+
+
+ curl https://get.docker.com | sh -s -- --version {data?.version}
+ {
+ copy(
+ `curl https://get.docker.com | sh -s -- --version ${data?.version}`,
+ );
+ toast.success("Copied to clipboard");
+ }}
+ >
+
+
+
+
+
+
+
+ 2. Run the following command to add the node(manager) to your
+ cluster
+
+
+
+ {data?.command}
+ {
+ copy(data?.command || "");
+ toast.success("Copied to clipboard");
+ }}
+ >
+
+
+
+
+ >
+ )}
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/cluster/nodes/show-node-data.tsx b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/show-node-data.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e2adbed76d2609bdf981cdbe03de3088394d619e
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/show-node-data.tsx
@@ -0,0 +1,50 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+
+interface Props {
+ data: unknown;
+}
+
+export const ShowNodeData = ({ data }: Props) => {
+ return (
+
+
+ e.preventDefault()}
+ >
+ View Config
+
+
+
+
+ Node Config
+
+ See in detail the metadata of this node
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/cluster/nodes/show-nodes-modal.tsx b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/show-nodes-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..82e6e1f9a440517719e6ad6815fdedd1b35ddd95
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/show-nodes-modal.tsx
@@ -0,0 +1,30 @@
+import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { useState } from "react";
+import { ShowNodes } from "./show-nodes";
+
+interface Props {
+ serverId: string;
+}
+
+export const ShowNodesModal = ({ serverId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+
+
+ e.preventDefault()}
+ >
+ Show Swarm Nodes
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/cluster/nodes/show-nodes.tsx b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/show-nodes.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..4354a8bcab3c1ddd80470fc2ab0f9a98123c9f59
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/show-nodes.tsx
@@ -0,0 +1,217 @@
+import { DateTooltip } from "@/components/shared/date-tooltip";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Table,
+ TableBody,
+ TableCaption,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import {
+ Boxes,
+ HelpCircle,
+ Loader2,
+ LockIcon,
+ MoreHorizontal,
+} from "lucide-react";
+import { toast } from "sonner";
+import { AddNode } from "./add-node";
+import { ShowNodeData } from "./show-node-data";
+
+interface Props {
+ serverId?: string;
+}
+
+export const ShowNodes = ({ serverId }: Props) => {
+ const { data, isLoading, refetch } = api.cluster.getNodes.useQuery({
+ serverId,
+ });
+ const { data: registry } = api.registry.all.useQuery();
+
+ const { mutateAsync: deleteNode } = api.cluster.removeWorker.useMutation();
+
+ const haveAtLeastOneRegistry = !!(registry && registry?.length > 0);
+ return (
+
+
+
+
+
+
+
+ Cluster
+
+ Add nodes to your cluster
+
+ {haveAtLeastOneRegistry && (
+
+ )}
+
+
+ {isLoading ? (
+
+
+
+ ) : haveAtLeastOneRegistry ? (
+
+
+
+ A list of your managers / workers.
+
+
+
+ Hostname
+ Status
+ Role
+ Availability
+
+ Engine Version
+
+ Created
+
+ Actions
+
+
+
+ {data?.map((node) => {
+ const isManager = node.Spec.Role === "manager";
+ return (
+
+
+ {node.Description.Hostname}
+
+
+ {node.Status.State}
+
+
+
+ {node?.Spec?.Role}
+
+
+
+ {node.Spec.Availability}
+
+
+
+ {node?.Description.Engine.EngineVersion}
+
+
+
+
+ Created{" "}
+
+
+
+
+
+
+ Open menu
+
+
+
+
+ Actions
+
+ {!node?.ManagerStatus?.Leader && (
+ {
+ await deleteNode({
+ nodeId: node.ID,
+ serverId,
+ })
+ .then(() => {
+ refetch();
+ toast.success(
+ "Node deleted successfully",
+ );
+ })
+ .catch(() => {
+ toast.error("Error deleting node");
+ });
+ }}
+ >
+ e.preventDefault()}
+ >
+ Delete
+
+
+ )}
+
+
+
+
+ );
+ })}
+
+
+
+ ) : (
+
+
+
+
+ To add nodes to your cluster, you need to configure at least
+ one registry.
+
+
+
+
+
+
+
+ Nodes need a registry to pull images from.
+
+
+
+
+
+
+
+ Docker Registry: Use custom registries like
+ Docker Hub, DigitalOcean Registry, etc.
+
+
+
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/cluster/nodes/workers/add-worker.tsx b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/workers/add-worker.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2623081bb1ac05121e9fe3dfa077b1e7b6a14204
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/cluster/nodes/workers/add-worker.tsx
@@ -0,0 +1,76 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CardContent } from "@/components/ui/card";
+import {
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { api } from "@/utils/api";
+import copy from "copy-to-clipboard";
+import { CopyIcon, Loader2 } from "lucide-react";
+import { toast } from "sonner";
+
+interface Props {
+ serverId?: string;
+}
+
+export const AddWorker = ({ serverId }: Props) => {
+ const { data, isLoading, error, isError } = api.cluster.addWorker.useQuery({
+ serverId,
+ });
+
+ return (
+
+
+ Add a new worker
+ Add a new worker
+
+ {isError && {error?.message} }
+ {isLoading ? (
+
+ ) : (
+ <>
+
+ 1. Go to your new server and run the following command
+
+ curl https://get.docker.com | sh -s -- --version {data?.version}
+ {
+ copy(
+ `curl https://get.docker.com | sh -s -- --version ${data?.version}`,
+ );
+ toast.success("Copied to clipboard");
+ }}
+ >
+
+
+
+
+
+
+
+ 2. Run the following command to add the node(worker) to your
+ cluster
+
+
+
+ {data?.command}
+ {
+ copy(data?.command || "");
+ toast.success("Copied to clipboard");
+ }}
+ >
+
+
+
+
+ >
+ )}
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/cluster/registry/handle-registry.tsx b/data/apps/dokploy/components/dashboard/settings/cluster/registry/handle-registry.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..d30ad6dda88f81c720580c9ff19b0d4229797160
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/cluster/registry/handle-registry.tsx
@@ -0,0 +1,378 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertTriangle, PenBoxIcon, PlusIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const AddRegistrySchema = z.object({
+ registryName: z.string().min(1, {
+ message: "Registry name is required",
+ }),
+ username: z.string().min(1, {
+ message: "Username is required",
+ }),
+ password: z.string().min(1, {
+ message: "Password is required",
+ }),
+ registryUrl: z.string(),
+ imagePrefix: z.string(),
+ serverId: z.string().optional(),
+});
+
+type AddRegistry = z.infer;
+
+interface Props {
+ registryId?: string;
+}
+
+export const HandleRegistry = ({ registryId }: Props) => {
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+
+ const { data: registry } = api.registry.one.useQuery(
+ {
+ registryId: registryId || "",
+ },
+ {
+ enabled: !!registryId,
+ },
+ );
+
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+
+ const { mutateAsync, error, isError } = registryId
+ ? api.registry.update.useMutation()
+ : api.registry.create.useMutation();
+ const { data: servers } = api.server.withSSHKey.useQuery();
+ const {
+ mutateAsync: testRegistry,
+ isLoading,
+ error: testRegistryError,
+ isError: testRegistryIsError,
+ } = api.registry.testRegistry.useMutation();
+ const form = useForm({
+ defaultValues: {
+ username: "",
+ password: "",
+ registryUrl: "",
+ imagePrefix: "",
+ registryName: "",
+ serverId: "",
+ },
+ resolver: zodResolver(AddRegistrySchema),
+ });
+
+ const password = form.watch("password");
+ const username = form.watch("username");
+ const registryUrl = form.watch("registryUrl");
+ const registryName = form.watch("registryName");
+ const imagePrefix = form.watch("imagePrefix");
+ const serverId = form.watch("serverId");
+
+ useEffect(() => {
+ if (registry) {
+ form.reset({
+ username: registry.username,
+ password: "",
+ registryUrl: registry.registryUrl,
+ imagePrefix: registry.imagePrefix || "",
+ registryName: registry.registryName,
+ });
+ } else {
+ form.reset({
+ username: "",
+ password: "",
+ registryUrl: "",
+ imagePrefix: "",
+ serverId: "",
+ });
+ }
+ }, [form, form.reset, form.formState.isSubmitSuccessful, registry]);
+
+ const onSubmit = async (data: AddRegistry) => {
+ await mutateAsync({
+ password: data.password,
+ registryName: data.registryName,
+ username: data.username,
+ registryUrl: data.registryUrl,
+ registryType: "cloud",
+ imagePrefix: data.imagePrefix,
+ serverId: data.serverId,
+ registryId: registryId || "",
+ })
+ .then(async (_data) => {
+ await utils.registry.all.invalidate();
+ toast.success(registryId ? "Registry updated" : "Registry added");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error(
+ registryId ? "Error updating a registry" : "Error adding a registry",
+ );
+ });
+ };
+
+ return (
+
+
+ {registryId ? (
+
+
+
+ ) : (
+
+
+ Add Registry
+
+ )}
+
+
+
+ Add a external registry
+
+ Fill the next fields to add a external registry.
+
+
+ {(isError || testRegistryIsError) && (
+
+
+
+ {testRegistryError?.message || error?.message || ""}
+
+
+ )}
+
+
+
+ (
+
+ Registry Name
+
+
+
+
+
+
+ )}
+ />
+
+
+ (
+
+ Username
+
+
+
+
+
+
+ )}
+ />
+
+
+ (
+
+ Password
+
+
+
+
+
+
+ )}
+ />
+
+
+ (
+
+ Image Prefix
+
+
+
+
+
+
+ )}
+ />
+
+
+ (
+
+ Registry URL
+
+
+
+
+
+
+ )}
+ />
+
+
+
+ (
+
+ Server {!isCloud && "(Optional)"}
+
+ Select a server to test the registry. this will run the
+ following command on the server
+
+
+
+
+
+
+
+
+ Servers
+ {servers?.map((server) => (
+
+ {server.name}
+
+ ))}
+ None
+
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ {
+ const validationResult = AddRegistrySchema.safeParse({
+ username,
+ password,
+ registryUrl,
+ registryName: "Dokploy Registry",
+ imagePrefix,
+ serverId,
+ });
+
+ if (!validationResult.success) {
+ for (const issue of validationResult.error.issues) {
+ form.setError(issue.path[0] as any, {
+ type: "manual",
+ message: issue.message,
+ });
+ }
+ return;
+ }
+
+ await testRegistry({
+ username: username,
+ password: password,
+ registryUrl: registryUrl,
+ registryName: registryName,
+ registryType: "cloud",
+ imagePrefix: imagePrefix,
+ serverId: serverId,
+ })
+ .then((data) => {
+ if (data) {
+ toast.success("Registry Tested Successfully");
+ } else {
+ toast.error("Registry Test Failed");
+ }
+ })
+ .catch(() => {
+ toast.error("Error testing the registry");
+ });
+ }}
+ >
+ Test Registry
+
+
+ {registryId ? "Update" : "Create"}
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/cluster/registry/show-registry.tsx b/data/apps/dokploy/components/dashboard/settings/cluster/registry/show-registry.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..9ae595d6faa89b947dbca5fcde642ffce6ebab0c
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/cluster/registry/show-registry.tsx
@@ -0,0 +1,124 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { Loader2, Package, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { HandleRegistry } from "./handle-registry";
+
+export const ShowRegistry = () => {
+ const { mutateAsync, isLoading: isRemoving } =
+ api.registry.remove.useMutation();
+ const { data, isLoading, refetch } = api.registry.all.useQuery();
+
+ return (
+
+
+
+
+
+
+ Docker Registry
+
+
+ Manage your Docker Registry configurations
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {data?.length === 0 ? (
+
+
+
+ You don't have any registry configurations
+
+
+
+ ) : (
+
+
+ {data?.map((registry, index) => (
+
+
+
+
+
+ {index + 1}. {registry.registryName}
+
+ {registry.registryUrl && (
+
+ {registry.registryUrl}
+
+ )}
+
+
+
+
+
+
+ {
+ await mutateAsync({
+ registryId: registry.registryId,
+ })
+ .then(() => {
+ toast.success(
+ "Registry configuration deleted successfully",
+ );
+ refetch();
+ })
+ .catch(() => {
+ toast.error(
+ "Error deleting registry configuration",
+ );
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+
+
+
+
+
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/destination/constants.ts b/data/apps/dokploy/components/dashboard/settings/destination/constants.ts
new file mode 100644
index 0000000000000000000000000000000000000000..f43e47d1a16d4d2c817a4ec18c85b0cd847c54ab
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/destination/constants.ts
@@ -0,0 +1,133 @@
+export const S3_PROVIDERS: Array<{
+ key: string;
+ name: string;
+}> = [
+ {
+ key: "AWS",
+ name: "Amazon Web Services (AWS) S3",
+ },
+ {
+ key: "Alibaba",
+ name: "Alibaba Cloud Object Storage System (OSS) formerly Aliyun",
+ },
+ {
+ key: "ArvanCloud",
+ name: "Arvan Cloud Object Storage (AOS)",
+ },
+ {
+ key: "Ceph",
+ name: "Ceph Object Storage",
+ },
+ {
+ key: "ChinaMobile",
+ name: "China Mobile Ecloud Elastic Object Storage (EOS)",
+ },
+ {
+ key: "Cloudflare",
+ name: "Cloudflare R2 Storage",
+ },
+ {
+ key: "DigitalOcean",
+ name: "DigitalOcean Spaces",
+ },
+ {
+ key: "Dreamhost",
+ name: "Dreamhost DreamObjects",
+ },
+ {
+ key: "GCS",
+ name: "Google Cloud Storage",
+ },
+ {
+ key: "HuaweiOBS",
+ name: "Huawei Object Storage Service",
+ },
+ {
+ key: "IBMCOS",
+ name: "IBM COS S3",
+ },
+ {
+ key: "IDrive",
+ name: "IDrive e2",
+ },
+ {
+ key: "IONOS",
+ name: "IONOS Cloud",
+ },
+ {
+ key: "LyveCloud",
+ name: "Seagate Lyve Cloud",
+ },
+ {
+ key: "Leviia",
+ name: "Leviia Object Storage",
+ },
+ {
+ key: "Liara",
+ name: "Liara Object Storage",
+ },
+ {
+ key: "Linode",
+ name: "Linode Object Storage",
+ },
+ {
+ key: "Magalu",
+ name: "Magalu Object Storage",
+ },
+ {
+ key: "Minio",
+ name: "Minio Object Storage",
+ },
+ {
+ key: "Netease",
+ name: "Netease Object Storage (NOS)",
+ },
+ {
+ key: "Petabox",
+ name: "Petabox Object Storage",
+ },
+ {
+ key: "RackCorp",
+ name: "RackCorp Object Storage",
+ },
+ {
+ key: "Rclone",
+ name: "Rclone S3 Server",
+ },
+ {
+ key: "Scaleway",
+ name: "Scaleway Object Storage",
+ },
+ {
+ key: "SeaweedFS",
+ name: "SeaweedFS S3",
+ },
+ {
+ key: "StackPath",
+ name: "StackPath Object Storage",
+ },
+ {
+ key: "Storj",
+ name: "Storj (S3 Compatible Gateway)",
+ },
+ {
+ key: "Synology",
+ name: "Synology C2 Object Storage",
+ },
+ {
+ key: "TencentCOS",
+ name: "Tencent Cloud Object Storage (COS)",
+ },
+ {
+ key: "Wasabi",
+ name: "Wasabi Object Storage",
+ },
+ {
+ key: "Qiniu",
+ name: "Qiniu Object Storage (Kodo)",
+ },
+ {
+ key: "Other",
+ name: "Any other S3 compatible provider",
+ },
+];
diff --git a/data/apps/dokploy/components/dashboard/settings/destination/handle-destinations.tsx b/data/apps/dokploy/components/dashboard/settings/destination/handle-destinations.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..aedf87445387134171981f0a1c48f16da719225c
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/destination/handle-destinations.tsx
@@ -0,0 +1,442 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon, PlusIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import { S3_PROVIDERS } from "./constants";
+
+const addDestination = z.object({
+ name: z.string().min(1, "Name is required"),
+ provider: z.string().min(1, "Provider is required"),
+ accessKeyId: z.string().min(1, "Access Key Id is required"),
+ secretAccessKey: z.string().min(1, "Secret Access Key is required"),
+ bucket: z.string().min(1, "Bucket is required"),
+ region: z.string(),
+ endpoint: z.string().min(1, "Endpoint is required"),
+ serverId: z.string().optional(),
+});
+
+type AddDestination = z.infer;
+
+interface Props {
+ destinationId?: string;
+}
+
+export const HandleDestinations = ({ destinationId }: Props) => {
+ const [open, setOpen] = useState(false);
+ const utils = api.useUtils();
+ const { data: servers } = api.server.withSSHKey.useQuery();
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+
+ const { mutateAsync, isError, error, isLoading } = destinationId
+ ? api.destination.update.useMutation()
+ : api.destination.create.useMutation();
+
+ const { data: destination } = api.destination.one.useQuery(
+ {
+ destinationId: destinationId || "",
+ },
+ {
+ enabled: !!destinationId,
+ },
+ );
+ const {
+ mutateAsync: testConnection,
+ isLoading: isLoadingConnection,
+ error: connectionError,
+ isError: isErrorConnection,
+ } = api.destination.testConnection.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ provider: "",
+ accessKeyId: "",
+ bucket: "",
+ name: "",
+ region: "",
+ secretAccessKey: "",
+ endpoint: "",
+ },
+ resolver: zodResolver(addDestination),
+ });
+ useEffect(() => {
+ if (destination) {
+ form.reset({
+ name: destination.name,
+ provider: destination.provider || "",
+ accessKeyId: destination.accessKey,
+ secretAccessKey: destination.secretAccessKey,
+ bucket: destination.bucket,
+ region: destination.region,
+ endpoint: destination.endpoint,
+ });
+ } else {
+ form.reset();
+ }
+ }, [form, form.reset, form.formState.isSubmitSuccessful, destination]);
+
+ const onSubmit = async (data: AddDestination) => {
+ await mutateAsync({
+ provider: data.provider || "",
+ accessKey: data.accessKeyId,
+ bucket: data.bucket,
+ endpoint: data.endpoint,
+ name: data.name,
+ region: data.region,
+ secretAccessKey: data.secretAccessKey,
+ destinationId: destinationId || "",
+ })
+ .then(async () => {
+ toast.success(`Destination ${destinationId ? "Updated" : "Created"}`);
+ await utils.destination.all.invalidate();
+ setOpen(false);
+ })
+ .catch(() => {
+ toast.error(
+ `Error ${destinationId ? "Updating" : "Creating"} the Destination`,
+ );
+ });
+ };
+
+ const handleTestConnection = async (serverId?: string) => {
+ const result = await form.trigger([
+ "provider",
+ "accessKeyId",
+ "secretAccessKey",
+ "bucket",
+ "endpoint",
+ ]);
+
+ if (!result) {
+ const errors = form.formState.errors;
+ const errorFields = Object.entries(errors)
+ .map(([field, error]) => `${field}: ${error?.message}`)
+ .filter(Boolean)
+ .join("\n");
+
+ toast.error("Please fill all required fields", {
+ description: errorFields,
+ });
+ return;
+ }
+
+ if (isCloud && !serverId) {
+ toast.error("Please select a server");
+ return;
+ }
+
+ const provider = form.getValues("provider");
+ const accessKey = form.getValues("accessKeyId");
+ const secretKey = form.getValues("secretAccessKey");
+ const bucket = form.getValues("bucket");
+ const endpoint = form.getValues("endpoint");
+ const region = form.getValues("region");
+
+ const connectionString = `:s3,provider=${provider},access_key_id=${accessKey},secret_access_key=${secretKey},endpoint=${endpoint}${region ? `,region=${region}` : ""}:${bucket}`;
+
+ await testConnection({
+ provider,
+ accessKey,
+ bucket,
+ endpoint,
+ name: "Test",
+ region,
+ secretAccessKey: secretKey,
+ serverId,
+ })
+ .then(() => {
+ toast.success("Connection Success");
+ })
+ .catch((e) => {
+ toast.error("Error connecting to provider", {
+ description: `${e.message}\n\nTry manually: rclone ls ${connectionString}`,
+ });
+ });
+ };
+
+ return (
+
+
+ {destinationId ? (
+
+
+
+ ) : (
+
+
+ Add Destination
+
+ )}
+
+
+
+
+ {destinationId ? "Update" : "Add"} Destination
+
+
+ In this section, you can configure and add new destinations for your
+ backups. Please ensure that you provide the correct information to
+ guarantee secure and efficient storage.
+
+
+ {(isError || isErrorConnection) && (
+
+ {connectionError?.message || error?.message}
+
+ )}
+
+
+
+ {
+ return (
+
+ Name
+
+
+
+
+
+ );
+ }}
+ />
+ {
+ return (
+
+ Provider
+
+
+
+
+
+
+
+
+ {S3_PROVIDERS.map((s3Provider) => (
+
+ {s3Provider.name}
+
+ ))}
+
+
+
+
+
+ );
+ }}
+ />
+
+ {
+ return (
+
+ Access Key Id
+
+
+
+
+
+ );
+ }}
+ />
+ (
+
+
+ Secret Access Key
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Bucket
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Region
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Endpoint
+
+
+
+
+
+ )}
+ />
+
+
+
+ {isCloud ? (
+
+
+ Select a server to test the destination. If you don't have a
+ server choose the default one.
+
+ (
+
+ Server (Optional)
+
+
+
+
+
+
+
+ Servers
+ {servers?.map((server) => (
+
+ {server.name}
+
+ ))}
+ None
+
+
+
+
+
+
+
+ )}
+ />
+ {
+ await handleTestConnection(form.getValues("serverId"));
+ }}
+ >
+ Test Connection
+
+
+ ) : (
+ {
+ await handleTestConnection();
+ }}
+ >
+ Test connection
+
+ )}
+
+
+ {destinationId ? "Update" : "Create"}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/destination/show-destinations.tsx b/data/apps/dokploy/components/dashboard/settings/destination/show-destinations.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..014596ce3c809a6ffceee4e707a87fe6bc979335
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/destination/show-destinations.tsx
@@ -0,0 +1,120 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { Database, FolderUp, Loader2, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { HandleDestinations } from "./handle-destinations";
+
+export const ShowDestinations = () => {
+ const { data, isLoading, refetch } = api.destination.all.useQuery();
+ const { mutateAsync, isLoading: isRemoving } =
+ api.destination.remove.useMutation();
+ return (
+
+
+
+
+
+
+ S3 Destinations
+
+
+ Add your providers like AWS S3, Cloudflare R2, Wasabi,
+ DigitalOcean Spaces etc.
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {data?.length === 0 ? (
+
+
+
+ To create a backup it is required to set at least 1
+ provider.
+
+
+
+ ) : (
+
+
+ {data?.map((destination, index) => (
+
+
+
+
+ {index + 1}. {destination.name}
+
+
+ Created at:{" "}
+ {new Date(
+ destination.createdAt,
+ ).toLocaleDateString()}
+
+
+
+
+ {
+ await mutateAsync({
+ destinationId: destination.destinationId,
+ })
+ .then(() => {
+ toast.success(
+ "Destination deleted successfully",
+ );
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error deleting destination");
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+
+
+
+
+
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/git/bitbucket/add-bitbucket-provider.tsx b/data/apps/dokploy/components/dashboard/settings/git/bitbucket/add-bitbucket-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..0df2d0610358c1751b14da945f8c06e4fdc34940
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/git/bitbucket/add-bitbucket-provider.tsx
@@ -0,0 +1,225 @@
+import { BitbucketIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { CardContent } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { useUrl } from "@/utils/hooks/use-url";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { ExternalLink } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const Schema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ username: z.string().min(1, {
+ message: "Username is required",
+ }),
+ password: z.string().min(1, {
+ message: "App Password is required",
+ }),
+ workspaceName: z.string().optional(),
+});
+
+type Schema = z.infer;
+
+export const AddBitbucketProvider = () => {
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+ const _url = useUrl();
+ const { mutateAsync, error, isError } = api.bitbucket.create.useMutation();
+ const { data: auth } = api.user.get.useQuery();
+ const _router = useRouter();
+ const form = useForm({
+ defaultValues: {
+ username: "",
+ password: "",
+ workspaceName: "",
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ username: "",
+ password: "",
+ workspaceName: "",
+ });
+ }, [form, isOpen]);
+
+ const onSubmit = async (data: Schema) => {
+ await mutateAsync({
+ bitbucketUsername: data.username,
+ appPassword: data.password,
+ bitbucketWorkspaceName: data.workspaceName || "",
+ authId: auth?.id || "",
+ name: data.name || "",
+ })
+ .then(async () => {
+ await utils.gitProvider.getAll.invalidate();
+ toast.success("Bitbucket configured successfully");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error configuring Bitbucket");
+ });
+ };
+
+ return (
+
+
+
+
+ Bitbucket
+
+
+
+
+
+ Bitbucket Provider
+
+
+
+ {isError && {error?.message} }
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/git/bitbucket/edit-bitbucket-provider.tsx b/data/apps/dokploy/components/dashboard/settings/git/bitbucket/edit-bitbucket-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e5a7f7529fd16bf3deef82bf07103a582f07be85
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/git/bitbucket/edit-bitbucket-provider.tsx
@@ -0,0 +1,206 @@
+import { BitbucketIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { CardContent } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const Schema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ username: z.string().min(1, {
+ message: "Username is required",
+ }),
+ workspaceName: z.string().optional(),
+});
+
+type Schema = z.infer;
+
+interface Props {
+ bitbucketId: string;
+}
+
+export const EditBitbucketProvider = ({ bitbucketId }: Props) => {
+ const { data: bitbucket } = api.bitbucket.one.useQuery(
+ {
+ bitbucketId,
+ },
+ {
+ enabled: !!bitbucketId,
+ },
+ );
+
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+ const { mutateAsync, error, isError } = api.bitbucket.update.useMutation();
+ const { mutateAsync: testConnection, isLoading } =
+ api.bitbucket.testConnection.useMutation();
+ const form = useForm({
+ defaultValues: {
+ username: "",
+ workspaceName: "",
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ const username = form.watch("username");
+ const workspaceName = form.watch("workspaceName");
+
+ useEffect(() => {
+ form.reset({
+ username: bitbucket?.bitbucketUsername || "",
+ workspaceName: bitbucket?.bitbucketWorkspaceName || "",
+ name: bitbucket?.gitProvider.name || "",
+ });
+ }, [form, isOpen, bitbucket]);
+
+ const onSubmit = async (data: Schema) => {
+ await mutateAsync({
+ bitbucketId,
+ gitProviderId: bitbucket?.gitProviderId || "",
+ bitbucketUsername: data.username,
+ bitbucketWorkspaceName: data.workspaceName || "",
+ name: data.name || "",
+ })
+ .then(async () => {
+ await utils.gitProvider.getAll.invalidate();
+ toast.success("Bitbucket updated successfully");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating Bitbucket");
+ });
+ };
+
+ return (
+
+
+
+
+
+
+
+
+
+ Update Bitbucket
+
+
+
+ {isError && {error?.message} }
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/git/gitea/add-gitea-provider.tsx b/data/apps/dokploy/components/dashboard/settings/git/gitea/add-gitea-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..13c65bdf3973aa940d282b9d59afe7b95cea62aa
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/git/gitea/add-gitea-provider.tsx
@@ -0,0 +1,286 @@
+import { GiteaIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { CardContent } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import {
+ type GiteaProviderResponse,
+ getGiteaOAuthUrl,
+} from "@/utils/gitea-utils";
+import { useUrl } from "@/utils/hooks/use-url";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { ExternalLink } from "lucide-react";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const Schema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ giteaUrl: z.string().min(1, {
+ message: "Gitea URL is required",
+ }),
+ clientId: z.string().min(1, {
+ message: "Client ID is required",
+ }),
+ clientSecret: z.string().min(1, {
+ message: "Client Secret is required",
+ }),
+ redirectUri: z.string().min(1, {
+ message: "Redirect URI is required",
+ }),
+ organizationName: z.string().optional(),
+});
+
+type Schema = z.infer;
+
+export const AddGiteaProvider = () => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ const urlObj = useUrl();
+ const baseUrl =
+ typeof urlObj === "string" ? urlObj : (urlObj as any)?.url || "";
+
+ const { mutateAsync, error, isError } = api.gitea.create.useMutation();
+ const webhookUrl = `${baseUrl}/api/providers/gitea/callback`;
+
+ const form = useForm({
+ defaultValues: {
+ clientId: "",
+ clientSecret: "",
+ redirectUri: webhookUrl,
+ name: "",
+ giteaUrl: "https://gitea.com",
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ const giteaUrl = form.watch("giteaUrl");
+
+ useEffect(() => {
+ form.reset({
+ clientId: "",
+ clientSecret: "",
+ redirectUri: webhookUrl,
+ name: "",
+ giteaUrl: "https://gitea.com",
+ });
+ }, [form, webhookUrl, isOpen]);
+
+ const onSubmit = async (data: Schema) => {
+ try {
+ // Send the form data to create the Gitea provider
+ const result = (await mutateAsync({
+ clientId: data.clientId,
+ clientSecret: data.clientSecret,
+ name: data.name,
+ redirectUri: data.redirectUri,
+ giteaUrl: data.giteaUrl,
+ organizationName: data.organizationName,
+ })) as unknown as GiteaProviderResponse;
+
+ // Check if we have a giteaId from the response
+ if (!result || !result.giteaId) {
+ toast.error("Failed to get Gitea ID from response");
+ return;
+ }
+
+ // Generate OAuth URL using the shared utility
+ const authUrl = getGiteaOAuthUrl(
+ result.giteaId,
+ data.clientId,
+ data.giteaUrl,
+ baseUrl,
+ );
+
+ // Open the Gitea OAuth URL
+ if (authUrl !== "#") {
+ window.open(authUrl, "_blank");
+ } else {
+ toast.error("Configuration Incomplete", {
+ description: "Please fill in Client ID and Gitea URL first.",
+ });
+ }
+
+ toast.success("Gitea provider created successfully");
+ setIsOpen(false);
+ } catch (error: unknown) {
+ if (error instanceof Error) {
+ toast.error(`Error configuring Gitea: ${error.message}`);
+ } else {
+ toast.error("An unknown error occurred.");
+ }
+ }
+ };
+
+ return (
+
+
+
+
+ Gitea
+
+
+
+
+
+ Gitea Provider
+
+
+
+ {isError && {error?.message} }
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/git/gitea/edit-gitea-provider.tsx b/data/apps/dokploy/components/dashboard/settings/git/gitea/edit-gitea-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..13e43fbf955edf7cd4bf0f1615ab9d370a3b754a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/git/gitea/edit-gitea-provider.tsx
@@ -0,0 +1,296 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { getGiteaOAuthUrl } from "@/utils/gitea-utils";
+import { useUrl } from "@/utils/hooks/use-url";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useRouter } from "next/router";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const formSchema = z.object({
+ name: z.string().min(1, "Name is required"),
+ giteaUrl: z.string().min(1, "Gitea URL is required"),
+ clientId: z.string().min(1, "Client ID is required"),
+ clientSecret: z.string().min(1, "Client Secret is required"),
+});
+
+interface Props {
+ giteaId: string;
+}
+
+export const EditGiteaProvider = ({ giteaId }: Props) => {
+ const router = useRouter();
+ const [open, setOpen] = useState(false);
+ const {
+ data: gitea,
+ isLoading,
+ refetch,
+ } = api.gitea.one.useQuery({ giteaId });
+ const { mutateAsync, isLoading: isUpdating } = api.gitea.update.useMutation();
+ const { mutateAsync: testConnection, isLoading: isTesting } =
+ api.gitea.testConnection.useMutation();
+ const url = useUrl();
+ const utils = api.useUtils();
+
+ useEffect(() => {
+ const { connected, error } = router.query;
+
+ if (!router.isReady) return;
+
+ if (connected) {
+ toast.success("Successfully connected to Gitea", {
+ description: "Your Gitea provider has been authorized.",
+ id: "gitea-connection-success",
+ });
+ refetch();
+ router.replace(
+ {
+ pathname: router.pathname,
+ query: {},
+ },
+ undefined,
+ { shallow: true },
+ );
+ }
+
+ if (error) {
+ toast.error("Gitea Connection Failed", {
+ description: decodeURIComponent(error as string),
+ id: "gitea-connection-error",
+ });
+ router.replace(
+ {
+ pathname: router.pathname,
+ query: {},
+ },
+ undefined,
+ { shallow: true },
+ );
+ }
+ }, [router.query, router.isReady, refetch]);
+
+ const form = useForm>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ name: "",
+ giteaUrl: "https://gitea.com",
+ clientId: "",
+ clientSecret: "",
+ },
+ });
+
+ useEffect(() => {
+ if (gitea) {
+ form.reset({
+ name: gitea.gitProvider?.name || "",
+ giteaUrl: gitea.giteaUrl || "https://gitea.com",
+ clientId: gitea.clientId || "",
+ clientSecret: gitea.clientSecret || "",
+ });
+ }
+ }, [gitea, form]);
+
+ const onSubmit = async (values: z.infer) => {
+ await mutateAsync({
+ giteaId: giteaId,
+ gitProviderId: gitea?.gitProvider?.gitProviderId || "",
+ name: values.name,
+ giteaUrl: values.giteaUrl,
+ clientId: values.clientId,
+ clientSecret: values.clientSecret,
+ })
+ .then(async () => {
+ await utils.gitProvider.getAll.invalidate();
+ toast.success("Gitea provider updated successfully");
+ await refetch();
+ setOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating Gitea provider");
+ });
+ };
+
+ const handleTestConnection = async () => {
+ try {
+ const result = await testConnection({ giteaId });
+ toast.success("Gitea Connection Verified", {
+ description: result,
+ });
+ } catch (error: any) {
+ const formValues = form.getValues();
+ const authUrl =
+ error.authorizationUrl ||
+ getGiteaOAuthUrl(
+ giteaId,
+ formValues.clientId,
+ formValues.giteaUrl,
+ typeof url === "string" ? url : (url as any).url || "",
+ );
+
+ toast.error("Gitea Not Connected", {
+ description:
+ error.message || "Please complete the OAuth authorization process.",
+ action:
+ authUrl && authUrl !== "#"
+ ? {
+ label: "Authorize Now",
+ onClick: () => window.open(authUrl, "_blank"),
+ }
+ : undefined,
+ });
+ }
+ };
+
+ if (isLoading) {
+ return (
+
+
+
+ );
+ }
+
+ // Function to handle dialog open state
+ const handleOpenChange = (newOpen: boolean) => {
+ setOpen(newOpen);
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ Edit Gitea Provider
+
+ Update your Gitea provider details.
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+ )}
+ />
+ (
+
+ Gitea URL
+
+
+
+
+
+ )}
+ />
+ (
+
+ Client ID
+
+
+
+
+
+ )}
+ />
+ (
+
+ Client Secret
+
+
+
+
+
+ )}
+ />
+
+
+
+ Test Connection
+
+
+ {
+ const formValues = form.getValues();
+ const authUrl = getGiteaOAuthUrl(
+ giteaId,
+ formValues.clientId,
+ formValues.giteaUrl,
+ typeof url === "string" ? url : (url as any).url || "",
+ );
+ if (authUrl !== "#") {
+ window.open(authUrl, "_blank");
+ }
+ }}
+ >
+ Connect to Gitea
+
+
+
+ Save
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/git/github/add-github-provider.tsx b/data/apps/dokploy/components/dashboard/settings/git/github/add-github-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..90cefe592efdd0813d646c9e0eef53dc1d645842
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/git/github/add-github-provider.tsx
@@ -0,0 +1,145 @@
+import { GithubIcon } from "@/components/icons/data-tools-icons";
+import { Button } from "@/components/ui/button";
+import { CardContent } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Switch } from "@/components/ui/switch";
+import { authClient } from "@/lib/auth-client";
+import { api } from "@/utils/api";
+import { format } from "date-fns";
+import { useEffect, useState } from "react";
+
+export const AddGithubProvider = () => {
+ const [isOpen, setIsOpen] = useState(false);
+ const { data: activeOrganization } = authClient.useActiveOrganization();
+ const { data } = api.user.get.useQuery();
+ const [manifest, setManifest] = useState("");
+ const [isOrganization, setIsOrganization] = useState(false);
+ const [organizationName, setOrganization] = useState("");
+
+ useEffect(() => {
+ const url = document.location.origin;
+ const manifest = JSON.stringify(
+ {
+ redirect_url: `${origin}/api/providers/github/setup?organizationId=${activeOrganization?.id}`,
+ name: `Dokploy-${format(new Date(), "yyyy-MM-dd")}`,
+ url: origin,
+ hook_attributes: {
+ url: `${url}/api/deploy/github`,
+ },
+ callback_urls: [`${origin}/api/providers/github/setup`],
+ public: false,
+ request_oauth_on_install: true,
+ default_permissions: {
+ contents: "read",
+ metadata: "read",
+ emails: "read",
+ pull_requests: "write",
+ },
+ default_events: ["pull_request", "push"],
+ },
+ null,
+ 4,
+ );
+
+ setManifest(manifest);
+ }, [data?.id]);
+
+ return (
+
+
+
+
+ Github
+
+
+
+
+
+ Github Provider
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/git/github/edit-github-provider.tsx b/data/apps/dokploy/components/dashboard/settings/git/github/edit-github-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..28c6e12334838ba5fa11e3041ad27bd3ededd5e6
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/git/github/edit-github-provider.tsx
@@ -0,0 +1,158 @@
+import { GithubIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { CardContent } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const Schema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+});
+
+type Schema = z.infer;
+
+interface Props {
+ githubId: string;
+}
+
+export const EditGithubProvider = ({ githubId }: Props) => {
+ const { data: github } = api.github.one.useQuery(
+ {
+ githubId,
+ },
+ {
+ enabled: !!githubId,
+ },
+ );
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+ const { mutateAsync, error, isError } = api.github.update.useMutation();
+ const { mutateAsync: testConnection, isLoading } =
+ api.github.testConnection.useMutation();
+ const form = useForm({
+ defaultValues: {
+ name: "",
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ name: github?.gitProvider.name || "",
+ });
+ }, [form, isOpen]);
+
+ const onSubmit = async (data: Schema) => {
+ await mutateAsync({
+ githubId,
+ name: data.name || "",
+ gitProviderId: github?.gitProviderId || "",
+ })
+ .then(async () => {
+ await utils.gitProvider.getAll.invalidate();
+ toast.success("Github updated successfully");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating Github");
+ });
+ };
+
+ return (
+
+
+
+
+
+
+
+
+
+ Update Github
+
+
+
+ {isError && {error?.message} }
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/git/gitlab/add-gitlab-provider.tsx b/data/apps/dokploy/components/dashboard/settings/git/gitlab/add-gitlab-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..023e46ed27ab8fdfc4e3484ff16d651ab177af69
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/git/gitlab/add-gitlab-provider.tsx
@@ -0,0 +1,275 @@
+import { GitlabIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { CardContent } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { useUrl } from "@/utils/hooks/use-url";
+import { zodResolver } from "@hookform/resolvers/zod";
+
+import { ExternalLink } from "lucide-react";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const Schema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ gitlabUrl: z.string().min(1, {
+ message: "GitLab URL is required",
+ }),
+ applicationId: z.string().min(1, {
+ message: "Application ID is required",
+ }),
+ applicationSecret: z.string().min(1, {
+ message: "Application Secret is required",
+ }),
+
+ redirectUri: z.string().min(1, {
+ message: "Redirect URI is required",
+ }),
+ groupName: z.string().optional(),
+});
+
+type Schema = z.infer;
+
+export const AddGitlabProvider = () => {
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+ const url = useUrl();
+ const { data: auth } = api.user.get.useQuery();
+ const { mutateAsync, error, isError } = api.gitlab.create.useMutation();
+ const webhookUrl = `${url}/api/providers/gitlab/callback`;
+
+ const form = useForm({
+ defaultValues: {
+ applicationId: "",
+ applicationSecret: "",
+ groupName: "",
+ redirectUri: webhookUrl,
+ name: "",
+ gitlabUrl: "https://gitlab.com",
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ const gitlabUrl = form.watch("gitlabUrl");
+
+ useEffect(() => {
+ form.reset({
+ applicationId: "",
+ applicationSecret: "",
+ groupName: "",
+ redirectUri: webhookUrl,
+ name: "",
+ gitlabUrl: "https://gitlab.com",
+ });
+ }, [form, isOpen]);
+
+ const onSubmit = async (data: Schema) => {
+ await mutateAsync({
+ applicationId: data.applicationId || "",
+ secret: data.applicationSecret || "",
+ groupName: data.groupName || "",
+ authId: auth?.id || "",
+ name: data.name || "",
+ redirectUri: data.redirectUri || "",
+ gitlabUrl: data.gitlabUrl || "https://gitlab.com",
+ })
+ .then(async () => {
+ await utils.gitProvider.getAll.invalidate();
+ toast.success("GitLab created successfully");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error configuring GitLab");
+ });
+ };
+
+ return (
+
+
+
+
+ GitLab
+
+
+
+
+
+ GitLab Provider
+
+
+
+ {isError && {error?.message} }
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/git/gitlab/edit-gitlab-provider.tsx b/data/apps/dokploy/components/dashboard/settings/git/gitlab/edit-gitlab-provider.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5142a3fe4ce0983268974f7e22144c1ac08af4b2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/git/gitlab/edit-gitlab-provider.tsx
@@ -0,0 +1,204 @@
+import { GitlabIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { CardContent } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const Schema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ gitlabUrl: z.string().url({
+ message: "Invalid Gitlab URL",
+ }),
+ groupName: z.string().optional(),
+});
+
+type Schema = z.infer;
+
+interface Props {
+ gitlabId: string;
+}
+
+export const EditGitlabProvider = ({ gitlabId }: Props) => {
+ const { data: gitlab, refetch } = api.gitlab.one.useQuery(
+ {
+ gitlabId,
+ },
+ {
+ enabled: !!gitlabId,
+ },
+ );
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+ const { mutateAsync, error, isError } = api.gitlab.update.useMutation();
+ const { mutateAsync: testConnection, isLoading } =
+ api.gitlab.testConnection.useMutation();
+ const form = useForm({
+ defaultValues: {
+ groupName: "",
+ name: "",
+ gitlabUrl: "https://gitlab.com",
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ const groupName = form.watch("groupName");
+
+ useEffect(() => {
+ form.reset({
+ groupName: gitlab?.groupName || "",
+ name: gitlab?.gitProvider.name || "",
+ gitlabUrl: gitlab?.gitlabUrl || "",
+ });
+ }, [form, isOpen]);
+
+ const onSubmit = async (data: Schema) => {
+ await mutateAsync({
+ gitlabId,
+ gitProviderId: gitlab?.gitProviderId || "",
+ groupName: data.groupName || "",
+ name: data.name || "",
+ gitlabUrl: data.gitlabUrl || "",
+ })
+ .then(async () => {
+ await utils.gitProvider.getAll.invalidate();
+ toast.success("Gitlab updated successfully");
+ setIsOpen(false);
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error updating Gitlab");
+ });
+ };
+
+ return (
+
+
+
+
+
+
+
+
+
+ Update GitLab
+
+
+
+ {isError && {error?.message} }
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/git/show-git-providers.tsx b/data/apps/dokploy/components/dashboard/settings/git/show-git-providers.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..35d9ef0d70a52082bb464d00074f9aea7336dda4
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/git/show-git-providers.tsx
@@ -0,0 +1,281 @@
+import {
+ BitbucketIcon,
+ GiteaIcon,
+ GithubIcon,
+ GitlabIcon,
+} from "@/components/icons/data-tools-icons";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button, buttonVariants } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { useUrl } from "@/utils/hooks/use-url";
+import { formatDate } from "date-fns";
+import {
+ ExternalLinkIcon,
+ GitBranch,
+ ImportIcon,
+ Loader2,
+ Trash2,
+} from "lucide-react";
+import Link from "next/link";
+import { toast } from "sonner";
+import { AddBitbucketProvider } from "./bitbucket/add-bitbucket-provider";
+import { EditBitbucketProvider } from "./bitbucket/edit-bitbucket-provider";
+import { AddGiteaProvider } from "./gitea/add-gitea-provider";
+import { EditGiteaProvider } from "./gitea/edit-gitea-provider";
+import { AddGithubProvider } from "./github/add-github-provider";
+import { EditGithubProvider } from "./github/edit-github-provider";
+import { AddGitlabProvider } from "./gitlab/add-gitlab-provider";
+import { EditGitlabProvider } from "./gitlab/edit-gitlab-provider";
+
+export const ShowGitProviders = () => {
+ const { data, isLoading, refetch } = api.gitProvider.getAll.useQuery();
+ const { mutateAsync, isLoading: isRemoving } =
+ api.gitProvider.remove.useMutation();
+ const url = useUrl();
+
+ const getGitlabUrl = (
+ clientId: string,
+ gitlabId: string,
+ gitlabUrl: string,
+ ) => {
+ const redirectUri = `${url}/api/providers/gitlab/callback?gitlabId=${gitlabId}`;
+ const scope = "api read_user read_repository";
+ const authUrl = `${gitlabUrl}/oauth/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${encodeURIComponent(scope)}`;
+ return authUrl;
+ };
+
+ return (
+
+
+
+
+
+
+ Git Providers
+
+
+ Connect your Git provider for authentication.
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {data?.length === 0 ? (
+
+
+
+ Create your first Git Provider
+
+
+
+ ) : (
+
+
+
+ Available Providers
+
+
+
+
+
+ {data?.map((gitProvider, _index) => {
+ const isGithub = gitProvider.providerType === "github";
+ const isGitlab = gitProvider.providerType === "gitlab";
+ const isBitbucket =
+ gitProvider.providerType === "bitbucket";
+ const isGitea = gitProvider.providerType === "gitea";
+
+ const haveGithubRequirements =
+ isGithub &&
+ gitProvider.github?.githubPrivateKey &&
+ gitProvider.github?.githubAppId &&
+ gitProvider.github?.githubInstallationId;
+
+ const haveGitlabRequirements =
+ isGitlab &&
+ gitProvider.gitlab?.accessToken &&
+ gitProvider.gitlab?.refreshToken;
+
+ return (
+
+
+
+
+ {isGithub && (
+
+ )}
+ {isGitlab && (
+
+ )}
+ {isBitbucket && (
+
+ )}
+ {isGitea &&
}
+
+
+ {gitProvider.name}
+
+
+ {formatDate(
+ gitProvider.createdAt,
+ "yyyy-MM-dd hh:mm:ss a",
+ )}
+
+
+
+
+
+
+ {!haveGithubRequirements && isGithub && (
+
+
+
+
+
+ )}
+ {haveGithubRequirements && isGithub && (
+
+
+
+
+
+ )}
+ {!haveGitlabRequirements && isGitlab && (
+
+
+
+
+
+ )}
+
+ {isGithub && haveGithubRequirements && (
+
+ )}
+
+ {isGitlab && (
+
+ )}
+
+ {isBitbucket && (
+
+ )}
+
+ {isGitea && (
+
+ )}
+
+
{
+ await mutateAsync({
+ gitProviderId: gitProvider.gitProviderId,
+ })
+ .then(() => {
+ toast.success(
+ "Git Provider deleted successfully",
+ );
+ refetch();
+ })
+ .catch(() => {
+ toast.error(
+ "Error deleting Git Provider",
+ );
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ );
+ })}
+
+
+
+
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/handle-ai.tsx b/data/apps/dokploy/components/dashboard/settings/handle-ai.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..567a8b08e984e29b20a5adc1d0ff044a665d97f8
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/handle-ai.tsx
@@ -0,0 +1,281 @@
+"use client";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PenBoxIcon, PlusIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const Schema = z.object({
+ name: z.string().min(1, { message: "Name is required" }),
+ apiUrl: z.string().url({ message: "Please enter a valid URL" }),
+ apiKey: z.string().min(1, { message: "API Key is required" }),
+ model: z.string().min(1, { message: "Model is required" }),
+ isEnabled: z.boolean(),
+});
+
+type Schema = z.infer;
+
+interface Props {
+ aiId?: string;
+}
+
+export const HandleAi = ({ aiId }: Props) => {
+ const utils = api.useUtils();
+ const [error, setError] = useState(null);
+ const [open, setOpen] = useState(false);
+ const { data, refetch } = api.ai.one.useQuery(
+ {
+ aiId: aiId || "",
+ },
+ {
+ enabled: !!aiId,
+ },
+ );
+ const { mutateAsync, isLoading } = aiId
+ ? api.ai.update.useMutation()
+ : api.ai.create.useMutation();
+
+ const form = useForm({
+ resolver: zodResolver(Schema),
+ defaultValues: {
+ name: "",
+ apiUrl: "",
+ apiKey: "",
+ model: "gpt-3.5-turbo",
+ isEnabled: true,
+ },
+ });
+
+ useEffect(() => {
+ form.reset({
+ name: data?.name ?? "",
+ apiUrl: data?.apiUrl ?? "https://api.openai.com/v1",
+ apiKey: data?.apiKey ?? "",
+ model: data?.model ?? "gpt-3.5-turbo",
+ isEnabled: data?.isEnabled ?? true,
+ });
+ }, [aiId, form, data]);
+
+ const apiUrl = form.watch("apiUrl");
+ const apiKey = form.watch("apiKey");
+
+ const { data: models, isLoading: isLoadingServerModels } =
+ api.ai.getModels.useQuery(
+ {
+ apiUrl: apiUrl ?? "",
+ apiKey: apiKey ?? "",
+ },
+ {
+ enabled: !!apiUrl && !!apiKey,
+ onError: (error) => {
+ setError(`Failed to fetch models: ${error.message}`);
+ },
+ },
+ );
+
+ useEffect(() => {
+ const apiUrl = form.watch("apiUrl");
+ const apiKey = form.watch("apiKey");
+ if (apiUrl && apiKey) {
+ form.setValue("model", "");
+ }
+ }, [form.watch("apiUrl"), form.watch("apiKey")]);
+
+ const onSubmit = async (data: Schema) => {
+ try {
+ await mutateAsync({
+ ...data,
+ aiId: aiId || "",
+ });
+
+ utils.ai.getAll.invalidate();
+ toast.success("AI settings saved successfully");
+ refetch();
+ setOpen(false);
+ } catch (error) {
+ toast.error("Failed to save AI settings", {
+ description: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ };
+
+ return (
+
+
+ {aiId ? (
+
+
+
+ ) : (
+
+
+ Add AI
+
+ )}
+
+
+
+ {aiId ? "Edit AI" : "Add AI"}
+
+ Configure your AI provider settings
+
+
+
+ {error && {error} }
+
+ (
+
+ Name
+
+
+
+
+ A name to identify this configuration
+
+
+
+ )}
+ />
+
+ (
+
+ API URL
+
+
+
+
+ The base URL for your AI provider's API
+
+
+
+ )}
+ />
+
+ (
+
+ API Key
+
+
+
+
+ Your API key for authentication
+
+
+
+ )}
+ />
+
+ {isLoadingServerModels && (
+
+ Loading models...
+
+ )}
+
+ {!isLoadingServerModels && models && models.length > 0 && (
+ (
+
+ Model
+
+
+
+
+
+
+
+ {models.map((model) => (
+
+ {model.id}
+
+ ))}
+
+
+ Select an AI model to use
+
+
+ )}
+ />
+ )}
+
+ (
+
+
+
+ Enable AI Features
+
+
+ Turn on/off AI functionality
+
+
+
+
+
+
+ )}
+ />
+
+
+
+ {aiId ? "Update" : "Create"}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/notifications/handle-notifications.tsx b/data/apps/dokploy/components/dashboard/settings/notifications/handle-notifications.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e0476529834362c784adf87d40b0f51094ca595f
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/notifications/handle-notifications.tsx
@@ -0,0 +1,1085 @@
+import {
+ DiscordIcon,
+ SlackIcon,
+ TelegramIcon,
+} from "@/components/icons/notification-icons";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ AlertTriangle,
+ Mail,
+ MessageCircleMore,
+ PenBoxIcon,
+ PlusIcon,
+} from "lucide-react";
+import { useEffect, useState } from "react";
+import { useFieldArray, useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const notificationBaseSchema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ appDeploy: z.boolean().default(false),
+ appBuildError: z.boolean().default(false),
+ databaseBackup: z.boolean().default(false),
+ dokployRestart: z.boolean().default(false),
+ dockerCleanup: z.boolean().default(false),
+ serverThreshold: z.boolean().default(false),
+});
+
+export const notificationSchema = z.discriminatedUnion("type", [
+ z
+ .object({
+ type: z.literal("slack"),
+ webhookUrl: z.string().min(1, { message: "Webhook URL is required" }),
+ channel: z.string(),
+ })
+ .merge(notificationBaseSchema),
+ z
+ .object({
+ type: z.literal("telegram"),
+ botToken: z.string().min(1, { message: "Bot Token is required" }),
+ chatId: z.string().min(1, { message: "Chat ID is required" }),
+ messageThreadId: z.string().optional(),
+ })
+ .merge(notificationBaseSchema),
+ z
+ .object({
+ type: z.literal("discord"),
+ webhookUrl: z.string().min(1, { message: "Webhook URL is required" }),
+ decoration: z.boolean().default(true),
+ })
+ .merge(notificationBaseSchema),
+ z
+ .object({
+ type: z.literal("email"),
+ smtpServer: z.string().min(1, { message: "SMTP Server is required" }),
+ smtpPort: z.number().min(1, { message: "SMTP Port is required" }),
+ username: z.string().min(1, { message: "Username is required" }),
+ password: z.string().min(1, { message: "Password is required" }),
+ fromAddress: z.string().min(1, { message: "From Address is required" }),
+ toAddresses: z
+ .array(
+ z.string().min(1, { message: "Email is required" }).email({
+ message: "Email is invalid",
+ }),
+ )
+ .min(1, { message: "At least one email is required" }),
+ })
+ .merge(notificationBaseSchema),
+ z
+ .object({
+ type: z.literal("gotify"),
+ serverUrl: z.string().min(1, { message: "Server URL is required" }),
+ appToken: z.string().min(1, { message: "App Token is required" }),
+ priority: z.number().min(1).max(10).default(5),
+ decoration: z.boolean().default(true),
+ })
+ .merge(notificationBaseSchema),
+]);
+
+export const notificationsMap = {
+ slack: {
+ icon: ,
+ label: "Slack",
+ },
+ telegram: {
+ icon: ,
+ label: "Telegram",
+ },
+ discord: {
+ icon: ,
+ label: "Discord",
+ },
+ email: {
+ icon: ,
+ label: "Email",
+ },
+ gotify: {
+ icon: ,
+ label: "Gotify",
+ },
+};
+
+export type NotificationSchema = z.infer;
+
+interface Props {
+ notificationId?: string;
+}
+
+export const HandleNotifications = ({ notificationId }: Props) => {
+ const utils = api.useUtils();
+ const [visible, setVisible] = useState(false);
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+
+ const { data: notification } = api.notification.one.useQuery(
+ {
+ notificationId: notificationId || "",
+ },
+ {
+ enabled: !!notificationId,
+ },
+ );
+ const { mutateAsync: testSlackConnection, isLoading: isLoadingSlack } =
+ api.notification.testSlackConnection.useMutation();
+ const { mutateAsync: testTelegramConnection, isLoading: isLoadingTelegram } =
+ api.notification.testTelegramConnection.useMutation();
+ const { mutateAsync: testDiscordConnection, isLoading: isLoadingDiscord } =
+ api.notification.testDiscordConnection.useMutation();
+ const { mutateAsync: testEmailConnection, isLoading: isLoadingEmail } =
+ api.notification.testEmailConnection.useMutation();
+ const { mutateAsync: testGotifyConnection, isLoading: isLoadingGotify } =
+ api.notification.testGotifyConnection.useMutation();
+ const slackMutation = notificationId
+ ? api.notification.updateSlack.useMutation()
+ : api.notification.createSlack.useMutation();
+ const telegramMutation = notificationId
+ ? api.notification.updateTelegram.useMutation()
+ : api.notification.createTelegram.useMutation();
+ const discordMutation = notificationId
+ ? api.notification.updateDiscord.useMutation()
+ : api.notification.createDiscord.useMutation();
+ const emailMutation = notificationId
+ ? api.notification.updateEmail.useMutation()
+ : api.notification.createEmail.useMutation();
+ const gotifyMutation = notificationId
+ ? api.notification.updateGotify.useMutation()
+ : api.notification.createGotify.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ type: "slack",
+ webhookUrl: "",
+ channel: "",
+ name: "",
+ },
+ resolver: zodResolver(notificationSchema),
+ });
+ const type = form.watch("type");
+
+ const { fields, append, remove } = useFieldArray({
+ control: form.control,
+ name: "toAddresses" as never,
+ });
+
+ useEffect(() => {
+ if (type === "email") {
+ append("");
+ }
+ }, [type, append]);
+
+ useEffect(() => {
+ if (notification) {
+ if (notification.notificationType === "slack") {
+ form.reset({
+ appBuildError: notification.appBuildError,
+ appDeploy: notification.appDeploy,
+ dokployRestart: notification.dokployRestart,
+ databaseBackup: notification.databaseBackup,
+ dockerCleanup: notification.dockerCleanup,
+ webhookUrl: notification.slack?.webhookUrl,
+ channel: notification.slack?.channel || "",
+ name: notification.name,
+ type: notification.notificationType,
+ serverThreshold: notification.serverThreshold,
+ });
+ } else if (notification.notificationType === "telegram") {
+ form.reset({
+ appBuildError: notification.appBuildError,
+ appDeploy: notification.appDeploy,
+ dokployRestart: notification.dokployRestart,
+ databaseBackup: notification.databaseBackup,
+ botToken: notification.telegram?.botToken,
+ messageThreadId: notification.telegram?.messageThreadId || "",
+ chatId: notification.telegram?.chatId,
+ type: notification.notificationType,
+ name: notification.name,
+ dockerCleanup: notification.dockerCleanup,
+ serverThreshold: notification.serverThreshold,
+ });
+ } else if (notification.notificationType === "discord") {
+ form.reset({
+ appBuildError: notification.appBuildError,
+ appDeploy: notification.appDeploy,
+ dokployRestart: notification.dokployRestart,
+ databaseBackup: notification.databaseBackup,
+ type: notification.notificationType,
+ webhookUrl: notification.discord?.webhookUrl,
+ decoration: notification.discord?.decoration || undefined,
+ name: notification.name,
+ dockerCleanup: notification.dockerCleanup,
+ serverThreshold: notification.serverThreshold,
+ });
+ } else if (notification.notificationType === "email") {
+ form.reset({
+ appBuildError: notification.appBuildError,
+ appDeploy: notification.appDeploy,
+ dokployRestart: notification.dokployRestart,
+ databaseBackup: notification.databaseBackup,
+ type: notification.notificationType,
+ smtpServer: notification.email?.smtpServer,
+ smtpPort: notification.email?.smtpPort,
+ username: notification.email?.username,
+ password: notification.email?.password,
+ toAddresses: notification.email?.toAddresses,
+ fromAddress: notification.email?.fromAddress,
+ name: notification.name,
+ dockerCleanup: notification.dockerCleanup,
+ serverThreshold: notification.serverThreshold,
+ });
+ } else if (notification.notificationType === "gotify") {
+ form.reset({
+ appBuildError: notification.appBuildError,
+ appDeploy: notification.appDeploy,
+ dokployRestart: notification.dokployRestart,
+ databaseBackup: notification.databaseBackup,
+ type: notification.notificationType,
+ appToken: notification.gotify?.appToken,
+ decoration: notification.gotify?.decoration || undefined,
+ priority: notification.gotify?.priority,
+ serverUrl: notification.gotify?.serverUrl,
+ name: notification.name,
+ dockerCleanup: notification.dockerCleanup,
+ });
+ }
+ } else {
+ form.reset();
+ }
+ }, [form, form.reset, form.formState.isSubmitSuccessful, notification]);
+
+ const activeMutation = {
+ slack: slackMutation,
+ telegram: telegramMutation,
+ discord: discordMutation,
+ email: emailMutation,
+ gotify: gotifyMutation,
+ };
+
+ const onSubmit = async (data: NotificationSchema) => {
+ const {
+ appBuildError,
+ appDeploy,
+ dokployRestart,
+ databaseBackup,
+ dockerCleanup,
+ serverThreshold,
+ } = data;
+ let promise: Promise | null = null;
+ if (data.type === "slack") {
+ promise = slackMutation.mutateAsync({
+ appBuildError: appBuildError,
+ appDeploy: appDeploy,
+ dokployRestart: dokployRestart,
+ databaseBackup: databaseBackup,
+ webhookUrl: data.webhookUrl,
+ channel: data.channel,
+ name: data.name,
+ dockerCleanup: dockerCleanup,
+ slackId: notification?.slackId || "",
+ notificationId: notificationId || "",
+ serverThreshold: serverThreshold,
+ });
+ } else if (data.type === "telegram") {
+ promise = telegramMutation.mutateAsync({
+ appBuildError: appBuildError,
+ appDeploy: appDeploy,
+ dokployRestart: dokployRestart,
+ databaseBackup: databaseBackup,
+ botToken: data.botToken,
+ messageThreadId: data.messageThreadId || "",
+ chatId: data.chatId,
+ name: data.name,
+ dockerCleanup: dockerCleanup,
+ notificationId: notificationId || "",
+ telegramId: notification?.telegramId || "",
+ serverThreshold: serverThreshold,
+ });
+ } else if (data.type === "discord") {
+ promise = discordMutation.mutateAsync({
+ appBuildError: appBuildError,
+ appDeploy: appDeploy,
+ dokployRestart: dokployRestart,
+ databaseBackup: databaseBackup,
+ webhookUrl: data.webhookUrl,
+ decoration: data.decoration,
+ name: data.name,
+ dockerCleanup: dockerCleanup,
+ notificationId: notificationId || "",
+ discordId: notification?.discordId || "",
+ serverThreshold: serverThreshold,
+ });
+ } else if (data.type === "email") {
+ promise = emailMutation.mutateAsync({
+ appBuildError: appBuildError,
+ appDeploy: appDeploy,
+ dokployRestart: dokployRestart,
+ databaseBackup: databaseBackup,
+ smtpServer: data.smtpServer,
+ smtpPort: data.smtpPort,
+ username: data.username,
+ password: data.password,
+ fromAddress: data.fromAddress,
+ toAddresses: data.toAddresses,
+ name: data.name,
+ dockerCleanup: dockerCleanup,
+ notificationId: notificationId || "",
+ emailId: notification?.emailId || "",
+ serverThreshold: serverThreshold,
+ });
+ } else if (data.type === "gotify") {
+ promise = gotifyMutation.mutateAsync({
+ appBuildError: appBuildError,
+ appDeploy: appDeploy,
+ dokployRestart: dokployRestart,
+ databaseBackup: databaseBackup,
+ serverUrl: data.serverUrl,
+ appToken: data.appToken,
+ priority: data.priority,
+ name: data.name,
+ dockerCleanup: dockerCleanup,
+ decoration: data.decoration,
+ notificationId: notificationId || "",
+ gotifyId: notification?.gotifyId || "",
+ });
+ }
+
+ if (promise) {
+ await promise
+ .then(async () => {
+ toast.success(
+ notificationId ? "Notification Updated" : "Notification Created",
+ );
+ form.reset({
+ type: "slack",
+ webhookUrl: "",
+ });
+ setVisible(false);
+ await utils.notification.all.invalidate();
+ })
+ .catch(() => {
+ toast.error(
+ notificationId
+ ? "Error updating a notification"
+ : "Error creating a notification",
+ );
+ });
+ }
+ };
+ return (
+
+
+ {notificationId ? (
+
+
+
+ ) : (
+
+
+ Add Notification
+
+ )}
+
+
+
+
+ {notificationId ? "Update" : "Add"} Notification
+
+
+ {notificationId
+ ? "Update your notification providers for multiple channels."
+ : "Create new notification providers for multiple channels."}
+
+
+
+
+ (
+
+
+ Select a provider
+
+
+
+ {Object.entries(notificationsMap).map(([key, value]) => (
+
+
+
+
+
+ {value.icon}
+ {value.label}
+
+
+
+
+ ))}
+
+
+
+ {activeMutation[field.value].isError && (
+
+
+
+ {activeMutation[field.value].error?.message}
+
+
+ )}
+
+ )}
+ />
+
+
+
+ Fill the next fields.
+
+
+
+
+
+ Select the actions.
+
+
+
+
(
+
+
+ App Deploy
+
+ Trigger the action when a app is deployed.
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ App Build Error
+
+ Trigger the action when the build fails.
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+
+ Database Backup
+
+ Trigger the action when a database backup is created.
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+
+ Docker Cleanup
+
+ Trigger the action when the docker cleanup is
+ performed.
+
+
+
+
+
+
+ )}
+ />
+
+ {!isCloud && (
+ (
+
+
+ Dokploy Restart
+
+ Trigger the action when dokploy is restarted.
+
+
+
+
+
+
+ )}
+ />
+ )}
+
+ {isCloud && (
+ (
+
+
+ Server Threshold
+
+ Trigger the action when the server threshold is
+ reached.
+
+
+
+
+
+
+ )}
+ />
+ )}
+
+
+
+
+
+ {
+ try {
+ if (type === "slack") {
+ await testSlackConnection({
+ webhookUrl: form.getValues("webhookUrl"),
+ channel: form.getValues("channel"),
+ });
+ } else if (type === "telegram") {
+ await testTelegramConnection({
+ botToken: form.getValues("botToken"),
+ chatId: form.getValues("chatId"),
+ messageThreadId: form.getValues("messageThreadId") || "",
+ });
+ } else if (type === "discord") {
+ await testDiscordConnection({
+ webhookUrl: form.getValues("webhookUrl"),
+ decoration: form.getValues("decoration"),
+ });
+ } else if (type === "email") {
+ await testEmailConnection({
+ smtpServer: form.getValues("smtpServer"),
+ smtpPort: form.getValues("smtpPort"),
+ username: form.getValues("username"),
+ password: form.getValues("password"),
+ toAddresses: form.getValues("toAddresses"),
+ fromAddress: form.getValues("fromAddress"),
+ });
+ } else if (type === "gotify") {
+ await testGotifyConnection({
+ serverUrl: form.getValues("serverUrl"),
+ appToken: form.getValues("appToken"),
+ priority: form.getValues("priority"),
+ decoration: form.getValues("decoration"),
+ });
+ }
+ toast.success("Connection Success");
+ } catch (_err) {
+ toast.error("Error testing the provider");
+ }
+ }}
+ >
+ Test Notification
+
+
+ {notificationId ? "Update" : "Create"}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/notifications/show-notifications.tsx b/data/apps/dokploy/components/dashboard/settings/notifications/show-notifications.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..26ac1793210b8782c0059f4d1ce0ca921e8056e9
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/notifications/show-notifications.tsx
@@ -0,0 +1,147 @@
+import {
+ DiscordIcon,
+ SlackIcon,
+ TelegramIcon,
+} from "@/components/icons/notification-icons";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { Bell, Loader2, Mail, MessageCircleMore, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { HandleNotifications } from "./handle-notifications";
+
+export const ShowNotifications = () => {
+ const { data, isLoading, refetch } = api.notification.all.useQuery();
+ const { mutateAsync, isLoading: isRemoving } =
+ api.notification.remove.useMutation();
+
+ return (
+
+
+
+
+
+
+ Notifications
+
+
+ Add your providers to receive notifications, like Discord, Slack,
+ Telegram, Email.
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {data?.length === 0 ? (
+
+
+
+ To send notifications it is required to set at least 1
+ provider.
+
+
+
+ ) : (
+
+
+ {data?.map((notification, _index) => (
+
+
+
+ {notification.notificationType === "slack" && (
+
+
+
+ )}
+ {notification.notificationType === "telegram" && (
+
+
+
+ )}
+ {notification.notificationType === "discord" && (
+
+
+
+ )}
+ {notification.notificationType === "email" && (
+
+
+
+ )}
+ {notification.notificationType === "gotify" && (
+
+
+
+ )}
+
+ {notification.name}
+
+
+
+
+ {
+ await mutateAsync({
+ notificationId: notification.notificationId,
+ })
+ .then(() => {
+ toast.success(
+ "Notification deleted successfully",
+ );
+ refetch();
+ })
+ .catch(() => {
+ toast.error(
+ "Error deleting notification",
+ );
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+
+
+
+
+
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/profile/disable-2fa.tsx b/data/apps/dokploy/components/dashboard/settings/profile/disable-2fa.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..458bf563203cd40d8affbd900694725dbaa6f5d2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/profile/disable-2fa.tsx
@@ -0,0 +1,135 @@
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { authClient } from "@/lib/auth-client";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const PasswordSchema = z.object({
+ password: z.string().min(8, {
+ message: "Password is required",
+ }),
+});
+
+type PasswordForm = z.infer;
+
+export const Disable2FA = () => {
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+
+ const form = useForm({
+ resolver: zodResolver(PasswordSchema),
+ defaultValues: {
+ password: "",
+ },
+ });
+
+ const handleSubmit = async (formData: PasswordForm) => {
+ setIsLoading(true);
+ try {
+ const result = await authClient.twoFactor.disable({
+ password: formData.password,
+ });
+
+ if (result.error) {
+ form.setError("password", {
+ message: result.error.message,
+ });
+ toast.error(result.error.message);
+ return;
+ }
+
+ toast.success("2FA disabled successfully");
+ utils.user.get.invalidate();
+ setIsOpen(false);
+ } catch (_error) {
+ form.setError("password", {
+ message: "Connection error. Please try again.",
+ });
+ toast.error("Connection error. Please try again.");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+
+
+ Disable 2FA
+
+
+
+ Are you absolutely sure?
+
+ This action cannot be undone. This will permanently disable
+ Two-Factor Authentication for your account.
+
+
+
+
+
+ (
+
+ Password
+
+
+
+
+ Enter your password to disable 2FA
+
+
+
+ )}
+ />
+
+ {
+ form.reset();
+ setIsOpen(false);
+ }}
+ >
+ Cancel
+
+
+ Disable 2FA
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/profile/enable-2fa.tsx b/data/apps/dokploy/components/dashboard/settings/profile/enable-2fa.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..afc859f41aac5fdde4a1d3819f4657e81bec8b36
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/profile/enable-2fa.tsx
@@ -0,0 +1,346 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ InputOTP,
+ InputOTPGroup,
+ InputOTPSlot,
+} from "@/components/ui/input-otp";
+import { authClient } from "@/lib/auth-client";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Fingerprint, QrCode } from "lucide-react";
+import QRCode from "qrcode";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const PasswordSchema = z.object({
+ password: z.string().min(8, {
+ message: "Password is required",
+ }),
+ issuer: z.string().optional(),
+});
+
+const PinSchema = z.object({
+ pin: z.string().min(6, {
+ message: "Pin is required",
+ }),
+});
+
+type TwoFactorSetupData = {
+ qrCodeUrl: string;
+ secret: string;
+ totpURI: string;
+};
+
+type PasswordForm = z.infer;
+type PinForm = z.infer;
+
+export const Enable2FA = () => {
+ const utils = api.useUtils();
+ const [data, setData] = useState(null);
+ const [backupCodes, setBackupCodes] = useState([]);
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+ const [step, setStep] = useState<"password" | "verify">("password");
+ const [isPasswordLoading, setIsPasswordLoading] = useState(false);
+ const [otpValue, setOtpValue] = useState("");
+
+ const handleVerifySubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ try {
+ const result = await authClient.twoFactor.verifyTotp({
+ code: otpValue,
+ });
+
+ if (result.error) {
+ if (result.error.code === "INVALID_TWO_FACTOR_AUTHENTICATION") {
+ toast.error("Invalid verification code");
+ return;
+ }
+
+ throw result.error;
+ }
+
+ if (!result.data) {
+ throw new Error("No response received from server");
+ }
+
+ toast.success("2FA configured successfully");
+ utils.user.get.invalidate();
+ setIsDialogOpen(false);
+ } catch (error) {
+ if (error instanceof Error) {
+ const errorMessage =
+ error.message === "Failed to fetch"
+ ? "Connection error. Please check your internet connection."
+ : error.message;
+
+ toast.error(errorMessage);
+ } else {
+ toast.error("Error verifying 2FA code", {
+ description: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ }
+ };
+
+ const passwordForm = useForm({
+ resolver: zodResolver(PasswordSchema),
+ defaultValues: {
+ password: "",
+ },
+ });
+
+ const pinForm = useForm({
+ resolver: zodResolver(PinSchema),
+ defaultValues: {
+ pin: "",
+ },
+ });
+
+ useEffect(() => {
+ if (!isDialogOpen) {
+ setStep("password");
+ setData(null);
+ setBackupCodes([]);
+ setOtpValue("");
+ passwordForm.reset({
+ password: "",
+ issuer: "",
+ });
+ }
+ }, [isDialogOpen, passwordForm]);
+
+ useEffect(() => {
+ if (step === "verify") {
+ setOtpValue("");
+ }
+ }, [step]);
+
+ const handlePasswordSubmit = async (formData: PasswordForm) => {
+ setIsPasswordLoading(true);
+ try {
+ const { data: enableData, error } = await authClient.twoFactor.enable({
+ password: formData.password,
+ issuer: formData.issuer,
+ });
+
+ if (!enableData) {
+ throw new Error(error?.message || "Error enabling 2FA");
+ }
+
+ if (enableData.backupCodes) {
+ setBackupCodes(enableData.backupCodes);
+ }
+
+ if (enableData.totpURI) {
+ const qrCodeUrl = await QRCode.toDataURL(enableData.totpURI);
+
+ setData({
+ qrCodeUrl,
+ secret: enableData.totpURI.split("secret=")[1]?.split("&")[0] || "",
+ totpURI: enableData.totpURI,
+ });
+
+ setStep("verify");
+ toast.success("Scan the QR code with your authenticator app");
+ } else {
+ throw new Error("No TOTP URI received from server");
+ }
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Error setting up 2FA",
+ );
+ passwordForm.setError("password", {
+ message:
+ error instanceof Error ? error.message : "Error setting up 2FA",
+ });
+ } finally {
+ setIsPasswordLoading(false);
+ }
+ };
+
+ return (
+
+
+
+
+ Enable 2FA
+
+
+
+
+ 2FA Setup
+
+ {step === "password"
+ ? "Enter your password to begin 2FA setup"
+ : "Scan the QR code and verify with your authenticator app"}
+
+
+
+ {step === "password" ? (
+
+
+ (
+
+ Password
+
+
+
+
+ Enter your password to enable 2FA
+
+
+
+ )}
+ />
+ (
+
+ Issuer
+
+
+
+
+ Use a custom issuer to identify the service you're
+ authenticating with.
+
+
+
+ )}
+ />
+
+ Continue
+
+
+
+ ) : (
+
+
+
+ {data?.qrCodeUrl ? (
+ <>
+
+
+
+ Scan this QR code with your authenticator app
+
+
+
+
+ Can't scan the QR code?
+
+
+ {data.secret}
+
+
+
+
+ {backupCodes && backupCodes.length > 0 && (
+
+
Backup Codes
+
+ {backupCodes.map((code, index) => (
+
+ {code}
+
+ ))}
+
+
+ Save these backup codes in a secure place. You can use
+ them to access your account if you lose access to your
+ authenticator device.
+
+
+ )}
+ >
+ ) : (
+
+
+
+ )}
+
+
+
+ Verification Code
+
+
+
+
+
+
+
+
+
+
+
+ Enter the 6-digit code from your authenticator app
+
+
+
+
+ Enable 2FA
+
+
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx b/data/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..59e4736deb6f015eb605e2402e6c4cbd638e8581
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx
@@ -0,0 +1,309 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { Switch } from "@/components/ui/switch";
+import { generateSHA256Hash } from "@/lib/utils";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Loader2, User } from "lucide-react";
+import { useTranslation } from "next-i18next";
+import { useEffect, useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import { Disable2FA } from "./disable-2fa";
+import { Enable2FA } from "./enable-2fa";
+
+const profileSchema = z.object({
+ email: z.string(),
+ password: z.string().nullable(),
+ currentPassword: z.string().nullable(),
+ image: z.string().optional(),
+ allowImpersonation: z.boolean().optional().default(false),
+});
+
+type Profile = z.infer;
+
+const randomImages = [
+ "/avatars/avatar-1.png",
+ "/avatars/avatar-2.png",
+ "/avatars/avatar-3.png",
+ "/avatars/avatar-4.png",
+ "/avatars/avatar-5.png",
+ "/avatars/avatar-6.png",
+ "/avatars/avatar-7.png",
+ "/avatars/avatar-8.png",
+ "/avatars/avatar-9.png",
+ "/avatars/avatar-10.png",
+ "/avatars/avatar-11.png",
+ "/avatars/avatar-12.png",
+];
+
+export const ProfileForm = () => {
+ const _utils = api.useUtils();
+ const { data, refetch, isLoading } = api.user.get.useQuery();
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+
+ const {
+ mutateAsync,
+ isLoading: isUpdating,
+ isError,
+ error,
+ } = api.user.update.useMutation();
+ const { t } = useTranslation("settings");
+ const [gravatarHash, setGravatarHash] = useState(null);
+
+ const availableAvatars = useMemo(() => {
+ if (gravatarHash === null) return randomImages;
+ return randomImages.concat([
+ `https://www.gravatar.com/avatar/${gravatarHash}`,
+ ]);
+ }, [gravatarHash]);
+
+ const form = useForm({
+ defaultValues: {
+ email: data?.user?.email || "",
+ password: "",
+ image: data?.user?.image || "",
+ currentPassword: "",
+ allowImpersonation: data?.user?.allowImpersonation || false,
+ },
+ resolver: zodResolver(profileSchema),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset(
+ {
+ email: data?.user?.email || "",
+ password: form.getValues("password") || "",
+ image: data?.user?.image || "",
+ currentPassword: form.getValues("currentPassword") || "",
+ allowImpersonation: data?.user?.allowImpersonation,
+ },
+ {
+ keepValues: true,
+ },
+ );
+ form.setValue("allowImpersonation", data?.user?.allowImpersonation);
+
+ if (data.user.email) {
+ generateSHA256Hash(data.user.email).then((hash) => {
+ setGravatarHash(hash);
+ });
+ }
+ }
+ }, [form, data]);
+
+ const onSubmit = async (values: Profile) => {
+ await mutateAsync({
+ email: values.email.toLowerCase(),
+ password: values.password || undefined,
+ image: values.image,
+ currentPassword: values.currentPassword || undefined,
+ allowImpersonation: values.allowImpersonation,
+ })
+ .then(async () => {
+ await refetch();
+ toast.success("Profile Updated");
+ form.reset({
+ email: values.email,
+ password: "",
+ image: values.image,
+ currentPassword: "",
+ });
+ })
+ .catch(() => {
+ toast.error("Error updating the profile");
+ });
+ };
+
+ return (
+
+
+
+
+
+
+
+ {t("settings.profile.title")}
+
+
+ {t("settings.profile.description")}
+
+
+ {!data?.user.twoFactorEnabled ? : }
+
+
+
+ {isError && {error?.message} }
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+
+
+
+
+
+
+ {t("settings.common.save")}
+
+
+
+
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/actions/show-dokploy-actions.tsx b/data/apps/dokploy/components/dashboard/settings/servers/actions/show-dokploy-actions.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..6850e86459e5c7c29f2f7939c2b42651d8ec6d75
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/actions/show-dokploy-actions.tsx
@@ -0,0 +1,109 @@
+import { Button } from "@/components/ui/button";
+
+import { UpdateServerIp } from "@/components/dashboard/settings/web-server/update-server-ip";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { api } from "@/utils/api";
+import { useTranslation } from "next-i18next";
+import { toast } from "sonner";
+import { ShowModalLogs } from "../../web-server/show-modal-logs";
+import { TerminalModal } from "../../web-server/terminal-modal";
+import { GPUSupportModal } from "../gpu-support-modal";
+
+export const ShowDokployActions = () => {
+ const { t } = useTranslation("settings");
+ const { mutateAsync: reloadServer, isLoading } =
+ api.settings.reloadServer.useMutation();
+
+ const { mutateAsync: cleanRedis } = api.settings.cleanRedis.useMutation();
+ const { mutateAsync: reloadRedis } = api.settings.reloadRedis.useMutation();
+
+ return (
+
+
+
+ {t("settings.server.webServer.server.label")}
+
+
+
+
+ {t("settings.server.webServer.actions")}
+
+
+
+ {
+ await reloadServer()
+ .then(async () => {
+ toast.success("Server Reloaded");
+ })
+ .catch(() => {
+ toast.success("Server Reloaded");
+ });
+ }}
+ className="cursor-pointer"
+ >
+ {t("settings.server.webServer.reload")}
+
+
+ {t("settings.common.enterTerminal")}
+
+
+ e.preventDefault()}
+ >
+ {t("settings.server.webServer.watchLogs")}
+
+
+
+
+ e.preventDefault()}
+ >
+ {t("settings.server.webServer.updateServerIp")}
+
+
+
+ {
+ await cleanRedis()
+ .then(async () => {
+ toast.success("Redis cleaned");
+ })
+ .catch(() => {
+ toast.error("Error cleaning Redis");
+ });
+ }}
+ >
+ Clean Redis
+
+
+ {
+ await reloadRedis()
+ .then(async () => {
+ toast.success("Redis reloaded");
+ })
+ .catch(() => {
+ toast.error("Error reloading Redis");
+ });
+ }}
+ >
+ Reload Redis
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/actions/show-server-actions.tsx b/data/apps/dokploy/components/dashboard/settings/servers/actions/show-server-actions.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..fcc0e315f98434cd0eacd9d507a6c3a3773da238
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/actions/show-server-actions.tsx
@@ -0,0 +1,43 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { useState } from "react";
+import { ShowStorageActions } from "./show-storage-actions";
+import { ShowTraefikActions } from "./show-traefik-actions";
+import { ToggleDockerCleanup } from "./toggle-docker-cleanup";
+interface Props {
+ serverId: string;
+}
+
+export const ShowServerActions = ({ serverId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+
+
+ e.preventDefault()}
+ >
+ View Actions
+
+
+
+
+ Web server settings
+ Reload or clean the web server.
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/actions/show-storage-actions.tsx b/data/apps/dokploy/components/dashboard/settings/servers/actions/show-storage-actions.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..3492ba7c274cc0cb1a1f2da47fc933cd019f922a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/actions/show-storage-actions.tsx
@@ -0,0 +1,190 @@
+import { Button } from "@/components/ui/button";
+
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { api } from "@/utils/api";
+import { useTranslation } from "next-i18next";
+import { toast } from "sonner";
+
+interface Props {
+ serverId?: string;
+}
+export const ShowStorageActions = ({ serverId }: Props) => {
+ const { t } = useTranslation("settings");
+ const { mutateAsync: cleanAll, isLoading: cleanAllIsLoading } =
+ api.settings.cleanAll.useMutation();
+
+ const {
+ mutateAsync: cleanDockerBuilder,
+ isLoading: cleanDockerBuilderIsLoading,
+ } = api.settings.cleanDockerBuilder.useMutation();
+
+ const { mutateAsync: cleanMonitoring } =
+ api.settings.cleanMonitoring.useMutation();
+ const {
+ mutateAsync: cleanUnusedImages,
+ isLoading: cleanUnusedImagesIsLoading,
+ } = api.settings.cleanUnusedImages.useMutation();
+
+ const {
+ mutateAsync: cleanUnusedVolumes,
+ isLoading: cleanUnusedVolumesIsLoading,
+ } = api.settings.cleanUnusedVolumes.useMutation();
+
+ const {
+ mutateAsync: cleanStoppedContainers,
+ isLoading: cleanStoppedContainersIsLoading,
+ } = api.settings.cleanStoppedContainers.useMutation();
+
+ return (
+
+
+
+ {t("settings.server.webServer.storage.label")}
+
+
+
+
+ {t("settings.server.webServer.actions")}
+
+
+
+ {
+ await cleanUnusedImages({
+ serverId: serverId,
+ })
+ .then(async () => {
+ toast.success("Cleaned images");
+ })
+ .catch(() => {
+ toast.error("Error cleaning images");
+ });
+ }}
+ >
+
+ {t("settings.server.webServer.storage.cleanUnusedImages")}
+
+
+ {
+ await cleanUnusedVolumes({
+ serverId: serverId,
+ })
+ .then(async () => {
+ toast.success("Cleaned volumes");
+ })
+ .catch(() => {
+ toast.error("Error cleaning volumes");
+ });
+ }}
+ >
+
+ {t("settings.server.webServer.storage.cleanUnusedVolumes")}
+
+
+
+ {
+ await cleanStoppedContainers({
+ serverId: serverId,
+ })
+ .then(async () => {
+ toast.success("Stopped containers cleaned");
+ })
+ .catch(() => {
+ toast.error("Error cleaning stopped containers");
+ });
+ }}
+ >
+
+ {t("settings.server.webServer.storage.cleanStoppedContainers")}
+
+
+
+ {
+ await cleanDockerBuilder({
+ serverId: serverId,
+ })
+ .then(async () => {
+ toast.success("Cleaned Docker Builder");
+ })
+ .catch(() => {
+ toast.error("Error cleaning Docker Builder");
+ });
+ }}
+ >
+
+ {t("settings.server.webServer.storage.cleanDockerBuilder")}
+
+
+ {!serverId && (
+ {
+ await cleanMonitoring()
+ .then(async () => {
+ toast.success("Cleaned Monitoring");
+ })
+ .catch(() => {
+ toast.error("Error cleaning Monitoring");
+ });
+ }}
+ >
+
+ {t("settings.server.webServer.storage.cleanMonitoring")}
+
+
+ )}
+
+ {
+ await cleanAll({
+ serverId: serverId,
+ })
+ .then(async () => {
+ toast.success("Cleaned all");
+ })
+ .catch(() => {
+ toast.error("Error cleaning all");
+ });
+ }}
+ >
+ {t("settings.server.webServer.storage.cleanAll")}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/actions/show-traefik-actions.tsx b/data/apps/dokploy/components/dashboard/settings/servers/actions/show-traefik-actions.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c0c45e147d08c600168ca366bafa579aff829625
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/actions/show-traefik-actions.tsx
@@ -0,0 +1,125 @@
+import { Button } from "@/components/ui/button";
+
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { api } from "@/utils/api";
+import { useTranslation } from "next-i18next";
+import { toast } from "sonner";
+import { EditTraefikEnv } from "../../web-server/edit-traefik-env";
+import { ManageTraefikPorts } from "../../web-server/manage-traefik-ports";
+import { ShowModalLogs } from "../../web-server/show-modal-logs";
+
+interface Props {
+ serverId?: string;
+}
+export const ShowTraefikActions = ({ serverId }: Props) => {
+ const { t } = useTranslation("settings");
+ const { mutateAsync: reloadTraefik, isLoading: reloadTraefikIsLoading } =
+ api.settings.reloadTraefik.useMutation();
+
+ const { mutateAsync: toggleDashboard, isLoading: toggleDashboardIsLoading } =
+ api.settings.toggleDashboard.useMutation();
+
+ const { data: haveTraefikDashboardPortEnabled, refetch: refetchDashboard } =
+ api.settings.haveTraefikDashboardPortEnabled.useQuery({
+ serverId,
+ });
+
+ return (
+
+
+
+ {t("settings.server.webServer.traefik.label")}
+
+
+
+
+ {t("settings.server.webServer.actions")}
+
+
+
+ {
+ await reloadTraefik({
+ serverId: serverId,
+ })
+ .then(async () => {
+ toast.success("Traefik Reloaded");
+ })
+ .catch(() => {});
+ }}
+ className="cursor-pointer"
+ >
+ {t("settings.server.webServer.reload")}
+
+
+ e.preventDefault()}
+ className="cursor-pointer"
+ >
+ {t("settings.server.webServer.watchLogs")}
+
+
+
+ e.preventDefault()}
+ className="cursor-pointer"
+ >
+ {t("settings.server.webServer.traefik.modifyEnv")}
+
+
+
+ {
+ await toggleDashboard({
+ enableDashboard: !haveTraefikDashboardPortEnabled,
+ serverId: serverId,
+ })
+ .then(async () => {
+ toast.success(
+ `${haveTraefikDashboardPortEnabled ? "Disabled" : "Enabled"} Dashboard`,
+ );
+ refetchDashboard();
+ })
+ .catch(() => {
+ toast.error(
+ `${haveTraefikDashboardPortEnabled ? "Disabled" : "Enabled"} Dashboard`,
+ );
+ });
+ }}
+ className="w-full cursor-pointer space-x-3"
+ >
+
+ {haveTraefikDashboardPortEnabled ? "Disable" : "Enable"} Dashboard
+
+
+
+ e.preventDefault()}
+ className="cursor-pointer"
+ >
+ {t("settings.server.webServer.traefik.managePorts")}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/actions/toggle-docker-cleanup.tsx b/data/apps/dokploy/components/dashboard/settings/servers/actions/toggle-docker-cleanup.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..12e279423d59da316d940d52389df61ebba3b226
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/actions/toggle-docker-cleanup.tsx
@@ -0,0 +1,50 @@
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { toast } from "sonner";
+
+interface Props {
+ serverId?: string;
+}
+export const ToggleDockerCleanup = ({ serverId }: Props) => {
+ const { data, refetch } = api.user.get.useQuery(undefined, {
+ enabled: !serverId,
+ });
+
+ const { data: server, refetch: refetchServer } = api.server.one.useQuery(
+ {
+ serverId: serverId || "",
+ },
+ {
+ enabled: !!serverId,
+ },
+ );
+
+ const enabled = data?.user.enableDockerCleanup || server?.enableDockerCleanup;
+
+ const { mutateAsync } = api.settings.updateDockerCleanup.useMutation();
+
+ const handleToggle = async (checked: boolean) => {
+ try {
+ await mutateAsync({
+ enableDockerCleanup: checked,
+ serverId: serverId,
+ });
+ if (serverId) {
+ await refetchServer();
+ } else {
+ await refetch();
+ }
+ toast.success("Docker Cleanup updated");
+ } catch (_error) {
+ toast.error("Docker Cleanup Error");
+ }
+ };
+
+ return (
+
+
+ Daily Docker Cleanup
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/edit-script.tsx b/data/apps/dokploy/components/dashboard/settings/servers/edit-script.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..6225ee771c37142a3bb6962cdee303094178f74b
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/edit-script.tsx
@@ -0,0 +1,168 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { FileTerminal } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+interface Props {
+ serverId: string;
+}
+
+const schema = z.object({
+ command: z.string().min(1, {
+ message: "Command is required",
+ }),
+});
+
+type Schema = z.infer;
+
+export const EditScript = ({ serverId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const { data: server } = api.server.one.useQuery(
+ {
+ serverId,
+ },
+ {
+ enabled: !!serverId,
+ },
+ );
+
+ const { mutateAsync, isLoading } = api.server.update.useMutation();
+
+ const { data: defaultCommand } = api.server.getDefaultCommand.useQuery(
+ {
+ serverId,
+ },
+ {
+ enabled: !!serverId,
+ },
+ );
+
+ const form = useForm({
+ defaultValues: {
+ command: "",
+ },
+ resolver: zodResolver(schema),
+ });
+
+ useEffect(() => {
+ if (server) {
+ form.reset({
+ command: server.command || defaultCommand,
+ });
+ }
+ }, [server, defaultCommand]);
+
+ const onSubmit = async (formData: Schema) => {
+ if (server) {
+ await mutateAsync({
+ ...server,
+ command: formData.command || "",
+ serverId,
+ })
+ .then((_data) => {
+ toast.success("Script modified successfully");
+ })
+ .catch(() => {
+ toast.error("Error modifying the script");
+ });
+ }
+ };
+
+ return (
+
+
+
+ Modify Script
+
+
+
+
+
+ Modify Script
+
+ Modify the script which install everything necessary to deploy
+ applications on your server,
+
+
+
+ We recommend not modifying this script unless you know what you are
+ doing.
+
+
+
+
+
+ (
+
+ Command
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ {
+ form.reset({
+ command: defaultCommand || "",
+ });
+ }}
+ >
+ Reset
+
+
+ Save
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/gpu-support-modal.tsx b/data/apps/dokploy/components/dashboard/settings/servers/gpu-support-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..9cf858cd34b4ae9087fd8f092ee3eedd4869aeee
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/gpu-support-modal.tsx
@@ -0,0 +1,36 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { useState } from "react";
+import { GPUSupport } from "./gpu-support";
+
+export const GPUSupportModal = () => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+
+
+ e.preventDefault()}
+ >
+ GPU Setup
+
+
+
+
+
+ Dokploy Server GPU Setup
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/gpu-support.tsx b/data/apps/dokploy/components/dashboard/settings/servers/gpu-support.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c24440a61973162ca80e74b300fbcb740d13779c
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/gpu-support.tsx
@@ -0,0 +1,281 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { CheckCircle2, Cpu, Loader2, RefreshCw, XCircle } from "lucide-react";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+
+interface GPUSupportProps {
+ serverId?: string;
+}
+
+export function GPUSupport({ serverId }: GPUSupportProps) {
+ const [isLoading, setIsLoading] = useState(false);
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ const utils = api.useContext();
+
+ const {
+ data: gpuStatus,
+ isLoading: isChecking,
+ refetch,
+ } = api.settings.checkGPUStatus.useQuery(
+ { serverId },
+ {
+ enabled: serverId !== undefined,
+ },
+ );
+
+ const setupGPU = api.settings.setupGPU.useMutation({
+ onMutate: () => {
+ setIsLoading(true);
+ },
+ onSuccess: async () => {
+ toast.success("GPU support enabled successfully");
+ setIsLoading(false);
+ await utils.settings.checkGPUStatus.invalidate({ serverId });
+ },
+ onError: (error) => {
+ toast.error(
+ error.message ||
+ "Failed to enable GPU support. Please check server logs.",
+ );
+ setIsLoading(false);
+ },
+ });
+
+ const handleRefresh = async () => {
+ setIsRefreshing(true);
+ try {
+ await utils.settings.checkGPUStatus.invalidate({ serverId });
+ await refetch();
+ } catch (_error) {
+ toast.error("Failed to refresh GPU status");
+ } finally {
+ setIsRefreshing(false);
+ }
+ };
+ useEffect(() => {
+ handleRefresh();
+ }, []);
+
+ const handleEnableGPU = async () => {
+ if (serverId === undefined) {
+ toast.error("No server selected");
+ return;
+ }
+
+ try {
+ await setupGPU.mutateAsync({ serverId });
+ } catch (_error) {
+ // Error handling is done in mutation's onError
+ }
+ };
+
+ return (
+
+
+
+
+
+
+
+
+ GPU Configuration
+
+
+ Configure and monitor GPU support
+
+
+
+
+
+ {isLoading
+ ? "Enabling GPU..."
+ : gpuStatus?.swarmEnabled
+ ? "Reconfigure GPU"
+ : "Enable GPU"}
+
+
+
+
+
+
+
+
+
+
+
+ System Requirements:
+
+ NVIDIA GPU hardware must be physically installed
+
+ NVIDIA drivers must be installed and running (check with
+ nvidia-smi)
+
+
+ NVIDIA Container Runtime must be installed
+ (nvidia-container-runtime)
+
+ User must have sudo/administrative privileges
+ System must support CUDA for GPU acceleration
+
+
+
+ {isChecking ? (
+
+
+ Checking GPU status...
+
+ ) : (
+
+ {/* Prerequisites Section */}
+
+
Prerequisites
+
+ Shows all software checks and available hardware
+
+
+
+
+
+
+
+
+
+
+
+ {/* Configuration Status */}
+
+
+ Docker Swarm GPU Status
+
+
+ Shows the configuration state that changes with the Enable
+ GPU
+
+
+
+
+
+
+
+ )}
+
+
+
+
+ );
+}
+
+interface StatusRowProps {
+ label: string;
+ isEnabled?: boolean;
+ description?: string;
+ value?: string | number;
+ showIcon?: boolean;
+}
+
+export function StatusRow({
+ label,
+ isEnabled,
+ description,
+ value,
+ showIcon = true,
+}: StatusRowProps) {
+ return (
+
+
{label}
+
+ {showIcon ? (
+ <>
+
+ {description || (isEnabled ? "Installed" : "Not Installed")}
+
+ {isEnabled ? (
+
+ ) : (
+
+ )}
+ >
+ ) : (
+ {value}
+ )}
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx b/data/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..a2c9b50a6169f99faabf5ea588523fbed1345d0a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx
@@ -0,0 +1,377 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PlusIcon } from "lucide-react";
+import { useTranslation } from "next-i18next";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const Schema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ description: z.string().optional(),
+ ipAddress: z.string().min(1, {
+ message: "IP Address is required",
+ }),
+ port: z.number().optional(),
+ username: z.string().optional(),
+ sshKeyId: z.string().min(1, {
+ message: "SSH Key is required",
+ }),
+});
+
+type Schema = z.infer;
+
+interface Props {
+ serverId?: string;
+}
+
+export const HandleServers = ({ serverId }: Props) => {
+ const { t } = useTranslation("settings");
+
+ const utils = api.useUtils();
+ const [isOpen, setIsOpen] = useState(false);
+ const { data: canCreateMoreServers, refetch } =
+ api.stripe.canCreateMoreServers.useQuery();
+
+ const { data, refetch: refetchServer } = api.server.one.useQuery(
+ {
+ serverId: serverId || "",
+ },
+ {
+ enabled: !!serverId,
+ },
+ );
+
+ const { data: sshKeys } = api.sshKey.all.useQuery();
+ const { mutateAsync, error, isLoading, isError } = serverId
+ ? api.server.update.useMutation()
+ : api.server.create.useMutation();
+ const form = useForm({
+ defaultValues: {
+ description: "",
+ name: "",
+ ipAddress: "",
+ port: 22,
+ username: "root",
+ sshKeyId: "",
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ description: data?.description || "",
+ name: data?.name || "",
+ ipAddress: data?.ipAddress || "",
+ port: data?.port || 22,
+ username: data?.username || "root",
+ sshKeyId: data?.sshKeyId || "",
+ });
+ }, [form, form.reset, form.formState.isSubmitSuccessful, data]);
+
+ useEffect(() => {
+ refetch();
+ }, [isOpen]);
+
+ const onSubmit = async (data: Schema) => {
+ await mutateAsync({
+ name: data.name,
+ description: data.description || "",
+ ipAddress: data.ipAddress || "",
+ port: data.port || 22,
+ username: data.username || "root",
+ sshKeyId: data.sshKeyId || "",
+ serverId: serverId || "",
+ })
+ .then(async (_data) => {
+ await utils.server.all.invalidate();
+ refetchServer();
+ toast.success(serverId ? "Server Updated" : "Server Created");
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error(
+ serverId ? "Error updating a server" : "Error creating a server",
+ );
+ });
+ };
+
+ return (
+
+
+ {serverId ? (
+ e.preventDefault()}
+ >
+ Edit Server
+
+ ) : (
+
+
+ Create Server
+
+ )}
+
+
+
+ {serverId ? "Edit" : "Create"} Server
+
+ {serverId ? "Edit" : "Create"} a server to deploy your applications
+ remotely.
+
+
+
+
+ You will need to purchase or rent a Virtual Private Server (VPS) to
+ proceed, we recommend to use one of these providers since has been
+ heavily tested.
+
+
+
+ You are free to use whatever provider, but we recommend to use one
+ of the above, to avoid issues.
+
+
+ {!canCreateMoreServers && (
+
+ You cannot create more servers,{" "}
+
+ Please upgrade your plan
+
+
+ )}
+ {isError && {error?.message} }
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Select a SSH Key
+
+
+
+
+
+
+ {sshKeys?.map((sshKey) => (
+
+ {sshKey.name}
+
+ ))}
+
+ Registries ({sshKeys?.length})
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+ {t("settings.terminal.ipAddress")}
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ {t("settings.terminal.port")}
+
+ {
+ const value = e.target.value;
+ if (value === "") {
+ field.onChange(0);
+ } else {
+ const number = Number.parseInt(value, 10);
+ if (!Number.isNaN(number)) {
+ field.onChange(number);
+ }
+ }
+ }}
+ />
+
+
+
+
+ )}
+ />
+
+
+ (
+
+ {t("settings.terminal.username")}
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ {serverId ? "Update" : "Create"}
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/security-audit.tsx b/data/apps/dokploy/components/dashboard/settings/servers/security-audit.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..851db40fb0750298ebfaa44fc5ae58373021f7b5
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/security-audit.tsx
@@ -0,0 +1,226 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { Loader2, LockKeyhole, RefreshCw } from "lucide-react";
+import { useState } from "react";
+import { StatusRow } from "./gpu-support";
+
+interface Props {
+ serverId: string;
+}
+
+export const SecurityAudit = ({ serverId }: Props) => {
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ const { data, refetch, error, isLoading, isError } =
+ api.server.security.useQuery(
+ { serverId },
+ {
+ enabled: !!serverId,
+ },
+ );
+
+ return (
+
+
+
+
+
+
+
+
+
+ Setup Security Suggestions
+
+
+
+ Check the security suggestions
+
+
+
{
+ setIsRefreshing(true);
+ await refetch();
+ setIsRefreshing(false);
+ }}
+ >
+
+ Refresh
+
+
+
+ {isError && (
+
+ {error.message}
+
+ )}
+
+
+
+
+
+ Ubuntu/Debian OS support is currently supported (Experimental)
+
+ {isLoading ? (
+
+
+ Checking Server configuration
+
+ ) : (
+
+
+
UFW
+
+ UFW (Uncomplicated Firewall) is a simple firewall that can
+ be used to block incoming and outgoing traffic from your
+ server.
+
+
+
+
+
+
+
+
+
+
SSH
+
+ SSH (Secure Shell) is a protocol that allows you to securely
+ connect to a server and execute commands on it.
+
+
+
+
+
+
+
+
+
+
+
Fail2Ban
+
+ Fail2Ban (Fail2Ban) is a service that can be used to prevent
+ brute force attacks on your server.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/setup-monitoring.tsx b/data/apps/dokploy/components/dashboard/settings/servers/setup-monitoring.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..9a49277e2008b6c18cba36edcd23c68ad4017249
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/setup-monitoring.tsx
@@ -0,0 +1,634 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input, NumberInput } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { extractServices } from "@/pages/dashboard/project/[projectId]";
+import { api } from "@/utils/api";
+import { useUrl } from "@/utils/hooks/use-url";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Eye, EyeOff, LayoutDashboardIcon, RefreshCw } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+interface Props {
+ serverId?: string;
+}
+
+const Schema = z.object({
+ metricsConfig: z.object({
+ server: z.object({
+ refreshRate: z.number().min(2, {
+ message: "Server Refresh Rate is required",
+ }),
+ port: z.number().min(1, {
+ message: "Port is required",
+ }),
+ token: z.string(),
+ urlCallback: z.string(),
+ retentionDays: z.number().min(1, {
+ message: "Retention days must be at least 1",
+ }),
+ thresholds: z.object({
+ cpu: z.number().min(0),
+ memory: z.number().min(0),
+ }),
+ cronJob: z.string().min(1, {
+ message: "Cron Job is required",
+ }),
+ }),
+ containers: z.object({
+ refreshRate: z.number().min(2, {
+ message: "Container Refresh Rate is required",
+ }),
+ services: z.object({
+ include: z.array(z.string()).optional(),
+ exclude: z.array(z.string()).optional(),
+ }),
+ }),
+ }),
+});
+
+type Schema = z.infer;
+
+export const SetupMonitoring = ({ serverId }: Props) => {
+ const { data } = serverId
+ ? api.server.one.useQuery(
+ {
+ serverId: serverId || "",
+ },
+ {
+ enabled: !!serverId,
+ },
+ )
+ : api.user.getServerMetrics.useQuery();
+
+ const url = useUrl();
+
+ const { data: projects } = api.project.all.useQuery();
+
+ const extractServicesFromProjects = (projects: any[] | undefined) => {
+ if (!projects) return [];
+
+ const allServices = projects.flatMap((project) => {
+ const services = extractServices(project);
+ return serverId
+ ? services
+ .filter((service) => service.serverId === serverId)
+ .map((service) => service.appName)
+ : services.map((service) => service.appName);
+ });
+
+ return [...new Set(allServices)];
+ };
+
+ const services = extractServicesFromProjects(projects);
+
+ const form = useForm({
+ resolver: zodResolver(Schema),
+ defaultValues: {
+ metricsConfig: {
+ server: {
+ refreshRate: 20,
+ port: 4500,
+ token: "",
+ urlCallback: `${url}/api/trpc/notification.receiveNotification`,
+ retentionDays: 7,
+ thresholds: {
+ cpu: 0,
+ memory: 0,
+ },
+ cronJob: "",
+ },
+ containers: {
+ refreshRate: 20,
+ services: {
+ include: [],
+ exclude: [],
+ },
+ },
+ },
+ },
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ metricsConfig: {
+ server: {
+ refreshRate: data?.metricsConfig?.server?.refreshRate,
+ port: data?.metricsConfig?.server?.port,
+ token: data?.metricsConfig?.server?.token || generateToken(),
+ urlCallback:
+ data?.metricsConfig?.server?.urlCallback ||
+ `${url}/api/trpc/notification.receiveNotification`,
+ retentionDays: data?.metricsConfig?.server?.retentionDays || 5,
+ thresholds: {
+ cpu: data?.metricsConfig?.server?.thresholds?.cpu,
+ memory: data?.metricsConfig?.server?.thresholds?.memory,
+ },
+ cronJob: data?.metricsConfig?.server?.cronJob || "0 0 * * *",
+ },
+ containers: {
+ refreshRate: data?.metricsConfig?.containers?.refreshRate,
+ services: {
+ include: data?.metricsConfig?.containers?.services?.include,
+ exclude: data?.metricsConfig?.containers?.services?.exclude,
+ },
+ },
+ },
+ });
+ }
+ }, [data, url]);
+
+ const [search, setSearch] = useState("");
+ const [searchExclude, setSearchExclude] = useState("");
+ const [showToken, setShowToken] = useState(false);
+
+ const availableServices = services?.filter(
+ (service) =>
+ !form
+ .watch("metricsConfig.containers.services.include")
+ ?.some((s) => s === service) &&
+ !form
+ .watch("metricsConfig.containers.services.exclude")
+ ?.includes(service) &&
+ service.toLowerCase().includes(search.toLowerCase()),
+ );
+
+ const availableServicesToExclude = [
+ ...(services?.filter(
+ (service) =>
+ !form
+ .watch("metricsConfig.containers.services.exclude")
+ ?.includes(service) &&
+ !form
+ .watch("metricsConfig.containers.services.include")
+ ?.some((s) => s === service) &&
+ service.toLowerCase().includes(searchExclude.toLowerCase()),
+ ) ?? []),
+ ...(!form.watch("metricsConfig.containers.services.exclude")?.includes("*")
+ ? ["*"]
+ : []),
+ ];
+
+ const { mutateAsync } = serverId
+ ? api.server.setupMonitoring.useMutation()
+ : api.admin.setupMonitoring.useMutation();
+
+ const generateToken = () => {
+ const array = new Uint8Array(64);
+ crypto.getRandomValues(array);
+ return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join(
+ "",
+ );
+ };
+
+ const onSubmit = async (values: Schema) => {
+ await mutateAsync({
+ serverId: serverId || "",
+ metricsConfig: values.metricsConfig,
+ })
+ .then(() => {
+ toast.success("Server updated successfully");
+ })
+ .catch(() => {
+ toast.error("Error updating the server");
+ });
+ };
+
+ return (
+ <>
+
+
+
+ Monitoring
+
+
+ Monitor your servers and containers in realtime with notifications
+ when they reach their thresholds.
+
+
+
+
+
+
+ Using a lower refresh rate will make your CPU and memory usage
+ higher, we recommend 30-60 seconds
+
+
+
(
+
+ Server Refresh Rate
+
+
+
+
+ Please set the refresh rate for the server in seconds
+
+
+
+ )}
+ />
+
+ (
+
+ Container Refresh Rate
+
+
+
+
+ Please set the refresh rate for the containers in seconds
+
+
+
+ )}
+ />
+
+ (
+
+ Cron Job
+
+
+
+
+ Cron job for cleaning up metrics
+
+
+
+ )}
+ />
+
+ (
+
+ Server Retention Days
+
+
+
+
+ Number of days to retain server metrics data
+
+
+
+ )}
+ />
+ (
+
+ Port
+
+
+
+
+ Please set the port for the metrics server
+
+
+
+ )}
+ />
+ (
+
+ Include Services
+
+
+
+
+
+ Add Service
+
+
+
+
+ {availableServices?.length === 0 ? (
+
+ No services available.
+
+ ) : (
+ <>
+
+ No service found.
+
+
+ {availableServices?.map((service) => (
+ {
+ field.onChange([
+ ...(field.value ?? []),
+ service,
+ ]);
+ setSearch("");
+ }}
+ >
+ {service}
+
+ ))}
+
+ >
+ )}
+
+
+
+
+
+ {field.value?.map((service) => (
+
+ {service}
+ {
+ field.onChange(
+ field.value?.filter((s) => s !== service),
+ );
+ }}
+ >
+ ×
+
+
+ ))}
+
+ Services to monitor.
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+ Exclude Services
+
+
+
+
+
+ Add Service
+
+
+
+
+ {availableServicesToExclude?.length === 0 ? (
+
+ No services available.
+
+ ) : (
+ <>
+
+ No service found.
+
+
+ {availableServicesToExclude.map(
+ (service) => (
+ {
+ field.onChange([
+ ...(field.value ?? []),
+ service,
+ ]);
+ setSearchExclude("");
+ }}
+ >
+ {service}
+
+ ),
+ )}
+
+ >
+ )}
+
+
+
+
+
+ {field.value?.map((service, index) => (
+
+ {service}
+ {
+ field.onChange(
+ field.value?.filter((_, i) => i !== index),
+ );
+ }}
+ >
+ ×
+
+
+ ))}
+
+ Services to exclude from monitoring
+
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+ CPU Threshold (%)
+
+
+
+
+ Alert when CPU usage exceeds this percentage
+
+
+
+ )}
+ />
+
+ (
+
+ Memory Threshold (%)
+
+
+
+
+ Alert when memory usage exceeds this percentage
+
+
+
+ )}
+ />
+
+ (
+
+ Metrics Token
+
+
+
+
+ setShowToken(!showToken)}
+ title={showToken ? "Hide token" : "Show token"}
+ >
+ {showToken ? (
+
+ ) : (
+
+ )}
+
+
+
{
+ const newToken = generateToken();
+ form.setValue(
+ "metricsConfig.server.token",
+ newToken,
+ );
+ toast.success("Token generated successfully");
+ }}
+ title="Generate new token"
+ >
+
+
+
+
+
+ Token for authenticating metrics requests
+
+
+
+ )}
+ />
+
+ (
+
+ Metrics Callback URL
+
+
+
+
+ URL where metrics will be sent
+
+
+
+ )}
+ />
+
+
+
+ Save changes
+
+
+
+
+
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/setup-server.tsx b/data/apps/dokploy/components/dashboard/settings/servers/setup-server.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..751167a4251820922edc18151573fa94e3588058
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/setup-server.tsx
@@ -0,0 +1,355 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { DrawerLogs } from "@/components/shared/drawer-logs";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { cn } from "@/lib/utils";
+import { api } from "@/utils/api";
+import copy from "copy-to-clipboard";
+import { CopyIcon, ExternalLinkIcon, ServerIcon } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { ShowDeployment } from "../../application/deployments/show-deployment";
+import { type LogLine, parseLogs } from "../../docker/logs/utils";
+import { EditScript } from "./edit-script";
+import { GPUSupport } from "./gpu-support";
+import { SecurityAudit } from "./security-audit";
+import { SetupMonitoring } from "./setup-monitoring";
+import { ValidateServer } from "./validate-server";
+
+interface Props {
+ serverId: string;
+}
+
+export const SetupServer = ({ serverId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const { data: server } = api.server.one.useQuery(
+ {
+ serverId,
+ },
+ {
+ enabled: !!serverId,
+ },
+ );
+
+ const [activeLog, setActiveLog] = useState(null);
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [filteredLogs, setFilteredLogs] = useState([]);
+ const [isDeploying, setIsDeploying] = useState(false);
+ api.server.setupWithLogs.useSubscription(
+ {
+ serverId: serverId,
+ },
+ {
+ enabled: isDeploying,
+ onData(log) {
+ if (!isDrawerOpen) {
+ setIsDrawerOpen(true);
+ }
+
+ if (log === "Deployment completed successfully!") {
+ setIsDeploying(false);
+ }
+ const parsedLogs = parseLogs(log);
+ setFilteredLogs((prev) => [...prev, ...parsedLogs]);
+ },
+ onError(error) {
+ console.error("Deployment logs error:", error);
+ setIsDeploying(false);
+ },
+ },
+ );
+
+ return (
+
+
+ e.preventDefault()}
+ >
+ Setup Server
+
+
+
+
+
+
+ Setup Server
+
+
+ To setup a server, please click on the button below.
+
+
+
+ {!server?.sshKeyId ? (
+
+
+ Please add a SSH Key to your server before setting up the server.
+ you can assign a SSH Key to your server in Edit Server.
+
+
+ ) : (
+
+ )}
+
+ {
+ setIsDrawerOpen(false);
+ setFilteredLogs([]);
+ setIsDeploying(false);
+ }}
+ filteredLogs={filteredLogs}
+ />
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/show-docker-containers-modal.tsx b/data/apps/dokploy/components/dashboard/settings/servers/show-docker-containers-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..ad82085c7f57a72e21f655d7b69d4c81780ed793
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/show-docker-containers-modal.tsx
@@ -0,0 +1,30 @@
+import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { useState } from "react";
+import { ShowContainers } from "../../docker/show/show-containers";
+
+interface Props {
+ serverId: string;
+}
+
+export const ShowDockerContainersModal = ({ serverId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+
+
+ e.preventDefault()}
+ >
+ Show Docker Containers
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/show-monitoring-modal.tsx b/data/apps/dokploy/components/dashboard/settings/servers/show-monitoring-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2a582ae1cdc9512998fc85c685a209804a7f518f
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/show-monitoring-modal.tsx
@@ -0,0 +1,31 @@
+import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { useState } from "react";
+import { ShowPaidMonitoring } from "../../monitoring/paid/servers/show-paid-monitoring";
+
+interface Props {
+ url: string;
+ token: string;
+}
+
+export const ShowMonitoringModal = ({ url, token }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+
+
+ e.preventDefault()}
+ >
+ Show Monitoring
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/show-schedules-modal.tsx b/data/apps/dokploy/components/dashboard/settings/servers/show-schedules-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..6f6a1a6d026e568beb911fee624b7eceeb2bb3cb
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/show-schedules-modal.tsx
@@ -0,0 +1,28 @@
+import { ShowSchedules } from "@/components/dashboard/application/schedules/show-schedules";
+import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { useState } from "react";
+
+interface Props {
+ serverId: string;
+}
+
+export const ShowSchedulesModal = ({ serverId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+
+
+ e.preventDefault()}
+ >
+ Show Schedules
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/show-servers.tsx b/data/apps/dokploy/components/dashboard/settings/servers/show-servers.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..813acb3407daaaec42cce55bc0db379369c4c7b6
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/show-servers.tsx
@@ -0,0 +1,369 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Table,
+ TableBody,
+ TableCaption,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { api } from "@/utils/api";
+import { format } from "date-fns";
+import { KeyIcon, Loader2, MoreHorizontal, ServerIcon } from "lucide-react";
+import { useTranslation } from "next-i18next";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { toast } from "sonner";
+import { ShowNodesModal } from "../cluster/nodes/show-nodes-modal";
+import { TerminalModal } from "../web-server/terminal-modal";
+import { ShowServerActions } from "./actions/show-server-actions";
+import { HandleServers } from "./handle-servers";
+import { SetupServer } from "./setup-server";
+import { ShowDockerContainersModal } from "./show-docker-containers-modal";
+import { ShowMonitoringModal } from "./show-monitoring-modal";
+import { ShowSchedulesModal } from "./show-schedules-modal";
+import { ShowSwarmOverviewModal } from "./show-swarm-overview-modal";
+import { ShowTraefikFileSystemModal } from "./show-traefik-file-system-modal";
+import { WelcomeSuscription } from "./welcome-stripe/welcome-suscription";
+
+export const ShowServers = () => {
+ const { t } = useTranslation("settings");
+ const router = useRouter();
+ const query = router.query;
+ const { data, refetch, isLoading } = api.server.all.useQuery();
+ const { mutateAsync } = api.server.remove.useMutation();
+ const { data: sshKeys } = api.sshKey.all.useQuery();
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const { data: canCreateMoreServers } =
+ api.stripe.canCreateMoreServers.useQuery();
+
+ return (
+
+ {query?.success && isCloud &&
}
+
+
+
+
+
+ Servers
+
+
+ Add servers to deploy your applications remotely.
+
+
+ {isCloud && (
+ {
+ router.push("/dashboard/settings/servers?success=true");
+ }}
+ >
+ Reset Onboarding
+
+ )}
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {sshKeys?.length === 0 && data?.length === 0 ? (
+
+
+
+ No SSH Keys found. Add a SSH Key to start adding servers.{" "}
+
+ Add SSH Key
+
+
+
+ ) : (
+ <>
+ {data?.length === 0 ? (
+
+
+
+ Start adding servers to deploy your applications
+ remotely.
+
+
+
+ ) : (
+
+ {!canCreateMoreServers && (
+
+
+
+
+ You cannot create more servers,{" "}
+
+ Please upgrade your plan
+
+
+
+
+
+ )}
+
+
+
+
+ See all servers
+
+
+
+
+ Name
+ {isCloud && (
+
+ Status
+
+ )}
+
+ IP Address
+
+
+ Port
+
+
+ Username
+
+
+ SSH Key
+
+
+ Created
+
+
+ Actions
+
+
+
+
+ {data?.map((server) => {
+ const canDelete = server.totalSum === 0;
+ const isActive = server.serverStatus === "active";
+ return (
+
+
+ {server.name}
+
+ {isCloud && (
+
+
+ {server.serverStatus}
+
+
+ )}
+
+ {server.ipAddress}
+
+
+ {server.port}
+
+
+ {server.username}
+
+
+
+ {server.sshKeyId ? "Yes" : "No"}
+
+
+
+
+ {format(
+ new Date(server.createdAt),
+ "PPpp",
+ )}
+
+
+
+
+
+
+
+
+ Open menu
+
+
+
+
+
+
+ Actions
+
+
+ {isActive && (
+ <>
+ {server.sshKeyId && (
+
+
+ {t(
+ "settings.common.enterTerminal",
+ )}
+
+
+ )}
+
+
+
+
+ {server.sshKeyId && (
+
+ )}
+ >
+ )}
+
+
+ You can not delete this server
+ because it has active services.
+
+ You have active services
+ associated with this server,
+ please delete them first.
+
+
+ )
+ }
+ onClick={async () => {
+ await mutateAsync({
+ serverId: server.serverId,
+ })
+ .then(() => {
+ refetch();
+ toast.success(
+ `Server ${server.name} deleted successfully`,
+ );
+ })
+ .catch((err) => {
+ toast.error(err.message);
+ });
+ }}
+ >
+ e.preventDefault()}
+ >
+ Delete Server
+
+
+
+ {isActive && server.sshKeyId && (
+ <>
+
+
+ Extra
+
+
+
+
+ {isCloud && (
+
+ )}
+
+
+
+
+
+ >
+ )}
+
+
+
+
+ );
+ })}
+
+
+
+
+ {data && data?.length > 0 && (
+
+
+
+ )}
+
+
+ )}
+ >
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/show-swarm-overview-modal.tsx b/data/apps/dokploy/components/dashboard/settings/servers/show-swarm-overview-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..b86311840ad768834ac1ba50ec3675ff485d7fa7
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/show-swarm-overview-modal.tsx
@@ -0,0 +1,30 @@
+import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { useState } from "react";
+import SwarmMonitorCard from "../../swarm/monitoring-card";
+
+interface Props {
+ serverId: string;
+}
+
+export const ShowSwarmOverviewModal = ({ serverId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+
+
+ e.preventDefault()}
+ >
+ Show Swarm Overview
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/show-traefik-file-system-modal.tsx b/data/apps/dokploy/components/dashboard/settings/servers/show-traefik-file-system-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..0c5763605a7160b530c6d7e4e9b2117e9fcd79dc
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/show-traefik-file-system-modal.tsx
@@ -0,0 +1,28 @@
+import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { useState } from "react";
+import { ShowTraefikSystem } from "../../file-system/show-traefik-system";
+
+interface Props {
+ serverId: string;
+}
+
+export const ShowTraefikFileSystemModal = ({ serverId }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+
+
+ e.preventDefault()}
+ >
+ Show Traefik File System
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/validate-server.tsx b/data/apps/dokploy/components/dashboard/settings/servers/validate-server.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..a489b390be160e96ae91c2b78d1a85fb47b5b934
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/validate-server.tsx
@@ -0,0 +1,160 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { Loader2, PcCase, RefreshCw } from "lucide-react";
+import { useState } from "react";
+import { StatusRow } from "./gpu-support";
+
+interface Props {
+ serverId: string;
+}
+
+export const ValidateServer = ({ serverId }: Props) => {
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ const { data, refetch, error, isLoading, isError } =
+ api.server.validate.useQuery(
+ { serverId },
+ {
+ enabled: !!serverId,
+ },
+ );
+ const _utils = api.useUtils();
+ return (
+
+
+
+
+
+
+
+
+ Check if your server is ready for deployment
+
+
+
{
+ setIsRefreshing(true);
+ await refetch();
+ setIsRefreshing(false);
+ }}
+ >
+
+ Refresh
+
+
+
+ {isError && (
+
+ {error.message}
+
+ )}
+
+
+
+
+ {isLoading ? (
+
+
+ Checking Server configuration
+
+ ) : (
+
+
+
Status
+
+ Shows the server configuration status
+
+
+
+
+
+
+
+
+
+
+
+
+
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-server.tsx b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-server.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..24d01553be359a558b11f273415870af3765c95c
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-server.tsx
@@ -0,0 +1,282 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import { DialogFooter } from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const Schema = z.object({
+ name: z.string().min(1, {
+ message: "Name is required",
+ }),
+ description: z.string().optional(),
+ ipAddress: z.string().min(1, {
+ message: "IP Address is required",
+ }),
+ port: z.number().optional(),
+ username: z.string().optional(),
+ sshKeyId: z.string().min(1, {
+ message: "SSH Key is required",
+ }),
+});
+
+type Schema = z.infer;
+
+interface Props {
+ stepper: any;
+}
+
+export const CreateServer = ({ stepper }: Props) => {
+ const { data: sshKeys } = api.sshKey.all.useQuery();
+ const [isOpen, _setIsOpen] = useState(false);
+ const { data: canCreateMoreServers, refetch } =
+ api.stripe.canCreateMoreServers.useQuery();
+ const { mutateAsync } = api.server.create.useMutation();
+ const cloudSSHKey = sshKeys?.find(
+ (sshKey) => sshKey.name === "dokploy-cloud-ssh-key",
+ );
+
+ const form = useForm({
+ defaultValues: {
+ description: "Dokploy Cloud Server",
+ name: "My First Server",
+ ipAddress: "",
+ port: 22,
+ username: "root",
+ sshKeyId: cloudSSHKey?.sshKeyId || "",
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ useEffect(() => {
+ form.reset({
+ description: "Dokploy Cloud Server",
+ name: "My First Server",
+ ipAddress: "",
+ port: 22,
+ username: "root",
+ sshKeyId: cloudSSHKey?.sshKeyId || "",
+ });
+ }, [form, form.reset, form.formState.isSubmitSuccessful, sshKeys]);
+
+ useEffect(() => {
+ refetch();
+ }, [isOpen]);
+
+ const onSubmit = async (data: Schema) => {
+ await mutateAsync({
+ name: data.name,
+ description: data.description || "",
+ ipAddress: data.ipAddress || "",
+ port: data.port || 22,
+ username: data.username || "root",
+ sshKeyId: data.sshKeyId || "",
+ })
+ .then(async (_data) => {
+ toast.success("Server Created");
+ stepper.next();
+ })
+ .catch(() => {
+ toast.error("Error creating a server");
+ });
+ };
+ return (
+
+
+ {!canCreateMoreServers && (
+
+ You cannot create more servers,{" "}
+
+ Please upgrade your plan
+
+
+ )}
+
+
+
+
+
+
+ (
+
+ Name
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Select a SSH Key
+ {!cloudSSHKey && (
+
+ Looks like you didn't have the SSH Key yet, you can create
+ one{" "}
+
+ here
+
+
+ )}
+
+
+
+
+
+
+
+ {sshKeys?.map((sshKey) => (
+
+ {sshKey.name}
+
+ ))}
+
+ Registries ({sshKeys?.length})
+
+
+
+
+
+
+ )}
+ />
+
+ (
+
+ IP Address
+
+
+
+
+
+
+ )}
+ />
+ (
+
+ Port
+
+ {
+ const value = e.target.value;
+ if (value === "") {
+ field.onChange(0);
+ } else {
+ const number = Number.parseInt(value, 10);
+ if (!Number.isNaN(number)) {
+ field.onChange(number);
+ }
+ }
+ }}
+ />
+
+
+
+
+ )}
+ />
+
+
+ (
+
+ Username
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ Create
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-ssh-key.tsx b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-ssh-key.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..b1a3f2d03dcd28de15472d5e450e30f7e4ffa04b
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-ssh-key.tsx
@@ -0,0 +1,153 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Card, CardContent } from "@/components/ui/card";
+import { api } from "@/utils/api";
+import copy from "copy-to-clipboard";
+import { ExternalLinkIcon, Loader2 } from "lucide-react";
+import { CopyIcon } from "lucide-react";
+import Link from "next/link";
+import { useEffect, useRef } from "react";
+import { toast } from "sonner";
+
+export const CreateSSHKey = () => {
+ const { data, refetch } = api.sshKey.all.useQuery();
+ const generateMutation = api.sshKey.generate.useMutation();
+ const { mutateAsync, isLoading } = api.sshKey.create.useMutation();
+ const hasCreatedKey = useRef(false);
+
+ const cloudSSHKey = data?.find(
+ (sshKey) => sshKey.name === "dokploy-cloud-ssh-key",
+ );
+
+ useEffect(() => {
+ const createKey = async () => {
+ if (!data || cloudSSHKey || hasCreatedKey.current || isLoading) {
+ return;
+ }
+
+ hasCreatedKey.current = true;
+
+ try {
+ const keys = await generateMutation.mutateAsync({
+ type: "rsa",
+ });
+ await mutateAsync({
+ name: "dokploy-cloud-ssh-key",
+ description: "Used on Dokploy Cloud",
+ privateKey: keys.privateKey,
+ publicKey: keys.publicKey,
+ organizationId: "",
+ });
+ await refetch();
+ } catch (error) {
+ console.error("Error creating SSH key:", error);
+ hasCreatedKey.current = false;
+ }
+ };
+
+ createKey();
+ }, [data]);
+
+ return (
+
+
+
+ {isLoading || !cloudSSHKey ? (
+
+
+
+ ) : (
+ <>
+
+
+ You have two options to add SSH Keys to your server:
+
+
+
+ 1. Add The SSH Key to Server Manually
+
+
+ 2. Add the public SSH Key when you create a server in your
+ preffered provider (Hostinger, Digital Ocean, Hetzner, etc){" "}
+
+
+
+
+
+
+ Option 2
+
+
+
+
+ Copy Public Key
+ {
+ copy(
+ cloudSSHKey?.publicKey || "Generate a SSH Key",
+ );
+ toast.success("SSH Copied to clipboard");
+ }}
+ >
+
+
+
+
+
+
+ View Tutorial
+
+
+
+ >
+ )}
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/setup.tsx b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/setup.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..56de47a4a26387f102e3e85ffa196874156add17
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/setup.tsx
@@ -0,0 +1,136 @@
+import {
+ type LogLine,
+ parseLogs,
+} from "@/components/dashboard/docker/logs/utils";
+import { DialogAction } from "@/components/shared/dialog-action";
+import { DrawerLogs } from "@/components/shared/drawer-logs";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { useState } from "react";
+import { EditScript } from "../edit-script";
+
+export const Setup = () => {
+ const { data: servers } = api.server.all.useQuery();
+ const [serverId, setServerId] = useState(
+ servers?.[0]?.serverId || "",
+ );
+ const { data: server } = api.server.one.useQuery(
+ {
+ serverId,
+ },
+ {
+ enabled: !!serverId,
+ },
+ );
+
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [filteredLogs, setFilteredLogs] = useState([]);
+ const [isDeploying, setIsDeploying] = useState(false);
+ api.server.setupWithLogs.useSubscription(
+ {
+ serverId: serverId,
+ },
+ {
+ enabled: isDeploying,
+ onData(log) {
+ if (!isDrawerOpen) {
+ setIsDrawerOpen(true);
+ }
+
+ if (log === "Deployment completed successfully!") {
+ setIsDeploying(false);
+ }
+ const parsedLogs = parseLogs(log);
+ setFilteredLogs((prev) => [...prev, ...parsedLogs]);
+ },
+ onError(error) {
+ console.error("Deployment logs error:", error);
+ setIsDeploying(false);
+ },
+ },
+ );
+
+ return (
+
+
+
+
+ Select the server and click on setup server
+
+
+
+
+
+
+ {servers?.map((server) => (
+
+ {server.name}
+
+ ))}
+ Servers ({servers?.length})
+
+
+
+
+
+
+ Setup Server
+
+ To setup a server, please click on the button below.
+
+
+
+
+
+
+
+ When your server is ready, you can click on the button below, to
+ directly run the script we use for setup the server or directly
+ modify the script
+
+
+
+ {
+ setIsDeploying(true);
+ }}
+ >
+ Setup Server
+
+
+
+
+ {
+ setIsDrawerOpen(false);
+ setFilteredLogs([]);
+ setIsDeploying(false);
+ }}
+ filteredLogs={filteredLogs}
+ />
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/verify.tsx b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/verify.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..f7c2a987c04ce2331c5295a506cc64aa36d17ca8
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/verify.tsx
@@ -0,0 +1,180 @@
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+import { Loader2, PcCase, RefreshCw } from "lucide-react";
+import { useState } from "react";
+
+import { AlertBlock } from "@/components/shared/alert-block";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { StatusRow } from "../gpu-support";
+
+export const Verify = () => {
+ const { data: servers } = api.server.all.useQuery();
+ const [serverId, setServerId] = useState(
+ servers?.[0]?.serverId || "",
+ );
+ const { data, refetch, error, isLoading, isError } =
+ api.server.validate.useQuery(
+ { serverId },
+ {
+ enabled: !!serverId,
+ },
+ );
+ const [isRefreshing, setIsRefreshing] = useState(false);
+
+ return (
+
+
+
+
+
+ Select a server
+
+
+
+
+
+
+ {servers?.map((server) => (
+
+ {server.name}
+
+ ))}
+ Servers ({servers?.length})
+
+
+
+
+
+
+
+
+ Check if your server is ready for deployment
+
+
+
{
+ setIsRefreshing(true);
+ await refetch();
+ setIsRefreshing(false);
+ }}
+ >
+
+ Refresh
+
+
+
+ {isError && (
+
+ {error.message}
+
+ )}
+
+
+
+
+ {isLoading ? (
+
+
+ Checking Server configuration
+
+ ) : (
+
+
+
Status
+
+ Shows the server configuration status
+
+
+
+
+
+
+
+
+
+
+
+
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/welcome-suscription.tsx b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/welcome-suscription.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..1ec4f2ab98abca95c63131e13ceb67c0fa140807
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/welcome-suscription.tsx
@@ -0,0 +1,419 @@
+import { GithubIcon } from "@/components/icons/data-tools-icons";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Separator } from "@/components/ui/separator";
+import { defineStepper } from "@stepperize/react";
+import { BookIcon, Puzzle } from "lucide-react";
+import { Code2, Database, GitMerge, Globe, Plug, Users } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { useEffect, useState } from "react";
+import React from "react";
+import ConfettiExplosion from "react-confetti-explosion";
+import { CreateServer } from "./create-server";
+import { CreateSSHKey } from "./create-ssh-key";
+import { Setup } from "./setup";
+import { Verify } from "./verify";
+
+export const { useStepper, steps, Scoped } = defineStepper(
+ {
+ id: "requisites",
+ title: "Requisites",
+ description: "Check your requisites",
+ },
+ {
+ id: "create-ssh-key",
+ title: "SSH Key",
+ description: "Create your ssh key",
+ },
+ {
+ id: "connect-server",
+ title: "Connect",
+ description: "Connect",
+ },
+ { id: "setup", title: "Setup", description: "Setup your server" },
+ { id: "verify", title: "Verify", description: "Verify your server" },
+ { id: "complete", title: "Complete", description: "Checkout complete" },
+);
+
+export const WelcomeSuscription = () => {
+ const [showConfetti, setShowConfetti] = useState(false);
+ const stepper = useStepper();
+ const [isOpen, setIsOpen] = useState(true);
+ const { push } = useRouter();
+
+ useEffect(() => {
+ const confettiShown = localStorage.getItem("hasShownConfetti");
+ if (!confettiShown) {
+ setShowConfetti(true);
+ localStorage.setItem("hasShownConfetti", "true");
+ }
+ }, [showConfetti]);
+
+ return (
+
+
+ {showConfetti ?? "Flaso"}
+
+ {showConfetti && (
+
+ )}
+
+
+
+
+ Welcome To Dokploy Cloud 🎉
+
+
+ Thank you for choosing Dokploy Cloud! 🚀 We're excited to have you
+ onboard. Before you dive in, you'll need to configure your remote
+ server to unlock all the features we offer.
+
+
+
+
+
Steps
+
+
+ Step {stepper.current.index + 1} of {steps.length}
+
+
+
+
+
+
+
+ {stepper.all.map((step, index, array) => (
+
+
+ stepper.goTo(step.id)}
+ >
+ {index + 1}
+
+ {step.title}
+
+ {index < array.length - 1 && (
+
+ )}
+
+ ))}
+
+
+ {stepper.switch({
+ requisites: () => (
+
+
+ Before getting started, please follow the steps below to
+ ensure the best experience:
+
+
+
+ Supported Distributions:
+
+
+ Ubuntu 24.04 LTS
+ Ubuntu 23.10
+ Ubuntu 22.04 LTS
+ Ubuntu 20.04 LTS
+ Ubuntu 18.04 LTS
+ Debian 12
+ Debian 11
+ Debian 10
+ Fedora 40
+ CentOS 9
+ CentOS 8
+
+
+
+
+ You will need to purchase or rent a Virtual Private Server
+ (VPS) to proceed, we recommend to use one of these
+ providers since has been heavily tested.
+
+
+
+ You are free to use whatever provider, but we recommend to
+ use one of the above, to avoid issues.
+
+
+
+ ),
+ "create-ssh-key": () => ,
+ "connect-server": () => ,
+ setup: () => ,
+ verify: () => ,
+ complete: () => {
+ const features = [
+ {
+ title: "Scalable Deployments",
+ description:
+ "Deploy and scale your applications effortlessly to handle any workload.",
+ icon: ,
+ },
+ {
+ title: "Automated Backups",
+ description: "Protect your data with automatic backups",
+ icon: ,
+ },
+ {
+ title: "Open Source Templates",
+ description:
+ "Big list of common open source templates in one-click",
+ icon: ,
+ },
+ {
+ title: "Custom Domains",
+ description:
+ "Link your own domains to your applications for a professional presence.",
+ icon: ,
+ },
+ {
+ title: "CI/CD Integration",
+ description:
+ "Implement continuous integration and deployment workflows to streamline development.",
+ icon: ,
+ },
+ {
+ title: "Database Management",
+ description:
+ "Efficiently manage your databases with intuitive tools.",
+ icon: ,
+ },
+ {
+ title: "Team Collaboration",
+ description:
+ "Collaborate with your team on shared projects with customizable permissions.",
+ icon: ,
+ },
+ {
+ title: "Multi-language Support",
+ description:
+ "Deploy applications in multiple programming languages to suit your needs.",
+ icon: ,
+ },
+ {
+ title: "API Access",
+ description:
+ "Integrate and manage your applications via robust and well-documented APIs.",
+ icon: ,
+ },
+ ];
+ return (
+
+
+
You're All Set!
+
+ Did you know you can deploy any number of applications
+ that your server can handle?
+
+
+ Here are some of the things you can do with Dokploy
+ Cloud:
+
+
+
+
+ {features.map((feature, index) => (
+
+
{feature.icon}
+
+ {feature.title}
+
+
+ {feature.description}
+
+
+ ))}
+
+
+
+
+ Need Help? We are here to help you.
+
+
+ Join to our Discord server and we will help you.
+
+
+
+
+
+
+
+ Join Discord
+
+
+
+
+
+ Github
+
+
+
+
+
+
+ Docs
+
+
+
+
+
+ );
+ },
+ })}
+
+
+
+
+ {!stepper.isLast && (
+
{
+ setIsOpen(false);
+ push("/dashboard/settings/servers");
+ }}
+ >
+ Skip for now
+
+ )}
+
+
+
+ Back
+
+ {
+ if (stepper.isLast) {
+ setIsOpen(false);
+ push("/dashboard/projects");
+ } else {
+ stepper.next();
+ }
+ }}
+ >
+ {stepper.isLast ? "Complete" : "Next"}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/ssh-keys/handle-ssh-keys.tsx b/data/apps/dokploy/components/dashboard/settings/ssh-keys/handle-ssh-keys.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..0c3f3529f24efc212a5611ebc9d5a03cc5894a1d
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/ssh-keys/handle-ssh-keys.tsx
@@ -0,0 +1,310 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { sshKeyCreate, type sshKeyType } from "@/server/db/validations";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { DownloadIcon, PenBoxIcon, PlusIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import type { z } from "zod";
+
+type SSHKey = z.infer;
+
+interface Props {
+ sshKeyId?: string;
+}
+
+export const HandleSSHKeys = ({ sshKeyId }: Props) => {
+ const utils = api.useUtils();
+
+ const [isOpen, setIsOpen] = useState(false);
+
+ const { data } = api.sshKey.one.useQuery(
+ {
+ sshKeyId: sshKeyId || "",
+ },
+ {
+ enabled: !!sshKeyId,
+ },
+ );
+
+ const { mutateAsync, isError, error, isLoading } = sshKeyId
+ ? api.sshKey.update.useMutation()
+ : api.sshKey.create.useMutation();
+
+ const generateMutation = api.sshKey.generate.useMutation();
+
+ const form = useForm({
+ resolver: zodResolver(sshKeyCreate),
+ defaultValues: {
+ name: "",
+ description: "",
+ publicKey: "",
+ privateKey: "",
+ },
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ ...data,
+ description: data.description || undefined,
+ });
+ } else {
+ form.reset();
+ }
+ }, [data, form, form.reset]);
+
+ const onSubmit = async (data: SSHKey) => {
+ await mutateAsync({
+ ...data,
+ organizationId: "",
+ sshKeyId: sshKeyId || "",
+ })
+ .then(async () => {
+ toast.success(
+ sshKeyId
+ ? "SSH key updated successfully"
+ : "SSH key created successfully",
+ );
+ await utils.sshKey.all.invalidate();
+ form.reset();
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error(
+ sshKeyId
+ ? "Error updating the SSH key"
+ : "Error creating the SSH key",
+ );
+ });
+ };
+
+ const onGenerateSSHKey = (type: z.infer) =>
+ generateMutation
+ .mutateAsync(type)
+ .then(async (data) => {
+ toast.success("SSH Key Generated");
+ form.setValue("privateKey", data.privateKey);
+ form.setValue("publicKey", data.publicKey);
+ })
+ .catch(() => {
+ toast.error("Error generating the SSH Key");
+ });
+
+ const downloadKey = (content: string, keyType: "private" | "public") => {
+ const keyName = form.watch("name");
+ const publicKey = form.watch("publicKey");
+
+ // Extract algorithm type from public key
+ const isEd25519 = publicKey.startsWith("ssh-ed25519");
+ const defaultName = isEd25519 ? "id_ed25519" : "id_rsa";
+
+ const filename = keyName
+ ? `${keyName}${sshKeyId ? `_${sshKeyId}` : ""}_${keyType}_${defaultName}${keyType === "public" ? ".pub" : ""}`
+ : `${defaultName}${keyType === "public" ? ".pub" : ""}`;
+ const blob = new Blob([content], { type: "text/plain" });
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ window.URL.revokeObjectURL(url);
+ };
+
+ return (
+
+
+ {sshKeyId ? (
+
+
+
+ ) : (
+
+
+ Add SSH Key
+
+ )}
+
+
+
+ SSH Key
+
+
+ In this section you can add one of your keys or generate a new
+ one.
+
+ {!sshKeyId && (
+
+
+ onGenerateSSHKey({
+ type: "rsa",
+ })
+ }
+ type="button"
+ >
+ Generate RSA SSH Key
+
+
+ onGenerateSSHKey({
+ type: "ed25519",
+ })
+ }
+ type="button"
+ >
+ Generate ED25519 SSH Key
+
+
+ )}
+
+
+ {isError && {error?.message} }
+
+
+
+ {
+ return (
+
+ Name
+
+
+
+
+
+ );
+ }}
+ />
+
+ {
+ return (
+
+ Description
+
+
+
+
+
+ );
+ }}
+ />
+ (
+
+
+ Private Key
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Public Key
+
+
+
+
+
+
+ )}
+ />
+
+
+ {form.watch("privateKey") && (
+
+ downloadKey(form.watch("privateKey"), "private")
+ }
+ className="flex items-center gap-2"
+ >
+
+ Private Key
+
+ )}
+ {form.watch("publicKey") && (
+
+ downloadKey(form.watch("publicKey"), "public")
+ }
+ className="flex items-center gap-2"
+ >
+
+ Public Key
+
+ )}
+
+
+ {sshKeyId ? "Update" : "Create"}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/ssh-keys/show-ssh-keys.tsx b/data/apps/dokploy/components/dashboard/settings/ssh-keys/show-ssh-keys.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..00d685a8dfc984a31f0cf892e4db0d86d06ae98a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/ssh-keys/show-ssh-keys.tsx
@@ -0,0 +1,133 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { formatDistanceToNow } from "date-fns";
+import { KeyRound, Loader2, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { HandleSSHKeys } from "./handle-ssh-keys";
+
+export const ShowDestinations = () => {
+ const { data, isLoading, refetch } = api.sshKey.all.useQuery();
+ const { mutateAsync, isLoading: isRemoving } =
+ api.sshKey.remove.useMutation();
+
+ return (
+
+
+
+
+
+
+ SSH Keys
+
+
+ Create and manage SSH Keys, you can use them to access your
+ servers, git private repositories, and more.
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {data?.length === 0 ? (
+
+
+
+ You don't have any SSH keys
+
+
+
+ ) : (
+
+
+ {data?.map((sshKey, index) => (
+
+
+
+
+
+ {index + 1}. {sshKey.name}
+
+ {sshKey.description && (
+
+
+ {sshKey.description}
+
+
+ Created:{" "}
+ {formatDistanceToNow(
+ new Date(sshKey.createdAt),
+ {
+ addSuffix: true,
+ },
+ )}
+
+
+ )}
+
+
+
+
+
+
+ {
+ await mutateAsync({
+ sshKeyId: sshKey.sshKeyId,
+ })
+ .then(() => {
+ toast.success(
+ "SSH Key deleted successfully",
+ );
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error deleting SSH Key");
+ });
+ }}
+ >
+
+
+
+
+
+
+
+ ))}
+
+
+
+
+
+
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/users/add-invitation.tsx b/data/apps/dokploy/components/dashboard/settings/users/add-invitation.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..d05409fb7cf2cb36f2a71cb3b58e3b536ca5bb9d
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/users/add-invitation.tsx
@@ -0,0 +1,166 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { authClient } from "@/lib/auth-client";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PlusIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const addInvitation = z.object({
+ email: z
+ .string()
+ .min(1, "Email is required")
+ .email({ message: "Invalid email" }),
+ role: z.enum(["member", "admin"]),
+});
+
+type AddInvitation = z.infer;
+
+export const AddInvitation = () => {
+ const [open, setOpen] = useState(false);
+ const utils = api.useUtils();
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState(null);
+ const { data: activeOrganization } = authClient.useActiveOrganization();
+
+ const form = useForm({
+ defaultValues: {
+ email: "",
+ role: "member",
+ },
+ resolver: zodResolver(addInvitation),
+ });
+ useEffect(() => {
+ form.reset();
+ }, [form, form.formState.isSubmitSuccessful, form.reset]);
+
+ const onSubmit = async (data: AddInvitation) => {
+ setIsLoading(true);
+ const result = await authClient.organization.inviteMember({
+ email: data.email.toLowerCase(),
+ role: data.role,
+ organizationId: activeOrganization?.id,
+ });
+
+ if (result.error) {
+ setError(result.error.message || "");
+ } else {
+ toast.success("Invitation created");
+ setError(null);
+ setOpen(false);
+ }
+
+ utils.organization.allInvitations.invalidate();
+ setIsLoading(false);
+ };
+ return (
+
+
+
+ Add Invitation
+
+
+
+
+ Add Invitation
+ Invite a new user
+
+ {error && {error} }
+
+
+
+ {
+ return (
+
+ Email
+
+
+
+
+ This will be the email of the new user
+
+
+
+ );
+ }}
+ />
+
+ {
+ return (
+
+ Role
+
+
+
+
+
+
+
+ Member
+
+
+
+ Select the role for the new user
+
+
+
+ );
+ }}
+ />
+
+
+ Create
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/users/add-permissions.tsx b/data/apps/dokploy/components/dashboard/settings/users/add-permissions.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..51d73b1f918b480f137ef30dbe7b0ead4ea2c48b
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/users/add-permissions.tsx
@@ -0,0 +1,444 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Switch } from "@/components/ui/switch";
+import { extractServices } from "@/pages/dashboard/project/[projectId]";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const addPermissions = z.object({
+ accessedProjects: z.array(z.string()).optional(),
+ accessedServices: z.array(z.string()).optional(),
+ canCreateProjects: z.boolean().optional().default(false),
+ canCreateServices: z.boolean().optional().default(false),
+ canDeleteProjects: z.boolean().optional().default(false),
+ canDeleteServices: z.boolean().optional().default(false),
+ canAccessToTraefikFiles: z.boolean().optional().default(false),
+ canAccessToDocker: z.boolean().optional().default(false),
+ canAccessToAPI: z.boolean().optional().default(false),
+ canAccessToSSHKeys: z.boolean().optional().default(false),
+ canAccessToGitProviders: z.boolean().optional().default(false),
+});
+
+type AddPermissions = z.infer;
+
+interface Props {
+ userId: string;
+}
+
+export const AddUserPermissions = ({ userId }: Props) => {
+ const { data: projects } = api.project.all.useQuery();
+
+ const { data, refetch } = api.user.one.useQuery(
+ {
+ userId,
+ },
+ {
+ enabled: !!userId,
+ },
+ );
+
+ const { mutateAsync, isError, error, isLoading } =
+ api.user.assignPermissions.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ accessedProjects: [],
+ accessedServices: [],
+ },
+ resolver: zodResolver(addPermissions),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ accessedProjects: data.accessedProjects || [],
+ accessedServices: data.accessedServices || [],
+ canCreateProjects: data.canCreateProjects,
+ canCreateServices: data.canCreateServices,
+ canDeleteProjects: data.canDeleteProjects,
+ canDeleteServices: data.canDeleteServices,
+ canAccessToTraefikFiles: data.canAccessToTraefikFiles,
+ canAccessToDocker: data.canAccessToDocker,
+ canAccessToAPI: data.canAccessToAPI,
+ canAccessToSSHKeys: data.canAccessToSSHKeys,
+ canAccessToGitProviders: data.canAccessToGitProviders,
+ });
+ }
+ }, [form, form.formState.isSubmitSuccessful, form.reset, data]);
+
+ const onSubmit = async (data: AddPermissions) => {
+ await mutateAsync({
+ id: userId,
+ canCreateServices: data.canCreateServices,
+ canCreateProjects: data.canCreateProjects,
+ canDeleteServices: data.canDeleteServices,
+ canDeleteProjects: data.canDeleteProjects,
+ canAccessToTraefikFiles: data.canAccessToTraefikFiles,
+ accessedProjects: data.accessedProjects || [],
+ accessedServices: data.accessedServices || [],
+ canAccessToDocker: data.canAccessToDocker,
+ canAccessToAPI: data.canAccessToAPI,
+ canAccessToSSHKeys: data.canAccessToSSHKeys,
+ canAccessToGitProviders: data.canAccessToGitProviders,
+ })
+ .then(async () => {
+ toast.success("Permissions updated");
+ refetch();
+ })
+ .catch(() => {
+ toast.error("Error updating the permissions");
+ });
+ };
+ return (
+
+
+ e.preventDefault()}
+ >
+ Add Permissions
+
+
+
+
+ Permissions
+ Add or remove permissions
+
+ {isError && {error?.message} }
+
+
+
+ (
+
+
+ Create Projects
+
+ Allow the user to create projects
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Delete Projects
+
+ Allow the user to delete projects
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Create Services
+
+ Allow the user to create services
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Delete Services
+
+ Allow the user to delete services
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Access to Traefik Files
+
+ Allow the user to access to the Traefik Tab Files
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Access to Docker
+
+ Allow the user to access to the Docker Tab
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Access to API/CLI
+
+ Allow the user to access to the API/CLI
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Access to SSH Keys
+
+ Allow to users to access to the SSH Keys section
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Access to Git Providers
+
+ Allow to users to access to the Git Providers section
+
+
+
+
+
+
+ )}
+ />
+ (
+
+
+ Projects
+
+ Select the Projects that the user can access
+
+
+ {projects?.length === 0 && (
+
+ No projects found
+
+ )}
+
+ {projects?.map((item, index) => {
+ const applications = extractServices(item);
+ return (
+
{
+ return (
+
+
+
+ {
+ return checked
+ ? field.onChange([
+ ...(field.value || []),
+ item.projectId,
+ ])
+ : field.onChange(
+ field.value?.filter(
+ (value) =>
+ value !== item.projectId,
+ ),
+ );
+ }}
+ />
+
+
+ {item.name}
+
+
+ {applications.length === 0 && (
+
+ No services found
+
+ )}
+ {applications?.map((item, index) => (
+ {
+ return (
+
+
+ {
+ return checked
+ ? field.onChange([
+ ...(field.value || []),
+ item.id,
+ ])
+ : field.onChange(
+ field.value?.filter(
+ (value) =>
+ value !== item.id,
+ ),
+ );
+ }}
+ />
+
+
+ {item.name}
+
+
+ );
+ }}
+ />
+ ))}
+
+ );
+ }}
+ />
+ );
+ })}
+
+
+
+
+ )}
+ />
+
+
+ Update
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/users/show-invitations.tsx b/data/apps/dokploy/components/dashboard/settings/users/show-invitations.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..76d368a386753d451043e2b277b61dcf09fadb95
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/users/show-invitations.tsx
@@ -0,0 +1,224 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Table,
+ TableBody,
+ TableCaption,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { authClient } from "@/lib/auth-client";
+import { api } from "@/utils/api";
+import copy from "copy-to-clipboard";
+import { format, isPast } from "date-fns";
+import { Mail, MoreHorizontal, Users } from "lucide-react";
+import { Loader2 } from "lucide-react";
+import { toast } from "sonner";
+import { AddInvitation } from "./add-invitation";
+
+export const ShowInvitations = () => {
+ const { data, isLoading, refetch } =
+ api.organization.allInvitations.useQuery();
+
+ const { mutateAsync: removeInvitation } =
+ api.organization.removeInvitation.useMutation();
+
+ return (
+
+
+
+
+
+
+ Invitations
+
+
+ Create invitations to your organization.
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {data?.length === 0 ? (
+
+
+
+ Invite users to your organization
+
+
+
+ ) : (
+
+
+ See all invitations
+
+
+ Email
+ Role
+ Status
+
+ Expires At
+
+ Actions
+
+
+
+ {data?.map((invitation) => {
+ const isExpired = isPast(
+ new Date(invitation.expiresAt),
+ );
+ return (
+
+
+ {invitation.email}
+
+
+
+ {invitation.role}
+
+
+
+
+ {invitation.status}
+
+
+
+ {format(new Date(invitation.expiresAt), "PPpp")}{" "}
+ {isExpired ? (
+
+ (Expired)
+
+ ) : null}
+
+
+
+
+
+
+ Open menu
+
+
+
+
+
+ Actions
+
+ {!isExpired && (
+ <>
+ {invitation.status === "pending" && (
+ {
+ copy(
+ `${origin}/invitation?token=${invitation.id}`,
+ );
+ toast.success(
+ "Invitation Copied to clipboard",
+ );
+ }}
+ >
+ Copy Invitation
+
+ )}
+
+ {invitation.status === "pending" && (
+ {
+ const result =
+ await authClient.organization.cancelInvitation(
+ {
+ invitationId: invitation.id,
+ },
+ );
+
+ if (result.error) {
+ toast.error(
+ result.error.message,
+ );
+ } else {
+ toast.success(
+ "Invitation deleted",
+ );
+ refetch();
+ }
+ }}
+ >
+ Cancel Invitation
+
+ )}
+ >
+ )}
+ {
+ await removeInvitation({
+ invitationId: invitation.id,
+ }).then(() => {
+ refetch();
+ toast.success("Invitation removed");
+ });
+ }}
+ >
+ Remove Invitation
+
+
+
+
+
+ );
+ })}
+
+
+
+
+
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/users/show-users.tsx b/data/apps/dokploy/components/dashboard/settings/users/show-users.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..9580240dfd3c659b3481b02d82b1556a756f75c2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/users/show-users.tsx
@@ -0,0 +1,250 @@
+import { DialogAction } from "@/components/shared/dialog-action";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Table,
+ TableBody,
+ TableCaption,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { authClient } from "@/lib/auth-client";
+import { api } from "@/utils/api";
+import { format } from "date-fns";
+import { MoreHorizontal, Users } from "lucide-react";
+import { Loader2 } from "lucide-react";
+import { toast } from "sonner";
+import { AddUserPermissions } from "./add-permissions";
+
+export const ShowUsers = () => {
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const { data, isLoading, refetch } = api.user.all.useQuery();
+ const { mutateAsync } = api.user.remove.useMutation();
+ const utils = api.useUtils();
+
+ return (
+
+
+
+
+
+
+ Users
+
+
+ Add your users to your Dokploy account.
+
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+ <>
+ {data?.length === 0 ? (
+
+
+
+ Invite users to your Dokploy account
+
+
+ ) : (
+
+
+ See all users
+
+
+ Email
+ Role
+ 2FA
+
+
+ Created At
+
+ Actions
+
+
+
+ {data?.map((member) => {
+ return (
+
+
+ {member.user.email}
+
+
+
+ {member.role}
+
+
+
+ {member.user.twoFactorEnabled
+ ? "Enabled"
+ : "Disabled"}
+
+
+
+ {format(new Date(member.createdAt), "PPpp")}
+
+
+
+
+
+
+
+ Open menu
+
+
+
+
+
+ Actions
+
+
+ {member.role !== "owner" && (
+
+ )}
+
+ {member.role !== "owner" && (
+ <>
+ {!isCloud && (
+ {
+ await mutateAsync({
+ userId: member.user.id,
+ })
+ .then(() => {
+ toast.success(
+ "User deleted successfully",
+ );
+ refetch();
+ })
+ .catch(() => {
+ toast.error(
+ "Error deleting destination",
+ );
+ });
+ }}
+ >
+
+ e.preventDefault()
+ }
+ >
+ Delete User
+
+
+ )}
+
+ {
+ if (!isCloud) {
+ const orgCount =
+ await utils.user.checkUserOrganizations.fetch(
+ {
+ userId: member.user.id,
+ },
+ );
+
+ console.log(orgCount);
+
+ if (orgCount === 1) {
+ await mutateAsync({
+ userId: member.user.id,
+ })
+ .then(() => {
+ toast.success(
+ "User deleted successfully",
+ );
+ refetch();
+ })
+ .catch(() => {
+ toast.error(
+ "Error deleting user",
+ );
+ });
+ return;
+ }
+ }
+
+ const { error } =
+ await authClient.organization.removeMember(
+ {
+ memberIdOrEmail: member.id,
+ },
+ );
+
+ if (!error) {
+ toast.success(
+ "User unlinked successfully",
+ );
+ refetch();
+ } else {
+ toast.error(
+ "Error unlinking user",
+ );
+ }
+ }}
+ >
+ e.preventDefault()}
+ >
+ Unlink User
+
+
+ >
+ )}
+
+
+
+
+ );
+ })}
+
+
+
+ )}
+ >
+ )}
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-domain.tsx b/data/apps/dokploy/components/dashboard/settings/web-domain.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..d35dae35b3eae765eb41cd8e1acf557c5050c24a
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-domain.tsx
@@ -0,0 +1,246 @@
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { GlobeIcon } from "lucide-react";
+import { useTranslation } from "next-i18next";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const addServerDomain = z
+ .object({
+ domain: z.string(),
+ letsEncryptEmail: z.string(),
+ https: z.boolean().optional(),
+ certificateType: z.enum(["letsencrypt", "none", "custom"]),
+ })
+ .superRefine((data, ctx) => {
+ if (data.https && !data.certificateType) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["certificateType"],
+ message: "Required",
+ });
+ }
+ if (data.certificateType === "letsencrypt" && !data.letsEncryptEmail) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message:
+ "LetsEncrypt email is required when certificate type is letsencrypt",
+ path: ["letsEncryptEmail"],
+ });
+ }
+ });
+
+type AddServerDomain = z.infer;
+
+export const WebDomain = () => {
+ const { t } = useTranslation("settings");
+ const { data, refetch } = api.user.get.useQuery();
+ const { mutateAsync, isLoading } =
+ api.settings.assignDomainServer.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ domain: "",
+ certificateType: "none",
+ letsEncryptEmail: "",
+ https: false,
+ },
+ resolver: zodResolver(addServerDomain),
+ });
+ const https = form.watch("https");
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ domain: data?.user?.host || "",
+ certificateType: data?.user?.certificateType,
+ letsEncryptEmail: data?.user?.letsEncryptEmail || "",
+ https: data?.user?.https || false,
+ });
+ }
+ }, [form, form.reset, data]);
+
+ const onSubmit = async (data: AddServerDomain) => {
+ await mutateAsync({
+ host: data.domain,
+ letsEncryptEmail: data.letsEncryptEmail,
+ certificateType: data.certificateType,
+ https: data.https,
+ })
+ .then(async () => {
+ await refetch();
+ toast.success("Domain Assigned");
+ })
+ .catch(() => {
+ toast.error("Error assigning the domain");
+ });
+ };
+
+ return (
+
+
+
+
+
+
+
+ {t("settings.server.domain.title")}
+
+
+ {t("settings.server.domain.description")}
+
+
+
+
+
+
+ {
+ return (
+
+
+ {t("settings.server.domain.form.domain")}
+
+
+
+
+
+
+ );
+ }}
+ />
+
+ {
+ return (
+
+
+ {t("settings.server.domain.form.letsEncryptEmail")}
+
+
+
+
+
+
+ );
+ }}
+ />
+ (
+
+
+ HTTPS
+
+ Automatically provision SSL Certificate.
+
+
+
+
+
+
+
+ )}
+ />
+ {https && (
+ {
+ return (
+
+
+ {t("settings.server.domain.form.certificate.label")}
+
+
+
+
+
+
+
+
+
+ {t(
+ "settings.server.domain.form.certificateOptions.none",
+ )}
+
+
+ {t(
+ "settings.server.domain.form.certificateOptions.letsencrypt",
+ )}
+
+
+
+
+
+ );
+ }}
+ />
+ )}
+
+
+
+ {t("settings.common.save")}
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server.tsx b/data/apps/dokploy/components/dashboard/settings/web-server.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..64b6d634e42165257c4f3b1d25545a1e69cfb98b
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server.tsx
@@ -0,0 +1,69 @@
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { ServerIcon } from "lucide-react";
+import { useTranslation } from "next-i18next";
+import { ShowDokployActions } from "./servers/actions/show-dokploy-actions";
+import { ShowStorageActions } from "./servers/actions/show-storage-actions";
+import { ShowTraefikActions } from "./servers/actions/show-traefik-actions";
+import { ToggleDockerCleanup } from "./servers/actions/toggle-docker-cleanup";
+import { UpdateServer } from "./web-server/update-server";
+
+export const WebServer = () => {
+ const { t } = useTranslation("settings");
+ const { data } = api.user.get.useQuery();
+
+ const { data: dokployVersion } = api.settings.getDokployVersion.useQuery();
+
+ return (
+
+ {/*
*/}
+
+
+
+
+
+ {t("settings.server.webServer.title")}
+
+
+ {t("settings.server.webServer.description")}
+
+
+ {/*
+
+ {t("settings.server.webServer.title")}
+
+
+ {t("settings.server.webServer.description")}
+
+ */}
+
+
+
+
+
+
+
+
+
+
+
+ Server IP: {data?.user.serverIp}
+
+
+ Version: {dokployVersion}
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/docker-terminal-modal.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/docker-terminal-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..44dda0d3698b2adcd7e3b8b3289fb54643d5e4f6
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/docker-terminal-modal.tsx
@@ -0,0 +1,150 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { Loader2 } from "lucide-react";
+import dynamic from "next/dynamic";
+import type React from "react";
+import { useEffect, useState } from "react";
+import { badgeStateColor } from "../../application/logs/show";
+
+const Terminal = dynamic(
+ () =>
+ import("@/components/dashboard/docker/terminal/docker-terminal").then(
+ (e) => e.DockerTerminal,
+ ),
+ {
+ ssr: false,
+ },
+);
+
+interface Props {
+ appName: string;
+ children?: React.ReactNode;
+ serverId?: string;
+}
+
+export const DockerTerminalModal = ({ children, appName, serverId }: Props) => {
+ const { data, isLoading } = api.docker.getContainersByAppNameMatch.useQuery(
+ {
+ appName,
+ serverId,
+ },
+ {
+ enabled: !!appName,
+ },
+ );
+ const [containerId, setContainerId] = useState();
+ const [mainDialogOpen, setMainDialogOpen] = useState(false);
+ const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
+
+ const handleMainDialogOpenChange = (open: boolean) => {
+ if (!open) {
+ setConfirmDialogOpen(true);
+ } else {
+ setMainDialogOpen(true);
+ }
+ };
+
+ const handleConfirm = () => {
+ setConfirmDialogOpen(false);
+ setMainDialogOpen(false);
+ };
+
+ const handleCancel = () => {
+ setConfirmDialogOpen(false);
+ };
+
+ useEffect(() => {
+ if (data && data?.length > 0) {
+ setContainerId(data[0]?.containerId);
+ }
+ }, [data]);
+
+ return (
+
+ {children}
+ event.preventDefault()}
+ >
+
+ Docker Terminal
+
+ Easy way to access to docker container
+
+
+ Select a container to view logs
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+
+ )}
+
+
+
+ {data?.map((container) => (
+
+ {container.name} ({container.containerId}){" "}
+
+ {container.state}
+
+
+ ))}
+ Containers ({data?.length})
+
+
+
+
+
+ event.preventDefault()}>
+
+
+ Are you sure you want to close the terminal?
+
+
+ By clicking the confirm button, the terminal will be closed.
+
+
+
+
+ Cancel
+
+ Confirm
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/edit-traefik-env.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/edit-traefik-env.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..07dc24078eea6e3fa96f0c4de29602aa4ceb42a5
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/edit-traefik-env.tsx
@@ -0,0 +1,154 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const schema = z.object({
+ env: z.string(),
+});
+
+type Schema = z.infer;
+
+interface Props {
+ children?: React.ReactNode;
+ serverId?: string;
+}
+
+export const EditTraefikEnv = ({ children, serverId }: Props) => {
+ const [canEdit, setCanEdit] = useState(true);
+
+ const { data } = api.settings.readTraefikEnv.useQuery({
+ serverId,
+ });
+
+ const { mutateAsync, isLoading, error, isError } =
+ api.settings.writeTraefikEnv.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ env: data || "",
+ },
+ disabled: canEdit,
+ resolver: zodResolver(schema),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ env: data || "",
+ });
+ }
+ }, [form, form.reset, data]);
+
+ const onSubmit = async (data: Schema) => {
+ await mutateAsync({
+ env: data.env,
+ serverId,
+ })
+ .then(async () => {
+ toast.success("Traefik Env Updated");
+ })
+ .catch(() => {
+ toast.error("Error updating the Traefik env");
+ });
+ };
+
+ return (
+
+ {children}
+
+
+ Update Traefik Environment
+
+ Update the traefik environment variables
+
+
+ {isError && {error?.message} }
+
+
+
+
+
(
+
+ Env
+
+
+
+
+
+
+
+
+ {
+ setCanEdit(!canEdit);
+ }}
+ >
+ {canEdit ? "Unlock" : "Lock"}
+
+
+
+ )}
+ />
+
+
+
+
+
+ Update
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/local-server-config.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/local-server-config.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e30408e6da452f367672b116bc1ab0600b8043a2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/local-server-config.tsx
@@ -0,0 +1,153 @@
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@/components/ui/accordion";
+import { Button, buttonVariants } from "@/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { cn } from "@/lib/utils";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Settings } from "lucide-react";
+import { useTranslation } from "next-i18next";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+
+const Schema = z.object({
+ port: z.number().min(1, "Port must be higher than 0"),
+ username: z.string().min(1, "Username is required"),
+});
+
+type Schema = z.infer;
+
+const DEFAULT_LOCAL_SERVER_DATA: Schema = {
+ port: 22,
+ username: "root",
+};
+
+/** Returns local server data for use with local server terminal */
+export const getLocalServerData = () => {
+ try {
+ const localServerData = localStorage.getItem("localServerData");
+ const parsedLocalServerData = localServerData
+ ? (JSON.parse(localServerData) as typeof DEFAULT_LOCAL_SERVER_DATA)
+ : DEFAULT_LOCAL_SERVER_DATA;
+
+ return parsedLocalServerData;
+ } catch {
+ return DEFAULT_LOCAL_SERVER_DATA;
+ }
+};
+
+interface Props {
+ onSave: () => void;
+}
+
+const LocalServerConfig = ({ onSave }: Props) => {
+ const { t } = useTranslation("settings");
+
+ const form = useForm({
+ defaultValues: getLocalServerData(),
+ resolver: zodResolver(Schema),
+ });
+
+ const onSubmit = (data: Schema) => {
+ localStorage.setItem("localServerData", JSON.stringify(data));
+ form.reset(data);
+ onSave();
+ };
+
+ return (
+
+
+
+
+
+
+
+ {t("settings.terminal.connectionSettings")}
+
+
+
+
+
+
+
+
+ (
+
+ {t("settings.terminal.port")}
+
+ {
+ const value = e.target.value;
+ if (value === "") {
+ field.onChange(1);
+ } else {
+ const number = Number.parseInt(value, 10);
+ if (!Number.isNaN(number)) {
+ field.onChange(number);
+ }
+ }
+ }}
+ />
+
+
+
+
+ )}
+ />
+
+ (
+
+ {t("settings.terminal.username")}
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ {t("settings.common.save")}
+
+
+
+
+ );
+};
+
+export default LocalServerConfig;
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/manage-traefik-ports.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/manage-traefik-ports.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..dd9839e3d9efb060dbd6ba817b31e990efa31068
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/manage-traefik-ports.tsx
@@ -0,0 +1,275 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { ArrowRightLeft, Plus, Trash2 } from "lucide-react";
+import { useTranslation } from "next-i18next";
+import type React from "react";
+import { useEffect, useState } from "react";
+import { useFieldArray, useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+interface Props {
+ children: React.ReactNode;
+ serverId?: string;
+}
+
+const PortSchema = z.object({
+ targetPort: z.number().min(1, "Target port is required"),
+ publishedPort: z.number().min(1, "Published port is required"),
+});
+
+const TraefikPortsSchema = z.object({
+ ports: z.array(PortSchema),
+});
+
+type TraefikPortsForm = z.infer;
+
+export const ManageTraefikPorts = ({ children, serverId }: Props) => {
+ const { t } = useTranslation("settings");
+ const [open, setOpen] = useState(false);
+
+ const form = useForm({
+ resolver: zodResolver(TraefikPortsSchema),
+ defaultValues: {
+ ports: [],
+ },
+ });
+
+ const { fields, append, remove } = useFieldArray({
+ control: form.control,
+ name: "ports",
+ });
+
+ const { data: currentPorts, refetch: refetchPorts } =
+ api.settings.getTraefikPorts.useQuery({
+ serverId,
+ });
+
+ const { mutateAsync: updatePorts, isLoading } =
+ api.settings.updateTraefikPorts.useMutation({
+ onSuccess: () => {
+ refetchPorts();
+ },
+ });
+
+ useEffect(() => {
+ if (currentPorts) {
+ form.reset({ ports: currentPorts });
+ }
+ }, [currentPorts, form]);
+
+ const handleAddPort = () => {
+ append({ targetPort: 0, publishedPort: 0 });
+ };
+
+ const onSubmit = async (data: TraefikPortsForm) => {
+ try {
+ await updatePorts({
+ serverId,
+ additionalPorts: data.ports,
+ });
+ toast.success(t("settings.server.webServer.traefik.portsUpdated"));
+ setOpen(false);
+ } catch (_error) {}
+ };
+
+ return (
+ <>
+ setOpen(true)}>{children}
+
+
+
+
+ {t("settings.server.webServer.traefik.managePorts")}
+
+
+
+
+ {t(
+ "settings.server.webServer.traefik.managePortsDescription",
+ )}
+
+ {fields.length} port mapping{fields.length !== 1 ? "s" : ""}{" "}
+ configured
+
+
+
+
+ Add Mapping
+
+
+
+
+
+
+
+
+ {fields.length === 0 ? (
+
+
+
+ No port mappings configured
+
+
+ Add one to get started
+
+
+ ) : (
+
+
+
+ )}
+
+ {fields.length > 0 && (
+
+
+
+
+ Each port mapping defines how external traffic reaches
+ your containers through Traefik.
+
+
+
+ Target Port: The port inside your
+ container that the service is listening on.
+
+
+ Published Port: The port on your
+ host machine that will be mapped to the target port.
+
+
+
+ All ports are bound directly to the host machine,
+ allowing Traefik to handle incoming traffic and route
+ it appropriately to your services.
+
+
+
+
+ )}
+
+
+
+ Save
+
+
+
+
+
+
+ >
+ );
+};
+
+export default ManageTraefikPorts;
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/show-modal-logs.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/show-modal-logs.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..aa7a3397919402f251862b1622bdf7df6d51cbbe
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/show-modal-logs.tsx
@@ -0,0 +1,114 @@
+import { Badge } from "@/components/ui/badge";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api } from "@/utils/api";
+import { Loader2 } from "lucide-react";
+import dynamic from "next/dynamic";
+import type React from "react";
+import { useEffect, useState } from "react";
+import { badgeStateColor } from "../../application/logs/show";
+
+export const DockerLogsId = dynamic(
+ () =>
+ import("@/components/dashboard/docker/logs/docker-logs-id").then(
+ (e) => e.DockerLogsId,
+ ),
+ {
+ ssr: false,
+ },
+);
+
+interface Props {
+ appName: string;
+ children?: React.ReactNode;
+ serverId?: string;
+ type?: "standalone" | "swarm";
+}
+
+export const ShowModalLogs = ({
+ appName,
+ children,
+ serverId,
+ type = "swarm",
+}: Props) => {
+ const { data, isLoading } = api.docker.getContainersByAppLabel.useQuery(
+ {
+ appName,
+ serverId,
+ type,
+ },
+ {
+ enabled: !!appName,
+ },
+ );
+ const [containerId, setContainerId] = useState();
+
+ useEffect(() => {
+ if (data && data?.length > 0) {
+ setContainerId(data[0]?.containerId);
+ }
+ }, [data]);
+ return (
+
+ {children}
+
+
+ View Logs
+ View the logs for {appName}
+
+
+
Select a container to view logs
+
+
+ {isLoading ? (
+
+ Loading...
+
+
+ ) : (
+
+ )}
+
+
+
+ {data?.map((container) => (
+
+ {container.name} ({container.containerId}){" "}
+
+ {container.state}
+
+
+ ))}
+ Containers ({data?.length})
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/terminal-modal.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/terminal-modal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..7c64ebc0907e2f008c81619cde5e60beccb8b2cf
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/terminal-modal.tsx
@@ -0,0 +1,74 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { api } from "@/utils/api";
+import dynamic from "next/dynamic";
+import type React from "react";
+import { useState } from "react";
+import LocalServerConfig from "./local-server-config";
+
+const Terminal = dynamic(() => import("./terminal").then((e) => e.Terminal), {
+ ssr: false,
+});
+
+const getTerminalKey = () => {
+ return `terminal-${Date.now()}`;
+};
+
+interface Props {
+ children?: React.ReactNode;
+ serverId: string;
+}
+
+export const TerminalModal = ({ children, serverId }: Props) => {
+ const [terminalKey, setTerminalKey] = useState(getTerminalKey());
+ const isLocalServer = serverId === "local";
+
+ const { data } = api.server.one.useQuery(
+ {
+ serverId,
+ },
+ { enabled: !!serverId && !isLocalServer },
+ );
+
+ const handleLocalServerConfigSave = () => {
+ // Rerender Terminal component to reconnect using new component key when saving local server config
+ setTerminalKey(getTerminalKey());
+ };
+
+ return (
+
+
+ e.preventDefault()}
+ >
+ {children}
+
+
+ event.preventDefault()}
+ >
+
+ Terminal ({data?.name ?? serverId})
+ Easy way to access the server
+
+
+ {isLocalServer && (
+
+ )}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..dccdec0030b4b32e8cb05a10bb1aa22e254e37b0
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx
@@ -0,0 +1,80 @@
+import { Terminal as XTerm } from "@xterm/xterm";
+import type React from "react";
+import { useEffect, useRef } from "react";
+import { FitAddon } from "xterm-addon-fit";
+import "@xterm/xterm/css/xterm.css";
+import { AttachAddon } from "@xterm/addon-attach";
+import { ClipboardAddon } from "@xterm/addon-clipboard";
+import { useTheme } from "next-themes";
+import { getLocalServerData } from "./local-server-config";
+
+interface Props {
+ id: string;
+ serverId: string;
+}
+
+export const Terminal: React.FC = ({ id, serverId }) => {
+ const termRef = useRef(null);
+ const initialized = useRef(false);
+ const { resolvedTheme } = useTheme();
+ useEffect(() => {
+ if (initialized.current) {
+ // Required in strict mode to avoid issues due to double wss connection
+ return;
+ }
+
+ initialized.current = true;
+ const container = document.getElementById(id);
+ if (container) {
+ container.innerHTML = "";
+ }
+ const term = new XTerm({
+ cursorBlink: true,
+ lineHeight: 1.4,
+ convertEol: true,
+ theme: {
+ cursor: resolvedTheme === "light" ? "#000000" : "transparent",
+ background: "rgba(0, 0, 0, 0)",
+ foreground: "currentColor",
+ },
+ });
+
+ const addonFit = new FitAddon();
+
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+
+ const urlParams = new URLSearchParams();
+ urlParams.set("serverId", serverId);
+
+ if (serverId === "local") {
+ const { port, username } = getLocalServerData();
+ urlParams.set("port", port.toString());
+ urlParams.set("username", username);
+ }
+
+ const wsUrl = `${protocol}//${window.location.host}/terminal?${urlParams}`;
+
+ const ws = new WebSocket(wsUrl);
+ const addonAttach = new AttachAddon(ws);
+ const clipboardAddon = new ClipboardAddon();
+ term.loadAddon(clipboardAddon);
+
+ // @ts-ignore
+ term.open(termRef.current);
+ // @ts-ignore
+ term.loadAddon(addonFit);
+ term.loadAddon(addonAttach);
+ addonFit.fit();
+ return () => {
+ ws.readyState === WebSocket.OPEN && ws.close();
+ };
+ }, [id, serverId]);
+
+ return (
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/toggle-auto-check-updates.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/toggle-auto-check-updates.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..fb3776b1179d1afe4f5fc9a8f1adc036a49f7963
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/toggle-auto-check-updates.tsx
@@ -0,0 +1,28 @@
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import { useState } from "react";
+
+export const ToggleAutoCheckUpdates = ({ disabled }: { disabled: boolean }) => {
+ const [enabled, setEnabled] = useState(
+ localStorage.getItem("enableAutoCheckUpdates") === "true",
+ );
+
+ const handleToggle = (checked: boolean) => {
+ setEnabled(checked);
+ localStorage.setItem("enableAutoCheckUpdates", String(checked));
+ };
+
+ return (
+
+
+
+ Automatically check for new updates
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/update-server-ip.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/update-server-ip.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..afe1e4c36a2a945f0e59b612bc2d0958cd20f995
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/update-server-ip.tsx
@@ -0,0 +1,160 @@
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { RefreshCw } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+const schema = z.object({
+ serverIp: z.string(),
+});
+
+type Schema = z.infer;
+
+interface Props {
+ children?: React.ReactNode;
+ serverId?: string;
+}
+
+export const UpdateServerIp = ({ children }: Props) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ const { data } = api.user.get.useQuery();
+ const { data: ip } = api.server.publicIp.useQuery();
+
+ const { mutateAsync, isLoading, error, isError } =
+ api.user.update.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ serverIp: data?.user.serverIp || "",
+ },
+ resolver: zodResolver(schema),
+ });
+
+ useEffect(() => {
+ if (data) {
+ form.reset({
+ serverIp: data.user.serverIp || "",
+ });
+ }
+ }, [form, form.reset, data]);
+
+ const utils = api.useUtils();
+
+ const setCurrentIp = () => {
+ if (!ip) return;
+ form.setValue("serverIp", ip);
+ };
+
+ const onSubmit = async (data: Schema) => {
+ await mutateAsync({
+ serverIp: data.serverIp,
+ })
+ .then(async () => {
+ toast.success("Server IP Updated");
+ await utils.user.get.invalidate();
+ setIsOpen(false);
+ })
+ .catch(() => {
+ toast.error("Error updating the IP of the server");
+ });
+ };
+
+ return (
+
+ {children}
+
+
+ Update Server IP
+ Update the IP of the server
+
+ {isError && {error?.message} }
+
+
+
+ (
+
+ Server IP
+
+
+
+
+
+
+
+
+
+
+
+
+ Set current public IP
+
+
+
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ Update
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/update-server.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/update-server.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..1b7eb91a251dc6c411074d1e0622c825c6256bf2
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/update-server.tsx
@@ -0,0 +1,289 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import type { IUpdateData } from "@dokploy/server/index";
+import {
+ Bug,
+ Download,
+ Info,
+ RefreshCcw,
+ Server,
+ Sparkles,
+ Stars,
+} from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { ToggleAutoCheckUpdates } from "./toggle-auto-check-updates";
+import { UpdateWebServer } from "./update-webserver";
+
+interface Props {
+ updateData?: IUpdateData;
+ children?: React.ReactNode;
+ isOpen?: boolean;
+ onOpenChange?: (open: boolean) => void;
+}
+
+export const UpdateServer = ({
+ updateData,
+ children,
+ isOpen: isOpenProp,
+ onOpenChange: onOpenChangeProp,
+}: Props) => {
+ const [hasCheckedUpdate, setHasCheckedUpdate] = useState(!!updateData);
+ const [isUpdateAvailable, setIsUpdateAvailable] = useState(
+ !!updateData?.updateAvailable,
+ );
+ const { mutateAsync: getUpdateData, isLoading } =
+ api.settings.getUpdateData.useMutation();
+ const { data: dokployVersion } = api.settings.getDokployVersion.useQuery();
+ const { data: releaseTag } = api.settings.getReleaseTag.useQuery();
+ const [latestVersion, setLatestVersion] = useState(
+ updateData?.latestVersion ?? "",
+ );
+ const [isOpenInternal, setIsOpenInternal] = useState(false);
+
+ const handleCheckUpdates = async () => {
+ try {
+ const updateData = await getUpdateData();
+ const versionToUpdate = updateData.latestVersion || "";
+ setHasCheckedUpdate(true);
+ setIsUpdateAvailable(updateData.updateAvailable);
+ setLatestVersion(versionToUpdate);
+
+ if (updateData.updateAvailable) {
+ toast.success(versionToUpdate, {
+ description: "New version available!",
+ });
+ } else {
+ toast.info("No updates available");
+ }
+ } catch (error) {
+ console.error("Error checking for updates:", error);
+ setHasCheckedUpdate(true);
+ setIsUpdateAvailable(false);
+ toast.error(
+ "An error occurred while checking for updates, please try again.",
+ );
+ }
+ };
+
+ const isOpen = isOpenInternal || isOpenProp;
+ const onOpenChange = (open: boolean) => {
+ setIsOpenInternal(open);
+ onOpenChangeProp?.(open);
+ };
+
+ return (
+
+
+ {children ? (
+ children
+ ) : (
+
+
+
+ onOpenChange?.(true)}
+ >
+
+ {updateData ? (
+
+ Update Available
+
+ ) : (
+
+ Check for updates
+
+ )}
+ {updateData && (
+
+
+
+
+ )}
+
+
+ {updateData && (
+
+ Update Available
+
+ )}
+
+
+ )}
+
+
+
+
+ Web Server Update
+
+ {dokployVersion && (
+
+
+
+ {dokployVersion} | {releaseTag}
+
+
+ )}
+
+
+ {/* Initial state */}
+ {!hasCheckedUpdate && (
+
+
+ Check for new releases and update Dokploy.
+
+
+ We recommend checking for updates regularly to ensure you have the
+ latest features and security improvements.
+
+
+ )}
+
+ {/* Update available state */}
+ {isUpdateAvailable && latestVersion && (
+
+
+
+
+
+ New version available:
+
+
+
+ {latestVersion}
+
+
+
+
+
+ A new version of the server software is available. Consider
+ updating if you:
+
+
+
+
+
+ Want to access the latest features and improvements
+
+
+
+
+
+ Are experiencing issues that may be resolved in the new
+ version
+
+
+
+
+
+ )}
+
+ {/* Up to date state */}
+ {hasCheckedUpdate && !isUpdateAvailable && !isLoading && (
+
+
+
+
+
+
+
+ You are using the latest version
+
+
+ Your server is up to date with all the latest features and
+ security improvements.
+
+
+
+
+ )}
+
+ {hasCheckedUpdate && isLoading && (
+
+
+
+
+
+
+
Checking for updates...
+
+ Please wait while we pull the latest version information from
+ Docker Hub.
+
+
+
+
+ )}
+
+ {isUpdateAvailable && (
+
+
+
+
+ We recommend reviewing the{" "}
+
+ release notes
+ {" "}
+ for any breaking changes before updating.
+
+
+
+ )}
+
+
+
+
+
+
+
+ onOpenChange?.(false)}>
+ Cancel
+
+ {isUpdateAvailable ? (
+
+ ) : (
+
+ {isLoading ? (
+ <>
+
+ Checking for updates
+ >
+ ) : (
+ <>
+
+ Check for updates
+ >
+ )}
+
+ )}
+
+
+
+
+ );
+};
+
+export default UpdateServer;
diff --git a/data/apps/dokploy/components/dashboard/settings/web-server/update-webserver.tsx b/data/apps/dokploy/components/dashboard/settings/web-server/update-webserver.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..537a1adde85822b19286b465e07f31118e1e54df
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/settings/web-server/update-webserver.tsx
@@ -0,0 +1,117 @@
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { api } from "@/utils/api";
+import { HardDriveDownload, Loader2 } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+
+export const UpdateWebServer = () => {
+ const [updating, setUpdating] = useState(false);
+ const [open, setOpen] = useState(false);
+
+ const { mutateAsync: updateServer } = api.settings.updateServer.useMutation();
+
+ const checkIsUpdateFinished = async () => {
+ try {
+ const response = await fetch("/api/health");
+ if (!response.ok) {
+ throw new Error("Health check failed");
+ }
+
+ toast.success(
+ "The server has been updated. The page will be reloaded to reflect the changes...",
+ );
+
+ setTimeout(() => {
+ // Allow seeing the toast before reloading
+ window.location.reload();
+ }, 2000);
+ } catch {
+ // Delay each request
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ // Keep running until it returns 200
+ void checkIsUpdateFinished();
+ }
+ };
+
+ const handleConfirm = async () => {
+ try {
+ setUpdating(true);
+ await updateServer();
+
+ // Give some time for docker service restart before starting to check status
+ await new Promise((resolve) => setTimeout(resolve, 8000));
+
+ await checkIsUpdateFinished();
+ } catch (error) {
+ setUpdating(false);
+ console.error("Error updating server:", error);
+ toast.error(
+ "An error occurred while updating the server, please try again.",
+ );
+ }
+ };
+
+ return (
+
+
+ setOpen(true)}
+ >
+
+
+
+
+
+ Update Server
+
+
+
+
+
+ {updating
+ ? "Server update in progress"
+ : "Are you absolutely sure?"}
+
+
+ {updating ? (
+
+
+ The server is being updated, please wait...
+
+ ) : (
+ <>
+ This action cannot be undone. This will update the web server to
+ the new version. You will not be able to use the panel during
+ the update process. The page will be reloaded once the update is
+ finished.
+ >
+ )}
+
+
+ {!updating && (
+
+ setOpen(false)}>
+ Cancel
+
+
+ Confirm
+
+
+ )}
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/shared/rebuild-database.tsx b/data/apps/dokploy/components/dashboard/shared/rebuild-database.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..cb6a643dfd71e68a6938ac410ba271f36589bb06
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/shared/rebuild-database.tsx
@@ -0,0 +1,119 @@
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { api } from "@/utils/api";
+import { AlertTriangle, DatabaseIcon } from "lucide-react";
+import { toast } from "sonner";
+
+interface Props {
+ id: string;
+ type: "postgres" | "mysql" | "mariadb" | "mongo" | "redis";
+}
+
+export const RebuildDatabase = ({ id, type }: Props) => {
+ const utils = api.useUtils();
+
+ const mutationMap = {
+ postgres: () => api.postgres.rebuild.useMutation(),
+ mysql: () => api.mysql.rebuild.useMutation(),
+ mariadb: () => api.mariadb.rebuild.useMutation(),
+ mongo: () => api.mongo.rebuild.useMutation(),
+ redis: () => api.redis.rebuild.useMutation(),
+ };
+
+ const { mutateAsync, isLoading } = mutationMap[type]();
+
+ const handleRebuild = async () => {
+ try {
+ await mutateAsync({
+ postgresId: type === "postgres" ? id : "",
+ mysqlId: type === "mysql" ? id : "",
+ mariadbId: type === "mariadb" ? id : "",
+ mongoId: type === "mongo" ? id : "",
+ redisId: type === "redis" ? id : "",
+ });
+ toast.success("Database rebuilt successfully");
+ await utils.invalidate();
+ } catch (error) {
+ toast.error("Error rebuilding database", {
+ description: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ };
+
+ return (
+
+
+
+
+ Danger Zone
+
+
+
+
+
+
Rebuild Database
+
+ This action will completely reset your database to its initial
+ state. All data, tables, and configurations will be removed.
+
+
+
+
+
+
+ Rebuild Database
+
+
+
+
+
+
+ Are you absolutely sure?
+
+
+ This action will:
+
+ Stop the current database service
+ Delete all existing data and volumes
+ Reset to the default configuration
+ Restart the service with a clean state
+
+
+ This action cannot be undone.
+
+
+
+
+ Cancel
+
+
+ Yes, rebuild database
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/shared/show-database-advanced-settings.tsx b/data/apps/dokploy/components/dashboard/shared/show-database-advanced-settings.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5d7b6f6b69879a69e0676c8d08eb64b3a8a7cadc
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/shared/show-database-advanced-settings.tsx
@@ -0,0 +1,20 @@
+import { ShowResources } from "@/components/dashboard/application/advanced/show-resources";
+import { ShowVolumes } from "@/components/dashboard/application/advanced/volumes/show-volumes";
+import { ShowCustomCommand } from "@/components/dashboard/postgres/advanced/show-custom-command";
+import { RebuildDatabase } from "./rebuild-database";
+
+interface Props {
+ id: string;
+ type: "postgres" | "mysql" | "mariadb" | "mongo" | "redis";
+}
+
+export const ShowDatabaseAdvancedSettings = ({ id, type }: Props) => {
+ return (
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/swarm/applications/columns.tsx b/data/apps/dokploy/components/dashboard/swarm/applications/columns.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5ae091a959849e714a8a37b8e5d1d297b6014470
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/swarm/applications/columns.tsx
@@ -0,0 +1,244 @@
+import type { ColumnDef } from "@tanstack/react-table";
+import { ArrowUpDown, MoreHorizontal } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+
+import { Badge } from "@/components/ui/badge";
+import { ShowDockerModalStackLogs } from "../../docker/logs/show-docker-modal-stack-logs";
+
+export interface ApplicationList {
+ ID: string;
+ Image: string;
+ Mode: string;
+ Name: string;
+ Ports: string;
+ Replicas: string;
+ CurrentState: string;
+ DesiredState: string;
+ Error: string;
+ Node: string;
+ serverId: string;
+}
+
+export const columns: ColumnDef[] = [
+ {
+ accessorKey: "ID",
+ accessorFn: (row) => row.ID,
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ ID
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("ID")}
;
+ },
+ },
+ {
+ accessorKey: "Name",
+ accessorFn: (row) => row.Name,
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Name
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("Name")}
;
+ },
+ },
+ {
+ accessorKey: "Image",
+ accessorFn: (row) => row.Image,
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Image
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("Image")}
;
+ },
+ },
+ {
+ accessorKey: "Mode",
+ accessorFn: (row) => row.Mode,
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Mode
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("Mode")}
;
+ },
+ },
+ {
+ accessorKey: "CurrentState",
+ accessorFn: (row) => row.CurrentState,
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Current State
+
+
+ );
+ },
+ cell: ({ row }) => {
+ const value = row.getValue("CurrentState") as string;
+ const valueStart = value.startsWith("Running")
+ ? "Running"
+ : value.startsWith("Shutdown")
+ ? "Shutdown"
+ : value;
+ return (
+
+
+ {value}
+
+
+ );
+ },
+ },
+ {
+ accessorKey: "DesiredState",
+ accessorFn: (row) => row.DesiredState,
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Desired State
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("DesiredState")}
;
+ },
+ },
+
+ {
+ accessorKey: "Replicas",
+ accessorFn: (row) => row.Replicas,
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Replicas
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("Replicas")}
;
+ },
+ },
+
+ {
+ accessorKey: "Ports",
+ accessorFn: (row) => row.Ports,
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Ports
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("Ports")}
;
+ },
+ },
+ {
+ accessorKey: "Errors",
+ accessorFn: (row) => row.Error,
+ header: ({ column }) => {
+ return (
+ column.toggleSorting(column.getIsSorted() === "asc")}
+ >
+ Errors
+
+
+ );
+ },
+ cell: ({ row }) => {
+ return {row.getValue("Errors")}
;
+ },
+ },
+ {
+ accessorKey: "Logs",
+ accessorFn: (row) => row.Error,
+ header: () => {
+ return Logs ;
+ },
+ cell: ({ row }) => {
+ return (
+
+
+
+
+ Open menu
+
+
+
+
+ Actions
+
+ View Logs
+
+
+
+
+ );
+ },
+ },
+];
diff --git a/data/apps/dokploy/components/dashboard/swarm/applications/data-table.tsx b/data/apps/dokploy/components/dashboard/swarm/applications/data-table.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..96f43e6177d319c68ef66e00b6024bf585cf7972
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/swarm/applications/data-table.tsx
@@ -0,0 +1,197 @@
+"use client";
+
+import {
+ type ColumnDef,
+ type ColumnFiltersState,
+ type SortingState,
+ type VisibilityState,
+ flexRender,
+ getCoreRowModel,
+ getFilteredRowModel,
+ getPaginationRowModel,
+ getSortedRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { DropdownMenuTrigger } from "@radix-ui/react-dropdown-menu";
+import { ChevronDown } from "lucide-react";
+import React from "react";
+
+interface DataTableProps {
+ columns: ColumnDef[];
+ data: TData[];
+}
+
+export function DataTable({
+ columns,
+ data,
+}: DataTableProps) {
+ const [sorting, setSorting] = React.useState([]);
+ const [columnFilters, setColumnFilters] = React.useState(
+ [],
+ );
+ const [columnVisibility, setColumnVisibility] =
+ React.useState({});
+ const [rowSelection, setRowSelection] = React.useState({});
+ const [_pagination, _setPagination] = React.useState({
+ pageIndex: 0, //initial page index
+ pageSize: 8, //default page size
+ });
+
+ const table = useReactTable({
+ data,
+ columns,
+ onSortingChange: setSorting,
+ onColumnFiltersChange: setColumnFilters,
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ getFilteredRowModel: getFilteredRowModel(),
+ onColumnVisibilityChange: setColumnVisibility,
+ onRowSelectionChange: setRowSelection,
+ state: {
+ sorting,
+ columnFilters,
+ columnVisibility,
+ rowSelection,
+ },
+ });
+
+ return (
+
+
+
+
+ table.getColumn("Name")?.setFilterValue(event.target.value)
+ }
+ className="md:max-w-sm"
+ />
+
+
+
+ Columns
+
+
+
+ {table
+ .getAllColumns()
+ .filter((column) => column.getCanHide())
+ .map((column) => {
+ return (
+
+ column.toggleVisibility(!!value)
+ }
+ >
+ {column.id}
+
+ );
+ })}
+
+
+
+
+
+ {table.getHeaderGroups().map((headerGroup) => (
+
+ {headerGroup.headers.map((header) => {
+ return (
+
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+
+ );
+ })}
+
+ ))}
+
+
+ {table?.getRowModel()?.rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+
+ {row.getVisibleCells().map((cell) => (
+
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+
+ ))}
+
+ ))
+ ) : (
+
+
+ No results.
+ {/* {isLoading ? (
+
+
+ Loading...
+
+
+ ) : (
+ <>No results.>
+ )} */}
+
+
+ )}
+
+
+
+ {data && data?.length > 0 && (
+
+
+ table.previousPage()}
+ disabled={!table.getCanPreviousPage()}
+ >
+ Previous
+
+ table.nextPage()}
+ disabled={!table.getCanNextPage()}
+ >
+ Next
+
+
+
+ )}
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/swarm/applications/show-applications.tsx b/data/apps/dokploy/components/dashboard/swarm/applications/show-applications.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..681afd755ec98c818c4b40c846f52d4fb27f5970
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/swarm/applications/show-applications.tsx
@@ -0,0 +1,103 @@
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { api } from "@/utils/api";
+import { Layers, Loader2 } from "lucide-react";
+import { type ApplicationList, columns } from "./columns";
+import { DataTable } from "./data-table";
+
+interface Props {
+ serverId?: string;
+}
+
+export const ShowNodeApplications = ({ serverId }: Props) => {
+ const { data: NodeApps, isLoading: NodeAppsLoading } =
+ api.swarm.getNodeApps.useQuery({ serverId });
+
+ let applicationList = "";
+
+ if (NodeApps && NodeApps.length > 0) {
+ applicationList = NodeApps.map((app) => app.Name).join(" ");
+ }
+
+ const { data: NodeAppDetails, isLoading: NodeAppDetailsLoading } =
+ api.swarm.getAppInfos.useQuery({ appName: applicationList, serverId });
+
+ if (NodeAppsLoading || NodeAppDetailsLoading) {
+ return (
+
+
+
+
+
+
+
+ );
+ }
+
+ if (!NodeApps || !NodeAppDetails) {
+ return (
+
+ No data found
+
+ );
+ }
+
+ const combinedData: ApplicationList[] = NodeApps.flatMap((app) => {
+ const appDetails =
+ NodeAppDetails?.filter((detail) =>
+ detail.Name.startsWith(`${app.Name}.`),
+ ) || [];
+
+ if (appDetails.length === 0) {
+ return [
+ {
+ ...app,
+ CurrentState: "N/A",
+ DesiredState: "N/A",
+ Error: "",
+ Node: "N/A",
+ Ports: app.Ports,
+ },
+ ];
+ }
+
+ return appDetails.map((detail) => ({
+ ...app,
+ CurrentState: detail.CurrentState,
+ DesiredState: detail.DesiredState,
+ Error: detail.Error,
+ Node: detail.Node,
+ Ports: detail.Ports || app.Ports,
+ serverId: serverId || "",
+ }));
+ });
+
+ return (
+
+
+
+
+ Services
+
+
+
+
+ Node Applications
+
+ See in detail the applications running on this node
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/swarm/details/details-card.tsx b/data/apps/dokploy/components/dashboard/swarm/details/details-card.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..52c90c0f1e2f0ce881e0091bc0026ead08138895
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/swarm/details/details-card.tsx
@@ -0,0 +1,121 @@
+import { Badge } from "@/components/ui/badge";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Separator } from "@/components/ui/separator";
+import { api } from "@/utils/api";
+import { Box, Cpu, Database, HardDrive, Loader2 } from "lucide-react";
+import { ShowNodeApplications } from "../applications/show-applications";
+import { ShowNodeConfig } from "./show-node-config";
+
+export interface SwarmList {
+ ID: string;
+ Hostname: string;
+ Availability: string;
+ EngineVersion: string;
+ Status: string;
+ ManagerStatus: string;
+ TLSStatus: string;
+}
+
+interface Props {
+ node: SwarmList;
+ serverId?: string;
+}
+
+export function NodeCard({ node, serverId }: Props) {
+ const { data, isLoading } = api.swarm.getNodeInfo.useQuery({
+ nodeId: node.ID,
+ serverId,
+ });
+
+ if (isLoading) {
+ return (
+
+
+
+ {node.Hostname}
+ {node.ManagerStatus || "Worker"}
+
+
+
+
+
+
+
+
+ );
+ }
+
+ return (
+
+
+ Node Status
+
+
+
+
+
+
+
{node.Hostname}
+
{node.ManagerStatus || "Worker"}
+
+
+ TLS Status: {node.TLSStatus}
+ Availability: {node.Availability}
+
+
+
+
+
+
+
+
+
+ Engine Version
+
+
{node.EngineVersion}
+
+
+
+
+ CPU
+
+
+ {data &&
+ (data.Description?.Resources?.NanoCPUs / 1e9).toFixed(2)}{" "}
+ Core(s)
+
+
+
+
+
+ Memory
+
+
+ {data &&
+ (
+ data.Description?.Resources?.MemoryBytes /
+ 1024 ** 3
+ ).toFixed(2)}{" "}
+ GB
+
+
+
+
+
+ IP Address
+
+
{data?.Status?.Addr}
+
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/dashboard/swarm/details/show-node-config.tsx b/data/apps/dokploy/components/dashboard/swarm/details/show-node-config.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..7f27fe3bf15bd6aac7e5f3b114ec585a50242f4d
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/swarm/details/show-node-config.tsx
@@ -0,0 +1,56 @@
+import { CodeEditor } from "@/components/shared/code-editor";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { api } from "@/utils/api";
+import { Settings } from "lucide-react";
+
+interface Props {
+ nodeId: string;
+ serverId?: string;
+}
+
+export const ShowNodeConfig = ({ nodeId, serverId }: Props) => {
+ const { data } = api.swarm.getNodeInfo.useQuery({
+ nodeId,
+ serverId,
+ });
+ return (
+
+
+
+
+ Config
+
+
+
+
+ Node Config
+
+ See in detail the metadata of this node
+
+
+
+
+
+ {/* {JSON.stringify(data, null, 2)} */}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/dashboard/swarm/monitoring-card.tsx b/data/apps/dokploy/components/dashboard/swarm/monitoring-card.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..5ab936102b160c7ed594b8c59ab771352338c16f
--- /dev/null
+++ b/data/apps/dokploy/components/dashboard/swarm/monitoring-card.tsx
@@ -0,0 +1,187 @@
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { api } from "@/utils/api";
+import {
+ Activity,
+ Loader2,
+ Monitor,
+ Server,
+ Settings,
+ WorkflowIcon,
+} from "lucide-react";
+import { NodeCard } from "./details/details-card";
+
+interface Props {
+ serverId?: string;
+}
+
+export default function SwarmMonitorCard({ serverId }: Props) {
+ const { data: nodes, isLoading } = api.swarm.getNodes.useQuery({
+ serverId,
+ });
+
+ if (isLoading) {
+ return (
+
+
+ {/*
*/}
+
+
+ Loading...
+
+
+ {/*
*/}
+
+
+ );
+ }
+
+ if (!nodes) {
+ return (
+
+
+
+ Failed to load data
+
+
+
+ );
+ }
+
+ const totalNodes = nodes.length;
+ const activeNodesCount = nodes.filter(
+ (node) => node.Status === "Ready",
+ ).length;
+ const managerNodesCount = nodes.filter(
+ (node) =>
+ node.ManagerStatus === "Leader" || node.ManagerStatus === "Reachable",
+ ).length;
+ const activeNodes = nodes.filter((node) => node.Status === "Ready");
+ const managerNodes = nodes.filter(
+ (node) =>
+ node.ManagerStatus === "Leader" || node.ManagerStatus === "Reachable",
+ );
+
+ return (
+
+
+
+
+
+
+
+ Total Nodes
+
+
+
+
+
+ {totalNodes}
+
+
+
+
+
+
+
+ Active Nodes
+
+ Online
+
+
+
+
+
+
+
+
+ {activeNodesCount} / {totalNodes}
+
+
+
+
+ {activeNodes.map((node) => (
+
+ {node.Hostname}
+
+ ))}
+
+
+
+
+
+
+
+
+
+
+
+ Manager Nodes
+
+ Online
+
+
+
+
+
+
+
+
+
+
+ {managerNodesCount} / {totalNodes}
+
+
+
+
+ {managerNodes.map((node) => (
+
+ {node.Hostname}
+
+ ))}
+
+
+
+
+
+
+
+
+
+ {nodes.map((node) => (
+
+ ))}
+
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/icons/data-tools-icons.tsx b/data/apps/dokploy/components/icons/data-tools-icons.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..806be0a6ebca7c89f66cdec8f1ba78d497bb7987
--- /dev/null
+++ b/data/apps/dokploy/components/icons/data-tools-icons.tsx
@@ -0,0 +1,309 @@
+import { cn } from "@/lib/utils";
+
+// https://worldvectorlogo.com/downloaded/redis Ref
+
+interface Props {
+ className?: string;
+}
+
+export const PostgresqlIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+
+
+
+ );
+};
+export const MysqlIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+ );
+};
+export const MariadbIcon = ({ className }: Props) => {
+ return (
+
+
+
+ );
+};
+export const MongodbIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+
+ );
+};
+
+export const RedisIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export const GitlabIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+
+
+ );
+};
+
+export const GithubIcon = ({ className }: Props) => {
+ return (
+
+
+
+ );
+};
+
+export const BitbucketIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export const GiteaIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export const DockerIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+
+
+ );
+};
+
+export const GitIcon = ({ className }: Props) => {
+ return (
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/icons/notification-icons.tsx b/data/apps/dokploy/components/icons/notification-icons.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..67104b2092edd7df3b9b530ac607a1b467da5bc6
--- /dev/null
+++ b/data/apps/dokploy/components/icons/notification-icons.tsx
@@ -0,0 +1,90 @@
+import { cn } from "@/lib/utils";
+
+interface Props {
+ className?: string;
+}
+export const SlackIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+
+
+
+
+ );
+};
+
+export const TelegramIcon = ({ className }: Props) => {
+ return (
+
+
+
+
+
+
+
+
+
+
+ );
+};
+
+export const DiscordIcon = ({ className }: Props) => {
+ return (
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/layouts/dashboard-layout.tsx b/data/apps/dokploy/components/layouts/dashboard-layout.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..4e2e15b3600f5fb523ac74533964df42f73c6989
--- /dev/null
+++ b/data/apps/dokploy/components/layouts/dashboard-layout.tsx
@@ -0,0 +1,25 @@
+import { api } from "@/utils/api";
+import { ImpersonationBar } from "../dashboard/impersonation/impersonation-bar";
+import Page from "./side";
+import { ChatwootWidget } from "../shared/ChatwootWidget";
+
+interface Props {
+ children: React.ReactNode;
+ metaName?: string;
+}
+
+export const DashboardLayout = ({ children }: Props) => {
+ const { data: haveRootAccess } = api.user.haveRootAccess.useQuery();
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+
+ return (
+ <>
+ {children}
+ {isCloud === true && (
+
+ )}
+
+ {haveRootAccess === true && }
+ >
+ );
+};
diff --git a/data/apps/dokploy/components/layouts/onboarding-layout.tsx b/data/apps/dokploy/components/layouts/onboarding-layout.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..270c906c413a6e5b1d8824dcaf8e2d1b085f625a
--- /dev/null
+++ b/data/apps/dokploy/components/layouts/onboarding-layout.tsx
@@ -0,0 +1,76 @@
+import { cn } from "@/lib/utils";
+import Link from "next/link";
+import type React from "react";
+import { GithubIcon } from "../icons/data-tools-icons";
+import { Logo } from "../shared/logo";
+import { Button } from "../ui/button";
+
+interface Props {
+ children: React.ReactNode;
+}
+export const OnboardingLayout = ({ children }: Props) => {
+ return (
+
+
+
+
+
+ Dokploy
+
+
+
+
+ “The Open Source alternative to Netlify, Vercel,
+ Heroku.”
+
+
+
+
+
+
+ {children}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/layouts/side.tsx b/data/apps/dokploy/components/layouts/side.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..8d180967e239963d13e3ba3c4d7bca7f060f0e10
--- /dev/null
+++ b/data/apps/dokploy/components/layouts/side.tsx
@@ -0,0 +1,1084 @@
+"use client";
+import {
+ Activity,
+ BarChartHorizontalBigIcon,
+ Bell,
+ BlocksIcon,
+ BookIcon,
+ BotIcon,
+ Boxes,
+ ChevronRight,
+ ChevronsUpDown,
+ CircleHelp,
+ Clock,
+ CreditCard,
+ Database,
+ Folder,
+ Forward,
+ GalleryVerticalEnd,
+ GitBranch,
+ HeartIcon,
+ KeyRound,
+ Loader2,
+ type LucideIcon,
+ Package,
+ PieChart,
+ Server,
+ ShieldCheck,
+ Trash2,
+ User,
+ Users,
+} from "lucide-react";
+import { usePathname } from "next/navigation";
+import type * as React from "react";
+import { useEffect, useState } from "react";
+
+import {
+ Breadcrumb,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbList,
+} from "@/components/ui/breadcrumb";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Separator } from "@/components/ui/separator";
+import {
+ SIDEBAR_COOKIE_NAME,
+ Sidebar,
+ SidebarContent,
+ SidebarFooter,
+ SidebarGroup,
+ SidebarGroupLabel,
+ SidebarHeader,
+ SidebarInset,
+ SidebarMenu,
+ SidebarMenuButton,
+ SidebarMenuItem,
+ SidebarMenuSub,
+ SidebarMenuSubButton,
+ SidebarMenuSubItem,
+ SidebarProvider,
+ SidebarRail,
+ SidebarTrigger,
+ useSidebar,
+} from "@/components/ui/sidebar";
+import { authClient } from "@/lib/auth-client";
+import { cn } from "@/lib/utils";
+import type { AppRouter } from "@/server/api/root";
+import { api } from "@/utils/api";
+import type { inferRouterOutputs } from "@trpc/server";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { toast } from "sonner";
+import { AddOrganization } from "../dashboard/organization/handle-organization";
+import { DialogAction } from "../shared/dialog-action";
+import { Logo } from "../shared/logo";
+import { Button } from "../ui/button";
+import { UpdateServerButton } from "./update-server";
+import { UserNav } from "./user-nav";
+
+// The types of the queries we are going to use
+type AuthQueryOutput = inferRouterOutputs["user"]["get"];
+
+type SingleNavItem = {
+ isSingle?: true;
+ title: string;
+ url: string;
+ icon?: LucideIcon;
+ isEnabled?: (opts: {
+ auth?: AuthQueryOutput;
+ isCloud: boolean;
+ }) => boolean;
+};
+
+// NavItem type
+// Consists of a single item or a group of items
+// If `isSingle` is true or undefined, the item is a single item
+// If `isSingle` is false, the item is a group of items
+type NavItem =
+ | SingleNavItem
+ | {
+ isSingle: false;
+ title: string;
+ icon: LucideIcon;
+ items: SingleNavItem[];
+ isEnabled?: (opts: {
+ auth?: AuthQueryOutput;
+ isCloud: boolean;
+ }) => boolean;
+ };
+
+// ExternalLink type
+// Represents an external link item (used for the help section)
+type ExternalLink = {
+ name: string;
+ url: string;
+ icon: React.ComponentType<{ className?: string }>;
+ isEnabled?: (opts: {
+ auth?: AuthQueryOutput;
+ isCloud: boolean;
+ }) => boolean;
+};
+
+// Menu type
+// Consists of home, settings, and help items
+type Menu = {
+ home: NavItem[];
+ settings: NavItem[];
+ help: ExternalLink[];
+};
+
+// Menu items
+// Consists of unfiltered home, settings, and help items
+// The items are filtered based on the user's role and permissions
+// The `isEnabled` function is called to determine if the item should be displayed
+const MENU: Menu = {
+ home: [
+ {
+ isSingle: true,
+ title: "Projects",
+ url: "/dashboard/projects",
+ icon: Folder,
+ },
+ {
+ isSingle: true,
+ title: "Monitoring",
+ url: "/dashboard/monitoring",
+ icon: BarChartHorizontalBigIcon,
+ // Only enabled in non-cloud environments
+ isEnabled: ({ isCloud }) => !isCloud,
+ },
+ {
+ isSingle: true,
+ title: "Schedules",
+ url: "/dashboard/schedules",
+ icon: Clock,
+ // Only enabled in non-cloud environments
+ isEnabled: ({ isCloud, auth }) => !isCloud && auth?.role === "owner",
+ },
+ {
+ isSingle: true,
+ title: "Traefik File System",
+ url: "/dashboard/traefik",
+ icon: GalleryVerticalEnd,
+ // Only enabled for admins and users with access to Traefik files in non-cloud environments
+ isEnabled: ({ auth, isCloud }) =>
+ !!(
+ (auth?.role === "owner" || auth?.canAccessToTraefikFiles) &&
+ !isCloud
+ ),
+ },
+ {
+ isSingle: true,
+ title: "Docker",
+ url: "/dashboard/docker",
+ icon: BlocksIcon,
+ // Only enabled for admins and users with access to Docker in non-cloud environments
+ isEnabled: ({ auth, isCloud }) =>
+ !!((auth?.role === "owner" || auth?.canAccessToDocker) && !isCloud),
+ },
+ {
+ isSingle: true,
+ title: "Swarm",
+ url: "/dashboard/swarm",
+ icon: PieChart,
+ // Only enabled for admins and users with access to Docker in non-cloud environments
+ isEnabled: ({ auth, isCloud }) =>
+ !!((auth?.role === "owner" || auth?.canAccessToDocker) && !isCloud),
+ },
+ {
+ isSingle: true,
+ title: "Requests",
+ url: "/dashboard/requests",
+ icon: Forward,
+ // Only enabled for admins and users with access to Docker in non-cloud environments
+ isEnabled: ({ auth, isCloud }) =>
+ !!((auth?.role === "owner" || auth?.canAccessToDocker) && !isCloud),
+ },
+
+ // Legacy unused menu, adjusted to the new structure
+ // {
+ // isSingle: true,
+ // title: "Projects",
+ // url: "/dashboard/projects",
+ // icon: Folder,
+ // },
+ // {
+ // isSingle: true,
+ // title: "Monitoring",
+ // icon: BarChartHorizontalBigIcon,
+ // url: "/dashboard/settings/monitoring",
+ // },
+ // {
+ // isSingle: false,
+ // title: "Settings",
+ // icon: Settings2,
+ // items: [
+ // {
+ // title: "Profile",
+ // url: "/dashboard/settings/profile",
+ // },
+ // {
+ // title: "Users",
+ // url: "/dashboard/settings/users",
+ // },
+ // {
+ // title: "SSH Key",
+ // url: "/dashboard/settings/ssh-keys",
+ // },
+ // {
+ // title: "Git",
+ // url: "/dashboard/settings/git-providers",
+ // },
+ // ],
+ // },
+ // {
+ // isSingle: false,
+ // title: "Integrations",
+ // icon: BlocksIcon,
+ // items: [
+ // {
+ // title: "S3 Destinations",
+ // url: "/dashboard/settings/destinations",
+ // },
+ // {
+ // title: "Registry",
+ // url: "/dashboard/settings/registry",
+ // },
+ // {
+ // title: "Notifications",
+ // url: "/dashboard/settings/notifications",
+ // },
+ // ],
+ // },
+ ],
+
+ settings: [
+ {
+ isSingle: true,
+ title: "Web Server",
+ url: "/dashboard/settings/server",
+ icon: Activity,
+ // Only enabled for admins in non-cloud environments
+ isEnabled: ({ auth, isCloud }) => !!(auth?.role === "owner" && !isCloud),
+ },
+ {
+ isSingle: true,
+ title: "Profile",
+ url: "/dashboard/settings/profile",
+ icon: User,
+ },
+ {
+ isSingle: true,
+ title: "Remote Servers",
+ url: "/dashboard/settings/servers",
+ icon: Server,
+ // Only enabled for admins
+ isEnabled: ({ auth }) => !!(auth?.role === "owner"),
+ },
+ {
+ isSingle: true,
+ title: "Users",
+ icon: Users,
+ url: "/dashboard/settings/users",
+ // Only enabled for admins
+ isEnabled: ({ auth }) => !!(auth?.role === "owner"),
+ },
+ {
+ isSingle: true,
+ title: "SSH Keys",
+ icon: KeyRound,
+ url: "/dashboard/settings/ssh-keys",
+ // Only enabled for admins and users with access to SSH keys
+ isEnabled: ({ auth }) =>
+ !!(auth?.role === "owner" || auth?.canAccessToSSHKeys),
+ },
+ {
+ title: "AI",
+ icon: BotIcon,
+ url: "/dashboard/settings/ai",
+ isSingle: true,
+ isEnabled: ({ auth }) => !!(auth?.role === "owner"),
+ },
+ {
+ isSingle: true,
+ title: "Git",
+ url: "/dashboard/settings/git-providers",
+ icon: GitBranch,
+ // Only enabled for admins and users with access to Git providers
+ isEnabled: ({ auth }) =>
+ !!(auth?.role === "owner" || auth?.canAccessToGitProviders),
+ },
+ {
+ isSingle: true,
+ title: "Registry",
+ url: "/dashboard/settings/registry",
+ icon: Package,
+ // Only enabled for admins
+ isEnabled: ({ auth }) => !!(auth?.role === "owner"),
+ },
+ {
+ isSingle: true,
+ title: "S3 Destinations",
+ url: "/dashboard/settings/destinations",
+ icon: Database,
+ // Only enabled for admins
+ isEnabled: ({ auth }) => !!(auth?.role === "owner"),
+ },
+
+ {
+ isSingle: true,
+ title: "Certificates",
+ url: "/dashboard/settings/certificates",
+ icon: ShieldCheck,
+ // Only enabled for admins
+ isEnabled: ({ auth }) => !!(auth?.role === "owner"),
+ },
+ {
+ isSingle: true,
+ title: "Cluster",
+ url: "/dashboard/settings/cluster",
+ icon: Boxes,
+ // Only enabled for admins in non-cloud environments
+ isEnabled: ({ auth, isCloud }) => !!(auth?.role === "owner" && !isCloud),
+ },
+ {
+ isSingle: true,
+ title: "Notifications",
+ url: "/dashboard/settings/notifications",
+ icon: Bell,
+ // Only enabled for admins
+ isEnabled: ({ auth }) => !!(auth?.role === "owner"),
+ },
+ {
+ isSingle: true,
+ title: "Billing",
+ url: "/dashboard/settings/billing",
+ icon: CreditCard,
+ // Only enabled for admins in cloud environments
+ isEnabled: ({ auth, isCloud }) => !!(auth?.role === "owner" && isCloud),
+ },
+ ],
+
+ help: [
+ {
+ name: "Documentation",
+ url: "https://docs.dokploy.com/docs/core",
+ icon: BookIcon,
+ },
+ {
+ name: "Support",
+ url: "https://discord.gg/2tBnJ3jDJc",
+ icon: CircleHelp,
+ },
+ {
+ name: "Sponsor",
+ url: "https://opencollective.com/dokploy",
+ icon: ({ className }) => (
+
+ ),
+ },
+ ],
+} as const;
+
+/**
+ * Creates a menu based on the current user's role and permissions
+ * @returns a menu object with the home, settings, and help items
+ */
+function createMenuForAuthUser(opts: {
+ auth?: AuthQueryOutput;
+ isCloud: boolean;
+}): Menu {
+ return {
+ // Filter the home items based on the user's role and permissions
+ // Calls the `isEnabled` function if it exists to determine if the item should be displayed
+ home: MENU.home.filter((item) =>
+ !item.isEnabled
+ ? true
+ : item.isEnabled({
+ auth: opts.auth,
+ isCloud: opts.isCloud,
+ }),
+ ),
+ // Filter the settings items based on the user's role and permissions
+ // Calls the `isEnabled` function if it exists to determine if the item should be displayed
+ settings: MENU.settings.filter((item) =>
+ !item.isEnabled
+ ? true
+ : item.isEnabled({
+ auth: opts.auth,
+ isCloud: opts.isCloud,
+ }),
+ ),
+ // Filter the help items based on the user's role and permissions
+ // Calls the `isEnabled` function if it exists to determine if the item should be displayed
+ help: MENU.help.filter((item) =>
+ !item.isEnabled
+ ? true
+ : item.isEnabled({
+ auth: opts.auth,
+ isCloud: opts.isCloud,
+ }),
+ ),
+ };
+}
+
+/**
+ * Determines if an item url is active based on the current pathname
+ * @returns true if the item url is active, false otherwise
+ */
+function isActiveRoute(opts: {
+ /** The url of the item. Usually obtained from `item.url` */
+ itemUrl: string;
+ /** The current pathname. Usually obtained from `usePathname()` */
+ pathname: string;
+}): boolean {
+ const normalizedItemUrl = opts.itemUrl?.replace("/projects", "/project");
+ const normalizedPathname = opts.pathname?.replace("/projects", "/project");
+
+ if (!normalizedPathname) return false;
+
+ if (normalizedPathname === normalizedItemUrl) return true;
+
+ if (normalizedPathname.startsWith(normalizedItemUrl)) {
+ const nextChar = normalizedPathname.charAt(normalizedItemUrl.length);
+ return nextChar === "/";
+ }
+
+ return false;
+}
+
+/**
+ * Finds the active nav item based on the current pathname
+ * @returns the active nav item with `SingleNavItem` type or undefined if none is active
+ */
+function findActiveNavItem(
+ navItems: NavItem[],
+ pathname: string,
+): SingleNavItem | undefined {
+ const found = navItems.find((item) =>
+ item.isSingle !== false
+ ? // The current item is single, so check if the item url is active
+ isActiveRoute({ itemUrl: item.url, pathname })
+ : // The current item is not single, so check if any of the sub items are active
+ item.items.some((item) =>
+ isActiveRoute({ itemUrl: item.url, pathname }),
+ ),
+ );
+
+ if (found?.isSingle !== false) {
+ // The found item is single, so return it
+ return found;
+ }
+
+ // The found item is not single, so find the active sub item
+ return found?.items.find((item) =>
+ isActiveRoute({ itemUrl: item.url, pathname }),
+ );
+}
+
+interface Props {
+ children: React.ReactNode;
+}
+
+function LogoWrapper() {
+ return ;
+}
+
+function SidebarLogo() {
+ const { state } = useSidebar();
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const { data: user } = api.user.get.useQuery();
+ const { data: session } = authClient.useSession();
+
+ const {
+ data: organizations,
+ refetch,
+ isLoading,
+ } = api.organization.all.useQuery();
+ const { mutateAsync: deleteOrganization, isLoading: isRemoving } =
+ api.organization.delete.useMutation();
+ const { isMobile } = useSidebar();
+ const { data: activeOrganization } = authClient.useActiveOrganization();
+ const _utils = api.useUtils();
+
+ const { data: invitations, refetch: refetchInvitations } =
+ api.user.getInvitations.useQuery();
+
+ const [_activeTeam, setActiveTeam] = useState<
+ typeof activeOrganization | null
+ >(null);
+
+ useEffect(() => {
+ if (activeOrganization) {
+ setActiveTeam(activeOrganization);
+ }
+ }, [activeOrganization]);
+
+ return (
+ <>
+ {isLoading ? (
+
+
+
+ ) : (
+
+ {/* Organization Logo and Selector */}
+
+
+
+
+
+
+
+
+
+
+ {activeOrganization?.name ?? "Select Organization"}
+
+
+
+
+
+
+
+
+ Organizations
+
+ {organizations?.map((org) => (
+
+
{
+ await authClient.organization.setActive({
+ organizationId: org.id,
+ });
+ window.location.reload();
+ }}
+ className="w-full gap-2 p-2"
+ >
+ {org.name}
+
+
+
+
+ {org.ownerId === session?.user?.id && (
+
+
+
{
+ await deleteOrganization({
+ organizationId: org.id,
+ })
+ .then(() => {
+ refetch();
+ toast.success(
+ "Organization deleted successfully",
+ );
+ })
+ .catch((error) => {
+ toast.error(
+ error?.message ||
+ "Error deleting organization",
+ );
+ });
+ }}
+ >
+
+
+
+
+
+ )}
+
+ ))}
+ {(user?.role === "owner" || isCloud) && (
+ <>
+
+
+ >
+ )}
+
+
+
+
+ {/* Notification Bell */}
+
+
+
+
+
+ {invitations && invitations.length > 0 && (
+
+ {invitations.length}
+
+ )}
+
+
+
+ Pending Invitations
+
+ {invitations && invitations.length > 0 ? (
+ invitations.map((invitation) => (
+
+
e.preventDefault()}
+ >
+
+ {invitation?.organization?.name}
+
+
+ Expires:{" "}
+ {new Date(invitation.expiresAt).toLocaleString()}
+
+
+ Role: {invitation.role}
+
+
+
{
+ const { error } =
+ await authClient.organization.acceptInvitation({
+ invitationId: invitation.id,
+ });
+
+ if (error) {
+ toast.error(
+ error.message || "Error accepting invitation",
+ );
+ } else {
+ toast.success("Invitation accepted successfully");
+ await refetchInvitations();
+ await refetch();
+ }
+ }}
+ >
+
+ Accept Invitation
+
+
+
+ ))
+ ) : (
+
+ No pending invitations
+
+ )}
+
+
+
+
+
+ )}
+ >
+ );
+}
+
+export default function Page({ children }: Props) {
+ const [defaultOpen, setDefaultOpen] = useState(
+ undefined,
+ );
+ const [isLoaded, setIsLoaded] = useState(false);
+
+ useEffect(() => {
+ const cookieValue = document.cookie
+ .split("; ")
+ .find((row) => row.startsWith(`${SIDEBAR_COOKIE_NAME}=`))
+ ?.split("=")[1];
+
+ setDefaultOpen(cookieValue === undefined ? true : cookieValue === "true");
+ setIsLoaded(true);
+ }, []);
+
+ const router = useRouter();
+ const pathname = usePathname();
+ const _currentPath = router.pathname;
+ const { data: auth } = api.user.get.useQuery();
+ const { data: dokployVersion } = api.settings.getDokployVersion.useQuery();
+
+ const includesProjects = pathname?.includes("/dashboard/project");
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+
+ const {
+ home: filteredHome,
+ settings: filteredSettings,
+ help,
+ } = createMenuForAuthUser({ auth, isCloud: !!isCloud });
+
+ const activeItem = findActiveNavItem(
+ [...filteredHome, ...filteredSettings],
+ pathname,
+ );
+
+ if (!isLoaded) {
+ return
; // Placeholder mientras se carga
+ }
+
+ return (
+ {
+ setDefaultOpen(open);
+
+ document.cookie = `${SIDEBAR_COOKIE_NAME}=${open}`;
+ }}
+ style={
+ {
+ "--sidebar-width": "19.5rem",
+ "--sidebar-width-mobile": "19.5rem",
+ } as React.CSSProperties
+ }
+ >
+
+
+ {/* */}
+
+ {/* */}
+
+
+
+ Home
+
+ {filteredHome.map((item) => {
+ const isSingle = item.isSingle !== false;
+ const isActive = isSingle
+ ? isActiveRoute({ itemUrl: item.url, pathname })
+ : item.items.some((item) =>
+ isActiveRoute({ itemUrl: item.url, pathname }),
+ );
+
+ return (
+
+
+ {isSingle ? (
+
+
+ {item.icon && (
+
+ )}
+ {item.title}
+
+
+ ) : (
+ <>
+
+
+ {item.icon && }
+
+ {item.title}
+ {item.items?.length && (
+
+ )}
+
+
+
+
+ {item.items?.map((subItem) => (
+
+
+
+ {subItem.icon && (
+
+
+
+ )}
+ {subItem.title}
+
+
+
+ ))}
+
+
+ >
+ )}
+
+
+ );
+ })}
+
+
+
+ Settings
+
+ {filteredSettings.map((item) => {
+ const isSingle = item.isSingle !== false;
+ const isActive = isSingle
+ ? isActiveRoute({ itemUrl: item.url, pathname })
+ : item.items.some((item) =>
+ isActiveRoute({ itemUrl: item.url, pathname }),
+ );
+
+ return (
+
+
+ {isSingle ? (
+
+
+ {item.icon && (
+
+ )}
+ {item.title}
+
+
+ ) : (
+ <>
+
+
+ {item.icon && }
+
+ {item.title}
+ {item.items?.length && (
+
+ )}
+
+
+
+
+ {item.items?.map((subItem) => (
+
+
+
+ {subItem.icon && (
+
+
+
+ )}
+ {subItem.title}
+
+
+
+ ))}
+
+
+ >
+ )}
+
+
+ );
+ })}
+
+
+
+ Extra
+
+ {help.map((item: ExternalLink) => (
+
+
+
+
+
+
+ {item.name}
+
+
+
+ ))}
+
+
+
+
+
+ {!isCloud && auth?.role === "owner" && (
+
+
+
+ )}
+
+
+
+ {dokployVersion && (
+ <>
+
+ Version {dokployVersion}
+
+
+ {dokployVersion}
+
+ >
+ )}
+
+
+
+
+
+ {!includesProjects && (
+
+ )}
+
+ {children}
+
+
+ );
+}
diff --git a/data/apps/dokploy/components/layouts/update-server.tsx b/data/apps/dokploy/components/layouts/update-server.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..42cac69f456d4edf7200136cb50791c6e43714fd
--- /dev/null
+++ b/data/apps/dokploy/components/layouts/update-server.tsx
@@ -0,0 +1,123 @@
+import { api } from "@/utils/api";
+import type { IUpdateData } from "@dokploy/server/index";
+import { Download } from "lucide-react";
+import { useRouter } from "next/router";
+import { useEffect, useRef, useState } from "react";
+import UpdateServer from "../dashboard/settings/web-server/update-server";
+import { Button } from "../ui/button";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "../ui/tooltip";
+const AUTO_CHECK_UPDATES_INTERVAL_MINUTES = 7;
+
+export const UpdateServerButton = () => {
+ const [updateData, setUpdateData] = useState({
+ latestVersion: null,
+ updateAvailable: false,
+ });
+ const _router = useRouter();
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const { mutateAsync: getUpdateData } =
+ api.settings.getUpdateData.useMutation();
+ const [isOpen, setIsOpen] = useState(false);
+
+ const checkUpdatesIntervalRef = useRef(null);
+
+ if (isCloud) {
+ return null;
+ }
+ useEffect(() => {
+ // Handling of automatic check for server updates
+ if (isCloud) {
+ return;
+ }
+
+ if (!localStorage.getItem("enableAutoCheckUpdates")) {
+ // Enable auto update checking by default if user didn't change it
+ localStorage.setItem("enableAutoCheckUpdates", "true");
+ }
+
+ const clearUpdatesInterval = () => {
+ if (checkUpdatesIntervalRef.current) {
+ clearInterval(checkUpdatesIntervalRef.current);
+ }
+ };
+
+ const checkUpdates = async () => {
+ try {
+ if (localStorage.getItem("enableAutoCheckUpdates") !== "true") {
+ return;
+ }
+
+ const fetchedUpdateData = await getUpdateData();
+
+ if (fetchedUpdateData?.updateAvailable) {
+ // Stop interval when update is available
+ clearUpdatesInterval();
+ setUpdateData(fetchedUpdateData);
+ }
+ } catch (error) {
+ console.error("Error auto-checking for updates:", error);
+ }
+ };
+
+ checkUpdatesIntervalRef.current = setInterval(
+ checkUpdates,
+ AUTO_CHECK_UPDATES_INTERVAL_MINUTES * 60000,
+ );
+
+ // Also check for updates on initial page load
+ checkUpdates();
+
+ return () => {
+ clearUpdatesInterval();
+ };
+ }, []);
+
+ return updateData.updateAvailable ? (
+
+
+
+
+
+ setIsOpen(true)}
+ >
+
+ {updateData ? (
+
+ Update Available
+
+ ) : (
+
+ Check for updates
+
+ )}
+ {updateData && (
+
+
+
+
+ )}
+
+
+ {updateData && (
+
+ Update Available
+
+ )}
+
+
+
+
+ ) : null;
+};
diff --git a/data/apps/dokploy/components/layouts/user-nav.tsx b/data/apps/dokploy/components/layouts/user-nav.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..05c601f6e9dad64a57bae05fa001dc8ecc54ffe4
--- /dev/null
+++ b/data/apps/dokploy/components/layouts/user-nav.tsx
@@ -0,0 +1,186 @@
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { authClient } from "@/lib/auth-client";
+import { Languages } from "@/lib/languages";
+import { api } from "@/utils/api";
+import useLocale from "@/utils/hooks/use-locale";
+import { ChevronsUpDown } from "lucide-react";
+import { useRouter } from "next/router";
+import { ModeToggle } from "../ui/modeToggle";
+import { SidebarMenuButton } from "../ui/sidebar";
+
+const _AUTO_CHECK_UPDATES_INTERVAL_MINUTES = 7;
+
+export const UserNav = () => {
+ const router = useRouter();
+ const { data } = api.user.get.useQuery();
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+
+ const { locale, setLocale } = useLocale();
+ // const { mutateAsync } = api.auth.logout.useMutation();
+
+ return (
+
+
+
+
+
+ CN
+
+
+ Account
+ {data?.user?.email}
+
+
+
+
+
+
+
+ My Account
+
+ {data?.user?.email}
+
+
+
+
+
+
+ {
+ router.push("/dashboard/settings/profile");
+ }}
+ >
+ Profile
+
+ {
+ router.push("/dashboard/projects");
+ }}
+ >
+ Projects
+
+ {!isCloud ? (
+ <>
+ {
+ router.push("/dashboard/monitoring");
+ }}
+ >
+ Monitoring
+
+ {(data?.role === "owner" || data?.canAccessToTraefikFiles) && (
+ {
+ router.push("/dashboard/traefik");
+ }}
+ >
+ Traefik
+
+ )}
+ {(data?.role === "owner" || data?.canAccessToDocker) && (
+ {
+ router.push("/dashboard/docker", undefined, {
+ shallow: true,
+ });
+ }}
+ >
+ Docker
+
+ )}
+ >
+ ) : (
+ <>
+ {data?.role === "owner" && (
+ {
+ router.push("/dashboard/settings/servers");
+ }}
+ >
+ Servers
+
+ )}
+ >
+ )}
+
+ {isCloud && data?.role === "owner" && (
+ {
+ router.push("/dashboard/settings/billing");
+ }}
+ >
+ Billing
+
+ )}
+
+
+
{
+ await authClient.signOut().then(() => {
+ router.push("/");
+ });
+ // await mutateAsync().then(() => {
+ // router.push("/");
+ // });
+ }}
+ >
+ Log out
+
+
+
+
+
+
+
+ {Object.values(Languages).map((language) => (
+
+ {language.name}
+
+ ))}
+
+
+
+
+
+
+ );
+};
diff --git a/data/apps/dokploy/components/shared/ChatwootWidget.tsx b/data/apps/dokploy/components/shared/ChatwootWidget.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..6694b13cc5514db671b11e83ee403876d80ab349
--- /dev/null
+++ b/data/apps/dokploy/components/shared/ChatwootWidget.tsx
@@ -0,0 +1,69 @@
+import Script from "next/script";
+import { useEffect } from "react";
+
+interface ChatwootWidgetProps {
+ websiteToken: string;
+ baseUrl?: string;
+ settings?: {
+ position?: "left" | "right";
+ type?: "standard" | "expanded_bubble";
+ launcherTitle?: string;
+ darkMode?: boolean;
+ hideMessageBubble?: boolean;
+ placement?: "right" | "left";
+ showPopoutButton?: boolean;
+ widgetStyle?: "standard" | "bubble";
+ };
+ user?: {
+ identifier: string;
+ name?: string;
+ email?: string;
+ phoneNumber?: string;
+ avatarUrl?: string;
+ customAttributes?: Record;
+ identifierHash?: string;
+ };
+}
+
+export const ChatwootWidget = ({
+ websiteToken,
+ baseUrl = "https://app.chatwoot.com",
+ settings = {
+ position: "right",
+ type: "standard",
+ launcherTitle: "Chat with us",
+ },
+ user,
+}: ChatwootWidgetProps) => {
+ useEffect(() => {
+ // Configurar los settings de Chatwoot
+ window.chatwootSettings = {
+ position: "right",
+ };
+
+ (window as any).chatwootSDKReady = () => {
+ window.chatwootSDK?.run({ websiteToken, baseUrl });
+
+ const trySetUser = () => {
+ if (window.$chatwoot && user) {
+ window.$chatwoot.setUser(user.identifier, {
+ email: user.email,
+ name: user.name,
+ avatar_url: user.avatarUrl,
+ phone_number: user.phoneNumber,
+ });
+ }
+ };
+
+ trySetUser();
+ };
+ }, [websiteToken, baseUrl, user, settings]);
+
+ return (
+