This commit is contained in:
Owen
2025-10-04 18:36:44 -07:00
parent 3123f858bb
commit c2c907852d
320 changed files with 35785 additions and 2984 deletions

View File

@@ -24,6 +24,10 @@ import { fromError } from "zod-validation-error";
import { defaultRoleAllowedActions } from "../role";
import { OpenAPITags, registry } from "@server/openApi";
import { isValidCIDR } from "@server/lib/validators";
import { createCustomer } from "@server/routers/private/billing/createCustomer";
import { usageService } from "@server/lib/private/billing/usageService";
import { FeatureId } from "@server/lib/private/billing";
import { build } from "@server/build";
const createOrgSchema = z
.object({
@@ -249,6 +253,19 @@ export async function createOrg(
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, error));
}
if (build == "saas") {
// make sure we have the stripe customer
const customerId = await createCustomer(orgId, req.user?.email);
if (customerId) {
await usageService.updateDaily(
orgId,
FeatureId.USERS,
1,
customerId
); // Only 1 because we are creating the org
}
}
return response(res, {
data: org,
success: true,

View File

@@ -17,7 +17,7 @@ const getOrgSchema = z
.strict();
export type GetOrgResponse = {
org: Org;
org: Org & { settings: { } | null };
};
registry.registerPath({
@@ -64,9 +64,27 @@ export async function getOrg(
);
}
// Parse settings from JSON string back to object
let parsedSettings = null;
if (org[0].settings) {
try {
parsedSettings = JSON.parse(org[0].settings);
} catch (error) {
// If parsing fails, keep as string for backward compatibility
parsedSettings = org[0].settings;
}
}
logger.info(
`returning data: ${JSON.stringify({ ...org[0], settings: parsedSettings })}`
);
return response<GetOrgResponse>(res, {
data: {
org: org[0]
org: {
...org[0],
settings: parsedSettings
}
},
success: true,
error: false,

View File

@@ -7,4 +7,5 @@ export * from "./checkId";
export * from "./getOrgOverview";
export * from "./listOrgs";
export * from "./pickOrgDefaults";
export * from "./applyBlueprint";
export * from "./privateSendUsageNotifications";
export * from "./applyBlueprint";

View File

@@ -0,0 +1,249 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { userOrgs, users, roles, orgs } from "@server/db";
import { eq, and, or } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { sendEmail } from "@server/emails";
import NotifyUsageLimitApproaching from "@server/emails/templates/PrivateNotifyUsageLimitApproaching";
import NotifyUsageLimitReached from "@server/emails/templates/PrivateNotifyUsageLimitReached";
import config from "@server/lib/config";
import { OpenAPITags, registry } from "@server/openApi";
const sendUsageNotificationParamsSchema = z.object({
orgId: z.string()
});
const sendUsageNotificationBodySchema = z.object({
notificationType: z.enum(["approaching_70", "approaching_90", "reached"]),
limitName: z.string(),
currentUsage: z.number(),
usageLimit: z.number(),
});
type SendUsageNotificationRequest = z.infer<typeof sendUsageNotificationBodySchema>;
export type SendUsageNotificationResponse = {
success: boolean;
emailsSent: number;
adminEmails: string[];
};
// WE SHOULD NOT REGISTER THE PATH IN SAAS
// registry.registerPath({
// method: "post",
// path: "/org/{orgId}/send-usage-notification",
// description: "Send usage limit notification emails to all organization admins.",
// tags: [OpenAPITags.Org],
// request: {
// params: sendUsageNotificationParamsSchema,
// body: {
// content: {
// "application/json": {
// schema: sendUsageNotificationBodySchema
// }
// }
// }
// },
// responses: {
// 200: {
// description: "Usage notifications sent successfully",
// content: {
// "application/json": {
// schema: z.object({
// success: z.boolean(),
// emailsSent: z.number(),
// adminEmails: z.array(z.string())
// })
// }
// }
// }
// }
// });
async function getOrgAdmins(orgId: string) {
// Get all users in the organization who are either:
// 1. Organization owners (isOwner = true)
// 2. Have admin roles (role.isAdmin = true)
const admins = await db
.select({
userId: users.userId,
email: users.email,
name: users.name,
isOwner: userOrgs.isOwner,
roleName: roles.name,
isAdminRole: roles.isAdmin
})
.from(userOrgs)
.innerJoin(users, eq(userOrgs.userId, users.userId))
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
.where(
and(
eq(userOrgs.orgId, orgId),
or(
eq(userOrgs.isOwner, true),
eq(roles.isAdmin, true)
)
)
);
// Filter to only include users with verified emails
const orgAdmins = admins.filter(admin =>
admin.email &&
admin.email.length > 0
);
return orgAdmins;
}
export async function sendUsageNotification(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = sendUsageNotificationParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = sendUsageNotificationBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { orgId } = parsedParams.data;
const {
notificationType,
limitName,
currentUsage,
usageLimit,
} = parsedBody.data;
// Verify organization exists
const org = await db
.select()
.from(orgs)
.where(eq(orgs.orgId, orgId))
.limit(1);
if (org.length === 0) {
return next(
createHttpError(HttpCode.NOT_FOUND, "Organization not found")
);
}
// Get all admin users for this organization
const orgAdmins = await getOrgAdmins(orgId);
if (orgAdmins.length === 0) {
logger.warn(`No admin users found for organization ${orgId}`);
return response<SendUsageNotificationResponse>(res, {
data: {
success: true,
emailsSent: 0,
adminEmails: []
},
success: true,
error: false,
message: "No admin users found to notify",
status: HttpCode.OK
});
}
// Default billing link if not provided
const defaultBillingLink = `${config.getRawConfig().app.dashboard_url}/${orgId}/settings/billing`;
let emailsSent = 0;
const adminEmails: string[] = [];
// Send emails to all admin users
for (const admin of orgAdmins) {
if (!admin.email) continue;
try {
let template;
let subject;
if (notificationType === "approaching_70" || notificationType === "approaching_90") {
template = NotifyUsageLimitApproaching({
email: admin.email,
limitName,
currentUsage,
usageLimit,
billingLink: defaultBillingLink
});
subject = `Usage limit warning for ${limitName}`;
} else {
template = NotifyUsageLimitReached({
email: admin.email,
limitName,
currentUsage,
usageLimit,
billingLink: defaultBillingLink
});
subject = `URGENT: Usage limit reached for ${limitName}`;
}
await sendEmail(template, {
to: admin.email,
from: config.getNoReplyEmail(),
subject
});
emailsSent++;
adminEmails.push(admin.email);
logger.info(`Usage notification sent to admin ${admin.email} for org ${orgId}`);
} catch (emailError) {
logger.error(`Failed to send usage notification to ${admin.email}:`, emailError);
// Continue with other admins even if one fails
}
}
return response<SendUsageNotificationResponse>(res, {
data: {
success: true,
emailsSent,
adminEmails
},
success: true,
error: false,
message: `Usage notifications sent to ${emailsSent} administrators`,
status: HttpCode.OK
});
} catch (error) {
logger.error("Error sending usage notifications:", error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "Failed to send usage notifications")
);
}
}

View File

@@ -12,13 +12,15 @@ import { OpenAPITags, registry } from "@server/openApi";
const updateOrgParamsSchema = z
.object({
orgId: z.string()
orgId: z.string(),
})
.strict();
const updateOrgBodySchema = z
.object({
name: z.string().min(1).max(255).optional()
name: z.string().min(1).max(255).optional(),
settings: z.object({
}).optional(),
})
.strict()
.refine((data) => Object.keys(data).length > 0, {
@@ -70,11 +72,15 @@ export async function updateOrg(
}
const { orgId } = parsedParams.data;
const updateData = parsedBody.data;
const settings = parsedBody.data.settings ? JSON.stringify(parsedBody.data.settings) : undefined;
const updatedOrg = await db
.update(orgs)
.set(updateData)
.set({
name: parsedBody.data.name,
settings: settings
})
.where(eq(orgs.orgId, orgId))
.returning();