54 lines
1.8 KiB
TypeScript
54 lines
1.8 KiB
TypeScript
import { readBody } from "h3";
|
|
import { prisma } from "../utils/prisma";
|
|
import { getAuthContext } from "../utils/auth";
|
|
|
|
function toDbChannel(channel: string) {
|
|
const c = channel.toLowerCase();
|
|
if (c === "telegram") return "TELEGRAM";
|
|
if (c === "whatsapp") return "WHATSAPP";
|
|
if (c === "instagram") return "INSTAGRAM";
|
|
if (c === "email") return "EMAIL";
|
|
return "PHONE";
|
|
}
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const auth = await getAuthContext(event);
|
|
const body = await readBody<{
|
|
contact?: string;
|
|
channel?: string;
|
|
kind?: "message" | "call";
|
|
direction?: "in" | "out";
|
|
text?: string;
|
|
at?: string;
|
|
durationSec?: number;
|
|
transcript?: string[];
|
|
}>(event);
|
|
|
|
const contactName = (body?.contact ?? "").trim();
|
|
if (!contactName) throw createError({ statusCode: 400, statusMessage: "contact is required" });
|
|
|
|
const contact = await prisma.contact.findFirst({
|
|
where: { teamId: auth.teamId, name: contactName },
|
|
select: { id: true, name: true },
|
|
});
|
|
if (!contact) throw createError({ statusCode: 404, statusMessage: "contact not found" });
|
|
|
|
const occurredAt = body?.at ? new Date(body.at) : new Date();
|
|
if (Number.isNaN(occurredAt.getTime())) throw createError({ statusCode: 400, statusMessage: "at is invalid" });
|
|
|
|
const created = await prisma.contactMessage.create({
|
|
data: {
|
|
contactId: contact.id,
|
|
kind: body?.kind === "call" ? "CALL" : "MESSAGE",
|
|
direction: body?.direction === "in" ? "IN" : "OUT",
|
|
channel: toDbChannel(body?.channel ?? "Phone") as any,
|
|
content: (body?.text ?? "").trim(),
|
|
durationSec: typeof body?.durationSec === "number" ? body.durationSec : null,
|
|
transcriptJson: Array.isArray(body?.transcript) ? body.transcript : undefined,
|
|
occurredAt,
|
|
},
|
|
});
|
|
|
|
return { ok: true, id: created.id };
|
|
});
|