echos-ocr/src/app/api/form-templates/route.ts

132 lines
3.6 KiB
TypeScript
Raw Normal View History

Add dynamic fields, people directory, analytics, security hardening, and UX polish Phase 1 - Security & Bug Fixes: - Add requireApiAuth helper and protect all 25 unprotected API routes - Add org-tenant scoping to all card, job, stats, and notification queries - Fix SSRF in ai-test, mask secrets in settings API, fix middleware bypass - Fix cards pagination routing, stat filter sync, drag-drop file passing - Add PUT /api/auth/me for profile persistence, stuck job recovery - Fix email watcher MIME type detection Phase 2 - Dynamic Fields & Digital Survey: - Add FormTemplate, FormField, Person, PasswordResetToken models to schema - Add fieldData, formTemplateId, firstName, lastName, personId to ResponseCard - Build FormTemplate CRUD API with field management and org scoping - Build Form Builder UI with field ordering, type config, and section management - Refactor card detail page to render fields dynamically from templates - Add dynamic OCR prompt/schema generation from template fields - Build public survey page at /s/[orgSlug]/[formSlug] with branding - Add QR code generation API and share section component Phase 3 - People & Analytics: - Build People CRUD API with merge and batch auto-link endpoints - Build People list and detail pages with search, merge dialog - Add auto-link logic in OCR completion to match/create Person records - Add /api/stats/trends endpoint with time series and team activity - Build Reports page with Recharts (area charts, bar charts, pipeline) - Upgrade dashboard with sparklines and People stat card Phase 4 - UX Polish: - Replace silent error handling with toast notifications across all pages - Add loading skeletons, differentiated empty states - Add ARIA labels, skip-to-content link, accessible column toggle - Add forgot password flow, Cmd+K command palette, Collection Days pages - Unify Echo branding and theme toggle consistency Made-with: Cursor
2026-04-17 00:29:26 -04:00
import { NextRequest, NextResponse } from "next/server";
import { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/db";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";
export async function GET(request: NextRequest) {
try {
const session = await requireApiAuthWithOrg();
const { searchParams } = new URL(request.url);
if (searchParams.get("default") === "true") {
const template = await prisma.formTemplate.findFirst({
where: {
organizationId: session.user.orgId,
isDefault: true,
isActive: true,
},
include: { fields: { orderBy: { sortOrder: "asc" } } },
});
return NextResponse.json({ template });
}
const templates = await prisma.formTemplate.findMany({
where: { organizationId: session.user.orgId },
orderBy: { createdAt: "desc" },
include: {
_count: { select: { fields: true, cards: true } },
},
});
return NextResponse.json({ templates });
} catch (error) {
return handleApiError(error);
}
}
function slugify(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "");
}
export async function POST(request: NextRequest) {
try {
const session = await requireApiAuthWithOrg();
const body = await request.json();
const { name, description, duplicateFrom } = body as {
name?: string;
description?: string;
duplicateFrom?: string;
};
if (!name?.trim()) {
return NextResponse.json(
{ error: "Name is required" },
{ status: 400 }
);
}
const baseSlug = slugify(name);
let slug = baseSlug;
let suffix = 1;
while (
await prisma.formTemplate.findUnique({
where: {
organizationId_slug: {
organizationId: session.user.orgId!,
slug,
},
},
})
) {
slug = `${baseSlug}-${suffix++}`;
}
let fieldsToCreate: Prisma.FormFieldCreateWithoutFormTemplateInput[] = [];
if (duplicateFrom) {
const source = await prisma.formTemplate.findFirst({
where: { id: duplicateFrom, organizationId: session.user.orgId },
include: { fields: { orderBy: { sortOrder: "asc" } } },
});
if (!source) {
return NextResponse.json(
{ error: "Source template not found" },
{ status: 404 }
);
}
fieldsToCreate = source.fields.map((f) => ({
key: f.key,
label: f.label,
type: f.type,
section: f.section,
required: f.required,
removable: f.removable,
isCore: f.isCore,
sortOrder: f.sortOrder,
options: (f.options ?? Prisma.JsonNull) as Prisma.InputJsonValue,
placeholder: f.placeholder,
helpText: f.helpText,
validation: (f.validation ?? Prisma.JsonNull) as Prisma.InputJsonValue,
visibleOnCard: f.visibleOnCard,
visibleOnSurvey: f.visibleOnSurvey,
}));
}
const template = await prisma.formTemplate.create({
data: {
organizationId: session.user.orgId!,
name: name.trim(),
slug,
description: description?.trim() || null,
isDefault: false,
isActive: true,
...(fieldsToCreate.length > 0 && {
fields: { create: fieldsToCreate },
}),
},
include: {
fields: { orderBy: { sortOrder: "asc" } },
_count: { select: { cards: true } },
},
});
return NextResponse.json(template, { status: 201 });
} catch (error) {
return handleApiError(error);
}
}