import type { PayloadRequest, PayloadHandler } from "payload"; export const convertInquiryEndpoint: PayloadHandler = async ( req: PayloadRequest, ) => { const { id } = req.routeParams; const payload = req.payload; try { const inquiry = await payload.findByID({ collection: "inquiries", id: String(id), }); if (!inquiry) { return Response.json({ error: "Inquiry not found" }, { status: 404 }); } if ((inquiry as any).processed) { return Response.json( { error: "Inquiry is already processed" }, { status: 400 }, ); } // 1. Create CrmAccount const companyName = inquiry.companyName || inquiry.name; const account = await payload.create({ collection: "crm-accounts", data: { name: companyName, status: "lead", leadTemperature: "warm", // Warm because they reached out }, }); // 2. Create CrmContact const contact = await payload.create({ collection: "crm-contacts", data: { firstName: inquiry.name.split(" ")[0] || inquiry.name, lastName: inquiry.name.split(" ").slice(1).join(" ") || "", email: inquiry.email, account: account.id, }, }); // 3. Create CrmInteraction (Journal) let journalSummary = `User submitted an inquiry.\n\nProject Type: ${inquiry.projectType || "N/A"}`; if (inquiry.message) { journalSummary += `\n\nMessage:\n${inquiry.message}`; } if (inquiry.config) { journalSummary += `\n\nConfigData:\n${JSON.stringify(inquiry.config, null, 2)}`; } await payload.create({ collection: "crm-interactions", data: { subject: `Website Anfrage: ${inquiry.projectType || "Allgemein"}`, type: "email", // Use "type" field underneath ("channel" label) date: new Date().toISOString(), summary: journalSummary, account: account.id, contact: contact.id, } as any, }); // 4. Mark Inquiry as processed await payload.update({ collection: "inquiries", id: String(id), data: { processed: true, } as any, }); return Response.json({ message: "Inquiry successfully converted to CRM Lead.", accountId: account.id, }); } catch (error) { console.error("Convert inquiry error:", error); return Response.json( { error: error instanceof Error ? error.message : "Unknown error" }, { status: 500 }, ); } };