echos-ocr/src/app/api/people/[id]/merge/route.ts

71 lines
2.4 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 "@/lib/db";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";
type Ctx = { params: Promise<{ id: string }> };
export async function POST(request: NextRequest, ctx: Ctx) {
try {
const session = await requireApiAuthWithOrg();
const orgId = session.user.orgId!;
const { id: sourceId } = await ctx.params;
const body = await request.json().catch(() => ({}));
const { targetPersonId } = body;
if (!targetPersonId) {
return NextResponse.json({ error: "targetPersonId is required" }, { status: 400 });
}
if (sourceId === targetPersonId) {
return NextResponse.json({ error: "Cannot merge a person into themselves" }, { status: 400 });
}
const [source, target] = await Promise.all([
prisma.person.findUnique({ where: { id: sourceId } }),
prisma.person.findUnique({ where: { id: targetPersonId } }),
]);
if (!source || source.organizationId !== orgId) {
return NextResponse.json({ error: "Source person not found" }, { status: 404 });
}
if (!target || target.organizationId !== orgId) {
return NextResponse.json({ error: "Target person not found" }, { status: 404 });
}
// 1. Move all cards from source to target
await prisma.responseCard.updateMany({
where: { personId: sourceId },
data: { personId: targetPersonId },
});
// 2. Merge fieldData: target values take priority, fill gaps from source
const mergedFieldData = {
...((source.fieldData as object) ?? {}),
...((target.fieldData as object) ?? {}),
};
// 3. Update target's core fields if target's are null but source's are not
const updates: Record<string, unknown> = {
fieldData: Object.keys(mergedFieldData).length > 0 ? mergedFieldData : null,
};
if (!target.email && source.email) updates.email = source.email;
if (!target.cellPhone && source.cellPhone) updates.cellPhone = source.cellPhone;
const targetPerson = await prisma.person.update({
where: { id: targetPersonId },
data: updates,
include: { _count: { select: { cards: true } } },
});
// 4. Mark source as merged
await prisma.person.update({
where: { id: sourceId },
data: { mergedIntoId: targetPersonId },
});
return NextResponse.json({ success: true, targetPerson });
} catch (error) {
return handleApiError(error);
}
}