import type { CollectionAfterChangeHook, CollectionConfig } from "payload"; import { isAdmin } from "@/access"; import { conversationReplyEmail } from "@/lib/email/conversationTemplates"; import { sendEmail } from "@/lib/email/sendBookingEmails"; const sendAdminReply: CollectionAfterChangeHook = async ({ doc, operation, req }) => { if (operation !== "create" || doc.senderType !== "admin") return doc; try { const conversation = await req.payload.findByID({ collection: "conversations", id: typeof doc.conversation === "object" ? doc.conversation.id : doc.conversation, depth: 0, req, }); const adminUser = req.user?.collection === "users" ? req.user : null; await sendEmail( conversation.email, conversationReplyEmail({ name: conversation.name, subject: conversation.subject, body: doc.body, senderName: doc.senderName || adminUser?.name || "Anouma", threadKey: conversation.threadKey, }), { replyTo: process.env.INBOUND_REPLY_TO || "reply-to@anouma.org" }, ); await req.payload.update({ collection: "conversations", id: conversation.id, req, data: { status: "waiting", lastMessageAt: new Date().toISOString() }, }); } catch (err) { req.payload.logger.error({ err, msg: "conversation admin reply email failed" }); } return doc; }; export const ConversationMessages: CollectionConfig = { slug: "conversation-messages", labels: { singular: "Nachricht", plural: "Nachrichten", }, admin: { useAsTitle: "body", defaultColumns: ["conversation", "senderType", "senderName", "createdAt"], group: "Kommunikation", description: "Einzelne Nachrichten innerhalb einer Anfrage. Antworten aus der Verwaltung werden automatisch per E-Mail verschickt.", hidden: true, }, access: { read: isAdmin, create: isAdmin, update: isAdmin, delete: isAdmin, }, timestamps: true, hooks: { afterChange: [sendAdminReply], }, fields: [ { name: "conversation", type: "relationship", relationTo: "conversations", label: "Anfrage", required: true, index: true, }, { name: "senderType", type: "select", label: "Absenderart", required: true, defaultValue: "admin", options: [ { label: "Anfragende Person", value: "visitor" }, { label: "Anouma", value: "admin" }, ], admin: { description: "Für Antworten aus der Verwaltung „Anouma“ auswählen. Eingehende E-Mails werden automatisch als anfragende Person gespeichert." }, }, { name: "senderName", type: "text", label: "Absendername" }, { name: "senderEmail", type: "email", label: "Absender-E-Mail" }, { name: "body", type: "textarea", label: "Nachricht", required: true, minLength: 1, }, { name: "externalMessageId", type: "text", label: "Externe Nachrichten-ID", unique: true, index: true, admin: { position: "sidebar", readOnly: true }, }, ], };