Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

3.5 KB
Raw Blame
import type { NextApiRequest, NextApiResponse } from "next";

import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";

import { teamPlanIsDataroomPlusTier } from "@/lib/billing/team-plan-custom-messaging";
import { getFeatureFlags } from "@/lib/featureFlags";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
import {
  calculateAndUpdateHierarchicalIndexes,
  clearHierarchicalIndexes,
} from "@/lib/utils/calculate-hierarchical-indexes";

export const config = {
  maxDuration: 300,
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  if (req.method !== "POST") {
    return res.status(405).json({ message: "Method not allowed" });
  }

  const session = await getServerSession(req, res, authOptions);
  if (!session) {
    return res.status(401).end("Unauthorized");
  }

  const { teamId, id: dataroomId } = req.query as {
    teamId: string;
    id: string;
  };
  const userId = (session.user as CustomUser).id;

  const action = (req.body as { action?: string } | undefined)?.action;
  if (action !== undefined && action !== "rebuild" && action !== "clear") {
    return res
      .status(400)
      .json({ message: "Invalid action. Use 'rebuild' or 'clear'." });
  }
  const shouldClear = action === "clear";

  if (!dataroomId || typeof dataroomId !== "string") {
    return res.status(400).json({ message: "Invalid dataroom ID" });
  }

  if (!teamId || typeof teamId !== "string") {
    return res.status(400).json({ message: "Invalid team ID" });
  }

  try {
    // Verify user has access to this dataroom and get team plan
    const dataroom = await prisma.dataroom.findUnique({
      where: {
        id: dataroomId,
        teamId,
        team: {
          users: {
            some: {
              userId: userId,
            },
          },
        },
      },
      select: {
        id: true,
        name: true,
        team: {
          select: {
            plan: true,
          },
        },
      },
    });

    if (!dataroom) {
      return res.status(404).json({ message: "Dataroom not found" });
    }

    // Check if user has access: feature flag enabled OR datarooms-plus plan
    const featureFlags = await getFeatureFlags({ teamId });
    const hasDataroomsPlusPlan = teamPlanIsDataroomPlusTier(
      dataroom.team.plan,
    );

    if (!featureFlags.dataroomIndex && !hasDataroomsPlusPlan) {
      return res.status(403).json({
        message: "This feature requires a Data Rooms Plus plan",
      });
    }

    // Calculate/update or clear hierarchical indexes
    const result = shouldClear
      ? await clearHierarchicalIndexes(dataroomId)
      : await calculateAndUpdateHierarchicalIndexes(dataroomId);

    res.status(200).json({
      message: shouldClear
        ? "Hierarchical indexes removed successfully"
        : "Hierarchical indexes calculated successfully",
      action: shouldClear ? "clear" : "rebuild",
      foldersUpdated: result.foldersUpdated,
      documentsUpdated: result.documentsUpdated,
      totalUpdated: result.foldersUpdated + result.documentsUpdated,
    });
  } catch (error) {
    console.error(
      shouldClear
        ? "Error removing hierarchical indexes:"
        : "Error calculating hierarchical indexes:",
      error,
    );
    res.status(500).json({
      message: shouldClear
        ? "Error removing hierarchical indexes"
        : "Error calculating hierarchical indexes",
      error: error instanceof Error ? error.message : "Unknown error",
    });
  }
}