Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat(ee): add workflows
Marc Seitz44190ff0f854
diff --git a/app/(ee)/api/workflow-entry/domains/[...domainSlug]/route.ts b/app/(ee)/api/workflow-entry/domains/[...domainSlug]/route.tsnew file mode 100644index 00000000..3d8d9e4c--- /dev/null+++ b/app/(ee)/api/workflow-entry/domains/[...domainSlug]/route.ts@@ -0,0 +1,378 @@+import { cookies } from "next/headers";+import { NextRequest, NextResponse } from "next/server";++import { WorkflowEngine } from "@/ee/features/workflows/lib/engine";+import {+ AccessRequestSchema,+ VerifyEmailRequestSchema,+} from "@/ee/features/workflows/lib/types";+import { ipAddress, waitUntil } from "@vercel/functions";+import { z } from "zod";++import { createDataroomSession } from "@/lib/auth/dataroom-auth";+import { createLinkSession } from "@/lib/auth/link-session";+import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";+import prisma from "@/lib/prisma";+import { ratelimit } from "@/lib/redis";+import { generateOTP } from "@/lib/utils/generate-otp";+import { LOCALHOST_IP } from "@/lib/utils/geo";++// POST /app/(ee)/api/workflow-entry/domains/[domain]/[slug]/[action]+// where action is "verify" or "access"+export async function POST(+ req: NextRequest,+ { params }: { params: { domainSlug: string[] } },+) {+ try {+ const domainSlug = params.domainSlug;++ if (!domainSlug || domainSlug.length < 3) {+ return NextResponse.json(+ { error: "Invalid URL format. Expected: domain/slug/action" },+ { status: 400 },+ );+ }++ const domain = domainSlug[0];+ const slug = domainSlug[1];+ const action = domainSlug[2]; // "verify" or "access"++ if (action !== "verify" && action !== "access") {+ return NextResponse.json(+ { error: "Invalid action. Must be 'verify' or 'access'" },+ { status: 400 },+ );+ }++ // Find workflow by entry link's domain and slug+ const link = await prisma.link.findUnique({+ where: {+ domainSlug_slug: {+ domainSlug: domain,+ slug: slug,+ },+ linkType: "WORKFLOW_LINK",+ },+ select: {+ id: true,+ isArchived: true,+ deletedAt: true,+ workflow: {+ select: {+ id: true,+ isActive: true,+ name: true,+ teamId: true,+ entryLinkId: true,+ },+ },+ },+ });++ if (!link || !link.workflow) {+ return NextResponse.json(+ { error: "Workflow entry link not found" },+ { status: 404 },+ );+ }++ if (!link.workflow.isActive) {+ return NextResponse.json(+ { error: "This workflow is currently inactive" },+ { status: 403 },+ );+ }++ if (link.isArchived || link.deletedAt) {+ return NextResponse.json(+ { error: "This link is no longer available" },+ { status: 404 },+ );+ }++ // Handle verify action+ if (action === "verify") {+ return handleVerify(req, link);+ }++ // Handle access action+ if (action === "access") {+ return handleAccess(req, link);+ }++ return NextResponse.json({ error: "Invalid action" }, { status: 400 });+ } catch (error) {+ console.error("Error in workflow entry endpoint:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}++// Handle verify (send OTP)+async function handleVerify(req: NextRequest, link: any) {+ const body = await req.json();++ // Validate request body+ const validation = VerifyEmailRequestSchema.safeParse(body);+ if (!validation.success) {+ return NextResponse.json(+ { error: "Invalid email address" },+ { status: 400 },+ );+ }++ const { email } = validation.data;++ // Rate limiting+ const ipAddressValue = ipAddress(req);+ const { success } = await ratelimit(10, "1 m").limit(+ `workflow-otp:${ipAddressValue}`,+ );+ if (!success) {+ return NextResponse.json(+ { error: "Too many requests. Please try again later." },+ { status: 429 },+ );+ }++ // Delete any existing OTP codes for this workflow entry + email+ await prisma.verificationToken.deleteMany({+ where: {+ identifier: `workflow-otp:${link.id}:${email}`,+ },+ });++ // Generate and store OTP+ const otpCode = generateOTP();+ const expiresAt = new Date();+ expiresAt.setMinutes(expiresAt.getMinutes() + 10); // expires in 10 minutes++ await prisma.verificationToken.create({+ data: {+ token: otpCode,+ identifier: `workflow-otp:${link.id}:${email}`,+ expires: expiresAt,+ },+ });++ // Send OTP email+ waitUntil(+ sendOtpVerificationEmail(email, otpCode, false, link.workflow.teamId),+ );++ return NextResponse.json({+ success: true,+ message: "Verification code sent to your email",+ });+}++// Handle access (verify OTP and execute workflow)+async function handleAccess(req: NextRequest, link: any) {+ const body = await req.json();++ // Validate request body+ const validation = AccessRequestSchema.safeParse(body);+ if (!validation.success) {+ return NextResponse.json(+ { error: "Invalid request data" },+ { status: 400 },+ );+ }++ const { email, code } = validation.data;++ // Rate limiting+ const ipAddressValue = ipAddress(req) ?? LOCALHOST_IP;+ const { success } = await ratelimit(10, "1 m").limit(+ `workflow-verify:${ipAddressValue}`,+ );+ if (!success) {+ return NextResponse.json(+ { error: "Too many requests. Please try again later." },+ { status: 429 },+ );+ }++ // Verify OTP code+ const verification = await prisma.verificationToken.findUnique({+ where: {+ token: code,+ identifier: `workflow-otp:${link.id}:${email}`,+ },+ });++ if (!verification) {+ return NextResponse.json(+ { error: "Invalid verification code", resetVerification: true },+ { status: 401 },+ );+ }++ // Check OTP expiration+ if (Date.now() > verification.expires.getTime()) {+ await prisma.verificationToken.delete({+ where: { token: code },+ });+ return NextResponse.json(+ { error: "Verification code expired", resetVerification: true },+ { status: 401 },+ );+ }++ // Delete OTP after successful verification+ await prisma.verificationToken.delete({+ where: { token: code },+ });++ // Execute workflow engine+ const engine = new WorkflowEngine();+ const userAgent = req.headers.get("user-agent") ?? "unknown";+ const referrer = req.headers.get("referer") ?? undefined;++ const executionResult = await engine.execute(link.workflow.entryLinkId, {+ visitorEmail: email,+ visitorIp: ipAddressValue,+ userAgent,+ referrer,+ });++ if (!executionResult.success) {+ return NextResponse.json(+ { error: executionResult.error || "Workflow execution failed" },+ { status: 400 },+ );+ }++ // Find or create viewer+ let viewer = await prisma.viewer.findUnique({+ where: {+ teamId_email: {+ teamId: link.workflow.teamId,+ email: email,+ },+ },+ select: { id: true },+ });++ if (!viewer) {+ viewer = await prisma.viewer.create({+ data: {+ email: email,+ verified: true,+ teamId: link.workflow.teamId,+ },+ select: { id: true },+ });+ }++ // Create a view record for the workflow execution+ const view = await prisma.view.create({+ data: {+ linkId: link.id,+ viewerEmail: email,+ viewerId: viewer.id,+ verified: true,+ teamId: link.workflow.teamId,+ documentId: executionResult.targetDocumentId ?? undefined,+ dataroomId: executionResult.targetDataroomId ?? undefined,+ viewType:+ executionResult.targetLinkType === "DATAROOM_LINK"+ ? "DATAROOM_VIEW"+ : "DOCUMENT_VIEW",+ },+ select: { id: true },+ });++ // Create link session for the target link+ const { token: sessionToken, expiresAt } = await createLinkSession(+ executionResult.targetLinkId!,+ executionResult.targetLinkType!,+ view.id,+ email,+ ipAddressValue,+ userAgent,+ true, // verified+ viewer.id, // viewerId+ executionResult.targetDocumentId,+ executionResult.targetDataroomId,+ );++ const targetPath = executionResult.targetUrl+ ? new URL(executionResult.targetUrl).pathname+ : "/";+ const cookieFlagId = executionResult.targetUrl+ ? new URL(executionResult.targetUrl).pathname.split("/").pop()+ : executionResult.targetLinkId;++ // Set link session cookie (httpOnly)+ cookies().set(`pm_ls_${executionResult.targetLinkId}`, sessionToken, {+ httpOnly: true,+ secure: process.env.NODE_ENV === "production",+ sameSite: "lax",+ expires: new Date(expiresAt),+ path: "/",+ });++ // Set client-readable flag cookie for auto-login detection+ const flagCookieId = `pm_link_flag_${cookieFlagId}`;+ cookies().set(flagCookieId, "true", {+ httpOnly: false, // Client-readable+ secure: process.env.NODE_ENV === "production",+ sameSite: "lax",+ expires: new Date(expiresAt),+ path: targetPath,+ });++ // If routing to a dataroom, also create and set dataroom session cookie+ if (+ executionResult.targetLinkType === "DATAROOM_LINK" &&+ executionResult.targetDataroomId &&+ viewer+ ) {+ const dataroomSession = await createDataroomSession(+ executionResult.targetDataroomId,+ executionResult.targetLinkId!,+ view.id,+ ipAddressValue,+ true, // verified+ viewer.id,+ );++ cookies().set(+ `pm_drs_${executionResult.targetLinkId}`,+ dataroomSession.token,+ {+ httpOnly: true,+ secure: process.env.NODE_ENV === "production",+ sameSite: "lax",+ expires: new Date(dataroomSession.expiresAt),+ path: "/",+ },+ );++ // Set client-readable flag cookie for dataroom+ const dataroomFlagId = `pm_drs_flag_${cookieFlagId}`;+ cookies().set(dataroomFlagId, "true", {+ httpOnly: false, // Client-readable+ secure: process.env.NODE_ENV === "production",+ sameSite: "lax",+ expires: new Date(dataroomSession.expiresAt),+ path: targetPath,+ });+ }++ console.log("--------------------------------");+ console.log("sessionToken", sessionToken);+ console.log("--------------------------------");+ console.log("executionResult", executionResult);+ console.log("--------------------------------");++ return NextResponse.json({+ success: true,+ targetUrl: executionResult.targetUrl,+ targetLinkId: executionResult.targetLinkId,+ targetLinkType: executionResult.targetLinkType,+ });+}diff --git a/app/(ee)/api/workflow-entry/link/[entryLinkId]/access/route.ts b/app/(ee)/api/workflow-entry/link/[entryLinkId]/access/route.tsnew file mode 100644index 00000000..05cbcef9--- /dev/null+++ b/app/(ee)/api/workflow-entry/link/[entryLinkId]/access/route.ts@@ -0,0 +1,277 @@+import { cookies } from "next/headers";+import { NextRequest, NextResponse } from "next/server";++import { WorkflowEngine } from "@/ee/features/workflows/lib/engine";+import { AccessRequestSchema } from "@/ee/features/workflows/lib/types";+import { ipAddress } from "@vercel/functions";+import { z } from "zod";++import { createDataroomSession } from "@/lib/auth/dataroom-auth";+import { createLinkSession } from "@/lib/auth/link-session";+import prisma from "@/lib/prisma";+import { ratelimit } from "@/lib/redis";+import { LOCALHOST_IP } from "@/lib/utils/geo";++// POST /app/(ee)/api/workflow-entry/[entryLinkId]/access - Verify OTP and execute workflow+export async function POST(+ req: NextRequest,+ { params }: { params: { entryLinkId: string } },+) {+ try {+ const { entryLinkId } = params;+ const body = await req.json();++ // Validate entryLinkId format+ const linkIdValidation = z.string().cuid().safeParse(entryLinkId);+ if (!linkIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid link ID format" },+ { status: 400 },+ );+ }++ // Validate request body+ const validation = AccessRequestSchema.safeParse(body);+ if (!validation.success) {+ return NextResponse.json(+ { error: "Invalid request data" },+ { status: 400 },+ );+ }++ const { email, code } = validation.data;++ // Rate limiting+ const ipAddressValue = ipAddress(req) ?? LOCALHOST_IP;+ const { success } = await ratelimit(10, "1 m").limit(+ `workflow-verify:${ipAddressValue}`,+ );+ if (!success) {+ return NextResponse.json(+ { error: "Too many requests. Please try again later." },+ { status: 429 },+ );+ }++ // Find workflow by entry link+ const workflow = await prisma.workflow.findUnique({+ where: { entryLinkId },+ select: {+ id: true,+ isActive: true,+ teamId: true,+ entryLink: {+ select: {+ id: true,+ isArchived: true,+ deletedAt: true,+ },+ },+ },+ });++ if (!workflow) {+ return NextResponse.json(+ { error: "Workflow entry link not found" },+ { status: 404 },+ );+ }++ if (!workflow.isActive) {+ return NextResponse.json(+ { error: "This workflow is currently inactive" },+ { status: 403 },+ );+ }++ if (workflow.entryLink.isArchived || workflow.entryLink.deletedAt) {+ return NextResponse.json(+ { error: "This link is no longer available" },+ { status: 404 },+ );+ }++ // Verify OTP code+ const verification = await prisma.verificationToken.findUnique({+ where: {+ token: code,+ identifier: `workflow-otp:${entryLinkId}:${email}`,+ },+ });++ if (!verification) {+ return NextResponse.json(+ { error: "Invalid verification code", resetVerification: true },+ { status: 401 },+ );+ }++ // Check OTP expiration+ if (Date.now() > verification.expires.getTime()) {+ await prisma.verificationToken.delete({+ where: { token: code },+ });+ return NextResponse.json(+ { error: "Verification code expired", resetVerification: true },+ { status: 401 },+ );+ }++ // Delete OTP after successful verification+ await prisma.verificationToken.delete({+ where: { token: code },+ });++ // Execute workflow engine+ const engine = new WorkflowEngine();+ const userAgent = req.headers.get("user-agent") ?? "unknown";+ const referrer = req.headers.get("referer") ?? undefined;++ const executionResult = await engine.execute(entryLinkId, {+ visitorEmail: email,+ visitorIp: ipAddressValue,+ userAgent,+ referrer,+ });++ if (!executionResult.success) {+ return NextResponse.json(+ { error: executionResult.error || "Workflow execution failed" },+ { status: 400 },+ );+ }++ // Find or create viewer+ let viewer = await prisma.viewer.findUnique({+ where: {+ teamId_email: {+ teamId: workflow.teamId,+ email: email,+ },+ },+ select: { id: true },+ });++ if (!viewer) {+ viewer = await prisma.viewer.create({+ data: {+ email: email,+ verified: true,+ teamId: workflow.teamId,+ },+ select: { id: true },+ });+ }++ // Create a view record for the workflow execution+ const view = await prisma.view.create({+ data: {+ linkId: entryLinkId,+ viewerEmail: email,+ viewerId: viewer.id,+ verified: true,+ teamId: workflow.teamId,+ viewType:+ executionResult.targetLinkType === "DATAROOM_LINK"+ ? "DATAROOM_VIEW"+ : "DOCUMENT_VIEW",+ documentId: executionResult.targetDocumentId ?? undefined,+ dataroomId: executionResult.targetDataroomId ?? undefined,+ },+ select: { id: true },+ });++ // Create link session for the target link+ const { token: sessionToken, expiresAt } = await createLinkSession(+ executionResult.targetLinkId!,+ executionResult.targetLinkType!,+ view.id,+ email,+ ipAddressValue,+ userAgent,+ true, // verified+ viewer.id, // viewerId+ executionResult.targetDocumentId,+ executionResult.targetDataroomId,+ );++ const targetPath = `/view/${executionResult.targetLinkId}`;+ const cookieFlagId = executionResult.targetLinkId;++ // Set link session cookie (httpOnly)+ cookies().set(`pm_ls_${executionResult.targetLinkId}`, sessionToken, {+ httpOnly: true,+ secure: process.env.NODE_ENV === "production",+ sameSite: "lax",+ expires: new Date(expiresAt),+ path: "/",+ });++ // Set client-readable flag cookie for auto-login detection+ const flagCookieId = `pm_link_flag_${cookieFlagId}`;+ cookies().set(flagCookieId, "true", {+ httpOnly: false, // Client-readable+ secure: process.env.NODE_ENV === "production",+ sameSite: "lax",+ expires: new Date(expiresAt),+ path: targetPath,+ });++ // If routing to a dataroom, also create and set dataroom session cookie+ if (+ executionResult.targetLinkType === "DATAROOM_LINK" &&+ executionResult.targetDataroomId &&+ viewer+ ) {+ const dataroomSession = await createDataroomSession(+ executionResult.targetDataroomId,+ executionResult.targetLinkId!,+ view.id,+ ipAddressValue,+ true, // verified+ viewer.id,+ );++ cookies().set(+ `pm_drs_${executionResult.targetLinkId}`,+ dataroomSession.token,+ {+ httpOnly: true,+ secure: process.env.NODE_ENV === "production",+ sameSite: "lax",+ expires: new Date(dataroomSession.expiresAt),+ path: "/",+ },+ );++ // Set client-readable flag cookie for dataroom+ const dataroomFlagId = `pm_drs_flag_${cookieFlagId}`;+ cookies().set(dataroomFlagId, "true", {+ httpOnly: false, // Client-readable+ secure: process.env.NODE_ENV === "production",+ sameSite: "lax",+ expires: new Date(dataroomSession.expiresAt),+ path: targetPath,+ });+ }++ console.log("--------------------------------");+ console.log("sessionToken", sessionToken);+ console.log("--------------------------------");+ console.log("executionResult", executionResult);+ console.log("--------------------------------");++ return NextResponse.json({+ success: true,+ targetUrl: executionResult.targetUrl,+ targetLinkId: executionResult.targetLinkId,+ targetLinkType: executionResult.targetLinkType,+ });+ } catch (error) {+ console.error("Error verifying workflow access:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}diff --git a/app/(ee)/api/workflow-entry/link/[entryLinkId]/verify/route.ts b/app/(ee)/api/workflow-entry/link/[entryLinkId]/verify/route.tsnew file mode 100644index 00000000..19dbfa0b--- /dev/null+++ b/app/(ee)/api/workflow-entry/link/[entryLinkId]/verify/route.ts@@ -0,0 +1,128 @@+import { NextRequest, NextResponse } from "next/server";+import { ipAddress, waitUntil } from "@vercel/functions";+import { z } from "zod";+import prisma from "@/lib/prisma";+import { ratelimit } from "@/lib/redis";+import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";+import { generateOTP } from "@/lib/utils/generate-otp";+import { validateEmail } from "@/lib/utils/validate-email";+import { VerifyEmailRequestSchema } from "@/ee/features/workflows/lib/types";++// POST /app/(ee)/api/workflow-entry/[entryLinkId]/verify - Send OTP+export async function POST(+ req: NextRequest,+ { params }: { params: { entryLinkId: string } },+) {+ try {+ const { entryLinkId } = params;+ const body = await req.json();++ // Validate entryLinkId format+ const linkIdValidation = z.string().cuid().safeParse(entryLinkId);+ if (!linkIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid link ID format" },+ { status: 400 },+ );+ }++ // Validate request body+ const validation = VerifyEmailRequestSchema.safeParse(body);+ if (!validation.success) {+ return NextResponse.json(+ { error: "Invalid email address" },+ { status: 400 },+ );+ }++ const { email } = validation.data;++ // Find workflow by entry link+ const workflow = await prisma.workflow.findUnique({+ where: { entryLinkId },+ select: {+ id: true,+ isActive: true,+ name: true,+ teamId: true,+ entryLink: {+ select: {+ id: true,+ isArchived: true,+ deletedAt: true,+ },+ },+ },+ });++ if (!workflow) {+ return NextResponse.json(+ { error: "Workflow entry link not found" },+ { status: 404 },+ );+ }++ if (!workflow.isActive) {+ return NextResponse.json(+ { error: "This workflow is currently inactive" },+ { status: 403 },+ );+ }++ if (workflow.entryLink.isArchived || workflow.entryLink.deletedAt) {+ return NextResponse.json(+ { error: "This link is no longer available" },+ { status: 404 },+ );+ }++ // Rate limiting+ const ipAddressValue = ipAddress(req);+ const { success } = await ratelimit(10, "1 m").limit(+ `workflow-otp:${ipAddressValue}`,+ );+ if (!success) {+ return NextResponse.json(+ { error: "Too many requests. Please try again later." },+ { status: 429 },+ );+ }++ // Delete any existing OTP codes for this workflow entry + email+ await prisma.verificationToken.deleteMany({+ where: {+ identifier: `workflow-otp:${entryLinkId}:${email}`,+ },+ });++ // Generate and store OTP+ const otpCode = generateOTP();+ const expiresAt = new Date();+ expiresAt.setMinutes(expiresAt.getMinutes() + 10); // expires in 10 minutes++ await prisma.verificationToken.create({+ data: {+ token: otpCode,+ identifier: `workflow-otp:${entryLinkId}:${email}`,+ expires: expiresAt,+ },+ });++ // Send OTP email+ waitUntil(+ sendOtpVerificationEmail(email, otpCode, false, workflow.teamId),+ );++ return NextResponse.json({+ success: true,+ message: "Verification code sent to your email",+ });+ } catch (error) {+ console.error("Error sending workflow verification code:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}+diff --git a/app/(ee)/api/workflows/[workflowId]/executions/route.ts b/app/(ee)/api/workflows/[workflowId]/executions/route.tsnew file mode 100644index 00000000..6a21272d--- /dev/null+++ b/app/(ee)/api/workflows/[workflowId]/executions/route.ts@@ -0,0 +1,111 @@+import { NextRequest, NextResponse } from "next/server";+import { getServerSession } from "next-auth";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { z } from "zod";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++// GET /app/(ee)/api/workflows/[workflowId]/executions - List workflow executions+export async function GET(+ req: NextRequest,+ { params }: { params: { workflowId: string } },+) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { workflowId } = params;+ const searchParams = req.nextUrl.searchParams;++ // Parse pagination parameters+ const page = parseInt(searchParams.get("page") || "1");+ const limit = Math.min(parseInt(searchParams.get("limit") || "20"), 100);+ const skip = (page - 1) * limit;++ // Validate workflowId format+ const workflowIdValidation = z.string().cuid().safeParse(workflowId);+ if (!workflowIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid workflowId format" },+ { status: 400 },+ );+ }++ // Check workflow exists and user has access+ const workflow = await prisma.workflow.findUnique({+ where: { id: workflowId },+ select: {+ id: true,+ teamId: true,+ team: {+ select: {+ users: { select: { userId: true } },+ },+ },+ },+ });++ if (!workflow) {+ return NextResponse.json(+ { error: "Workflow not found" },+ { status: 404 },+ );+ }++ const isUserPartOfTeam = workflow.team.users.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );++ if (!isUserPartOfTeam) {+ return NextResponse.json(+ { error: "Unauthorized to access this workflow" },+ { status: 403 },+ );+ }++ // Fetch executions with pagination+ const [executions, totalCount] = await Promise.all([+ prisma.workflowExecution.findMany({+ where: { workflowId },+ include: {+ stepLogs: {+ select: {+ id: true,+ workflowStepId: true,+ conditionsMatched: true,+ executedAt: true,+ duration: true,+ error: true,+ },+ orderBy: { executedAt: "asc" },+ },+ },+ orderBy: { startedAt: "desc" },+ skip,+ take: limit,+ }),+ prisma.workflowExecution.count({+ where: { workflowId },+ }),+ ]);++ return NextResponse.json({+ executions,+ pagination: {+ page,+ limit,+ totalCount,+ totalPages: Math.ceil(totalCount / limit),+ },+ });+ } catch (error) {+ console.error("Error fetching workflow executions:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}+diff --git a/app/(ee)/api/workflows/[workflowId]/route.ts b/app/(ee)/api/workflows/[workflowId]/route.tsnew file mode 100644index 00000000..a13ceafd--- /dev/null+++ b/app/(ee)/api/workflows/[workflowId]/route.ts@@ -0,0 +1,274 @@+import { NextRequest, NextResponse } from "next/server";++import {+ UpdateWorkflowRequestSchema,+ formatZodError,+} from "@/ee/features/workflows/lib/validation";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth";+import { z } from "zod";++import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++// GET /app/(ee)/api/workflows/[workflowId] - Get single workflow with details+export async function GET(+ req: NextRequest,+ { params }: { params: { workflowId: string } },+) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { workflowId } = params;++ // Validate workflowId format+ const workflowIdValidation = z.string().cuid().safeParse(workflowId);+ if (!workflowIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid workflowId format" },+ { status: 400 },+ );+ }++ // Fetch workflow+ const workflow = await prisma.workflow.findUnique({+ where: { id: workflowId },+ include: {+ entryLink: {+ select: {+ id: true,+ slug: true,+ domainSlug: true,+ },+ },+ steps: {+ orderBy: { stepOrder: "asc" },+ },+ team: {+ select: {+ id: true,+ users: { select: { userId: true } },+ },+ },+ },+ });++ if (!workflow) {+ return NextResponse.json(+ { error: "Workflow not found" },+ { status: 404 },+ );+ }++ // Check user is part of the team+ const isUserPartOfTeam = workflow.team.users.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );++ if (!isUserPartOfTeam) {+ return NextResponse.json(+ { error: "Unauthorized to access this workflow" },+ { status: 403 },+ );+ }++ // Build entry URL+ const entryUrl =+ workflow.entryLink.domainSlug && workflow.entryLink.slug+ ? `https://${workflow.entryLink.domainSlug}/${workflow.entryLink.slug}`+ : `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${workflow.entryLink.id}`;++ // Remove team data from response+ const { team, ...workflowData } = workflow;++ return NextResponse.json({+ ...workflowData,+ entryUrl,+ });+ } catch (error) {+ console.error("Error fetching workflow:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}++// PATCH /app/(ee)/api/workflows/[workflowId] - Update workflow+export async function PATCH(+ req: NextRequest,+ { params }: { params: { workflowId: string } },+) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { workflowId } = params;+ const body = await req.json();++ // Validate workflowId format+ const workflowIdValidation = z.string().cuid().safeParse(workflowId);+ if (!workflowIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid workflowId format" },+ { status: 400 },+ );+ }++ // Validate request body+ const validation = UpdateWorkflowRequestSchema.safeParse(body);+ if (!validation.success) {+ return NextResponse.json(+ {+ error: "Invalid request data",+ details: formatZodError(validation.error),+ },+ { status: 400 },+ );+ }++ // Fetch workflow to check ownership+ const workflow = await prisma.workflow.findUnique({+ where: { id: workflowId },+ select: {+ id: true,+ teamId: true,+ team: {+ select: {+ users: { select: { userId: true } },+ },+ },+ },+ });++ if (!workflow) {+ return NextResponse.json(+ { error: "Workflow not found" },+ { status: 404 },+ );+ }++ // Check user is part of the team+ const isUserPartOfTeam = workflow.team.users.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );++ if (!isUserPartOfTeam) {+ return NextResponse.json(+ { error: "Unauthorized to modify this workflow" },+ { status: 403 },+ );+ }++ // Update workflow+ const updatedWorkflow = await prisma.workflow.update({+ where: { id: workflowId },+ data: validation.data,+ include: {+ entryLink: {+ select: {+ id: true,+ slug: true,+ domainSlug: true,+ },+ },+ },+ });++ return NextResponse.json(updatedWorkflow);+ } catch (error) {+ console.error("Error updating workflow:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}++// DELETE /app/(ee)/api/workflows/[workflowId] - Delete workflow+export async function DELETE(+ req: NextRequest,+ { params }: { params: { workflowId: string } },+) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { workflowId } = params;++ // Validate workflowId format+ const workflowIdValidation = z.string().cuid().safeParse(workflowId);+ if (!workflowIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid workflowId format" },+ { status: 400 },+ );+ }++ // Fetch workflow to check ownership+ const workflow = await prisma.workflow.findUnique({+ where: { id: workflowId },+ select: {+ id: true,+ entryLinkId: true,+ teamId: true,+ team: {+ select: {+ users: { select: { userId: true } },+ },+ },+ },+ });++ if (!workflow) {+ return NextResponse.json(+ { error: "Workflow not found" },+ { status: 404 },+ );+ }++ // Check user is part of the team+ const isUserPartOfTeam = workflow.team.users.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );++ if (!isUserPartOfTeam) {+ return NextResponse.json(+ { error: "Unauthorized to delete this workflow" },+ { status: 403 },+ );+ }++ // Delete workflow and entry link in transaction+ // Note: Steps and executions will cascade delete via Prisma relations+ await prisma.$transaction([+ // Delete workflow first (cascade deletes steps and executions)+ prisma.workflow.delete({+ where: { id: workflowId },+ }),+ // Delete entry link+ prisma.link.update({+ where: { id: workflow.entryLinkId },+ data: {+ deletedAt: new Date(),+ isArchived: true,+ },+ }),+ ]);++ return NextResponse.json({ success: true });+ } catch (error) {+ console.error("Error deleting workflow:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}diff --git a/app/(ee)/api/workflows/[workflowId]/steps/[stepId]/route.ts b/app/(ee)/api/workflows/[workflowId]/steps/[stepId]/route.tsnew file mode 100644index 00000000..deb7a1e9--- /dev/null+++ b/app/(ee)/api/workflows/[workflowId]/steps/[stepId]/route.ts@@ -0,0 +1,323 @@+import { NextRequest, NextResponse } from "next/server";+import { getServerSession } from "next-auth";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { z } from "zod";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import {+ UpdateWorkflowStepRequestSchema,+ formatZodError,+ validateConditions,+ validateActions,+} from "@/ee/features/workflows/lib/validation";++// PATCH /app/(ee)/api/workflows/[workflowId]/steps/[stepId] - Update step+export async function PATCH(+ req: NextRequest,+ { params }: { params: { workflowId: string; stepId: string } },+) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { workflowId, stepId } = params;+ const body = await req.json();++ // Validate IDs format+ const idsValidation = z.object({+ workflowId: z.string().cuid(),+ stepId: z.string().cuid(),+ }).safeParse({ workflowId, stepId });++ if (!idsValidation.success) {+ return NextResponse.json(+ { error: "Invalid ID format" },+ { status: 400 },+ );+ }++ // Validate request body+ const validation = UpdateWorkflowStepRequestSchema.safeParse(body);+ if (!validation.success) {+ return NextResponse.json(+ {+ error: "Invalid request data",+ details: formatZodError(validation.error),+ },+ { status: 400 },+ );+ }++ // Validate conditions if provided+ if (validation.data.conditions) {+ const conditionsValidation = validateConditions(+ validation.data.conditions,+ );+ if (!conditionsValidation.valid) {+ return NextResponse.json(+ { error: conditionsValidation.error },+ { status: 400 },+ );+ }+ }++ // Validate actions if provided+ if (validation.data.actions) {+ const actionsValidation = validateActions(validation.data.actions);+ if (!actionsValidation.valid) {+ return NextResponse.json(+ { error: actionsValidation.error },+ { status: 400 },+ );+ }++ // Validate target link exists and belongs to the team+ const routeAction = validation.data.actions.find((a) => a.type === "route");+ if (routeAction && routeAction.targetLinkId) {+ // First get the workflow to get teamId+ const workflow = await prisma.workflow.findUnique({+ where: { id: workflowId },+ select: { teamId: true },+ });++ if (workflow) {+ const targetLink = await prisma.link.findUnique({+ where: {+ id: routeAction.targetLinkId,+ teamId: workflow.teamId,+ },+ });++ if (!targetLink) {+ return NextResponse.json(+ { error: "Target link not found or not accessible" },+ { status: 400 },+ );+ }++ // Update action with target details+ if (targetLink.linkType === "DOCUMENT_LINK" && targetLink.documentId) {+ routeAction.targetDocumentId = targetLink.documentId;+ } else if (+ targetLink.linkType === "DATAROOM_LINK" &&+ targetLink.dataroomId+ ) {+ routeAction.targetDataroomId = targetLink.dataroomId;+ }+ }+ }+ }++ // Check step exists and user has access+ const step = await prisma.workflowStep.findUnique({+ where: { id: stepId, workflowId },+ select: {+ id: true,+ workflow: {+ select: {+ id: true,+ teamId: true,+ team: {+ select: {+ users: { select: { userId: true } },+ },+ },+ },+ },+ },+ });++ if (!step) {+ return NextResponse.json(+ { error: "Step not found" },+ { status: 404 },+ );+ }++ const isUserPartOfTeam = step.workflow.team.users.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );++ if (!isUserPartOfTeam) {+ return NextResponse.json(+ { error: "Unauthorized to modify this step" },+ { status: 403 },+ );+ }++ // Extract emails and domains from conditions to sync with link allowList (if conditions updated)+ let allowListItems: string[] | undefined;+ if (validation.data.conditions) {+ allowListItems = [];+ const conditionsData = validation.data.conditions as any;+ if (conditionsData.items) {+ conditionsData.items.forEach((condition: any) => {+ const values = Array.isArray(condition.value)+ ? condition.value+ : [condition.value];+ if (condition.type === "domain") {+ // Add @ prefix for domains in allowList+ allowListItems!.push(...values.map((v: string) => `@${v}`));+ } else if (condition.type === "email") {+ allowListItems!.push(...values);+ }+ });+ }+ }++ // Get target link ID (either from update or existing step)+ let targetLinkId: string | undefined;+ if (validation.data.actions) {+ const routeAction = validation.data.actions.find((a) => a.type === "route");+ targetLinkId = routeAction?.targetLinkId;+ } else {+ // Get from existing step+ const existingStep = await prisma.workflowStep.findUnique({+ where: { id: stepId },+ select: { actions: true },+ });+ const existingActions = existingStep?.actions as any[];+ const existingRouteAction = existingActions?.find((a) => a.type === "route");+ targetLinkId = existingRouteAction?.targetLinkId;+ }++ // Update step and optionally update link allowList in transaction+ const updates: any[] = [+ prisma.workflowStep.update({+ where: { id: stepId },+ data: validation.data as any,+ }),+ ];++ // If we have allowList updates and a target link, sync the link+ if (allowListItems !== undefined && targetLinkId) {+ updates.push(+ prisma.link.update({+ where: { id: targetLinkId },+ data: { allowList: allowListItems },+ }),+ );+ }++ const [updatedStep] = await prisma.$transaction(updates);++ return NextResponse.json(updatedStep);+ } catch (error) {+ console.error("Error updating workflow step:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}++// DELETE /app/(ee)/api/workflows/[workflowId]/steps/[stepId] - Delete step+export async function DELETE(+ req: NextRequest,+ { params }: { params: { workflowId: string; stepId: string } },+) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { workflowId, stepId } = params;++ // Validate IDs format+ const idsValidation = z.object({+ workflowId: z.string().cuid(),+ stepId: z.string().cuid(),+ }).safeParse({ workflowId, stepId });++ if (!idsValidation.success) {+ return NextResponse.json(+ { error: "Invalid ID format" },+ { status: 400 },+ );+ }++ // Check step exists and user has access+ const step = await prisma.workflowStep.findUnique({+ where: { id: stepId, workflowId },+ select: {+ id: true,+ stepOrder: true,+ workflow: {+ select: {+ id: true,+ teamId: true,+ team: {+ select: {+ users: { select: { userId: true } },+ },+ },+ steps: {+ where: {+ stepOrder: { gt: 0 }, // placeholder, will be updated below+ },+ select: {+ id: true,+ stepOrder: true,+ },+ },+ },+ },+ },+ });++ if (!step) {+ return NextResponse.json(+ { error: "Step not found" },+ { status: 404 },+ );+ }++ const isUserPartOfTeam = step.workflow.team.users.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );++ if (!isUserPartOfTeam) {+ return NextResponse.json(+ { error: "Unauthorized to delete this step" },+ { status: 403 },+ );+ }++ // Get steps that need reordering (those after the deleted step)+ const stepsToReorder = await prisma.workflowStep.findMany({+ where: {+ workflowId,+ stepOrder: { gt: step.stepOrder },+ },+ select: {+ id: true,+ stepOrder: true,+ },+ });++ // Delete step and reorder remaining steps in a transaction+ await prisma.$transaction([+ prisma.workflowStep.delete({+ where: { id: stepId },+ }),+ ...stepsToReorder.map((s) =>+ prisma.workflowStep.update({+ where: { id: s.id },+ data: { stepOrder: s.stepOrder - 1 },+ }),+ ),+ ]);++ return NextResponse.json({ success: true });+ } catch (error) {+ console.error("Error deleting workflow step:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}+diff --git a/app/(ee)/api/workflows/[workflowId]/steps/route.ts b/app/(ee)/api/workflows/[workflowId]/steps/route.tsnew file mode 100644index 00000000..df2e89a1--- /dev/null+++ b/app/(ee)/api/workflows/[workflowId]/steps/route.ts@@ -0,0 +1,375 @@+import { NextRequest, NextResponse } from "next/server";+import { getServerSession } from "next-auth";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { z } from "zod";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import {+ CreateWorkflowStepRequestSchema,+ ReorderStepsRequestSchema,+ formatZodError,+ validateConditions,+ validateActions,+} from "@/ee/features/workflows/lib/validation";+import { ReorderStepsRequest } from "@/ee/features/workflows/lib/types";++// GET /app/(ee)/api/workflows/[workflowId]/steps - List all steps+export async function GET(+ req: NextRequest,+ { params }: { params: { workflowId: string } },+) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { workflowId } = params;++ // Validate workflowId format+ const workflowIdValidation = z.string().cuid().safeParse(workflowId);+ if (!workflowIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid workflowId format" },+ { status: 400 },+ );+ }++ // Check workflow exists and user has access+ const workflow = await prisma.workflow.findUnique({+ where: { id: workflowId },+ select: {+ id: true,+ teamId: true,+ team: {+ select: {+ users: { select: { userId: true } },+ },+ },+ },+ });++ if (!workflow) {+ return NextResponse.json(+ { error: "Workflow not found" },+ { status: 404 },+ );+ }++ const isUserPartOfTeam = workflow.team.users.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );++ if (!isUserPartOfTeam) {+ return NextResponse.json(+ { error: "Unauthorized to access this workflow" },+ { status: 403 },+ );+ }++ // Fetch steps+ const steps = await prisma.workflowStep.findMany({+ where: { workflowId },+ orderBy: { stepOrder: "asc" },+ });++ // Enrich steps with target link details+ const enrichedSteps = await Promise.all(+ steps.map(async (step) => {+ const actions = step.actions as any[];+ const routeAction = actions.find((a) => a.type === "route");++ if (routeAction && routeAction.targetLinkId) {+ const targetLink = await prisma.link.findUnique({+ where: { id: routeAction.targetLinkId },+ select: {+ id: true,+ name: true,+ slug: true,+ domainSlug: true,+ linkType: true,+ },+ });++ return {+ ...step,+ targetLink,+ };+ }++ return step;+ }),+ );++ return NextResponse.json(enrichedSteps);+ } catch (error) {+ console.error("Error fetching workflow steps:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}++// POST /app/(ee)/api/workflows/[workflowId]/steps - Create a new step+export async function POST(+ req: NextRequest,+ { params }: { params: { workflowId: string } },+) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { workflowId } = params;+ const body = await req.json();++ // Validate workflowId format+ const workflowIdValidation = z.string().cuid().safeParse(workflowId);+ if (!workflowIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid workflowId format" },+ { status: 400 },+ );+ }++ // Validate request body+ const validation = CreateWorkflowStepRequestSchema.safeParse(body);+ if (!validation.success) {+ return NextResponse.json(+ {+ error: "Invalid request data",+ details: formatZodError(validation.error),+ },+ { status: 400 },+ );+ }++ const { name, conditions, actions } = validation.data;++ // Validate conditions and actions+ const conditionsValidation = validateConditions(conditions);+ if (!conditionsValidation.valid) {+ return NextResponse.json(+ { error: conditionsValidation.error },+ { status: 400 },+ );+ }++ const actionsValidation = validateActions(actions);+ if (!actionsValidation.valid) {+ return NextResponse.json(+ { error: actionsValidation.error },+ { status: 400 },+ );+ }++ // Check workflow exists and user has access+ const workflow = await prisma.workflow.findUnique({+ where: { id: workflowId },+ select: {+ id: true,+ teamId: true,+ team: {+ select: {+ users: { select: { userId: true } },+ },+ },+ steps: {+ select: { stepOrder: true },+ orderBy: { stepOrder: "desc" },+ take: 1,+ },+ },+ });++ if (!workflow) {+ return NextResponse.json(+ { error: "Workflow not found" },+ { status: 404 },+ );+ }++ const isUserPartOfTeam = workflow.team.users.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );++ if (!isUserPartOfTeam) {+ return NextResponse.json(+ { error: "Unauthorized to modify this workflow" },+ { status: 403 },+ );+ }++ // Validate target link exists and belongs to the team+ const routeAction = actions.find((a) => a.type === "route");+ if (routeAction && routeAction.targetLinkId) {+ const targetLink = await prisma.link.findUnique({+ where: {+ id: routeAction.targetLinkId,+ teamId: workflow.teamId,+ },+ });++ if (!targetLink) {+ return NextResponse.json(+ { error: "Target link not found or not accessible" },+ { status: 400 },+ );+ }++ // Update action with target details+ if (targetLink.linkType === "DOCUMENT_LINK" && targetLink.documentId) {+ routeAction.targetDocumentId = targetLink.documentId;+ } else if (+ targetLink.linkType === "DATAROOM_LINK" &&+ targetLink.dataroomId+ ) {+ routeAction.targetDataroomId = targetLink.dataroomId;+ }+ }++ // Calculate next step order+ const maxStepOrder = workflow.steps[0]?.stepOrder ?? -1;+ const nextStepOrder = maxStepOrder + 1;++ // Extract emails and domains from conditions to sync with link allowList+ const allowListItems: string[] = [];+ if (conditionsValidation.data.items) {+ conditionsValidation.data.items.forEach((condition: any) => {+ const values = Array.isArray(condition.value)+ ? condition.value+ : [condition.value];+ if (condition.type === "domain") {+ // Add @ prefix for domains in allowList+ allowListItems.push(...values.map((v: string) => `@${v}`));+ } else if (condition.type === "email") {+ allowListItems.push(...values);+ }+ });+ }++ // Create step and update target link's allowList in transaction+ const [newStep] = await prisma.$transaction([+ prisma.workflowStep.create({+ data: {+ workflowId,+ name,+ stepOrder: nextStepOrder,+ stepType: "ROUTER",+ conditions: conditionsValidation.data as any,+ actions: actionsValidation.data as any,+ },+ }),+ // Update target link's allowList+ prisma.link.update({+ where: { id: routeAction.targetLinkId },+ data: {+ allowList: allowListItems,+ },+ }),+ ]);++ return NextResponse.json(newStep, { status: 201 });+ } catch (error) {+ console.error("Error creating workflow step:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}++// PUT /app/(ee)/api/workflows/[workflowId]/steps - Reorder steps+export async function PUT(+ req: NextRequest,+ { params }: { params: { workflowId: string } },+) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const { workflowId } = params;+ const body = await req.json();++ // Validate workflowId format+ const workflowIdValidation = z.string().cuid().safeParse(workflowId);+ if (!workflowIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid workflowId format" },+ { status: 400 },+ );+ }++ // Validate request body+ const validation = ReorderStepsRequestSchema.safeParse(body);+ if (!validation.success) {+ return NextResponse.json(+ {+ error: "Invalid request data",+ details: formatZodError(validation.error),+ },+ { status: 400 },+ );+ }++ // Check workflow exists and user has access+ const workflow = await prisma.workflow.findUnique({+ where: { id: workflowId },+ select: {+ id: true,+ teamId: true,+ team: {+ select: {+ users: { select: { userId: true } },+ },+ },+ },+ });++ if (!workflow) {+ return NextResponse.json(+ { error: "Workflow not found" },+ { status: 404 },+ );+ }++ const isUserPartOfTeam = workflow.team.users.some(+ (user) => user.userId === (session.user as CustomUser).id,+ );++ if (!isUserPartOfTeam) {+ return NextResponse.json(+ { error: "Unauthorized to modify this workflow" },+ { status: 403 },+ );+ }++ // Update step orders in a transaction+ await prisma.$transaction(+ validation.data.steps.map((step) =>+ prisma.workflowStep.update({+ where: {+ id: step.stepId,+ workflowId, // Ensure step belongs to this workflow+ },+ data: {+ stepOrder: step.stepOrder,+ },+ }),+ ),+ );++ return NextResponse.json({ success: true });+ } catch (error) {+ console.error("Error reordering workflow steps:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}+diff --git a/app/(ee)/api/workflows/route.ts b/app/(ee)/api/workflows/route.tsnew file mode 100644index 00000000..3467aac5--- /dev/null+++ b/app/(ee)/api/workflows/route.ts@@ -0,0 +1,259 @@+import { NextRequest, NextResponse } from "next/server";++import {+ CreateWorkflowRequestSchema,+ formatZodError,+} from "@/ee/features/workflows/lib/validation";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth";+import { z } from "zod";++import { getFeatureFlags } from "@/lib/featureFlags";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++// GET /app/(ee)/api/workflows?teamId=xxx - List all workflows for a team+export async function GET(req: NextRequest) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const searchParams = req.nextUrl.searchParams;+ const teamId = searchParams.get("teamId");++ if (!teamId) {+ return NextResponse.json(+ { error: "teamId parameter is required" },+ { status: 400 },+ );+ }++ // Validate teamId format+ const teamIdValidation = z.string().cuid().safeParse(teamId);+ if (!teamIdValidation.success) {+ return NextResponse.json(+ { error: "Invalid teamId format" },+ { status: 400 },+ );+ }++ // Check user is part of the team+ const teamAccess = await prisma.userTeam.findUnique({+ where: {+ userId_teamId: {+ userId: (session.user as CustomUser).id,+ teamId: teamId,+ },+ },+ });++ if (!teamAccess) {+ return NextResponse.json(+ { error: "Unauthorized to access this team" },+ { status: 403 },+ );+ }++ // Fetch workflows with entry link and step count+ const workflows = await prisma.workflow.findMany({+ where: { teamId },+ include: {+ entryLink: {+ select: {+ id: true,+ slug: true,+ domainSlug: true,+ },+ },+ _count: {+ select: {+ steps: true,+ executions: true,+ },+ },+ },+ orderBy: { createdAt: "desc" },+ });++ return NextResponse.json(workflows);+ } catch (error) {+ console.error("Error fetching workflows:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}++// POST /app/(ee)/api/workflows - Create a new workflow+export async function POST(req: NextRequest) {+ try {+ const session = await getServerSession(authOptions);+ if (!session) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const userId = (session.user as CustomUser).id;+ const body = await req.json();++ // Validate request body+ const validation = CreateWorkflowRequestSchema.safeParse(body);+ if (!validation.success) {+ return NextResponse.json(+ {+ error: "Invalid request data",+ details: formatZodError(validation.error),+ },+ { status: 400 },+ );+ }++ const { name, description, teamId, domain, slug } = validation.data;++ // Check user is part of the team+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: { userId },+ },+ },+ select: {+ id: true,+ plan: true,+ },+ });++ if (!team) {+ return NextResponse.json(+ { error: "Team not found or unauthorized" },+ { status: 403 },+ );+ }++ // Check if workflows feature flag is enabled+ const featureFlags = await getFeatureFlags({ teamId });+ if (!featureFlags.workflows) {+ return NextResponse.json(+ { error: "This feature is not available for your team" },+ { status: 403 },+ );+ }++ // Check plan - require Business or DataRooms plan+ if (team.plan === "free" || team.plan === "pro") {+ return NextResponse.json(+ {+ error: "Workflows require a Business or Data Rooms plan",+ requiresUpgrade: true,+ },+ { status: 403 },+ );+ }++ // Validate domain and slug+ let domainId: string | null = null;+ let domainSlug: string | null = null;++ if (domain && slug) {+ // Check if domain exists and belongs to team+ const domainRecord = await prisma.domain.findUnique({+ where: {+ slug: domain,+ teamId: teamId,+ },+ select: { id: true, slug: true },+ });++ if (!domainRecord) {+ return NextResponse.json(+ { error: "Domain not found or not associated with this team" },+ { status: 400 },+ );+ }++ domainId = domainRecord.id;+ domainSlug = domainRecord.slug;++ // Check if slug is already in use on this domain+ const existingLink = await prisma.link.findUnique({+ where: {+ domainSlug_slug: {+ slug: slug,+ domainSlug: domain,+ },+ },+ });++ if (existingLink) {+ return NextResponse.json(+ { error: "This slug is already in use on the selected domain" },+ { status: 400 },+ );+ }+ }++ // Create workflow with entry link in a transaction+ const workflow = await prisma.$transaction(async (tx) => {+ // Create entry link+ const entryLink = await tx.link.create({+ data: {+ linkType: "WORKFLOW_LINK",+ teamId,+ name: `${name} - Entry Link`,+ slug: slug || null,+ domainId: domainId,+ domainSlug: domainSlug,+ emailProtected: true, // Workflows always require email+ emailAuthenticated: true, // Workflows always require OTP+ allowDownload: false,+ enableNotification: false,+ },+ });++ // Create workflow+ const newWorkflow = await tx.workflow.create({+ data: {+ name,+ description,+ teamId,+ entryLinkId: entryLink.id,+ isActive: true,+ },+ include: {+ entryLink: {+ select: {+ id: true,+ slug: true,+ domainSlug: true,+ },+ },+ },+ });++ return newWorkflow;+ });++ // Build entry URL+ const entryUrl =+ workflow.entryLink.domainSlug && workflow.entryLink.slug+ ? `https://${workflow.entryLink.domainSlug}/${workflow.entryLink.slug}`+ : `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${workflow.entryLink.id}`;++ return NextResponse.json(+ {+ ...workflow,+ entryUrl,+ },+ { status: 201 },+ );+ } catch (error) {+ console.error("Error creating workflow:", error);+ return NextResponse.json(+ { error: "Internal server error" },+ { status: 500 },+ );+ }+}diff --git a/components/sidebar/app-sidebar.tsx b/components/sidebar/app-sidebar.tsxindex 5b72d6f0..d06d00b5 100644--- a/components/sidebar/app-sidebar.tsx+++ b/components/sidebar/app-sidebar.tsx@@ -17,8 +17,10 @@ import {HouseIcon,Loader,ServerIcon,+ WorkflowIcon,} from "lucide-react";+import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";import { usePlan } from "@/lib/swr/use-billing";import useDatarooms from "@/lib/swr/use-datarooms";import useLimits from "@/lib/swr/use-limits";@@ -71,6 +73,9 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {enabled: !!currentTeam?.id,});+ // Check feature flags+ const { features } = useFeatureFlags();+// Fetch datarooms for the current teamconst { datarooms } = useDatarooms();@@ -147,6 +152,16 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {plan: PlanEnum.Pro,highlightItem: ["visitors"],},+ {+ title: "Workflows",+ url: "/workflows",+ icon: WorkflowIcon,+ current: router.pathname.includes("/workflows"),+ disabled: !features?.workflows,+ trigger: "sidebar_workflows",+ plan: PlanEnum.DataRoomsPlus,+ highlightItem: ["workflows"],+ },{title: "Branding",url: "/branding",@@ -200,6 +215,15 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {],};+ // Filter out items that should be hidden based on feature flags+ const filteredNavMain = data.navMain.filter((item) => {+ // Hide workflows if feature flag is not enabled+ if (item.title === "Workflows" && !features?.workflows) {+ return false;+ }+ return true;+ });+return (<SidebarclassName="bg-gray-50 dark:bg-black"@@ -244,7 +268,7 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {)}</SidebarHeader><SidebarContent>- <NavMain items={data.navMain} />+ <NavMain items={filteredNavMain} /></SidebarContent><SidebarFooter><SidebarMenu className="group-data-[collapsible=icon]:hidden">diff --git a/ee/features/workflows/README.md b/ee/features/workflows/README.mdnew file mode 100644index 00000000..3470c197--- /dev/null+++ b/ee/features/workflows/README.md@@ -0,0 +1,73 @@+# Workflow Routing System++Enterprise feature for routing visitors to different links based on email/domain matching.++## Structure++```+ee/features/workflows/+├── components/ # UI components+│ ├── index.ts # Component exports+│ ├── workflow-list.tsx+│ ├── workflow-empty-state.tsx+│ ├── workflow-header.tsx+│ ├── step-list.tsx+│ ├── step-form-dialog.tsx+│ └── workflow-access-view.tsx+├── lib/ # Core logic+│ ├── types.ts # Zod schemas & TypeScript types+│ ├── validation.ts # Validation helpers+│ └── engine.ts # Workflow execution engine+└── index.ts # Feature exports++pages/workflows/+├── index.tsx # List all workflows+├── new.tsx # Create new workflow+└── [id].tsx # Workflow detail & step builder++app/(ee)/api/+├── workflows/+│ ├── route.ts # List & create workflows+│ ├── [workflowId]/+│ │ ├── route.ts # Get, update, delete workflow+│ │ ├── steps/+│ │ │ ├── route.ts # List, create, reorder steps+│ │ │ └── [stepId]/route.ts # Update, delete step+│ │ └── executions/route.ts # List execution history+└── workflow-entry/+ ├── [entryLinkId]/+ │ ├── verify/route.ts # Send OTP (by linkId)+ │ └── access/route.ts # Verify OTP & execute (by linkId)+ └── domains/[...domainSlug]/+ ├── verify/route.ts # Send OTP (by domain/slug)+ └── access/route.ts # Verify OTP & execute (by domain/slug)+```++## Features++- **Single Entry Point**: One URL routes to multiple datarooms/documents+- **Email-Based Routing**: Match exact emails or email domains+- **Priority-Based**: Steps execute in order, first match wins+- **Custom Domains**: Support for branded entry links+- **Security**: OTP verification, Redis sessions, rate limiting+- **Audit Trail**: Complete execution logging++## Usage++### Admin Flow+1. Navigate to `/workflows`+2. Create workflow with entry link (domain + slug)+3. Add routing steps with email/domain conditions+4. Activate workflow++### Visitor Flow+1. Access entry link (e.g., `docs.example.com/dashboard`)+2. Enter email address+3. Receive & enter OTP code+4. Automatically routed to matching dataroom/document link++## Plan Requirements++- Business or Data Rooms plan required+- Feature flag: `workflows` must be enabled+diff --git a/ee/features/workflows/components/index.ts b/ee/features/workflows/components/index.tsnew file mode 100644index 00000000..4d6738ed--- /dev/null+++ b/ee/features/workflows/components/index.ts@@ -0,0 +1,7 @@+export { WorkflowList } from "./workflow-list";+export { WorkflowEmptyState } from "./workflow-empty-state";+export { WorkflowHeader } from "./workflow-header";+export { StepList } from "./step-list";+export { StepFormDialog } from "./step-form-dialog";+export { default as WorkflowAccessView } from "./workflow-access-view";+diff --git a/ee/features/workflows/components/step-form-dialog.tsx b/ee/features/workflows/components/step-form-dialog.tsxnew file mode 100644index 00000000..b01251be--- /dev/null+++ b/ee/features/workflows/components/step-form-dialog.tsx@@ -0,0 +1,356 @@+import { useState } from "react";++import { toast } from "sonner";++import { cn } from "@/lib/utils";++import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { SingleSelect } from "@/components/ui/single-select";+import { Textarea } from "@/components/ui/textarea";++interface WorkflowStep {+ id: string;+ name: string;+ stepOrder: number;+ conditions: {+ logic: "AND" | "OR";+ items: Array<{+ type: "email" | "domain";+ operator: string;+ value: string | string[];+ }>;+ };+ actions: Array<{+ type: "route";+ targetLinkId: string;+ }>;+}++interface Link {+ id: string;+ name: string | null;+ slug: string | null;+ domainSlug: string | null;+ linkType: "DOCUMENT_LINK" | "DATAROOM_LINK";+ documentId: string | null;+ dataroomId: string | null;+ allowList: string[]; // Pre-populate from link+ resourceName: string | null; // Document or Dataroom name+ displayName: string; // Human-readable label+}++interface StepFormDialogProps {+ workflowId: string;+ step: WorkflowStep | null;+ links: Link[];+ open: boolean;+ onClose: () => void;+ onSuccess: () => void;+}++export function StepFormDialog({+ workflowId,+ step,+ links,+ open,+ onClose,+ onSuccess,+}: StepFormDialogProps) {+ const [name, setName] = useState(step?.name || "");+ const [targetLinkId, setTargetLinkId] = useState(+ step?.actions[0]?.targetLinkId || "",+ );+ const [allowListInput, setAllowListInput] = useState(() => {+ // Pre-populate from existing step when editing+ if (step && step.conditions.items.length > 0) {+ const allValues: string[] = [];+ step.conditions.items.forEach((condition) => {+ const values = Array.isArray(condition.value)+ ? condition.value+ : [condition.value];+ if (condition.type === "domain") {+ // Prefix domains with @+ allValues.push(...values.map((v) => `@${v}`));+ } else {+ // Email addresses as-is+ allValues.push(...values);+ }+ });+ return allValues.join("\n");+ }+ return "";+ });+ const [isSubmitting, setIsSubmitting] = useState(false);++ // When link is selected, pre-fill allowList+ const handleLinkChange = (linkId: string) => {+ setTargetLinkId(linkId);+ const selectedLink = links.find((l) => l.id === linkId);+ if (selectedLink && selectedLink.allowList.length > 0) {+ setAllowListInput(selectedLink.allowList.join("\n"));+ // Auto-fill step name if empty+ if (!name && selectedLink.resourceName) {+ setName(`Route to ${selectedLink.resourceName}`);+ }+ } else {+ setAllowListInput("");+ }+ };++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();++ if (!name.trim()) {+ toast.error("Step name is required");+ return;+ }++ if (!targetLinkId) {+ toast.error("Target link is required");+ return;+ }++ if (!allowListInput.trim()) {+ toast.error("At least one email or domain is required");+ return;+ }++ setIsSubmitting(true);++ try {+ // Parse allowList input - separate emails and domains+ const lines = allowListInput+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0);++ const emails: string[] = [];+ const domains: string[] = [];++ lines.forEach((line) => {+ if (line.startsWith("@")) {+ // Domain (remove @ prefix)+ domains.push(line.substring(1));+ } else {+ // Email address+ emails.push(line);+ }+ });++ // Build conditions array+ const conditionItems = [];+ if (emails.length > 0) {+ conditionItems.push({+ type: "email",+ operator: "in_list",+ value: emails,+ });+ }+ if (domains.length > 0) {+ conditionItems.push({+ type: "domain",+ operator: "in_list",+ value: domains,+ });+ }++ const payload = {+ name: name.trim(),+ conditions: {+ logic: "OR", // Match ANY email or domain+ items: conditionItems,+ },+ actions: [+ {+ type: "route",+ targetLinkId,+ },+ ],+ };++ const url = step+ ? `/api/workflows/${workflowId}/steps/${step.id}`+ : `/api/workflows/${workflowId}/steps`;++ const response = await fetch(url, {+ method: step ? "PATCH" : "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(payload),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to save step");+ }++ toast.success(step ? "Step updated" : "Step created");+ onSuccess();+ } catch (error) {+ console.error("Error saving step:", error);+ toast.error(+ error instanceof Error ? error.message : "Failed to save step",+ );+ } finally {+ setIsSubmitting(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={onClose}>+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>{step ? "Edit Step" : "Add Step"}</DialogTitle>+ <DialogDescription>+ Configure the routing condition and target link+ </DialogDescription>+ </DialogHeader>++ <form onSubmit={handleSubmit} className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="step-name">Step Name *</Label>+ <Input+ id="step-name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="e.g., Route Company A"+ required+ />+ </div>++ <div className="space-y-2">+ <Label htmlFor="target-link">Route to Link *</Label>+ <SingleSelect+ options={links.map((link) => ({+ value: link.id,+ label: link.displayName,+ searchableText: `${link.displayName} ${link.resourceName || ""} ${link.slug || ""} ${link.domainSlug || ""} ${link.id}`,+ meta: link,+ }))}+ value={targetLinkId}+ onValueChange={handleLinkChange}+ placeholder="Select a link..."+ searchPlaceholder="Search links by name, slug, domain, or ID..."+ emptyText="No links found."+ className="w-full"+ renderOption={(option, isSelected) => {+ const link = option.meta as Link;+ if (!link) return null;++ return (+ <div className="flex w-full flex-col gap-1.5">+ <div className="flex items-center gap-2">+ <span className="font-medium">{link.displayName}</span>+ <Badge+ variant="outline"+ className={cn(+ "text-xs",+ isSelected && "bg-primary/10 text-primary",+ )}+ >+ {link.linkType === "DOCUMENT_LINK"+ ? "Document"+ : "Dataroom"}+ </Badge>+ </div>+ {link.resourceName && (+ <span className="text-xs text-muted-foreground">+ {link.resourceName}+ </span>+ )}+ {link.domainSlug && link.slug && (+ <span className="font-mono text-xs text-muted-foreground">+ {link.domainSlug}/{link.slug}+ </span>+ )}+ {!link.domainSlug && link.slug && (+ <span className="font-mono text-xs text-muted-foreground">+ papermark.io/{link.slug}+ </span>+ )}+ <span className="font-mono text-xs text-muted-foreground">+ ID: {link.id.substring(0, 15)}...+ </span>+ </div>+ );+ }}+ renderTrigger={(selectedOption) => {+ if (!selectedOption) return null;+ const link = selectedOption.meta as Link;+ if (!link) return selectedOption.label;++ return (+ <div className="flex w-full flex-col gap-1 overflow-hidden">+ <div className="flex items-center gap-2">+ <span className="truncate font-medium text-foreground">+ {link.displayName}+ </span>+ <Badge variant="outline" className="shrink-0 text-xs">+ {link.linkType === "DOCUMENT_LINK"+ ? "Document"+ : "Dataroom"}+ </Badge>+ </div>+ {link.resourceName && (+ <div className="flex truncate text-xs text-muted-foreground">+ {link.resourceName}+ </div>+ )}+ </div>+ );+ }}+ />+ </div>++ <div className="space-y-2">+ <Label htmlFor="allow-list">Allowed Emails & Domains *</Label>+ <Textarea+ id="allow-list"+ value={allowListInput}+ onChange={(e) => setAllowListInput(e.target.value)}+ placeholder={`Enter allowed emails/domains, one per line:+ rows={6}+ required+ />+ <p className="text-xs text-muted-foreground">+ Prefix domains with @ (e.g., @company.com). One entry per line.+ </p>+ </div>++ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={onClose}+ disabled={isSubmitting}+ >+ Cancel+ </Button>+ <Button type="submit" disabled={isSubmitting}>+ {isSubmitting+ ? "Saving..."+ : step+ ? "Update Step"+ : "Create Step"}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/ee/features/workflows/components/step-list.tsx b/ee/features/workflows/components/step-list.tsxnew file mode 100644index 00000000..83b6de67--- /dev/null+++ b/ee/features/workflows/components/step-list.tsx@@ -0,0 +1,111 @@+import { PencilIcon, PlusIcon, TrashIcon } from "lucide-react";++import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";++interface WorkflowStep {+ id: string;+ name: string;+ stepOrder: number;+ conditions: {+ logic: "AND" | "OR";+ items: Array<{+ type: "email" | "domain";+ operator: string;+ value: string | string[];+ }>;+ };+ actions: Array<{+ type: "route";+ targetLinkId: string;+ }>;+ targetLink?: {+ id: string;+ name: string | null;+ slug: string | null;+ linkType: string;+ };+}++interface StepListProps {+ steps: WorkflowStep[];+ onAddStep: () => void;+ onEditStep: (step: WorkflowStep) => void;+ onDeleteStep: (stepId: string) => void;+}++export function StepList({+ steps,+ onAddStep,+ onEditStep,+ onDeleteStep,+}: StepListProps) {+ return (+ <div>+ <div className="mb-4 flex items-center justify-between">+ <div>+ <h3 className="text-lg font-medium">Routing Steps</h3>+ <p className="text-sm text-muted-foreground">+ Steps are evaluated in order (priority-based)+ </p>+ </div>+ <Button onClick={onAddStep}>+ <PlusIcon className="mr-2 h-4 w-4" />+ Add Step+ </Button>+ </div>++ {steps.length === 0 ? (+ <div className="rounded-lg border border-dashed py-12 text-center">+ <p className="text-sm text-muted-foreground">+ No routing steps yet. Add your first step to start routing visitors.+ </p>+ </div>+ ) : (+ <div className="space-y-3">+ {steps.map((step, index) => (+ <div key={step.id} className="rounded-lg border bg-card p-4">+ <div className="flex items-start justify-between">+ <div className="flex-1">+ <div className="flex items-center gap-2">+ <Badge variant="outline">Step {index + 1}</Badge>+ <span className="font-medium">{step.name}</span>+ </div>+ <div className="mt-2 space-y-1 text-sm text-muted-foreground">+ <p>+ <strong>If:</strong> Match{" "}+ {step.conditions.logic === "AND" ? "all" : "any"} of{" "}+ {step.conditions.items.length} condition(s)+ </p>+ {step.targetLink && (+ <p>+ <strong>Then:</strong> Route to{" "}+ {step.targetLink.name || step.targetLink.slug || "link"}+ </p>+ )}+ </div>+ </div>+ <div className="flex gap-2">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => onEditStep(step)}+ >+ <PencilIcon className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => onDeleteStep(step.id)}+ >+ <TrashIcon className="h-4 w-4" />+ </Button>+ </div>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/ee/features/workflows/components/workflow-access-view.tsx b/ee/features/workflows/components/workflow-access-view.tsxnew file mode 100644index 00000000..95636804--- /dev/null+++ b/ee/features/workflows/components/workflow-access-view.tsx@@ -0,0 +1,203 @@+import { useState } from "react";++import NotFound from "@/pages/404";+import { Brand, DataroomBrand } from "@prisma/client";+import { toast } from "sonner";++import AccessForm, {+ DEFAULT_ACCESS_FORM_TYPE,+} from "@/components/view/access-form";+import EmailVerificationMessage from "@/components/view/access-form/email-verification-form";++interface WorkflowAccessViewProps {+ entryLinkId: string;+ domain?: string;+ slug?: string;+ brand?: Partial<Brand> | Partial<DataroomBrand> | null;+}++export default function WorkflowAccessView({+ entryLinkId,+ domain,+ slug,+ brand,+}: WorkflowAccessViewProps) {+ const [data, setData] = useState<DEFAULT_ACCESS_FORM_TYPE>({+ email: "",+ password: "",+ });+ const [code, setCode] = useState<string | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [showVerification, setShowVerification] = useState(false);+ const [isInvalidCode, setIsInvalidCode] = useState(false);+ const [showNotFound, setShowNotFound] = useState(false);++ // Build API endpoints based on whether we have domain/slug or just linkId+ const verifyEndpoint =+ domain && slug+ ? `/api/workflow-entry/domains/${domain}/${slug}/verify`+ : `/api/workflow-entry/link/${entryLinkId}/verify`;++ const accessEndpoint =+ domain && slug+ ? `/api/workflow-entry/domains/${domain}/${slug}/access`+ : `/api/workflow-entry/link/${entryLinkId}/access`;++ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {+ e.preventDefault();++ if (!data.email) {+ toast.error("Email is required");+ return;+ }++ // If we're in verification mode, verify the code+ if (showVerification && code) {+ await handleVerifyCode();+ return;+ }++ // Otherwise, request OTP+ await handleRequestOTP();+ };++ const handleRequestOTP = async () => {+ setIsLoading(true);++ try {+ const response = await fetch(verifyEndpoint, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ email: data.email,+ }),+ });++ const result = await response.json();++ if (!response.ok) {+ // Show 404 for inactive/deleted workflows+ if (response.status === 403 && result.error?.includes("inactive")) {+ setShowNotFound(true);+ return;+ }+ if (response.status === 404) {+ setShowNotFound(true);+ return;+ }+ throw new Error(result.error || "Failed to send verification code");+ }++ setShowVerification(true);+ toast.success("Verification code sent to your email");+ } catch (error) {+ console.error("Error requesting OTP:", error);+ toast.error(+ error instanceof Error+ ? error.message+ : "Failed to send verification code",+ );+ } finally {+ setIsLoading(false);+ }+ };++ const handleVerifyCode = async () => {+ if (!code || code.length !== 6) {+ setIsInvalidCode(true);+ return;+ }++ setIsLoading(true);+ setIsInvalidCode(false);++ try {+ const response = await fetch(accessEndpoint, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ email: data.email,+ code: code,+ }),+ });++ const result = await response.json();++ console.log("--------------------------------");+ console.log("result", result);+ console.log("--------------------------------");++ if (!response.ok) {+ // Show 404 for inactive/deleted workflows+ if (response.status === 403 && result.error?.includes("inactive")) {+ setShowNotFound(true);+ return;+ }+ if (response.status === 404) {+ setShowNotFound(true);+ return;+ }+ if (result.resetVerification) {+ // Reset to email entry if verification expired/invalid+ setShowVerification(false);+ setCode(null);+ }+ throw new Error(result.error || "Failed to verify code");+ }++ // Redirect to target URL+ if (result.targetUrl) {+ window.location.href = result.targetUrl;+ } else {+ throw new Error("No target URL provided");+ }+ } catch (error) {+ console.error("Error verifying code:", error);+ setIsInvalidCode(true);+ toast.error(+ error instanceof Error ? error.message : "Failed to verify code",+ );+ } finally {+ setIsLoading(false);+ }+ };++ if (showNotFound) {+ return <NotFound message="Sorry, this workflow is no longer available." />;+ }++ if (showVerification) {+ return (+ <EmailVerificationMessage+ onSubmitHandler={handleSubmit}+ data={data}+ isLoading={isLoading}+ code={code}+ setCode={setCode}+ isInvalidCode={isInvalidCode}+ setIsInvalidCode={setIsInvalidCode}+ brand={brand}+ />+ );+ }++ return (+ <AccessForm+ data={data}+ email={data.email}+ setData={setData}+ onSubmitHandler={handleSubmit}+ brand={brand}+ requireEmail={true}+ requirePassword={false}+ isLoading={isLoading}+ linkId={entryLinkId}+ disableEditEmail={false}+ linkWelcomeMessage="Enter your email to access the workflow"+ />+ );+}diff --git a/ee/features/workflows/components/workflow-empty-state.tsx b/ee/features/workflows/components/workflow-empty-state.tsxnew file mode 100644index 00000000..37031c74--- /dev/null+++ b/ee/features/workflows/components/workflow-empty-state.tsx@@ -0,0 +1,26 @@+import { WorkflowIcon } from "lucide-react";++interface WorkflowEmptyStateProps {+ title: string;+ description: string;+}++export function WorkflowEmptyState({+ title,+ description,+}: WorkflowEmptyStateProps) {+ return (+ <div className="flex flex-col items-center justify-center space-y-4 rounded-lg border border-dashed py-12">+ <div className="rounded-full bg-muted p-3">+ <WorkflowIcon className="h-6 w-6 text-muted-foreground" />+ </div>+ <div className="text-center">+ <h3 className="font-medium">{title}</h3>+ <p className="mt-1 max-w-sm text-sm text-muted-foreground">+ {description}+ </p>+ </div>+ </div>+ );+}+diff --git a/ee/features/workflows/components/workflow-header.tsx b/ee/features/workflows/components/workflow-header.tsxnew file mode 100644index 00000000..67ca657d--- /dev/null+++ b/ee/features/workflows/components/workflow-header.tsx@@ -0,0 +1,172 @@+import { useState } from "react";+import { useRouter } from "next/router";+import { toast } from "sonner";+import { TrashIcon, CopyIcon } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { Label } from "@/components/ui/label";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";++interface WorkflowHeaderProps {+ workflowId: string;+ name: string;+ description: string | null;+ isActive: boolean;+ entryUrl: string;+ onUpdate: () => void;+}++export function WorkflowHeader({+ workflowId,+ name,+ description,+ isActive,+ entryUrl,+ onUpdate,+}: WorkflowHeaderProps) {+ const router = useRouter();+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);+ const [isDeleting, setIsDeleting] = useState(false);++ const handleToggleActive = async () => {+ try {+ const response = await fetch(`/api/workflows/${workflowId}`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ isActive: !isActive,+ }),+ });++ if (!response.ok) {+ throw new Error("Failed to update workflow");+ }++ onUpdate();+ toast.success(isActive ? "Workflow deactivated" : "Workflow activated");+ } catch (error) {+ toast.error("Failed to update workflow");+ }+ };++ const handleDeleteWorkflow = async () => {+ setIsDeleting(true);++ try {+ const response = await fetch(`/api/workflows/${workflowId}`, {+ method: "DELETE",+ });++ if (!response.ok) {+ throw new Error("Failed to delete workflow");+ }++ toast.success("Workflow deleted");+ router.push("/workflows");+ } catch (error) {+ toast.error("Failed to delete workflow");+ setIsDeleting(false);+ }+ };++ const copyToClipboard = (text: string) => {+ navigator.clipboard.writeText(text);+ toast.success("Copied to clipboard");+ };++ return (+ <>+ <div className="space-y-6">+ {/* Header */}+ <div className="flex items-start justify-between">+ <div>+ <h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">+ {name}+ </h1>+ {description && (+ <p className="mt-1 text-sm text-muted-foreground">+ {description}+ </p>+ )}+ </div>+ <div className="flex items-center gap-3">+ <div className="flex items-center gap-2">+ <Label htmlFor="active-toggle" className="text-sm">+ {isActive ? "Active" : "Inactive"}+ </Label>+ <Switch+ id="active-toggle"+ checked={isActive}+ onCheckedChange={handleToggleActive}+ />+ </div>+ <Button+ variant="destructive"+ size="sm"+ onClick={() => setShowDeleteDialog(true)}+ >+ <TrashIcon className="mr-2 h-4 w-4" />+ Delete+ </Button>+ </div>+ </div>++ {/* Entry Link */}+ <div className="rounded-lg border bg-card p-4">+ <h3 className="text-sm font-medium">Entry Link</h3>+ <div className="mt-2 flex items-center gap-2">+ <code className="flex-1 rounded bg-muted px-3 py-2 text-sm">+ {entryUrl}+ </code>+ <Button+ variant="outline"+ size="sm"+ onClick={() => copyToClipboard(entryUrl)}+ >+ <CopyIcon className="h-4 w-4" />+ </Button>+ </div>+ </div>+ </div>++ {/* Delete Dialog */}+ <Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Delete Workflow</DialogTitle>+ <DialogDescription>+ Are you sure you want to delete this workflow? This action cannot+ be undone.+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={() => setShowDeleteDialog(false)}+ disabled={isDeleting}+ >+ Cancel+ </Button>+ <Button+ variant="destructive"+ onClick={handleDeleteWorkflow}+ disabled={isDeleting}+ >+ {isDeleting ? "Deleting..." : "Delete Workflow"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}+diff --git a/ee/features/workflows/components/workflow-list.tsx b/ee/features/workflows/components/workflow-list.tsxnew file mode 100644index 00000000..1791534d--- /dev/null+++ b/ee/features/workflows/components/workflow-list.tsx@@ -0,0 +1,75 @@+import Link from "next/link";+import { Badge } from "@/components/ui/badge";+import { timeAgo } from "@/lib/utils";++interface Workflow {+ id: string;+ name: string;+ description: string | null;+ isActive: boolean;+ createdAt: string;+ entryLink: {+ id: string;+ slug: string | null;+ domainSlug: string | null;+ };+ _count: {+ steps: number;+ executions: number;+ };+}++interface WorkflowListProps {+ workflows: Workflow[];+}++export function WorkflowList({ workflows }: WorkflowListProps) {+ const getEntryUrl = (workflow: Workflow) => {+ if (workflow.entryLink.domainSlug && workflow.entryLink.slug) {+ return `https://${workflow.entryLink.domainSlug}/${workflow.entryLink.slug}`;+ }+ return `${process.env.NEXT_PUBLIC_MARKETING_URL || "https://www.papermark.io"}/view/${workflow.entryLink.id}`;+ };++ return (+ <div className="grid grid-cols-1 gap-3">+ {workflows.map((workflow) => (+ <Link+ key={workflow.id}+ href={`/workflows/${workflow.id}`}+ className="group rounded-xl border bg-card p-5 transition-all hover:border-gray-400 hover:shadow-sm dark:border-gray-700 dark:bg-secondary dark:hover:border-gray-600"+ >+ <div className="flex items-start justify-between">+ <div className="flex-1">+ <div className="flex items-center gap-2">+ <h4 className="font-semibold text-foreground group-hover:text-primary">+ {workflow.name}+ </h4>+ {!workflow.isActive && (+ <Badge variant="secondary">Inactive</Badge>+ )}+ </div>+ {workflow.description && (+ <p className="mt-1 text-sm text-muted-foreground">+ {workflow.description}+ </p>+ )}+ <div className="mt-3 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">+ <span className="font-mono text-xs">+ {getEntryUrl(workflow)}+ </span>+ <span>•</span>+ <span>{workflow._count.steps} steps</span>+ <span>•</span>+ <span>{workflow._count.executions} executions</span>+ <span>•</span>+ <span>Created {timeAgo(workflow.createdAt)}</span>+ </div>+ </div>+ </div>+ </Link>+ ))}+ </div>+ );+}+diff --git a/ee/features/workflows/index.ts b/ee/features/workflows/index.tsnew file mode 100644index 00000000..71cb6d60--- /dev/null+++ b/ee/features/workflows/index.ts@@ -0,0 +1,10 @@+// Workflow Components+export * from "./components";++// Workflow Engine+export { WorkflowEngine } from "./lib/engine";++// Workflow Types & Validation+export * from "./lib/types";+export * from "./lib/validation";+diff --git a/ee/features/workflows/lib/engine.ts b/ee/features/workflows/lib/engine.tsnew file mode 100644index 00000000..5ac0ad8b--- /dev/null+++ b/ee/features/workflows/lib/engine.ts@@ -0,0 +1,348 @@+import prisma from "@/lib/prisma";++import {+ type Action,+ ActionSchema,+ type Condition,+ ConditionsConfigSchema,+ type StepExecutionResult,+ type WorkflowExecutionContext,+ type WorkflowExecutionResult,+} from "./types";++export class WorkflowEngine {+ /**+ * Execute a workflow by entry link ID+ */+ async execute(+ entryLinkId: string,+ context: WorkflowExecutionContext,+ ): Promise<WorkflowExecutionResult> {+ try {+ // 1. Find workflow by entry link+ const workflow = await prisma.workflow.findUnique({+ where: { entryLinkId },+ include: {+ steps: {+ orderBy: { stepOrder: "asc" },+ },+ },+ });++ if (!workflow) {+ return {+ success: false,+ error: "Workflow not found",+ };+ }++ if (!workflow.isActive) {+ return {+ success: false,+ error: "Workflow is not active",+ };+ }++ if (workflow.steps.length === 0) {+ return {+ success: false,+ error: "Workflow has no routing steps configured",+ };+ }++ // 2. Create execution record+ const execution = await prisma.workflowExecution.create({+ data: {+ workflowId: workflow.id,+ visitorEmail: context.visitorEmail,+ visitorIp: context.visitorIp,+ status: "IN_PROGRESS",+ metadata: context.metadata || {},+ },+ });++ try {+ // 3. Execute steps in order until a match is found+ let targetLinkId: string | undefined;+ let targetDocumentId: string | undefined;+ let targetDataroomId: string | undefined;++ for (const step of workflow.steps) {+ const startTime = Date.now();++ try {+ // Parse step data+ const conditions = ConditionsConfigSchema.parse(step.conditions);+ const actions = (step.actions as any[]).map((action) =>+ ActionSchema.parse(action),+ );++ // Evaluate conditions+ const conditionsMatched = await this.evaluateConditions(+ conditions,+ context,+ );++ let actionsResult = null;++ // If conditions matched, execute the route action+ if (conditionsMatched && actions.length > 0) {+ const routeAction = actions[0]; // Only support single route action for now+ if (routeAction.type === "route") {+ targetLinkId = routeAction.targetLinkId;+ targetDocumentId = routeAction.targetDocumentId;+ targetDataroomId = routeAction.targetDataroomId;+ actionsResult = { routed: true, targetLinkId };+ }+ }++ // Log step execution+ await prisma.workflowStepLog.create({+ data: {+ executionId: execution.id,+ workflowStepId: step.id,+ conditionsMatched,+ conditionResults: conditions,+ actionsExecuted: actionsResult ? [actionsResult] : null,+ duration: Date.now() - startTime,+ },+ });++ // If we found a match, stop processing further steps+ if (conditionsMatched && targetLinkId) {+ break;+ }+ } catch (stepError) {+ // Log step error+ await prisma.workflowStepLog.create({+ data: {+ executionId: execution.id,+ workflowStepId: step.id,+ conditionsMatched: false,+ error:+ stepError instanceof Error+ ? stepError.message+ : "Unknown error",+ duration: Date.now() - startTime,+ },+ });+ console.error(`Error executing step ${step.id}:`, stepError);+ }+ }++ // 4. Check if we found a target link+ if (!targetLinkId) {+ await prisma.workflowExecution.update({+ where: { id: execution.id },+ data: {+ status: "COMPLETED",+ completedAt: new Date(),+ result: {+ success: false,+ error: "No matching routing rule found for this email",+ },+ },+ });++ return {+ success: false,+ error: "No matching routing rule found for this email",+ executionId: execution.id,+ };+ }++ // 5. Fetch target link details+ const targetLink = await prisma.link.findUnique({+ where: { id: targetLinkId },+ select: {+ id: true,+ linkType: true,+ documentId: true,+ dataroomId: true,+ domainSlug: true,+ slug: true,+ },+ });++ if (!targetLink) {+ await prisma.workflowExecution.update({+ where: { id: execution.id },+ data: {+ status: "FAILED",+ completedAt: new Date(),+ result: {+ success: false,+ error: "Target link not found",+ },+ },+ });++ return {+ success: false,+ error: "Target link not found",+ executionId: execution.id,+ };+ }++ // 6. Build target URL+ let targetUrl: string;+ if (targetLink.domainSlug && targetLink.slug) {+ targetUrl = `https://${targetLink.domainSlug}/${targetLink.slug}`;+ } else {+ targetUrl = `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${targetLink.id}`;+ }++ // 7. Mark execution as completed+ await prisma.workflowExecution.update({+ where: { id: execution.id },+ data: {+ status: "COMPLETED",+ completedAt: new Date(),+ result: {+ success: true,+ targetLinkId: targetLink.id,+ targetLinkType: targetLink.linkType,+ targetUrl,+ },+ },+ });++ return {+ success: true,+ targetLinkId: targetLink.id,+ targetLinkType: targetLink.linkType as+ | "DOCUMENT_LINK"+ | "DATAROOM_LINK",+ targetDocumentId: targetLink.documentId || undefined,+ targetDataroomId: targetLink.dataroomId || undefined,+ targetUrl,+ executionId: execution.id,+ };+ } catch (error) {+ // Mark execution as failed+ await prisma.workflowExecution.update({+ where: { id: execution.id },+ data: {+ status: "FAILED",+ completedAt: new Date(),+ result: {+ success: false,+ error: error instanceof Error ? error.message : "Unknown error",+ },+ },+ });+ throw error;+ }+ } catch (error) {+ console.error("Workflow execution error:", error);+ return {+ success: false,+ error:+ error instanceof Error ? error.message : "Workflow execution failed",+ };+ }+ }++ /**+ * Evaluate conditions for a workflow step+ */+ private async evaluateConditions(+ conditionsConfig: { logic: "AND" | "OR"; items: Condition[] },+ context: WorkflowExecutionContext,+ ): Promise<boolean> {+ if (!conditionsConfig || !conditionsConfig.items?.length) {+ return true; // No conditions = always pass+ }++ const results = await Promise.all(+ conditionsConfig.items.map((condition) =>+ this.evaluateCondition(condition, context),+ ),+ );++ return conditionsConfig.logic === "AND"+ ? results.every((r) => r)+ : results.some((r) => r);+ }++ /**+ * Evaluate a single condition+ */+ private async evaluateCondition(+ condition: Condition,+ context: WorkflowExecutionContext,+ ): Promise<boolean> {+ switch (condition.type) {+ case "email":+ return this.evaluateEmailCondition(condition, context.visitorEmail);++ case "domain":+ return this.evaluateDomainCondition(condition, context.visitorEmail);++ default:+ return false;+ }+ }++ /**+ * Evaluate email condition+ */+ private evaluateEmailCondition(+ condition: { operator: string; value: string | string[] },+ email: string,+ ): boolean {+ const normalizedEmail = email.toLowerCase();++ switch (condition.operator) {+ case "equals":+ return normalizedEmail === (condition.value as string).toLowerCase();++ case "contains":+ return normalizedEmail.includes(+ (condition.value as string).toLowerCase(),+ );++ case "matches":+ try {+ return new RegExp(condition.value as string).test(normalizedEmail);+ } catch {+ return false;+ }++ case "in_list":+ return (condition.value as string[]).some(+ (v) => normalizedEmail === v.toLowerCase(),+ );++ default:+ return false;+ }+ }++ /**+ * Evaluate domain condition+ */+ private evaluateDomainCondition(+ condition: { operator: string; value: string | string[] },+ email: string,+ ): boolean {+ const domain = email.split("@")[1]?.toLowerCase();+ if (!domain) return false;++ switch (condition.operator) {+ case "equals":+ return domain === (condition.value as string).toLowerCase();++ case "contains":+ return domain.includes((condition.value as string).toLowerCase());++ case "in_list":+ return (condition.value as string[]).some(+ (v) => domain === v.toLowerCase(),+ );++ default:+ return false;+ }+ }+}diff --git a/ee/features/workflows/lib/types.ts b/ee/features/workflows/lib/types.tsnew file mode 100644index 00000000..ca09075d--- /dev/null+++ b/ee/features/workflows/lib/types.ts@@ -0,0 +1,151 @@+import { z } from "zod";++// ============ CONDITIONS ============++export const EmailConditionSchema = z.object({+ type: z.literal("email"),+ operator: z.enum(["equals", "contains", "matches", "in_list"]),+ value: z.union([z.string(), z.array(z.string())]),+});++export const DomainConditionSchema = z.object({+ type: z.literal("domain"),+ operator: z.enum(["equals", "contains", "in_list"]),+ value: z.union([z.string(), z.array(z.string())]),+});++export const ConditionSchema = z.discriminatedUnion("type", [+ EmailConditionSchema,+ DomainConditionSchema,+]);++export type EmailCondition = z.infer<typeof EmailConditionSchema>;+export type DomainCondition = z.infer<typeof DomainConditionSchema>;+export type Condition = z.infer<typeof ConditionSchema>;++// ============ ACTIONS ============++export const RouteActionSchema = z.object({+ type: z.literal("route"),+ targetLinkId: z.string().cuid(),+ // These are populated from the target link for reference+ targetDocumentId: z.string().cuid().optional(),+ targetDataroomId: z.string().cuid().optional(),+});++export const ActionSchema = z.discriminatedUnion("type", [RouteActionSchema]);++export type RouteAction = z.infer<typeof RouteActionSchema>;+export type Action = z.infer<typeof ActionSchema>;++// ============ WORKFLOW STEP DEFINITION ============++export const ConditionsConfigSchema = z.object({+ logic: z.enum(["AND", "OR"]),+ items: z.array(ConditionSchema),+});++export const WorkflowStepDefinitionSchema = z.object({+ name: z.string().min(1, "Step name is required"),+ stepOrder: z.number().int().nonnegative(),+ stepType: z.literal("ROUTER"),+ conditions: ConditionsConfigSchema,+ actions: z.array(ActionSchema).min(1, "At least one action is required"),+});++export type ConditionsConfig = z.infer<typeof ConditionsConfigSchema>;+export type WorkflowStepDefinition = z.infer<+ typeof WorkflowStepDefinitionSchema+>;++// ============ WORKFLOW API SCHEMAS ============++export const CreateWorkflowRequestSchema = z.object({+ name: z.string().min(1, "Workflow name is required").max(100),+ description: z.string().max(500).optional(),+ teamId: z.string().cuid(),+ // Entry link details+ domain: z.string().optional(), // null means papermark.com+ slug: z+ .string()+ .regex(/^[a-zA-Z0-9_-]+$/, "Slug must contain only letters, numbers, hyphens, and underscores")+ .min(1)+ .max(100),+});++export const UpdateWorkflowRequestSchema = z.object({+ name: z.string().min(1).max(100).optional(),+ description: z.string().max(500).optional().nullable(),+ isActive: z.boolean().optional(),+});++export const CreateWorkflowStepRequestSchema = z.object({+ name: z.string().min(1, "Step name is required"),+ conditions: ConditionsConfigSchema,+ actions: z.array(ActionSchema).min(1, "At least one action is required"),+});++export const UpdateWorkflowStepRequestSchema = z.object({+ name: z.string().min(1).optional(),+ conditions: ConditionsConfigSchema.optional(),+ actions: z.array(ActionSchema).min(1).optional(),+});++export const ReorderStepsRequestSchema = z.object({+ steps: z.array(+ z.object({+ stepId: z.string().cuid(),+ stepOrder: z.number().int().nonnegative(),+ }),+ ),+});++export const VerifyEmailRequestSchema = z.object({+ email: z.string().email("Invalid email address"),+});++export const AccessRequestSchema = z.object({+ email: z.string().email("Invalid email address"),+ code: z.string().length(6, "Verification code must be 6 digits"),+});++export type CreateWorkflowRequest = z.infer<typeof CreateWorkflowRequestSchema>;+export type UpdateWorkflowRequest = z.infer<typeof UpdateWorkflowRequestSchema>;+export type CreateWorkflowStepRequest = z.infer<+ typeof CreateWorkflowStepRequestSchema+>;+export type UpdateWorkflowStepRequest = z.infer<+ typeof UpdateWorkflowStepRequestSchema+>;+export type ReorderStepsRequest = z.infer<typeof ReorderStepsRequestSchema>;+export type VerifyEmailRequest = z.infer<typeof VerifyEmailRequestSchema>;+export type AccessRequest = z.infer<typeof AccessRequestSchema>;++// ============ WORKFLOW ENGINE TYPES ============++export interface WorkflowExecutionContext {+ visitorEmail: string;+ visitorIp?: string;+ userAgent?: string;+ referrer?: string;+ metadata?: Record<string, any>;+}++export interface WorkflowExecutionResult {+ success: boolean;+ targetLinkId?: string;+ targetLinkType?: "DOCUMENT_LINK" | "DATAROOM_LINK";+ targetDocumentId?: string;+ targetDataroomId?: string;+ targetUrl?: string;+ error?: string;+ executionId?: string;+}++export interface StepExecutionResult {+ success: boolean;+ conditionsMatched: boolean;+ actionsResult?: any;+ error?: string;+}+diff --git a/ee/features/workflows/lib/validation.ts b/ee/features/workflows/lib/validation.tsnew file mode 100644index 00000000..e640d79f--- /dev/null+++ b/ee/features/workflows/lib/validation.ts@@ -0,0 +1,93 @@+import { ZodError } from "zod";+import {+ ConditionsConfigSchema,+ ActionSchema,+ WorkflowStepDefinitionSchema,+ CreateWorkflowRequestSchema,+ UpdateWorkflowRequestSchema,+ CreateWorkflowStepRequestSchema,+ UpdateWorkflowStepRequestSchema,+ type ConditionsConfig,+ type Action,+ type WorkflowStepDefinition,+} from "./types";++export {+ CreateWorkflowRequestSchema,+ UpdateWorkflowRequestSchema,+ CreateWorkflowStepRequestSchema,+ UpdateWorkflowStepRequestSchema,+};++/**+ * Validates workflow step conditions JSON against the schema+ */+export function validateConditions(+ conditions: unknown,+): { valid: true; data: ConditionsConfig } | { valid: false; error: string } {+ try {+ const data = ConditionsConfigSchema.parse(conditions);+ return { valid: true, data };+ } catch (error) {+ if (error instanceof ZodError) {+ return {+ valid: false,+ error: error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", "),+ };+ }+ return { valid: false, error: "Invalid conditions format" };+ }+}++/**+ * Validates workflow step actions JSON against the schema+ */+export function validateActions(+ actions: unknown,+): { valid: true; data: Action[] } | { valid: false; error: string } {+ try {+ if (!Array.isArray(actions)) {+ return { valid: false, error: "Actions must be an array" };+ }+ const data = actions.map((action) => ActionSchema.parse(action));+ return { valid: true, data };+ } catch (error) {+ if (error instanceof ZodError) {+ return {+ valid: false,+ error: error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", "),+ };+ }+ return { valid: false, error: "Invalid actions format" };+ }+}++/**+ * Validates complete workflow step definition+ */+export function validateWorkflowStep(+ step: unknown,+):+ | { valid: true; data: WorkflowStepDefinition }+ | { valid: false; error: string } {+ try {+ const data = WorkflowStepDefinitionSchema.parse(step);+ return { valid: true, data };+ } catch (error) {+ if (error instanceof ZodError) {+ return {+ valid: false,+ error: error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", "),+ };+ }+ return { valid: false, error: "Invalid workflow step format" };+ }+}++/**+ * Helper to format Zod validation errors for API responses+ */+export function formatZodError(error: ZodError): string {+ return error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ");+}+diff --git a/ee/features/workflows/pages/workflow-detail.tsx b/ee/features/workflows/pages/workflow-detail.tsxnew file mode 100644index 00000000..6a834c48--- /dev/null+++ b/ee/features/workflows/pages/workflow-detail.tsx@@ -0,0 +1,192 @@+import { useRouter } from "next/router";++import { useState } from "react";++import { useTeam } from "@/context/team-context";+import { toast } from "sonner";+import useSWR from "swr";++import { fetcher } from "@/lib/utils";++import AppLayout from "@/components/layouts/app";++import { StepFormDialog } from "../components/step-form-dialog";+import { StepList } from "../components/step-list";+import { WorkflowHeader } from "../components/workflow-header";++interface Workflow {+ id: string;+ name: string;+ description: string | null;+ isActive: boolean;+ entryLink: {+ id: string;+ slug: string | null;+ domainSlug: string | null;+ };+ steps: WorkflowStep[];+}++interface WorkflowStep {+ id: string;+ name: string;+ stepOrder: number;+ conditions: {+ logic: "AND" | "OR";+ items: Array<{+ type: "email" | "domain";+ operator: string;+ value: string | string[];+ }>;+ };+ actions: Array<{+ type: "route";+ targetLinkId: string;+ }>;+ targetLink?: {+ id: string;+ name: string | null;+ slug: string | null;+ linkType: string;+ };+}++interface Link {+ id: string;+ name: string | null;+ slug: string | null;+ domainSlug: string | null;+ linkType: "DOCUMENT_LINK" | "DATAROOM_LINK";+ documentId: string | null;+ dataroomId: string | null;+ allowList: string[];+ resourceName: string | null;+ displayName: string;+}++export default function WorkflowDetailPage() {+ const router = useRouter();+ const { id: workflowId } = router.query as { id: string };+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const [showStepDialog, setShowStepDialog] = useState(false);+ const [editingStep, setEditingStep] = useState<WorkflowStep | null>(null);++ const {+ data: workflow,+ error,+ mutate,+ } = useSWR<Workflow>(+ workflowId ? `/api/workflows/${workflowId}` : null,+ fetcher,+ );++ const { data: links } = useSWR<Link[]>(+ teamId ? `/api/teams/${teamId}/workflow-links` : null,+ fetcher,+ );++ const getEntryUrl = () => {+ if (!workflow) return "";+ if (workflow.entryLink.domainSlug && workflow.entryLink.slug) {+ return `https://${workflow.entryLink.domainSlug}/${workflow.entryLink.slug}`;+ }+ return `${process.env.NEXT_PUBLIC_MARKETING_URL || "https://www.papermark.io"}/view/${workflow.entryLink.id}`;+ };++ const handleDeleteStep = async (stepId: string) => {+ try {+ const response = await fetch(+ `/api/workflows/${workflowId}/steps/${stepId}`,+ {+ method: "DELETE",+ },+ );++ if (!response.ok) {+ throw new Error("Failed to delete step");+ }++ mutate();+ toast.success("Step deleted");+ } catch (error) {+ toast.error("Failed to delete step");+ }+ };++ if (error) {+ return (+ <AppLayout>+ <main className="relative mx-2 mb-10 mt-4 px-1">+ <div className="mt-8 text-center">+ <p className="text-sm text-muted-foreground">+ Failed to load workflow+ </p>+ </div>+ </main>+ </AppLayout>+ );+ }++ if (!workflow) {+ return (+ <AppLayout>+ <main className="relative mx-2 mb-10 mt-4 px-1">+ <div className="mt-8 text-center">+ <p className="text-sm text-muted-foreground">Loading workflow...</p>+ </div>+ </main>+ </AppLayout>+ );+ }++ return (+ <AppLayout>+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">+ <div className="max-w-4xl space-y-6">+ <WorkflowHeader+ workflowId={workflowId}+ name={workflow.name}+ description={workflow.description}+ isActive={workflow.isActive}+ entryUrl={getEntryUrl()}+ onUpdate={mutate}+ />++ <StepList+ steps={workflow.steps}+ onAddStep={() => {+ setEditingStep(null);+ setShowStepDialog(true);+ }}+ onEditStep={(step) => {+ setEditingStep(step);+ setShowStepDialog(true);+ }}+ onDeleteStep={handleDeleteStep}+ />+ </div>++ {/* Step Form Dialog */}+ {showStepDialog && (+ <StepFormDialog+ workflowId={workflowId}+ step={editingStep}+ links={links || []}+ open={showStepDialog}+ onClose={() => {+ setShowStepDialog(false);+ setEditingStep(null);+ }}+ onSuccess={() => {+ mutate();+ setShowStepDialog(false);+ setEditingStep(null);+ }}+ />+ )}+ </main>+ </AppLayout>+ );+}diff --git a/ee/features/workflows/pages/workflow-new.tsx b/ee/features/workflows/pages/workflow-new.tsxnew file mode 100644index 00000000..81a868ec--- /dev/null+++ b/ee/features/workflows/pages/workflow-new.tsx@@ -0,0 +1,200 @@+import { useState } from "react";+import { useRouter } from "next/router";+import { useTeam } from "@/context/team-context";+import { toast } from "sonner";+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import AppLayout from "@/components/layouts/app";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Textarea } from "@/components/ui/textarea";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++interface Domain {+ id: string;+ slug: string;+}++export default function NewWorkflowPage() {+ const router = useRouter();+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const [name, setName] = useState("");+ const [description, setDescription] = useState("");+ const [domain, setDomain] = useState<string>("papermark.com");+ const [slug, setSlug] = useState("");+ const [isLoading, setIsLoading] = useState(false);++ const { data: domains } = useSWR<Domain[]>(+ teamId ? `/api/teams/${teamId}/domains` : null,+ fetcher,+ );++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();++ if (!name.trim()) {+ toast.error("Workflow name is required");+ return;+ }++ if (domain !== "papermark.com" && !slug.trim()) {+ toast.error("Entry link slug is required for custom domains");+ return;+ }++ setIsLoading(true);++ try {+ const response = await fetch("/api/workflows", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name: name.trim(),+ description: description.trim() || undefined,+ teamId,+ domain: domain === "papermark.com" ? undefined : domain,+ slug: slug.trim(),+ }),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to create workflow");+ }++ const workflow = await response.json();+ toast.success("Workflow created successfully");+ router.push(`/workflows/${workflow.id}`);+ } catch (error) {+ console.error("Error creating workflow:", error);+ toast.error(+ error instanceof Error ? error.message : "Failed to create workflow",+ );+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <AppLayout>+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">+ <div className="max-w-2xl">+ <div className="mb-6">+ <h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">+ Create Workflow+ </h1>+ <p className="mt-1 text-sm text-muted-foreground">+ Set up a new routing workflow with an entry link+ </p>+ </div>++ <form onSubmit={handleSubmit} className="space-y-6">+ <div className="space-y-2">+ <Label htmlFor="name">Workflow Name *</Label>+ <Input+ id="name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="e.g., Client Dashboard Routing"+ maxLength={100}+ required+ />+ </div>++ <div className="space-y-2">+ <Label htmlFor="description">Description</Label>+ <Textarea+ id="description"+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ placeholder="Describe what this workflow does..."+ maxLength={500}+ rows={3}+ />+ </div>++ <div className="space-y-4">+ <h3 className="text-sm font-medium">Entry Link</h3>+ <p className="text-sm text-muted-foreground">+ This is the single URL visitors will use to access the workflow+ </p>++ <div className="space-y-2">+ <Label htmlFor="domain">Domain</Label>+ <Select value={domain} onValueChange={setDomain}>+ <SelectTrigger id="domain">+ <SelectValue placeholder="papermark.com (default)" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="papermark.com">papermark.com</SelectItem>+ {domains?.map((d) => (+ <SelectItem key={d.id} value={d.slug}>+ {d.slug}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ {domain !== "papermark.com" && (+ <>+ <div className="space-y-2">+ <Label htmlFor="slug">Slug *</Label>+ <Input+ id="slug"+ value={slug}+ onChange={(e) =>+ setSlug(+ e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, ""),+ )+ }+ placeholder="dashboard"+ pattern="[a-z0-9_-]+"+ maxLength={100}+ required+ />+ <p className="text-xs text-muted-foreground">+ Entry URL: {domain}/{slug || "your-slug"}+ </p>+ </div>+ </>+ )}++ {domain === "papermark.com" && (+ <p className="text-xs text-muted-foreground">+ Entry URL will be generated automatically (e.g., papermark.com/view/clxxx...)+ </p>+ )}+ </div>++ <div className="flex gap-3 pt-4">+ <Button type="submit" disabled={isLoading}>+ {isLoading ? "Creating..." : "Create Workflow"}+ </Button>+ <Button+ type="button"+ variant="outline"+ onClick={() => router.back()}+ disabled={isLoading}+ >+ Cancel+ </Button>+ </div>+ </form>+ </div>+ </main>+ </AppLayout>+ );+}+diff --git a/ee/features/workflows/pages/workflow-overview.tsx b/ee/features/workflows/pages/workflow-overview.tsxnew file mode 100644index 00000000..0a5c29f8--- /dev/null+++ b/ee/features/workflows/pages/workflow-overview.tsx@@ -0,0 +1,96 @@+import Link from "next/link";+import { useRouter } from "next/router";++import { useTeam } from "@/context/team-context";+import { PlusIcon } from "lucide-react";+import useSWR from "swr";++import { usePlan } from "@/lib/swr/use-billing";+import { fetcher } from "@/lib/utils";++import PlanBadge from "@/components/billing/plan-badge";+import AppLayout from "@/components/layouts/app";+import { Button } from "@/components/ui/button";++import { WorkflowEmptyState } from "../components/workflow-empty-state";+import { WorkflowList } from "../components/workflow-list";++interface Workflow {+ id: string;+ name: string;+ description: string | null;+ isActive: boolean;+ createdAt: string;+ entryLink: {+ id: string;+ slug: string | null;+ domainSlug: string | null;+ };+ _count: {+ steps: number;+ executions: number;+ };+}++export default function WorkflowsPage() {+ const router = useRouter();+ const teamInfo = useTeam();+ const { isFree, isPro, isTrial } = usePlan();+ const teamId = teamInfo?.currentTeam?.id;++ const { data: workflows, error } = useSWR<Workflow[]>(+ teamId ? `/api/workflows?teamId=${teamId}` : null,+ fetcher,+ );++ const isLoading = !workflows && !error;+ const requiresUpgrade = (isFree || isPro) && !isTrial;++ return (+ <AppLayout>+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">+ <div>+ <div className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">+ <div className="space-y-1">+ <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground sm:text-3xl">+ Workflows+ {requiresUpgrade ? <PlanBadge plan="Business" /> : null}+ </h1>+ <p className="text-sm text-muted-foreground">+ Route visitors to different links based on their email or domain+ </p>+ </div>+ {!requiresUpgrade && (+ <Link href="/workflows/new">+ <Button>+ <PlusIcon className="mr-2 h-4 w-4" />+ Create Workflow+ </Button>+ </Link>+ )}+ </div>++ {requiresUpgrade ? (+ <WorkflowEmptyState+ title="Workflows require an upgrade"+ description="Upgrade to Business or Data Rooms plan to create routing workflows. Click the button below to upgrade your plan."+ />+ ) : isLoading ? (+ <div className="flex items-center justify-center py-12">+ <div className="text-sm text-muted-foreground">+ Loading workflows...+ </div>+ </div>+ ) : !workflows || workflows.length === 0 ? (+ <WorkflowEmptyState+ title="No workflows yet"+ description="Create your first routing workflow to intelligently direct visitors to different links"+ />+ ) : (+ <WorkflowList workflows={workflows} />+ )}+ </div>+ </main>+ </AppLayout>+ );+}diff --git a/lib/featureFlags/index.ts b/lib/featureFlags/index.tsindex 47d50691..cdcdbc5c 100644--- a/lib/featureFlags/index.ts+++ b/lib/featureFlags/index.ts@@ -11,7 +11,8 @@ export type BetaFeatures =| "usStorage"| "dataroomIndex"| "slack"- | "annotations";+ | "annotations"+ | "workflows";type BetaFeaturesRecord = Record<BetaFeatures, string[]>;@@ -28,6 +29,7 @@ export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {dataroomIndex: false,slack: false,annotations: false,+ workflows: false,};// Return all features as true if edge config is not availablediff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.tsindex 639dba4e..9c4955f0 100644--- a/pages/api/links/[id]/index.ts+++ b/pages/api/links/[id]/index.ts@@ -120,6 +120,25 @@ export default async function handle(const linkType = link.linkType;+ // Handle workflow links separately+ if (linkType === "WORKFLOW_LINK") {+ // For workflow links, fetch brand if available+ let brand: Partial<Brand> | null = null;+ if (link.teamId) {+ const teamBrand = await prisma.brand.findUnique({+ where: { teamId: link.teamId },+ select: {+ logo: true,+ brandColor: true,+ accentColor: true,+ },+ });+ brand = teamBrand;+ }++ return res.status(200).json({ linkType, brand });+ }+let brand: Partial<Brand> | Partial<DataroomBrand> | null = null;let linkData: any;diff --git a/pages/api/links/domains/[...domainSlug].ts b/pages/api/links/domains/[...domainSlug].tsindex b1d46305..60c61b03 100644--- a/pages/api/links/domains/[...domainSlug].ts+++ b/pages/api/links/domains/[...domainSlug].ts@@ -157,6 +157,26 @@ export default async function handle(}const linkType = link.linkType;++ // Handle workflow links separately+ if (linkType === "WORKFLOW_LINK") {+ // For workflow links, fetch brand if available+ let brand: Partial<Brand> | null = null;+ if (link.teamId) {+ const teamBrand = await prisma.brand.findUnique({+ where: { teamId: link.teamId },+ select: {+ logo: true,+ brandColor: true,+ accentColor: true,+ },+ });+ brand = teamBrand;+ }++ return res.status(200).json({ linkType, brand, linkId: link.id });+ }+let brand: Partial<Brand> | Partial<DataroomBrand> | null = null;let linkData: any;diff --git a/pages/api/teams/[teamId]/workflow-links.ts b/pages/api/teams/[teamId]/workflow-links.tsnew file mode 100644index 00000000..37ed8ecf--- /dev/null+++ b/pages/api/teams/[teamId]/workflow-links.ts@@ -0,0 +1,115 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth";++import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId } = req.query as { teamId: string };+ const userId = (session.user as CustomUser).id;++ try {+ // Check if user is part of the team+ const hasAccess = await prisma.userTeam.findUnique({+ where: {+ userId_teamId: {+ userId: userId,+ teamId: teamId,+ },+ },+ });+ if (!hasAccess) {+ return res.status(403).json({ error: "Unauthorized" });+ }++ // Fetch all links with document/dataroom info+ const links = await prisma.link.findMany({+ where: {+ teamId,+ linkType: {+ in: ["DOCUMENT_LINK", "DATAROOM_LINK"],+ },+ deletedAt: null,+ isArchived: false,+ },+ select: {+ id: true,+ name: true,+ slug: true,+ domainSlug: true,+ linkType: true,+ documentId: true,+ dataroomId: true,+ allowList: true,+ document: {+ select: {+ id: true,+ name: true,+ },+ },+ dataroom: {+ select: {+ id: true,+ name: true,+ },+ },+ },+ orderBy: {+ createdAt: "desc",+ },+ });++ // Format response with better labels+ const formattedLinks = links.map((link) => {+ const resourceName =+ link.linkType === "DOCUMENT_LINK"+ ? link.document?.name+ : link.dataroom?.name;++ // Build display name priority: name > domain/slug > slug > resource name > id+ let displayName = link.name;+ if (!displayName && link.domainSlug && link.slug) {+ displayName = `${link.domainSlug}/${link.slug}`;+ } else if (!displayName && link.slug) {+ displayName = link.slug;+ } else if (!displayName && resourceName) {+ displayName = resourceName;+ } else if (!displayName) {+ displayName = link.id.substring(0, 8);+ }++ return {+ id: link.id,+ name: link.name,+ slug: link.slug,+ domainSlug: link.domainSlug, // Will be null for papermark.com links+ linkType: link.linkType,+ documentId: link.documentId,+ dataroomId: link.dataroomId,+ allowList: link.allowList, // Pre-populate conditions from link+ resourceName, // Document or Dataroom name+ displayName, // Human-readable label+ };+ });++ return res.status(200).json(formattedLinks);+ } catch (error) {+ console.error("Error fetching workflow links:", error);+ return res.status(500).json({ error: "Internal server error" });+ }+ }++ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+}diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsxindex cc61bc39..75287447 100644--- a/pages/view/[linkId]/index.tsx+++ b/pages/view/[linkId]/index.tsx@@ -3,6 +3,7 @@ import { useRouter } from "next/router";import { useEffect, useState } from "react";+import WorkflowAccessView from "@/ee/features/workflows/components/workflow-access-view";import NotFound from "@/pages/404";import { Brand, DataroomBrand } from "@prisma/client";import Cookies from "js-cookie";@@ -38,8 +39,14 @@ type DataroomLinkData = {brand: DataroomBrand | null;};+type WorkflowLinkData = {+ linkType: "WORKFLOW_LINK";+ entryLinkId: string;+ brand: Brand | null;+};+export interface ViewPageProps {- linkData: DocumentLinkData | DataroomLinkData;+ linkData: DocumentLinkData | DataroomLinkData | WorkflowLinkData;notionData: {rootNotionPageId: string | null;recordMap: ExtendedRecordMap | null;@@ -72,11 +79,47 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {throw new Error(`Failed to fetch: ${res.status}`);}- const { linkType, link, brand } = (await res.json()) as- | DocumentLinkData- | DataroomLinkData;+ const { linkType, link, brand } = (await res.json()) as any;++ if (!linkType) {+ return {+ notFound: true,+ };+ }++ // Handle workflow links - minimal props needed+ if (linkType === "WORKFLOW_LINK") {+ return {+ props: {+ linkData: {+ linkType: "WORKFLOW_LINK",+ entryLinkId: linkId,+ brand: brand || null,+ },+ notionData: {+ rootNotionPageId: null,+ recordMap: null,+ theme: null,+ },+ meta: {+ enableCustomMetatag: false,+ metaTitle: null,+ metaDescription: null,+ metaImage: null,+ metaUrl: `https://www.papermark.com/view/${linkId}`,+ metaFavicon: "/favicon.ico",+ },+ showPoweredByBanner: false,+ showAccountCreationSlide: false,+ useAdvancedExcelViewer: false,+ useCustomAccessForm: false,+ logoOnAccessForm: false,+ },+ revalidate: 60,+ };+ }- if (!link || !linkType) {+ if (!link) {return {notFound: true,};@@ -323,10 +366,31 @@ export default function ViewPage({previewToken?: string;preview?: string;};- const { linkType, link, brand } = linkData;+ const { linkType } = linkData;++ // Render workflow access view for WORKFLOW_LINK+ if (linkType === "WORKFLOW_LINK") {+ const { entryLinkId, brand } = linkData as WorkflowLinkData;++ return (+ <>+ <CustomMetaTag+ favicon={meta.metaFavicon}+ enableBranding={false}+ title="Access Workflow | Powered by Papermark"+ description={null}+ imageUrl={null}+ url={meta.metaUrl ?? ""}+ />+ <WorkflowAccessView entryLinkId={entryLinkId} brand={brand} />+ </>+ );+ }// Render the document view for DOCUMENT_LINKif (linkType === "DOCUMENT_LINK") {+ const { link, brand } = linkData as DocumentLinkData;+if (!linkData || status === "loading" || router.isFallback) {return (<>@@ -408,6 +472,8 @@ export default function ViewPage({// Render the dataroom view for DATAROOM_LINKif (linkType === "DATAROOM_LINK") {+ const { link, brand } = linkData as DataroomLinkData;+if (!link || status === "loading" || router.isFallback) {return (<>diff --git a/pages/view/domains/[domain]/[slug]/index.tsx b/pages/view/domains/[domain]/[slug]/index.tsxindex 82c98824..79d72400 100644--- a/pages/view/domains/[domain]/[slug]/index.tsx+++ b/pages/view/domains/[domain]/[slug]/index.tsx@@ -3,6 +3,7 @@ import { useRouter } from "next/router";import { useEffect, useState } from "react";+import WorkflowAccessView from "@/ee/features/workflows/components/workflow-access-view";import NotFound from "@/pages/404";import { Brand, DataroomBrand } from "@prisma/client";import Cookies from "js-cookie";@@ -37,6 +38,14 @@ type DataroomLinkData = {brand: DataroomBrand | null;};+type WorkflowLinkData = {+ linkType: "WORKFLOW_LINK";+ entryLinkId: string;+ domain: string;+ slug: string;+ brand: Brand | null;+};+export const getStaticProps = async (context: GetStaticPropsContext) => {const { domain: domainParam, slug: slugParam } = context.params as {domain: string;@@ -61,11 +70,50 @@ export const getStaticProps = async (context: GetStaticPropsContext) => {if (!res.ok) {throw new Error(`Failed to fetch: ${res.status}`);}- const { linkType, link, brand } = (await res.json()) as- | DocumentLinkData- | DataroomLinkData;+ const responseData = (await res.json()) as any;+ const { linkType, link, brand, linkId } = responseData;- if (!link || !linkType) {+ if (!linkType) {+ return {+ notFound: true,+ };+ }++ // Handle workflow links - minimal props needed+ if (linkType === "WORKFLOW_LINK") {+ return {+ props: {+ linkData: {+ linkType: "WORKFLOW_LINK",+ entryLinkId: linkId || "",+ domain,+ slug,+ brand: brand || null,+ },+ notionData: {+ rootNotionPageId: null,+ recordMap: null,+ theme: null,+ },+ meta: {+ enableCustomMetatag: false,+ metaTitle: null,+ metaDescription: null,+ metaImage: null,+ metaUrl: `https://${domain}/${slug}`,+ metaFavicon: "/favicon.ico",+ },+ showPoweredByBanner: false,+ showAccountCreationSlide: false,+ useAdvancedExcelViewer: false,+ useCustomAccessForm: false,+ logoOnAccessForm: false,+ },+ revalidate: 60,+ };+ }++ if (!link) {return {notFound: true,};@@ -243,7 +291,7 @@ export default function ViewPage({dataroomIndexEnabled,error,}: {- linkData: DocumentLinkData | DataroomLinkData;+ linkData: DocumentLinkData | DataroomLinkData | WorkflowLinkData;notionData: {rootNotionPageId: string | null;recordMap: ExtendedRecordMap | null;@@ -307,10 +355,36 @@ export default function ViewPage({previewToken?: string;preview?: string;};- const { linkType, link, brand } = linkData;+ const { linkType } = linkData;++ // Render workflow access view for WORKFLOW_LINK+ if (linkType === "WORKFLOW_LINK") {+ const { entryLinkId, domain, slug, brand } = linkData as WorkflowLinkData;++ return (+ <>+ <CustomMetaTag+ favicon={meta.metaFavicon}+ enableBranding={false}+ title="Access Workflow | Powered by Papermark"+ description={null}+ imageUrl={null}+ url={meta.metaUrl ?? ""}+ />+ <WorkflowAccessView+ entryLinkId={entryLinkId}+ domain={domain}+ slug={slug}+ brand={brand}+ />+ </>+ );+ }// Render the document view for DOCUMENT_LINKif (linkType === "DOCUMENT_LINK") {+ const { link, brand } = linkData as DocumentLinkData;+if (!link || status === "loading") {return (<>@@ -389,6 +463,8 @@ export default function ViewPage({// Render the dataroom view for DATAROOM_LINKif (linkType === "DATAROOM_LINK") {+ const { link, brand } = linkData as DataroomLinkData;+if (!link || status === "loading" || router.isFallback) {return (<>diff --git a/pages/workflows/[id].tsx b/pages/workflows/[id].tsxnew file mode 100644index 00000000..2c0238da--- /dev/null+++ b/pages/workflows/[id].tsx@@ -0,0 +1,5 @@+import WorkflowDetail from "@/ee/features/workflows/pages/workflow-detail";++export default function WorkflowDetailPage() {+ return <WorkflowDetail />;+}diff --git a/pages/workflows/index.tsx b/pages/workflows/index.tsxnew file mode 100644index 00000000..71740fe4--- /dev/null+++ b/pages/workflows/index.tsx@@ -0,0 +1,5 @@+import WorkflowOverview from "@/ee/features/workflows/pages/workflow-overview";++export default function WorkflowOverviewPage() {+ return <WorkflowOverview />;+}diff --git a/pages/workflows/new.tsx b/pages/workflows/new.tsxnew file mode 100644index 00000000..3a8a02ae--- /dev/null+++ b/pages/workflows/new.tsx@@ -0,0 +1,5 @@+import WorkflowNew from "@/ee/features/workflows/pages/workflow-new";++export default function WorkflowNewPage() {+ return <WorkflowNew />;+}diff --git a/prisma/migrations/20251116000000_add_workflow/migration.sql b/prisma/migrations/20251116000000_add_workflow/migration.sqlnew file mode 100644index 00000000..b74912ce--- /dev/null+++ b/prisma/migrations/20251116000000_add_workflow/migration.sql@@ -0,0 +1,119 @@+-- CreateEnum+CREATE TYPE "ExecutionStatus" AS ENUM ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'FAILED', 'BLOCKED');++-- CreateEnum+CREATE TYPE "WorkflowStepType" AS ENUM ('ROUTER');++-- AlterEnum+ALTER TYPE "LinkType" ADD VALUE 'WORKFLOW_LINK';++-- CreateTable+CREATE TABLE "Workflow" (+ "id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT,+ "entryLinkId" TEXT NOT NULL,+ "teamId" TEXT NOT NULL,+ "isActive" BOOLEAN NOT NULL DEFAULT true,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "Workflow_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "WorkflowExecution" (+ "id" TEXT NOT NULL,+ "workflowId" TEXT NOT NULL,+ "visitorEmail" TEXT,+ "visitorIp" TEXT,+ "status" "ExecutionStatus" NOT NULL,+ "startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "completedAt" TIMESTAMP(3),+ "result" JSONB,+ "metadata" JSONB,++ CONSTRAINT "WorkflowExecution_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "WorkflowStep" (+ "id" TEXT NOT NULL,+ "workflowId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "stepOrder" INTEGER NOT NULL,+ "stepType" "WorkflowStepType" NOT NULL DEFAULT 'ROUTER',+ "conditions" JSONB NOT NULL,+ "actions" JSONB NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "WorkflowStep_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "WorkflowStepLog" (+ "id" TEXT NOT NULL,+ "executionId" TEXT NOT NULL,+ "workflowStepId" TEXT NOT NULL,+ "conditionsMatched" BOOLEAN NOT NULL,+ "conditionResults" JSONB,+ "actionsExecuted" JSONB,+ "executedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "duration" INTEGER,+ "error" TEXT,++ CONSTRAINT "WorkflowStepLog_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "Workflow_entryLinkId_idx" ON "Workflow"("entryLinkId" ASC);++-- CreateIndex+CREATE UNIQUE INDEX "Workflow_entryLinkId_key" ON "Workflow"("entryLinkId" ASC);++-- CreateIndex+CREATE INDEX "Workflow_isActive_idx" ON "Workflow"("isActive" ASC);++-- CreateIndex+CREATE INDEX "Workflow_teamId_idx" ON "Workflow"("teamId" ASC);++-- CreateIndex+CREATE INDEX "WorkflowExecution_status_idx" ON "WorkflowExecution"("status" ASC);++-- CreateIndex+CREATE INDEX "WorkflowExecution_visitorEmail_idx" ON "WorkflowExecution"("visitorEmail" ASC);++-- CreateIndex+CREATE INDEX "WorkflowExecution_workflowId_startedAt_idx" ON "WorkflowExecution"("workflowId" ASC, "startedAt" ASC);++-- CreateIndex+CREATE INDEX "WorkflowStep_workflowId_idx" ON "WorkflowStep"("workflowId" ASC);++-- CreateIndex+CREATE UNIQUE INDEX "WorkflowStep_workflowId_stepOrder_key" ON "WorkflowStep"("workflowId" ASC, "stepOrder" ASC);++-- CreateIndex+CREATE INDEX "WorkflowStepLog_executionId_idx" ON "WorkflowStepLog"("executionId" ASC);++-- CreateIndex+CREATE INDEX "WorkflowStepLog_workflowStepId_idx" ON "WorkflowStepLog"("workflowStepId" ASC);++-- AddForeignKey+ALTER TABLE "Workflow" ADD CONSTRAINT "Workflow_entryLinkId_fkey" FOREIGN KEY ("entryLinkId") REFERENCES "Link"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "Workflow" ADD CONSTRAINT "Workflow_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "WorkflowExecution" ADD CONSTRAINT "WorkflowExecution_workflowId_fkey" FOREIGN KEY ("workflowId") REFERENCES "Workflow"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "WorkflowStep" ADD CONSTRAINT "WorkflowStep_workflowId_fkey" FOREIGN KEY ("workflowId") REFERENCES "Workflow"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "WorkflowStepLog" ADD CONSTRAINT "WorkflowStepLog_executionId_fkey" FOREIGN KEY ("executionId") REFERENCES "WorkflowExecution"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "WorkflowStepLog" ADD CONSTRAINT "WorkflowStepLog_workflowStepId_fkey" FOREIGN KEY ("workflowStepId") REFERENCES "WorkflowStep"("id") ON DELETE CASCADE ON UPDATE CASCADE;+diff --git a/prisma/schema/link.prisma b/prisma/schema/link.prismaindex 0171260b..207f4470 100644--- a/prisma/schema/link.prisma+++ b/prisma/schema/link.prisma@@ -1,6 +1,7 @@enum LinkType {DOCUMENT_LINKDATAROOM_LINK+ WORKFLOW_LINK}enum LinkAudienceType {@@ -87,6 +88,9 @@ model Link {tags TagItem[]+ // workflow entry link+ workflow Workflow?+@@unique([domainSlug, slug])@@index([documentId])@@index([teamId])diff --git a/prisma/schema/team.prisma b/prisma/schema/team.prismaindex a168550e..b688020d 100644--- a/prisma/schema/team.prisma+++ b/prisma/schema/team.prisma@@ -28,6 +28,7 @@ model Team {links Link[]views View[]+ workflows Workflow[]plan String @default("free")stripeId String? @unique // Stripe customer IDdiff --git a/prisma/schema/workflow.prisma b/prisma/schema/workflow.prismanew file mode 100644index 00000000..a573787a--- /dev/null+++ b/prisma/schema/workflow.prisma@@ -0,0 +1,89 @@+// Workflow models for routing visitors based on email/domain rules++enum WorkflowStepType {+ ROUTER // Route to different links based on conditions+}++enum ExecutionStatus {+ PENDING+ IN_PROGRESS+ COMPLETED+ FAILED+ BLOCKED+}++model Workflow {+ id String @id @default(cuid())+ name String+ description String?+ entryLinkId String @unique+ teamId String+ isActive Boolean @default(true)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ entryLink Link @relation(fields: [entryLinkId], references: [id], onDelete: Cascade)+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)+ steps WorkflowStep[]+ executions WorkflowExecution[]++ @@index([entryLinkId])+ @@index([teamId])+ @@index([isActive])+}++model WorkflowStep {+ id String @id @default(cuid())+ workflowId String+ name String+ stepOrder Int // Execution order (priority-based routing)+ stepType WorkflowStepType @default(ROUTER)+ conditions Json // JSON array of conditions to evaluate+ actions Json // JSON array of actions to execute+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ workflow Workflow @relation(fields: [workflowId], references: [id], onDelete: Cascade)+ executionLogs WorkflowStepLog[]++ @@unique([workflowId, stepOrder])+ @@index([workflowId])+}++model WorkflowExecution {+ id String @id @default(cuid())+ workflowId String+ visitorEmail String?+ visitorIp String?+ status ExecutionStatus+ startedAt DateTime @default(now())+ completedAt DateTime?+ result Json? // Final result/output (routing target)+ metadata Json? // Context data (referrer, user agent, etc.)++ workflow Workflow @relation(fields: [workflowId], references: [id], onDelete: Cascade)+ stepLogs WorkflowStepLog[]++ @@index([workflowId, startedAt])+ @@index([visitorEmail])+ @@index([status])+}++model WorkflowStepLog {+ id String @id @default(cuid())+ executionId String+ workflowStepId String+ conditionsMatched Boolean+ conditionResults Json? // Which conditions passed/failed+ actionsExecuted Json? // Which actions ran+ executedAt DateTime @default(now())+ duration Int? // Execution time in ms+ error String?++ execution WorkflowExecution @relation(fields: [executionId], references: [id], onDelete: Cascade)+ step WorkflowStep @relation(fields: [workflowStepId], references: [id], onDelete: Cascade)++ @@index([executionId])+ @@index([workflowStepId])+}+