feat: make billing better (#203)

This commit is contained in:
KM Koushik
2025-08-25 22:35:21 +10:00
committed by GitHub
parent 8ce5e4b2dd
commit 3f9094e95d
25 changed files with 956 additions and 360 deletions

View File

@@ -11,6 +11,7 @@ import { billingRouter } from "./routers/billing";
import { invitationRouter } from "./routers/invitiation";
import { dashboardRouter } from "./routers/dashboard";
import { suppressionRouter } from "./routers/suppression";
import { limitsRouter } from "./routers/limits";
/**
* This is the primary router for your server.
@@ -30,6 +31,7 @@ export const appRouter = createTRPCRouter({
invitation: invitationRouter,
dashboard: dashboardRouter,
suppression: suppressionRouter,
limits: limitsRouter,
});
// export type definition of API

View File

@@ -2,6 +2,7 @@ import { DailyEmailUsage, EmailUsageType, Subscription } from "@prisma/client";
import { TRPCError } from "@trpc/server";
import { format, sub } from "date-fns";
import { z } from "zod";
import { getThisMonthUsage } from "~/server/service/usage-service";
import {
apiKeyProcedure,
@@ -25,48 +26,7 @@ export const billingRouter = createTRPCRouter({
}),
getThisMonthUsage: teamProcedure.query(async ({ ctx }) => {
const isPaidPlan = ctx.team.plan !== "FREE";
let subscription: Subscription | null = null;
if (isPaidPlan) {
subscription = await db.subscription.findFirst({
where: { teamId: ctx.team.id },
orderBy: { status: "asc" },
});
}
const isoStartDate = subscription?.currentPeriodStart
? format(subscription.currentPeriodStart, "yyyy-MM-dd")
: format(new Date(), "yyyy-MM-01"); // First day of current month
const today = format(new Date(), "yyyy-MM-dd");
const [monthUsage, dayUsage] = await Promise.all([
// Get month usage
db.$queryRaw<Array<{ type: EmailUsageType; sent: number }>>`
SELECT
type,
SUM(sent)::integer AS sent
FROM "DailyEmailUsage"
WHERE "teamId" = ${ctx.team.id}
AND "date" >= ${isoStartDate}
GROUP BY "type"
`,
// Get today's usage
db.$queryRaw<Array<{ type: EmailUsageType; sent: number }>>`
SELECT
type,
SUM(sent)::integer AS sent
FROM "DailyEmailUsage"
WHERE "teamId" = ${ctx.team.id}
AND "date" = ${today}
GROUP BY "type"
`,
]);
return {
month: monthUsage,
day: dayUsage,
};
return await getThisMonthUsage(ctx.team.id);
}),
getSubscriptionDetails: teamProcedure.query(async ({ ctx }) => {

View File

@@ -7,24 +7,13 @@ import {
teamProcedure,
} from "~/server/api/trpc";
import * as contactService from "~/server/service/contact-service";
import * as contactBookService from "~/server/service/contact-book-service";
export const contactsRouter = createTRPCRouter({
getContactBooks: teamProcedure
.input(z.object({ search: z.string().optional() }))
.query(async ({ ctx: { db, team }, input }) => {
return db.contactBook.findMany({
where: {
teamId: team.id,
...(input.search
? { name: { contains: input.search, mode: "insensitive" } }
: {}),
},
include: {
_count: {
select: { contacts: true },
},
},
});
.query(async ({ ctx: { team }, input }) => {
return contactBookService.getContactBooks(team.id, input.search);
}),
createContactBook: teamProcedure
@@ -33,40 +22,15 @@ export const contactsRouter = createTRPCRouter({
name: z.string(),
})
)
.mutation(async ({ ctx: { db, team }, input }) => {
.mutation(async ({ ctx: { team }, input }) => {
const { name } = input;
const contactBook = await db.contactBook.create({
data: {
name,
teamId: team.id,
properties: {},
},
});
return contactBook;
return contactBookService.createContactBook(team.id, name);
}),
getContactBookDetails: contactBookProcedure.query(
async ({ ctx: { contactBook, db } }) => {
const [totalContacts, unsubscribedContacts, campaigns] =
await Promise.all([
db.contact.count({
where: { contactBookId: contactBook.id },
}),
db.contact.count({
where: { contactBookId: contactBook.id, subscribed: false },
}),
db.campaign.findMany({
where: {
contactBookId: contactBook.id,
status: CampaignStatus.SENT,
},
orderBy: {
createdAt: "desc",
},
take: 2,
}),
]);
async ({ ctx: { contactBook } }) => {
const { totalContacts, unsubscribedContacts, campaigns } =
await contactBookService.getContactBookDetails(contactBook.id);
return {
...contactBook,
@@ -86,18 +50,14 @@ export const contactsRouter = createTRPCRouter({
emoji: z.string().optional(),
})
)
.mutation(async ({ ctx: { db }, input }) => {
const { contactBookId, ...data } = input;
return db.contactBook.update({
where: { id: contactBookId },
data,
});
.mutation(async ({ ctx: { contactBook }, input }) => {
return contactBookService.updateContactBook(contactBook.id, input);
}),
deleteContactBook: contactBookProcedure
.input(z.object({ contactBookId: z.string() }))
.mutation(async ({ ctx: { db }, input }) => {
return db.contactBook.delete({ where: { id: input.contactBookId } });
.mutation(async ({ ctx: { contactBook }, input }) => {
return contactBookService.deleteContactBook(contactBook.id);
}),
contacts: contactBookProcedure

View File

@@ -0,0 +1,28 @@
import { z } from "zod";
import { createTRPCRouter, teamProcedure } from "~/server/api/trpc";
import { LimitService } from "~/server/service/limit-service";
import { LimitReason } from "~/lib/constants/plans";
export const limitsRouter = createTRPCRouter({
get: teamProcedure
.input(
z.object({
type: z.nativeEnum(LimitReason),
}),
)
.query(async ({ ctx, input }) => {
switch (input.type) {
case LimitReason.CONTACT_BOOK:
return LimitService.checkContactBookLimit(ctx.team.id);
case LimitReason.DOMAIN:
return LimitService.checkDomainLimit(ctx.team.id);
case LimitReason.TEAM_MEMBER:
return LimitService.checkTeamMemberLimit(ctx.team.id);
case LimitReason.EMAIL:
return LimitService.checkEmailLimit(ctx.team.id);
default:
// exhaustive guard
throw new Error("Unsupported limit type");
}
}),
});

View File

@@ -1,6 +1,4 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { env } from "~/env";
import {
createTRPCRouter,
@@ -8,94 +6,25 @@ import {
teamProcedure,
teamAdminProcedure,
} from "~/server/api/trpc";
import { sendTeamInviteEmail } from "~/server/mailer";
import send from "~/server/public-api/api/emails/send-email";
import { logger } from "~/server/logger/log";
import { TeamService } from "~/server/service/team-service";
export const teamRouter = createTRPCRouter({
createTeam: protectedProcedure
.input(z.object({ name: z.string() }))
.mutation(async ({ ctx, input }) => {
const teams = await ctx.db.team.findMany({
where: {
teamUsers: {
some: {
userId: ctx.session.user.id,
},
},
},
});
if (teams.length > 0) {
logger.info({ userId: ctx.session.user.id }, "User already has a team");
return;
}
if (!env.NEXT_PUBLIC_IS_CLOUD) {
const _team = await ctx.db.team.findFirst();
if (_team) {
throw new TRPCError({
message: "Can't have multiple teams in self hosted version",
code: "UNAUTHORIZED",
});
}
}
return ctx.db.team.create({
data: {
name: input.name,
teamUsers: {
create: {
userId: ctx.session.user.id,
role: "ADMIN",
},
},
},
});
return TeamService.createTeam(ctx.session.user.id, input.name);
}),
getTeams: protectedProcedure.query(async ({ ctx }) => {
const teams = await ctx.db.team.findMany({
where: {
teamUsers: {
some: {
userId: ctx.session.user.id,
},
},
},
include: {
teamUsers: {
where: {
userId: ctx.session.user.id,
},
},
},
});
return teams;
return TeamService.getUserTeams(ctx.session.user.id);
}),
getTeamUsers: teamProcedure.query(async ({ ctx }) => {
const teamUsers = await ctx.db.teamUser.findMany({
where: {
teamId: ctx.team.id,
},
include: {
user: true,
},
});
return teamUsers;
return TeamService.getTeamUsers(ctx.team.id);
}),
getTeamInvites: teamProcedure.query(async ({ ctx }) => {
const teamInvites = await ctx.db.teamInvite.findMany({
where: {
teamId: ctx.team.id,
},
});
return teamInvites;
return TeamService.getTeamInvites(ctx.team.id);
}),
createTeamInvite: teamAdminProcedure
@@ -107,44 +36,13 @@ export const teamRouter = createTRPCRouter({
})
)
.mutation(async ({ ctx, input }) => {
if (!input.email) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Email is required",
});
}
const user = await ctx.db.user.findUnique({
where: {
email: input.email,
},
include: {
teamUsers: true,
},
});
if (user && user.teamUsers.length > 0) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "User already part of a team",
});
}
const teamInvite = await ctx.db.teamInvite.create({
data: {
teamId: ctx.team.id,
email: input.email,
role: input.role,
},
});
const teamUrl = `${env.NEXTAUTH_URL}/join-team?inviteId=${teamInvite.id}`;
if (input.sendEmail) {
await sendTeamInviteEmail(input.email, teamUrl, ctx.team.name);
}
return teamInvite;
return TeamService.createTeamInvite(
ctx.team.id,
input.email,
input.role,
ctx.team.name,
input.sendEmail
);
}),
updateTeamUserRole: teamAdminProcedure
@@ -155,150 +53,33 @@ export const teamRouter = createTRPCRouter({
})
)
.mutation(async ({ ctx, input }) => {
const teamUser = await ctx.db.teamUser.findFirst({
where: {
teamId: ctx.team.id,
userId: Number(input.userId),
},
});
if (!teamUser) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Team member not found",
});
}
// Check if this is the last admin
const adminCount = await ctx.db.teamUser.count({
where: {
teamId: ctx.team.id,
role: "ADMIN",
},
});
if (adminCount === 1 && teamUser.role === "ADMIN") {
throw new TRPCError({
code: "FORBIDDEN",
message: "Need at least one admin",
});
}
return ctx.db.teamUser.update({
where: {
teamId_userId: {
teamId: ctx.team.id,
userId: Number(input.userId),
},
},
data: {
role: input.role,
},
});
return TeamService.updateTeamUserRole(
ctx.team.id,
input.userId,
input.role
);
}),
deleteTeamUser: teamProcedure
.input(z.object({ userId: z.string() }))
.mutation(async ({ ctx, input }) => {
const teamUser = await ctx.db.teamUser.findFirst({
where: {
teamId: ctx.team.id,
userId: Number(input.userId),
},
});
if (!teamUser) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Team member not found",
});
}
if (
ctx.teamUser.role !== "ADMIN" &&
ctx.session.user.id !== Number(input.userId)
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to delete this team member",
});
}
// Check if this is the last admin
const adminCount = await ctx.db.teamUser.count({
where: {
teamId: ctx.team.id,
role: "ADMIN",
},
});
if (adminCount === 1 && teamUser.role === "ADMIN") {
throw new TRPCError({
code: "FORBIDDEN",
message: "Need at least one admin",
});
}
return ctx.db.teamUser.delete({
where: {
teamId_userId: {
teamId: ctx.team.id,
userId: Number(input.userId),
},
},
});
return TeamService.deleteTeamUser(
ctx.team.id,
input.userId,
ctx.teamUser.role,
ctx.session.user.id
);
}),
resendTeamInvite: teamAdminProcedure
.input(z.object({ inviteId: z.string() }))
.mutation(async ({ ctx, input }) => {
const invite = await ctx.db.teamInvite.findUnique({
where: {
id: input.inviteId,
},
});
if (!invite) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Invite not found",
});
}
const teamUrl = `${env.NEXTAUTH_URL}/join-team?inviteId=${invite.id}`;
// TODO: Implement email sending logic
await sendTeamInviteEmail(invite.email, teamUrl, ctx.team.name);
return { success: true };
return TeamService.resendTeamInvite(input.inviteId, ctx.team.name);
}),
deleteTeamInvite: teamAdminProcedure
.input(z.object({ inviteId: z.string() }))
.mutation(async ({ ctx, input }) => {
const invite = await ctx.db.teamInvite.findFirst({
where: {
teamId: ctx.team.id,
id: {
equals: input.inviteId,
},
},
});
if (!invite) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Invite not found",
});
}
return ctx.db.teamInvite.delete({
where: {
teamId_email: {
teamId: ctx.team.id,
email: invite.email,
},
},
});
return TeamService.deleteTeamInvite(ctx.team.id, input.inviteId);
}),
});

View File

@@ -47,7 +47,11 @@ export async function createCheckoutSessionForTeam(teamId: number) {
customerId = customer.id;
}
if (!env.STRIPE_BASIC_PRICE_ID || !customerId) {
if (
!env.STRIPE_BASIC_PRICE_ID ||
!env.STRIPE_BASIC_USAGE_PRICE_ID ||
!customerId
) {
throw new Error("Stripe prices are not set");
}
@@ -57,6 +61,10 @@ export async function createCheckoutSessionForTeam(teamId: number) {
line_items: [
{
price: env.STRIPE_BASIC_PRICE_ID,
quantity: 1,
},
{
price: env.STRIPE_BASIC_USAGE_PRICE_ID,
},
],
success_url: `${env.NEXTAUTH_URL}/payments?success=true&session_id={CHECKOUT_SESSION_ID}`,
@@ -70,8 +78,13 @@ export async function createCheckoutSessionForTeam(teamId: number) {
return session;
}
function getPlanFromPriceId(priceId: string) {
if (priceId === env.STRIPE_BASIC_PRICE_ID) {
function getPlanFromPriceIds(priceIds: string[]) {
if (
(env.STRIPE_BASIC_PRICE_ID &&
priceIds.includes(env.STRIPE_BASIC_PRICE_ID)) ||
(env.STRIPE_LEGACY_BASIC_PRICE_ID &&
priceIds.includes(env.STRIPE_LEGACY_BASIC_PRICE_ID))
) {
return "BASIC";
}
@@ -129,11 +142,16 @@ export async function syncStripeData(customerId: string) {
return;
}
const priceIds = subscription.items.data
.map((item) => item.price?.id)
.filter((id): id is string => Boolean(id));
await db.subscription.upsert({
where: { id: subscription.id },
update: {
status: subscription.status,
priceId: subscription.items.data[0]?.price?.id || "",
priceIds: priceIds,
currentPeriodEnd: new Date(
subscription.items.data[0]?.current_period_end * 1000
),
@@ -150,6 +168,7 @@ export async function syncStripeData(customerId: string) {
id: subscription.id,
status: subscription.status,
priceId: subscription.items.data[0]?.price?.id || "",
priceIds: priceIds,
currentPeriodEnd: new Date(
subscription.items.data[0]?.current_period_end * 1000
),
@@ -167,7 +186,7 @@ export async function syncStripeData(customerId: string) {
await db.team.update({
where: { id: team.id },
data: {
plan: getPlanFromPriceId(subscription.items.data[0]?.price?.id || ""),
plan: getPlanFromPriceIds(priceIds),
isActive: subscription.status === "active",
},
});

View File

@@ -0,0 +1,83 @@
import { CampaignStatus, type ContactBook } from "@prisma/client";
import { db } from "../db";
import { LimitService } from "./limit-service";
import { UnsendApiError } from "../public-api/api-error";
export async function getContactBooks(teamId: number, search?: string) {
return db.contactBook.findMany({
where: {
teamId,
...(search ? { name: { contains: search, mode: "insensitive" } } : {}),
},
include: {
_count: {
select: { contacts: true },
},
},
});
}
export async function createContactBook(teamId: number, name: string) {
const { isLimitReached, reason } =
await LimitService.checkContactBookLimit(teamId);
if (isLimitReached) {
throw new UnsendApiError({
code: "FORBIDDEN",
message: reason ?? "Contact book limit reached",
});
}
return db.contactBook.create({
data: {
name,
teamId,
properties: {},
},
});
}
export async function getContactBookDetails(contactBookId: string) {
const [totalContacts, unsubscribedContacts, campaigns] = await Promise.all([
db.contact.count({
where: { contactBookId },
}),
db.contact.count({
where: { contactBookId, subscribed: false },
}),
db.campaign.findMany({
where: {
contactBookId,
status: CampaignStatus.SENT,
},
orderBy: {
createdAt: "desc",
},
take: 2,
}),
]);
return {
totalContacts,
unsubscribedContacts,
campaigns,
};
}
export async function updateContactBook(
contactBookId: string,
data: {
name?: string;
properties?: Record<string, string>;
emoji?: string;
}
) {
return db.contactBook.update({
where: { id: contactBookId },
data,
});
}
export async function deleteContactBook(contactBookId: string) {
return db.contactBook.delete({ where: { id: contactBookId } });
}

View File

@@ -6,6 +6,7 @@ import { db } from "~/server/db";
import { SesSettingsService } from "./ses-settings-service";
import { UnsendApiError } from "../public-api/api-error";
import { logger } from "../logger/log";
import { LimitService } from "./limit-service";
const dnsResolveTxt = util.promisify(dns.resolveTxt);
@@ -58,7 +59,7 @@ export async function createDomain(
teamId: number,
name: string,
region: string,
sesTenantId?: string,
sesTenantId?: string
) {
const domainStr = tldts.getDomain(name);
@@ -74,6 +75,16 @@ export async function createDomain(
throw new Error("Ses setting not found");
}
const { isLimitReached, reason } =
await LimitService.checkDomainLimit(teamId);
if (isLimitReached) {
throw new UnsendApiError({
code: "FORBIDDEN",
message: reason ?? "Domain limit reached",
});
}
const subdomain = tldts.getSubdomain(name);
const publicKey = await ses.addDomain(name, region, sesTenantId);
@@ -105,7 +116,7 @@ export async function getDomain(id: number) {
if (domain.isVerifying) {
const domainIdentity = await ses.getDomainIdentity(
domain.name,
domain.region,
domain.region
);
const dkimStatus = domainIdentity.DkimAttributes?.Status;
@@ -150,7 +161,7 @@ export async function getDomain(id: number) {
export async function updateDomain(
id: number,
data: { clickTracking?: boolean; openTracking?: boolean },
data: { clickTracking?: boolean; openTracking?: boolean }
) {
return db.domain.update({
where: { id },
@@ -170,7 +181,7 @@ export async function deleteDomain(id: number) {
const deleted = await ses.deleteDomain(
domain.name,
domain.region,
domain.sesTenantId ?? undefined,
domain.sesTenantId ?? undefined
);
if (!deleted) {

View File

@@ -0,0 +1,160 @@
import { PLAN_LIMITS, LimitReason } from "~/lib/constants/plans";
import { db } from "../db";
import { getThisMonthUsage } from "./usage-service";
function isLimitExceeded(current: number, limit: number): boolean {
if (limit === -1) return false; // unlimited
return current >= limit;
}
export class LimitService {
static async checkDomainLimit(teamId: number): Promise<{
isLimitReached: boolean;
limit: number;
reason?: LimitReason;
}> {
const team = await db.team.findUnique({
where: { id: teamId },
include: {
_count: {
select: {
domains: true,
},
},
},
});
if (!team) {
throw new Error("Team not found");
}
const limit = PLAN_LIMITS[team.plan].domains;
if (isLimitExceeded(team._count.domains, limit)) {
return {
isLimitReached: true,
limit,
reason: LimitReason.DOMAIN,
};
}
return {
isLimitReached: false,
limit,
};
}
static async checkContactBookLimit(teamId: number): Promise<{
isLimitReached: boolean;
limit: number;
reason?: LimitReason;
}> {
const team = await db.team.findUnique({
where: { id: teamId },
include: {
_count: {
select: {
contactBooks: true,
},
},
},
});
if (!team) {
throw new Error("Team not found");
}
const limit = PLAN_LIMITS[team.plan].contactBooks;
if (isLimitExceeded(team._count.contactBooks, limit)) {
return {
isLimitReached: true,
limit,
reason: LimitReason.CONTACT_BOOK,
};
}
return {
isLimitReached: false,
limit,
};
}
static async checkTeamMemberLimit(teamId: number): Promise<{
isLimitReached: boolean;
limit: number;
reason?: LimitReason;
}> {
const team = await db.team.findUnique({
where: { id: teamId },
include: {
teamUsers: true,
},
});
if (!team) {
throw new Error("Team not found");
}
const limit = PLAN_LIMITS[team.plan].teamMembers;
if (isLimitExceeded(team.teamUsers.length, limit)) {
return {
isLimitReached: true,
limit,
reason: LimitReason.TEAM_MEMBER,
};
}
return {
isLimitReached: false,
limit,
};
}
static async checkEmailLimit(teamId: number): Promise<{
isLimitReached: boolean;
limit: number;
reason?: LimitReason;
}> {
const team = await db.team.findUnique({
where: { id: teamId },
});
if (!team) {
throw new Error("Team not found");
}
// FREE plan has hard limits; paid plans are unlimited (-1)
if (team.plan === "FREE") {
const usage = await getThisMonthUsage(teamId);
const monthlyUsage = usage.month.reduce(
(acc, curr) => acc + curr.sent,
0,
);
const dailyUsage = usage.day.reduce((acc, curr) => acc + curr.sent, 0);
const monthlyLimit = PLAN_LIMITS[team.plan].emailsPerMonth;
const dailyLimit = PLAN_LIMITS[team.plan].emailsPerDay;
if (isLimitExceeded(monthlyUsage, monthlyLimit)) {
return {
isLimitReached: true,
limit: monthlyLimit,
reason: LimitReason.EMAIL,
};
}
if (isLimitExceeded(dailyUsage, dailyLimit)) {
return {
isLimitReached: true,
limit: dailyLimit,
reason: LimitReason.EMAIL,
};
}
}
return {
isLimitReached: false,
limit: PLAN_LIMITS[team.plan].emailsPerMonth,
};
}
}

View File

@@ -0,0 +1,293 @@
import { TRPCError } from "@trpc/server";
import { env } from "~/env";
import { db } from "~/server/db";
import { sendTeamInviteEmail } from "~/server/mailer";
import { logger } from "~/server/logger/log";
import type { Team, TeamInvite } from "@prisma/client";
import { LimitService } from "./limit-service";
import { UnsendApiError } from "../public-api/api-error";
export class TeamService {
static async createTeam(
userId: number,
name: string
): Promise<Team | undefined> {
const teams = await db.team.findMany({
where: {
teamUsers: {
some: {
userId: userId,
},
},
},
});
if (teams.length > 0) {
logger.info({ userId }, "User already has a team");
return;
}
if (!env.NEXT_PUBLIC_IS_CLOUD) {
const _team = await db.team.findFirst();
if (_team) {
throw new TRPCError({
message: "Can't have multiple teams in self hosted version",
code: "UNAUTHORIZED",
});
}
}
return db.team.create({
data: {
name,
teamUsers: {
create: {
userId,
role: "ADMIN",
},
},
},
});
}
static async getUserTeams(userId: number) {
return db.team.findMany({
where: {
teamUsers: {
some: {
userId: userId,
},
},
},
include: {
teamUsers: {
where: {
userId: userId,
},
},
},
});
}
static async getTeamUsers(teamId: number) {
return db.teamUser.findMany({
where: {
teamId,
},
include: {
user: true,
},
});
}
static async getTeamInvites(teamId: number) {
return db.teamInvite.findMany({
where: {
teamId,
},
});
}
static async createTeamInvite(
teamId: number,
email: string,
role: "MEMBER" | "ADMIN",
teamName: string,
sendEmail: boolean = true
): Promise<TeamInvite> {
if (!email) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Email is required",
});
}
const { isLimitReached, reason } =
await LimitService.checkTeamMemberLimit(teamId);
if (isLimitReached) {
throw new UnsendApiError({
code: "FORBIDDEN",
message: reason ?? "Team invite limit reached",
});
}
const user = await db.user.findUnique({
where: {
email,
},
include: {
teamUsers: true,
},
});
if (user && user.teamUsers.length > 0) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "User already part of a team",
});
}
const teamInvite = await db.teamInvite.create({
data: {
teamId,
email,
role,
},
});
const teamUrl = `${env.NEXTAUTH_URL}/join-team?inviteId=${teamInvite.id}`;
if (sendEmail) {
await sendTeamInviteEmail(email, teamUrl, teamName);
}
return teamInvite;
}
static async updateTeamUserRole(
teamId: number,
userId: string,
role: "MEMBER" | "ADMIN"
) {
const teamUser = await db.teamUser.findFirst({
where: {
teamId,
userId: Number(userId),
},
});
if (!teamUser) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Team member not found",
});
}
// Check if this is the last admin
const adminCount = await db.teamUser.count({
where: {
teamId,
role: "ADMIN",
},
});
if (adminCount === 1 && teamUser.role === "ADMIN") {
throw new TRPCError({
code: "FORBIDDEN",
message: "Need at least one admin",
});
}
return db.teamUser.update({
where: {
teamId_userId: {
teamId,
userId: Number(userId),
},
},
data: {
role,
},
});
}
static async deleteTeamUser(
teamId: number,
userId: string,
requestorRole: string,
requestorId: number
) {
const teamUser = await db.teamUser.findFirst({
where: {
teamId,
userId: Number(userId),
},
});
if (!teamUser) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Team member not found",
});
}
if (requestorRole !== "ADMIN" && requestorId !== Number(userId)) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to delete this team member",
});
}
// Check if this is the last admin
const adminCount = await db.teamUser.count({
where: {
teamId,
role: "ADMIN",
},
});
if (adminCount === 1 && teamUser.role === "ADMIN") {
throw new TRPCError({
code: "FORBIDDEN",
message: "Need at least one admin",
});
}
return db.teamUser.delete({
where: {
teamId_userId: {
teamId,
userId: Number(userId),
},
},
});
}
static async resendTeamInvite(inviteId: string, teamName: string) {
const invite = await db.teamInvite.findUnique({
where: {
id: inviteId,
},
});
if (!invite) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Invite not found",
});
}
const teamUrl = `${env.NEXTAUTH_URL}/join-team?inviteId=${invite.id}`;
await sendTeamInviteEmail(invite.email, teamUrl, teamName);
return { success: true };
}
static async deleteTeamInvite(teamId: number, inviteId: string) {
const invite = await db.teamInvite.findFirst({
where: {
teamId,
id: {
equals: inviteId,
},
},
});
if (!invite) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Invite not found",
});
}
return db.teamInvite.delete({
where: {
teamId_email: {
teamId,
email: invite.email,
},
},
});
}
}

View File

@@ -0,0 +1,63 @@
import { EmailUsageType, Subscription } from "@prisma/client";
import { db } from "../db";
import { format } from "date-fns";
/**
* Gets the monthly and daily usage for a team
* @param teamId - The team ID to get usage for
* @param db - Prisma database client
* @param subscription - Optional subscription to determine billing period start
* @returns Object containing month and day usage arrays
*/
export async function getThisMonthUsage(teamId: number) {
const team = await db.team.findUnique({
where: { id: teamId },
});
if (!team) {
throw new Error("Team not found");
}
let subscription: Subscription | null = null;
const isPaidPlan = team.plan !== "FREE";
if (isPaidPlan) {
subscription = await db.subscription.findFirst({
where: { teamId: team.id },
orderBy: { status: "asc" },
});
}
const isoStartDate = subscription?.currentPeriodStart
? format(subscription.currentPeriodStart, "yyyy-MM-dd")
: format(new Date(), "yyyy-MM-01"); // First day of current month
const today = format(new Date(), "yyyy-MM-dd");
const [monthUsage, dayUsage] = await Promise.all([
// Get month usage
db.$queryRaw<Array<{ type: EmailUsageType; sent: number }>>`
SELECT
type,
SUM(sent)::integer AS sent
FROM "DailyEmailUsage"
WHERE "teamId" = ${team.id}
AND "date" >= ${isoStartDate}
GROUP BY "type"
`,
// Get today's usage
db.$queryRaw<Array<{ type: EmailUsageType; sent: number }>>`
SELECT
type,
SUM(sent)::integer AS sent
FROM "DailyEmailUsage"
WHERE "teamId" = ${team.id}
AND "date" = ${today}
GROUP BY "type"
`,
]);
return {
month: monthUsage,
day: dayUsage,
};
}