Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

7.5 KB
Raw Blame
import "server-only";

import type { SpaceMemberRole as DBSpaceMemberRole } from "@rallly/database";
import { prisma } from "@rallly/database";
import { createLogger } from "@rallly/logger";
import { cache } from "react";

import { isBillingEnabled } from "@/features/billing/constants";
import { getSpaceSubscription } from "@/features/billing/data";
import { getInstancePolicy } from "@/features/instance-policy/data";
import { cached_getInstanceLicense } from "@/features/licensing/data";
import type { LicenseType } from "@/features/licensing/schema";
import type { MemberDTO } from "@/features/space/member/types";
import { effectiveSpaceMemberWhere } from "@/features/space/member/utils";
import {
  createSpaceDTO,
  fromDBRole,
  isSpaceBrandingActive,
} from "@/features/space/utils";
import { AppError } from "@/lib/errors/app-error";

const logger = createLogger("space/data");

function createMemberDTO(member: {
  id: string;
  userId: string;
  spaceId: string;
  role: DBSpaceMemberRole;
  space: {
    ownerId: string;
  };
  user: {
    name: string;
    email: string;
    image?: string | null;
  };
}) {
  return {
    id: member.id,
    name: member.user.name,
    userId: member.userId,
    spaceId: member.spaceId,
    email: member.user.email,
    image: member.user.image ?? undefined,
    role: fromDBRole(member.role),
    isOwner: member.userId === member.space.ownerId,
  } satisfies MemberDTO;
}

export async function spaceExists(spaceId: string) {
  const space = await prisma.space.findUnique({
    where: { id: spaceId },
    select: { id: true },
  });
  return space !== null;
}

export async function getSpaceSeatCount(spaceId: string) {
  return await prisma.spaceMember.count({
    where: {
      spaceId: spaceId,
    },
  });
}

/**
 * Default seat limit for spaces without active subscriptions
 */
const DEFAULT_SEAT_LIMIT = 1;
const MAX_SEAT_LIMIT = 100;

/**
 * Returns the seat limit for self-hosted instances based on license type
 */
function getSelfHostedSeatLimit(licenseType: LicenseType | null): number {
  if (!licenseType) {
    return DEFAULT_SEAT_LIMIT;
  }

  switch (licenseType) {
    case "PLUS":
      return 5;
    case "ORGANIZATION":
      return 50;
    case "ENTERPRISE":
      return MAX_SEAT_LIMIT;
    default:
      return DEFAULT_SEAT_LIMIT;
  }
}

/**
 * Gets the total number of seats available for a space
 * Handles both cloud-hosted (Stripe subscription) and self-hosted (license-based) deployments
 */
export async function getTotalSeatsForSpace(spaceId: string): Promise<number> {
  try {
    if (!isBillingEnabled) {
      // Without billing, seats come from the instance license
      const license = await cached_getInstanceLicense();

      if (!license) {
        // No license found, return default limit
        return DEFAULT_SEAT_LIMIT;
      }

      // If license has explicit seats defined, use that
      if (license.seats && license.seats > 0) {
        return Math.min(license.seats, MAX_SEAT_LIMIT);
      }

      // Otherwise, use the license type to determine seat limit
      return getSelfHostedSeatLimit(license.type);
    } else {
      // For cloud-hosted instances, get seat count from Stripe subscription
      const subscription = await getSpaceSubscription(spaceId);

      if (!subscription || !subscription.active) {
        // Return default limit for spaces without active subscriptions
        return DEFAULT_SEAT_LIMIT;
      }

      return subscription.quantity || DEFAULT_SEAT_LIMIT;
    }
  } catch (error) {
    logger.error({ error, spaceId }, "Failed to get total seats for space");

    if (error instanceof AppError) {
      throw error;
    }

    throw new AppError({
      code: "INTERNAL_SERVER_ERROR",
      message: "Failed to retrieve seat information",
      cause: error,
    });
  }
}

export const getMember = async (id: string) => {
  const member = await prisma.spaceMember.findUnique({
    where: {
      id,
    },
    select: {
      id: true,
      userId: true,
      spaceId: true,
      role: true,
      space: {
        select: {
          ownerId: true,
        },
      },
      user: {
        select: {
          name: true,
          email: true,
          image: true,
        },
      },
    },
  });

  if (!member) {
    return null;
  }

  return createMemberDTO(member);
};

export async function getSpaceBranding(spaceId: string) {
  const space = await prisma.space.findUnique({
    where: { id: spaceId },
    select: {
      name: true,
      image: true,
      tier: true,
      showBranding: true,
      primaryColor: true,
    },
  });

  if (!space) {
    return null;
  }

  const { spaceBrandingAllowed } = await getInstancePolicy();

  if (!isSpaceBrandingActive({ ...space, spaceBrandingAllowed })) {
    return { ...space, showBranding: false, primaryColor: null };
  }

  return space;
}

export const getOwnedSpace = cache(async (userId: string) => {
  return prisma.space.findFirst({
    where: { ownerId: userId },
    select: { id: true },
  });
});

export const listSpacesForUser = cache(async (userId: string) => {
  const result = await prisma.spaceMember.findMany({
    where: effectiveSpaceMemberWhere({ userId }),
    select: {
      role: true,
      space: {
        select: {
          id: true,
          name: true,
          image: true,
          ownerId: true,
          tier: true,
          primaryColor: true,
          showBranding: true,
          hideAttribution: true,
          shared: true,
          subscriptions: {
            where: { active: true },
            select: { quantity: true },
            orderBy: { createdAt: "desc" },
            take: 1,
          },
        },
      },
    },
  });

  // Counted for these spaces only: a relation _count over more than one
  // space compiles to a GROUP BY over the whole space_members table
  const [memberCounts, policy] = await Promise.all([
    prisma.spaceMember.groupBy({
      by: ["spaceId"],
      where: { spaceId: { in: result.map(({ space }) => space.id) } },
      _count: { _all: true },
    }),
    getInstancePolicy(),
  ]);
  const memberCountBySpaceId = new Map(
    memberCounts.map((row) => [row.spaceId, row._count._all]),
  );

  return result.map((spaceMember) =>
    createSpaceDTO({
      space: {
        ...spaceMember.space,
        role: spaceMember.role,
        memberCount: memberCountBySpaceId.get(spaceMember.space.id) ?? 0,
        seatCount: spaceMember.space.subscriptions[0]?.quantity ?? 1,
      },
      policy,
    }),
  );
});

export const getActiveSpaceForUser = cache(async (userId: string) => {
  const spaceMember = await prisma.spaceMember.findFirst({
    where: effectiveSpaceMemberWhere({ userId }),
    orderBy: {
      lastSelectedAt: "desc",
    },
    include: {
      space: {
        include: {
          _count: { select: { members: true } },
          subscriptions: {
            where: { active: true },
            select: { quantity: true, status: true },
            // Newest first, matching getSpaceSubscription: nothing stops a
            // space having two active rows, and an unordered take(1) could
            // otherwise disagree with the billing page about which one counts.
            orderBy: { createdAt: "desc" },
            take: 1,
          },
        },
      },
    },
  });

  if (!spaceMember) {
    return null;
  }

  return createSpaceDTO({
    space: {
      ...spaceMember.space,
      role: spaceMember.role,
      memberCount: spaceMember.space._count.members,
      seatCount: spaceMember.space.subscriptions[0]?.quantity ?? 1,
      subscriptionPastDue:
        spaceMember.space.subscriptions[0]?.status === "past_due",
    },
    policy: await getInstancePolicy(),
  });
});