refactor: migrate endpoints

This commit is contained in:
Mauricio Siu 2025-02-14 02:52:37 -06:00
parent b6c29ccf05
commit 55abac3f2f
19 changed files with 260 additions and 256 deletions

View File

@ -1,7 +1,7 @@
import { buffer } from "node:stream/consumers"; import { buffer } from "node:stream/consumers";
import { db } from "@/server/db"; import { db } from "@/server/db";
import { admins, server } from "@/server/db/schema"; import { admins, server, users_temp } from "@/server/db/schema";
import { findAdminById } from "@dokploy/server"; import { findAdminById, findUserById } from "@dokploy/server";
import { asc, eq } from "drizzle-orm"; import { asc, eq } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import Stripe from "stripe"; import Stripe from "stripe";
@ -18,242 +18,246 @@ export default async function handler(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse, res: NextApiResponse,
) { ) {
// if (!endpointSecret) { if (!endpointSecret) {
// return res.status(400).send("Webhook Error: Missing Stripe Secret Key"); return res.status(400).send("Webhook Error: Missing Stripe Secret Key");
// } }
// const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// apiVersion: "2024-09-30.acacia", apiVersion: "2024-09-30.acacia",
// maxNetworkRetries: 3, maxNetworkRetries: 3,
// }); });
// const buf = await buffer(req); const buf = await buffer(req);
// const sig = req.headers["stripe-signature"] as string; const sig = req.headers["stripe-signature"] as string;
// let event: Stripe.Event; let event: Stripe.Event;
// try { try {
// event = stripe.webhooks.constructEvent(buf, sig, endpointSecret); event = stripe.webhooks.constructEvent(buf, sig, endpointSecret);
// } catch (err) { } catch (err) {
// console.error( console.error(
// "Webhook signature verification failed.", "Webhook signature verification failed.",
// err instanceof Error ? err.message : err, err instanceof Error ? err.message : err,
// ); );
// return res.status(400).send("Webhook Error: "); return res.status(400).send("Webhook Error: ");
// } }
// const webhooksAllowed = [ const webhooksAllowed = [
// "customer.subscription.created", "customer.subscription.created",
// "customer.subscription.deleted", "customer.subscription.deleted",
// "customer.subscription.updated", "customer.subscription.updated",
// "invoice.payment_succeeded", "invoice.payment_succeeded",
// "invoice.payment_failed", "invoice.payment_failed",
// "customer.deleted", "customer.deleted",
// "checkout.session.completed", "checkout.session.completed",
// ]; ];
// if (!webhooksAllowed.includes(event.type)) { if (!webhooksAllowed.includes(event.type)) {
// return res.status(400).send("Webhook Error: Invalid Event Type"); return res.status(400).send("Webhook Error: Invalid Event Type");
// } }
// switch (event.type) { switch (event.type) {
// case "checkout.session.completed": { case "checkout.session.completed": {
// const session = event.data.object as Stripe.Checkout.Session; const session = event.data.object as Stripe.Checkout.Session;
// const adminId = session?.metadata?.adminId as string; const adminId = session?.metadata?.adminId as string;
// const subscription = await stripe.subscriptions.retrieve( const subscription = await stripe.subscriptions.retrieve(
// session.subscription as string, session.subscription as string,
// ); );
// await db await db
// .update(admins) .update(users_temp)
// .set({ .set({
// stripeCustomerId: session.customer as string, stripeCustomerId: session.customer as string,
// stripeSubscriptionId: session.subscription as string, stripeSubscriptionId: session.subscription as string,
// serversQuantity: subscription?.items?.data?.[0]?.quantity ?? 0, serversQuantity: subscription?.items?.data?.[0]?.quantity ?? 0,
// }) })
// .where(eq(admins.adminId, adminId)) .where(eq(users_temp.id, adminId))
// .returning(); .returning();
// const admin = await findAdminById(adminId); const admin = await findUserById(adminId);
// if (!admin) { if (!admin) {
// return res.status(400).send("Webhook Error: Admin not found"); return res.status(400).send("Webhook Error: Admin not found");
// } }
// const newServersQuantity = admin.serversQuantity; const newServersQuantity = admin.serversQuantity;
// await updateServersBasedOnQuantity(admin.adminId, newServersQuantity); await updateServersBasedOnQuantity(admin.id, newServersQuantity);
// break; break;
// } }
// case "customer.subscription.created": { case "customer.subscription.created": {
// const newSubscription = event.data.object as Stripe.Subscription; const newSubscription = event.data.object as Stripe.Subscription;
// await db await db
// .update(admins) .update(users_temp)
// .set({ .set({
// stripeSubscriptionId: newSubscription.id, stripeSubscriptionId: newSubscription.id,
// stripeCustomerId: newSubscription.customer as string, stripeCustomerId: newSubscription.customer as string,
// }) })
// .where(eq(admins.stripeCustomerId, newSubscription.customer as string)) .where(
// .returning(); eq(users_temp.stripeCustomerId, newSubscription.customer as string),
)
.returning();
// break; break;
// } }
// case "customer.subscription.deleted": { case "customer.subscription.deleted": {
// const newSubscription = event.data.object as Stripe.Subscription; const newSubscription = event.data.object as Stripe.Subscription;
// await db await db
// .update(admins) .update(users_temp)
// .set({ .set({
// stripeSubscriptionId: null, stripeSubscriptionId: null,
// serversQuantity: 0, serversQuantity: 0,
// }) })
// .where(eq(admins.stripeCustomerId, newSubscription.customer as string)); .where(
eq(users_temp.stripeCustomerId, newSubscription.customer as string),
);
// const admin = await findAdminByStripeCustomerId( const admin = await findUserByStripeCustomerId(
// newSubscription.customer as string, newSubscription.customer as string,
// ); );
// if (!admin) { if (!admin) {
// return res.status(400).send("Webhook Error: Admin not found"); return res.status(400).send("Webhook Error: Admin not found");
// } }
// await disableServers(admin.adminId); await disableServers(admin.id);
// break; break;
// } }
// case "customer.subscription.updated": { case "customer.subscription.updated": {
// const newSubscription = event.data.object as Stripe.Subscription; const newSubscription = event.data.object as Stripe.Subscription;
// const admin = await findAdminByStripeCustomerId( const admin = await findUserByStripeCustomerId(
// newSubscription.customer as string, newSubscription.customer as string,
// ); );
// if (!admin) { if (!admin) {
// return res.status(400).send("Webhook Error: Admin not found"); return res.status(400).send("Webhook Error: Admin not found");
// } }
// if (newSubscription.status === "active") { if (newSubscription.status === "active") {
// await db await db
// .update(admins) .update(users_temp)
// .set({ .set({
// serversQuantity: newSubscription?.items?.data?.[0]?.quantity ?? 0, serversQuantity: newSubscription?.items?.data?.[0]?.quantity ?? 0,
// }) })
// .where( .where(
// eq(admins.stripeCustomerId, newSubscription.customer as string), eq(users_temp.stripeCustomerId, newSubscription.customer as string),
// ); );
// const newServersQuantity = admin.serversQuantity; const newServersQuantity = admin.serversQuantity;
// await updateServersBasedOnQuantity(admin.adminId, newServersQuantity); await updateServersBasedOnQuantity(admin.id, newServersQuantity);
// } else { } else {
// await disableServers(admin.adminId); await disableServers(admin.id);
// await db await db
// .update(admins) .update(users_temp)
// .set({ serversQuantity: 0 }) .set({ serversQuantity: 0 })
// .where( .where(
// eq(admins.stripeCustomerId, newSubscription.customer as string), eq(users_temp.stripeCustomerId, newSubscription.customer as string),
// ); );
// } }
// break; break;
// } }
// case "invoice.payment_succeeded": { case "invoice.payment_succeeded": {
// const newInvoice = event.data.object as Stripe.Invoice; const newInvoice = event.data.object as Stripe.Invoice;
// const suscription = await stripe.subscriptions.retrieve( const suscription = await stripe.subscriptions.retrieve(
// newInvoice.subscription as string, newInvoice.subscription as string,
// ); );
// if (suscription.status !== "active") { if (suscription.status !== "active") {
// console.log( console.log(
// `Skipping invoice.payment_succeeded for subscription ${suscription.id} with status ${suscription.status}`, `Skipping invoice.payment_succeeded for subscription ${suscription.id} with status ${suscription.status}`,
// ); );
// break; break;
// } }
// await db await db
// .update(admins) .update(admins)
// .set({ .set({
// serversQuantity: suscription?.items?.data?.[0]?.quantity ?? 0, serversQuantity: suscription?.items?.data?.[0]?.quantity ?? 0,
// }) })
// .where(eq(admins.stripeCustomerId, suscription.customer as string)); .where(eq(admins.stripeCustomerId, suscription.customer as string));
// const admin = await findAdminByStripeCustomerId( const admin = await findUserByStripeCustomerId(
// suscription.customer as string, suscription.customer as string,
// ); );
// if (!admin) { if (!admin) {
// return res.status(400).send("Webhook Error: Admin not found"); return res.status(400).send("Webhook Error: Admin not found");
// } }
// const newServersQuantity = admin.serversQuantity; const newServersQuantity = admin.serversQuantity;
// await updateServersBasedOnQuantity(admin.adminId, newServersQuantity); await updateServersBasedOnQuantity(admin.id, newServersQuantity);
// break; break;
// } }
// case "invoice.payment_failed": { case "invoice.payment_failed": {
// const newInvoice = event.data.object as Stripe.Invoice; const newInvoice = event.data.object as Stripe.Invoice;
// const subscription = await stripe.subscriptions.retrieve( const subscription = await stripe.subscriptions.retrieve(
// newInvoice.subscription as string, newInvoice.subscription as string,
// ); );
// if (subscription.status !== "active") { if (subscription.status !== "active") {
// const admin = await findAdminByStripeCustomerId( const admin = await findUserByStripeCustomerId(
// newInvoice.customer as string, newInvoice.customer as string,
// ); );
// if (!admin) { if (!admin) {
// return res.status(400).send("Webhook Error: Admin not found"); return res.status(400).send("Webhook Error: Admin not found");
// } }
// await db await db
// .update(admins) .update(admins)
// .set({ .set({
// serversQuantity: 0, serversQuantity: 0,
// }) })
// .where(eq(admins.stripeCustomerId, newInvoice.customer as string)); .where(eq(admins.stripeCustomerId, newInvoice.customer as string));
// await disableServers(admin.adminId); await disableServers(admin.id);
// } }
// break; break;
// } }
// case "customer.deleted": { case "customer.deleted": {
// const customer = event.data.object as Stripe.Customer; const customer = event.data.object as Stripe.Customer;
// const admin = await findAdminByStripeCustomerId(customer.id); const admin = await findUserByStripeCustomerId(customer.id);
// if (!admin) { if (!admin) {
// return res.status(400).send("Webhook Error: Admin not found"); return res.status(400).send("Webhook Error: Admin not found");
// } }
// await disableServers(admin.adminId); await disableServers(admin.id);
// await db await db
// .update(admins) .update(users_temp)
// .set({ .set({
// stripeCustomerId: null, stripeCustomerId: null,
// stripeSubscriptionId: null, stripeSubscriptionId: null,
// serversQuantity: 0, serversQuantity: 0,
// }) })
// .where(eq(admins.stripeCustomerId, customer.id)); .where(eq(users_temp.stripeCustomerId, customer.id));
// break; break;
// } }
// default: default:
// console.log(`Unhandled event type: ${event.type}`); console.log(`Unhandled event type: ${event.type}`);
// } }
return res.status(200).json({ received: true }); return res.status(200).json({ received: true });
} }
const disableServers = async (adminId: string) => { const disableServers = async (userId: string) => {
await db await db
.update(server) .update(server)
.set({ .set({
serverStatus: "inactive", serverStatus: "inactive",
}) })
.where(eq(server.adminId, adminId)); .where(eq(server.userId, userId));
}; };
const findAdminByStripeCustomerId = async (stripeCustomerId: string) => { const findUserByStripeCustomerId = async (stripeCustomerId: string) => {
const admin = db.query.admins.findFirst({ const user = db.query.users_temp.findFirst({
where: eq(admins.stripeCustomerId, stripeCustomerId), where: eq(users_temp.stripeCustomerId, stripeCustomerId),
}); });
return admin; return user;
}; };
const activateServer = async (serverId: string) => { const activateServer = async (serverId: string) => {
@ -270,19 +274,19 @@ const deactivateServer = async (serverId: string) => {
.where(eq(server.serverId, serverId)); .where(eq(server.serverId, serverId));
}; };
export const findServersByAdminIdSorted = async (adminId: string) => { export const findServersByUserIdSorted = async (userId: string) => {
const servers = await db.query.server.findMany({ const servers = await db.query.server.findMany({
where: eq(server.adminId, adminId), where: eq(server.userId, userId),
orderBy: asc(server.createdAt), orderBy: asc(server.createdAt),
}); });
return servers; return servers;
}; };
export const updateServersBasedOnQuantity = async ( export const updateServersBasedOnQuantity = async (
adminId: string, userId: string,
newServersQuantity: number, newServersQuantity: number,
) => { ) => {
const servers = await findServersByAdminIdSorted(adminId); const servers = await findServersByUserIdSorted(userId);
if (servers.length > newServersQuantity) { if (servers.length > newServersQuantity) {
for (const [index, server] of servers.entries()) { for (const [index, server] of servers.entries()) {

View File

@ -10,10 +10,10 @@ import {
import { createInsertSchema } from "drizzle-zod"; import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { z } from "zod"; import { z } from "zod";
import { account } from "./account";
import { admins } from "./admin"; import { admins } from "./admin";
import { auth } from "./auth"; import { auth } from "./auth";
import { certificateType } from "./shared"; import { certificateType } from "./shared";
import { account } from "./account";
/** /**
* This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same * This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same
* database instance for multiple projects. * database instance for multiple projects.

View File

@ -40,7 +40,7 @@ import { createTraefikConfig } from "@dokploy/server/utils/traefik/application";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { encodeBase64 } from "../utils/docker/utils"; import { encodeBase64 } from "../utils/docker/utils";
import { findAdminById, getDokployUrl } from "./admin"; import { findAdminById, findUserById, getDokployUrl } from "./admin";
import { import {
createDeployment, createDeployment,
createDeploymentPreview, createDeploymentPreview,
@ -185,7 +185,7 @@ export const deployApplication = async ({
}); });
try { try {
const admin = await findAdminById(application.project.adminId); const admin = await findUserById(application.project.userId);
if (admin.cleanupCacheApplications) { if (admin.cleanupCacheApplications) {
await cleanupFullDocker(application?.serverId); await cleanupFullDocker(application?.serverId);
@ -220,7 +220,7 @@ export const deployApplication = async ({
applicationName: application.name, applicationName: application.name,
applicationType: "application", applicationType: "application",
buildLink, buildLink,
adminId: application.project.adminId, userId: application.project.userId,
domains: application.domains, domains: application.domains,
}); });
} catch (error) { } catch (error) {
@ -233,7 +233,7 @@ export const deployApplication = async ({
// @ts-ignore // @ts-ignore
errorMessage: error?.message || "Error building", errorMessage: error?.message || "Error building",
buildLink, buildLink,
adminId: application.project.adminId, userId: application.project.userId,
}); });
throw error; throw error;
@ -260,7 +260,7 @@ export const rebuildApplication = async ({
}); });
try { try {
const admin = await findAdminById(application.project.adminId); const admin = await findUserById(application.project.userId);
if (admin.cleanupCacheApplications) { if (admin.cleanupCacheApplications) {
await cleanupFullDocker(application?.serverId); await cleanupFullDocker(application?.serverId);
@ -309,7 +309,7 @@ export const deployRemoteApplication = async ({
try { try {
if (application.serverId) { if (application.serverId) {
const admin = await findAdminById(application.project.adminId); const admin = await findUserById(application.project.userId);
if (admin.cleanupCacheApplications) { if (admin.cleanupCacheApplications) {
await cleanupFullDocker(application?.serverId); await cleanupFullDocker(application?.serverId);
@ -352,7 +352,7 @@ export const deployRemoteApplication = async ({
applicationName: application.name, applicationName: application.name,
applicationType: "application", applicationType: "application",
buildLink, buildLink,
adminId: application.project.adminId, userId: application.project.userId,
domains: application.domains, domains: application.domains,
}); });
} catch (error) { } catch (error) {
@ -376,7 +376,7 @@ export const deployRemoteApplication = async ({
// @ts-ignore // @ts-ignore
errorMessage: error?.message || "Error building", errorMessage: error?.message || "Error building",
buildLink, buildLink,
adminId: application.project.adminId, userId: application.project.userId,
}); });
throw error; throw error;
@ -454,7 +454,7 @@ export const deployPreviewApplication = async ({
application.env = `${application.previewEnv}\nDOKPLOY_DEPLOY_URL=${previewDeployment?.domain}`; application.env = `${application.previewEnv}\nDOKPLOY_DEPLOY_URL=${previewDeployment?.domain}`;
application.buildArgs = application.previewBuildArgs; application.buildArgs = application.previewBuildArgs;
const admin = await findAdminById(application.project.adminId); const admin = await findUserById(application.project.userId);
if (admin.cleanupCacheOnPreviews) { if (admin.cleanupCacheOnPreviews) {
await cleanupFullDocker(application?.serverId); await cleanupFullDocker(application?.serverId);
@ -568,7 +568,7 @@ export const deployRemotePreviewApplication = async ({
application.buildArgs = application.previewBuildArgs; application.buildArgs = application.previewBuildArgs;
if (application.serverId) { if (application.serverId) {
const admin = await findAdminById(application.project.adminId); const admin = await findUserById(application.project.userId);
if (admin.cleanupCacheOnPreviews) { if (admin.cleanupCacheOnPreviews) {
await cleanupFullDocker(application?.serverId); await cleanupFullDocker(application?.serverId);
@ -637,7 +637,7 @@ export const rebuildRemoteApplication = async ({
try { try {
if (application.serverId) { if (application.serverId) {
const admin = await findAdminById(application.project.adminId); const admin = await findUserById(application.project.userId);
if (admin.cleanupCacheApplications) { if (admin.cleanupCacheApplications) {
await cleanupFullDocker(application?.serverId); await cleanupFullDocker(application?.serverId);

View File

@ -33,13 +33,13 @@ export const findCertificateById = async (certificateId: string) => {
export const createCertificate = async ( export const createCertificate = async (
certificateData: z.infer<typeof apiCreateCertificate>, certificateData: z.infer<typeof apiCreateCertificate>,
adminId: string, userId: string,
) => { ) => {
const certificate = await db const certificate = await db
.insert(certificates) .insert(certificates)
.values({ .values({
...certificateData, ...certificateData,
adminId: adminId, userId: userId,
}) })
.returning(); .returning();

View File

@ -44,7 +44,7 @@ import {
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { encodeBase64 } from "../utils/docker/utils"; import { encodeBase64 } from "../utils/docker/utils";
import { findAdminById, getDokployUrl } from "./admin"; import { findAdminById, findUserById, getDokployUrl } from "./admin";
import { createDeploymentCompose, updateDeploymentStatus } from "./deployment"; import { createDeploymentCompose, updateDeploymentStatus } from "./deployment";
import { validUniqueServerAppName } from "./project"; import { validUniqueServerAppName } from "./project";
import { cleanupFullDocker } from "./settings"; import { cleanupFullDocker } from "./settings";
@ -217,7 +217,7 @@ export const deployCompose = async ({
}); });
try { try {
const admin = await findAdminById(compose.project.adminId); const admin = await findUserById(compose.project.userId);
if (admin.cleanupCacheOnCompose) { if (admin.cleanupCacheOnCompose) {
await cleanupFullDocker(compose?.serverId); await cleanupFullDocker(compose?.serverId);
} }
@ -247,7 +247,7 @@ export const deployCompose = async ({
applicationName: compose.name, applicationName: compose.name,
applicationType: "compose", applicationType: "compose",
buildLink, buildLink,
adminId: compose.project.adminId, userId: compose.project.userId,
domains: compose.domains, domains: compose.domains,
}); });
} catch (error) { } catch (error) {
@ -262,7 +262,7 @@ export const deployCompose = async ({
// @ts-ignore // @ts-ignore
errorMessage: error?.message || "Error building", errorMessage: error?.message || "Error building",
buildLink, buildLink,
adminId: compose.project.adminId, userId: compose.project.userId,
}); });
throw error; throw error;
} }
@ -286,7 +286,7 @@ export const rebuildCompose = async ({
}); });
try { try {
const admin = await findAdminById(compose.project.adminId); const admin = await findUserById(compose.project.userId);
if (admin.cleanupCacheOnCompose) { if (admin.cleanupCacheOnCompose) {
await cleanupFullDocker(compose?.serverId); await cleanupFullDocker(compose?.serverId);
} }
@ -332,7 +332,7 @@ export const deployRemoteCompose = async ({
}); });
try { try {
if (compose.serverId) { if (compose.serverId) {
const admin = await findAdminById(compose.project.adminId); const admin = await findUserById(compose.project.userId);
if (admin.cleanupCacheOnCompose) { if (admin.cleanupCacheOnCompose) {
await cleanupFullDocker(compose?.serverId); await cleanupFullDocker(compose?.serverId);
} }
@ -381,7 +381,7 @@ export const deployRemoteCompose = async ({
applicationName: compose.name, applicationName: compose.name,
applicationType: "compose", applicationType: "compose",
buildLink, buildLink,
adminId: compose.project.adminId, userId: compose.project.userId,
domains: compose.domains, domains: compose.domains,
}); });
} catch (error) { } catch (error) {
@ -406,7 +406,7 @@ export const deployRemoteCompose = async ({
// @ts-ignore // @ts-ignore
errorMessage: error?.message || "Error building", errorMessage: error?.message || "Error building",
buildLink, buildLink,
adminId: compose.project.adminId, userId: compose.project.userId,
}); });
throw error; throw error;
} }
@ -430,7 +430,7 @@ export const rebuildRemoteCompose = async ({
}); });
try { try {
const admin = await findAdminById(compose.project.adminId); const admin = await findUserById(compose.project.userId);
if (admin.cleanupCacheOnCompose) { if (admin.cleanupCacheOnCompose) {
await cleanupFullDocker(compose?.serverId); await cleanupFullDocker(compose?.serverId);
} }

View File

@ -10,13 +10,13 @@ export type Destination = typeof destinations.$inferSelect;
export const createDestintation = async ( export const createDestintation = async (
input: typeof apiCreateDestination._type, input: typeof apiCreateDestination._type,
adminId: string, userId: string,
) => { ) => {
const newDestination = await db const newDestination = await db
.insert(destinations) .insert(destinations)
.values({ .values({
...input, ...input,
adminId: adminId, userId: userId,
}) })
.returning() .returning()
.then((value) => value[0]); .then((value) => value[0]);
@ -46,14 +46,14 @@ export const findDestinationById = async (destinationId: string) => {
export const removeDestinationById = async ( export const removeDestinationById = async (
destinationId: string, destinationId: string,
adminId: string, userId: string,
) => { ) => {
const result = await db const result = await db
.delete(destinations) .delete(destinations)
.where( .where(
and( and(
eq(destinations.destinationId, destinationId), eq(destinations.destinationId, destinationId),
eq(destinations.adminId, adminId), eq(destinations.userId, userId),
), ),
) )
.returning(); .returning();
@ -73,7 +73,7 @@ export const updateDestinationById = async (
.where( .where(
and( and(
eq(destinations.destinationId, destinationId), eq(destinations.destinationId, destinationId),
eq(destinations.adminId, destinationData.adminId || ""), eq(destinations.userId, destinationData.userId || ""),
), ),
) )
.returning(); .returning();

View File

@ -4,7 +4,7 @@ import { manageDomain } from "@dokploy/server/utils/traefik/domain";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { type apiCreateDomain, domains } from "../db/schema"; import { type apiCreateDomain, domains } from "../db/schema";
import { findAdmin, findAdminById } from "./admin"; import { findAdmin, findAdminById, findUserById } from "./admin";
import { findApplicationById } from "./application"; import { findApplicationById } from "./application";
import { findServerById } from "./server"; import { findServerById } from "./server";
@ -40,7 +40,7 @@ export const createDomain = async (input: typeof apiCreateDomain._type) => {
export const generateTraefikMeDomain = async ( export const generateTraefikMeDomain = async (
appName: string, appName: string,
adminId: string, userId: string,
serverId?: string, serverId?: string,
) => { ) => {
if (serverId) { if (serverId) {
@ -57,7 +57,7 @@ export const generateTraefikMeDomain = async (
projectName: appName, projectName: appName,
}); });
} }
const admin = await findAdminById(adminId); const admin = await findUserById(userId);
return generateRandomDomain({ return generateRandomDomain({
serverIp: admin?.serverIp || "", serverIp: admin?.serverIp || "",
projectName: appName, projectName: appName,

View File

@ -13,14 +13,14 @@ export type Gitlab = typeof gitlab.$inferSelect;
export const createGitlab = async ( export const createGitlab = async (
input: typeof apiCreateGitlab._type, input: typeof apiCreateGitlab._type,
adminId: string, userId: string,
) => { ) => {
return await db.transaction(async (tx) => { return await db.transaction(async (tx) => {
const newGitProvider = await tx const newGitProvider = await tx
.insert(gitProvider) .insert(gitProvider)
.values({ .values({
providerType: "gitlab", providerType: "gitlab",
adminId: adminId, userId: userId,
name: input.name, name: input.name,
}) })
.returning() .returning()

View File

@ -13,7 +13,7 @@ import { removeDirectoryCode } from "../utils/filesystem/directory";
import { authGithub } from "../utils/providers/github"; import { authGithub } from "../utils/providers/github";
import { removeTraefikConfig } from "../utils/traefik/application"; import { removeTraefikConfig } from "../utils/traefik/application";
import { manageDomain } from "../utils/traefik/domain"; import { manageDomain } from "../utils/traefik/domain";
import { findAdminById } from "./admin"; import { findAdminById, findUserById } from "./admin";
import { findApplicationById } from "./application"; import { findApplicationById } from "./application";
import { import {
removeDeployments, removeDeployments,
@ -158,7 +158,7 @@ export const createPreviewDeployment = async (
application.previewWildcard || "*.traefik.me", application.previewWildcard || "*.traefik.me",
appName, appName,
application.server?.ipAddress || "", application.server?.ipAddress || "",
application.project.adminId, application.project.userId,
); );
const octokit = authGithub(application?.github as Github); const octokit = authGithub(application?.github as Github);
@ -250,7 +250,7 @@ const generateWildcardDomain = async (
baseDomain: string, baseDomain: string,
appName: string, appName: string,
serverIp: string, serverIp: string,
adminId: string, userId: string,
): Promise<string> => { ): Promise<string> => {
if (!baseDomain.startsWith("*.")) { if (!baseDomain.startsWith("*.")) {
throw new Error('The base domain must start with "*."'); throw new Error('The base domain must start with "*."');
@ -268,7 +268,7 @@ const generateWildcardDomain = async (
} }
if (!ip) { if (!ip) {
const admin = await findAdminById(adminId); const admin = await findUserById(userId);
ip = admin?.serverIp || ""; ip = admin?.serverIp || "";
} }

View File

@ -16,13 +16,13 @@ export type Project = typeof projects.$inferSelect;
export const createProject = async ( export const createProject = async (
input: typeof apiCreateProject._type, input: typeof apiCreateProject._type,
adminId: string, userId: string,
) => { ) => {
const newProject = await db const newProject = await db
.insert(projects) .insert(projects)
.values({ .values({
...input, ...input,
adminId: adminId, userId: userId,
}) })
.returning() .returning()
.then((value) => value[0]); .then((value) => value[0]);

View File

@ -49,7 +49,7 @@ export const runMariadbBackup = async (
projectName: project.name, projectName: project.name,
databaseType: "mariadb", databaseType: "mariadb",
type: "success", type: "success",
adminId: project.adminId, userId: project.userId,
}); });
} catch (error) { } catch (error) {
console.log(error); console.log(error);
@ -60,7 +60,7 @@ export const runMariadbBackup = async (
type: "error", type: "error",
// @ts-ignore // @ts-ignore
errorMessage: error?.message || "Error message not provided", errorMessage: error?.message || "Error message not provided",
adminId: project.adminId, userId: project.userId,
}); });
throw error; throw error;
} }

View File

@ -46,7 +46,7 @@ export const runMongoBackup = async (mongo: Mongo, backup: BackupSchedule) => {
projectName: project.name, projectName: project.name,
databaseType: "mongodb", databaseType: "mongodb",
type: "success", type: "success",
adminId: project.adminId, userId: project.userId,
}); });
} catch (error) { } catch (error) {
console.log(error); console.log(error);
@ -57,7 +57,7 @@ export const runMongoBackup = async (mongo: Mongo, backup: BackupSchedule) => {
type: "error", type: "error",
// @ts-ignore // @ts-ignore
errorMessage: error?.message || "Error message not provided", errorMessage: error?.message || "Error message not provided",
adminId: project.adminId, userId: project.userId,
}); });
throw error; throw error;
} }

View File

@ -46,7 +46,7 @@ export const runMySqlBackup = async (mysql: MySql, backup: BackupSchedule) => {
projectName: project.name, projectName: project.name,
databaseType: "mysql", databaseType: "mysql",
type: "success", type: "success",
adminId: project.adminId, userId: project.userId,
}); });
} catch (error) { } catch (error) {
console.log(error); console.log(error);
@ -57,7 +57,7 @@ export const runMySqlBackup = async (mysql: MySql, backup: BackupSchedule) => {
type: "error", type: "error",
// @ts-ignore // @ts-ignore
errorMessage: error?.message || "Error message not provided", errorMessage: error?.message || "Error message not provided",
adminId: project.adminId, userId: project.userId,
}); });
throw error; throw error;
} }

View File

@ -49,7 +49,7 @@ export const runPostgresBackup = async (
projectName: project.name, projectName: project.name,
databaseType: "postgres", databaseType: "postgres",
type: "success", type: "success",
adminId: project.adminId, userId: project.userId,
}); });
} catch (error) { } catch (error) {
await sendDatabaseBackupNotifications({ await sendDatabaseBackupNotifications({
@ -59,7 +59,7 @@ export const runPostgresBackup = async (
type: "error", type: "error",
// @ts-ignore // @ts-ignore
errorMessage: error?.message || "Error message not provided", errorMessage: error?.message || "Error message not provided",
adminId: project.adminId, userId: project.userId,
}); });
throw error; throw error;

View File

@ -18,7 +18,7 @@ interface Props {
applicationType: string; applicationType: string;
errorMessage: string; errorMessage: string;
buildLink: string; buildLink: string;
adminId: string; userId: string;
} }
export const sendBuildErrorNotifications = async ({ export const sendBuildErrorNotifications = async ({
@ -27,14 +27,14 @@ export const sendBuildErrorNotifications = async ({
applicationType, applicationType,
errorMessage, errorMessage,
buildLink, buildLink,
adminId, userId,
}: Props) => { }: Props) => {
const date = new Date(); const date = new Date();
const unixDate = ~~(Number(date) / 1000); const unixDate = ~~(Number(date) / 1000);
const notificationList = await db.query.notifications.findMany({ const notificationList = await db.query.notifications.findMany({
where: and( where: and(
eq(notifications.appBuildError, true), eq(notifications.appBuildError, true),
eq(notifications.adminId, adminId), eq(notifications.userId, userId),
), ),
with: { with: {
email: true, email: true,

View File

@ -18,7 +18,7 @@ interface Props {
applicationName: string; applicationName: string;
applicationType: string; applicationType: string;
buildLink: string; buildLink: string;
adminId: string; userId: string;
domains: Domain[]; domains: Domain[];
} }
@ -27,7 +27,7 @@ export const sendBuildSuccessNotifications = async ({
applicationName, applicationName,
applicationType, applicationType,
buildLink, buildLink,
adminId, userId,
domains, domains,
}: Props) => { }: Props) => {
const date = new Date(); const date = new Date();
@ -35,7 +35,7 @@ export const sendBuildSuccessNotifications = async ({
const notificationList = await db.query.notifications.findMany({ const notificationList = await db.query.notifications.findMany({
where: and( where: and(
eq(notifications.appDeploy, true), eq(notifications.appDeploy, true),
eq(notifications.adminId, adminId), eq(notifications.userId, userId),
), ),
with: { with: {
email: true, email: true,

View File

@ -19,13 +19,13 @@ export const sendDatabaseBackupNotifications = async ({
databaseType, databaseType,
type, type,
errorMessage, errorMessage,
adminId, userId,
}: { }: {
projectName: string; projectName: string;
applicationName: string; applicationName: string;
databaseType: "postgres" | "mysql" | "mongodb" | "mariadb"; databaseType: "postgres" | "mysql" | "mongodb" | "mariadb";
type: "error" | "success"; type: "error" | "success";
adminId: string; userId: string;
errorMessage?: string; errorMessage?: string;
}) => { }) => {
const date = new Date(); const date = new Date();
@ -33,7 +33,7 @@ export const sendDatabaseBackupNotifications = async ({
const notificationList = await db.query.notifications.findMany({ const notificationList = await db.query.notifications.findMany({
where: and( where: and(
eq(notifications.databaseBackup, true), eq(notifications.databaseBackup, true),
eq(notifications.adminId, adminId), eq(notifications.userId, userId),
), ),
with: { with: {
email: true, email: true,

View File

@ -13,7 +13,7 @@ import {
} from "./utils"; } from "./utils";
export const sendDockerCleanupNotifications = async ( export const sendDockerCleanupNotifications = async (
adminId: string, userId: string,
message = "Docker cleanup for dokploy", message = "Docker cleanup for dokploy",
) => { ) => {
const date = new Date(); const date = new Date();
@ -21,7 +21,7 @@ export const sendDockerCleanupNotifications = async (
const notificationList = await db.query.notifications.findMany({ const notificationList = await db.query.notifications.findMany({
where: and( where: and(
eq(notifications.dockerCleanup, true), eq(notifications.dockerCleanup, true),
eq(notifications.adminId, adminId), eq(notifications.userId, userId),
), ),
with: { with: {
email: true, email: true,

View File

@ -18,7 +18,7 @@ interface ServerThresholdPayload {
} }
export const sendServerThresholdNotifications = async ( export const sendServerThresholdNotifications = async (
adminId: string, userId: string,
payload: ServerThresholdPayload, payload: ServerThresholdPayload,
) => { ) => {
const date = new Date(payload.Timestamp); const date = new Date(payload.Timestamp);
@ -27,7 +27,7 @@ export const sendServerThresholdNotifications = async (
const notificationList = await db.query.notifications.findMany({ const notificationList = await db.query.notifications.findMany({
where: and( where: and(
eq(notifications.serverThreshold, true), eq(notifications.serverThreshold, true),
eq(notifications.adminId, adminId), eq(notifications.userId, userId),
), ),
with: { with: {
email: true, email: true,