import { NextResponse } from 'next/server'; import { civicrmApi } from '@/lib/civicrm'; import mapping from '@/config/mapping.json'; export async function POST(request) { try { const body = await request.json(); const { contactId, orgId, formData } = body; if (!contactId || !orgId || !formData) { return NextResponse.json({ error: 'Missing required fields' }, { status: 400 }); } // 1. Separate fields by entity for updating const contactUpdates = {}; mapping.stages.forEach(stage => { stage.fields.forEach(field => { if (formData[field.name] !== undefined) { if (field.entity === 'Contact') { contactUpdates[field.crmField] = formData[field.name]; } } }); }); // 2. Update Contact in CiviCRM if (Object.keys(contactUpdates).length > 0) { await civicrmApi('Contact', 'save', { records: [{ id: parseInt(contactId), ...contactUpdates }], }); } // 3. Create Activity in CiviCRM to record the submission await civicrmApi('Activity', 'create', { values: { activity_type_id: 'Meeting', // Or a custom "Form Submission" activity type subject: `Stage Progression Form Submission (Org ID: ${orgId})`, target_contact_id: [parseInt(contactId)], source_contact_id: parseInt(contactId), // Assuming contact submits for themselves or adjust status_id: 'Completed', details: JSON.stringify(formData, null, 2), }, }); return NextResponse.json({ success: true, message: 'Data saved and activity created' }); } catch (error) { console.error('Submission Error:', error); // Mock success for development if (process.env.NODE_ENV === 'development') { return NextResponse.json({ success: true, message: 'Mock Success' }); } return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); } }