shellphone.app/app/phone-calls/api/queue/insert-calls.ts

70 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Queue } from "quirrel/blitz";
import type { CallInstance } from "twilio/lib/rest/api/v2010/account/call";
2021-07-31 14:33:18 +00:00
2021-08-01 10:46:10 +00:00
import db, { Direction, CallStatus } from "../../../../db";
2021-07-31 14:33:18 +00:00
type Payload = {
2021-08-05 17:07:15 +00:00
organizationId: string;
phoneNumberId: string;
calls: CallInstance[];
};
2021-07-31 14:33:18 +00:00
2021-08-05 17:07:15 +00:00
const insertCallsQueue = Queue<Payload>("api/queue/insert-calls", async ({ calls, organizationId, phoneNumberId }) => {
const phoneNumber = await db.phoneNumber.findFirst({
where: { id: phoneNumberId, organizationId },
include: { organization: true },
});
if (!phoneNumber) {
return;
}
2021-07-31 14:33:18 +00:00
const phoneCalls = calls
.map((call) => ({
2021-08-05 17:07:15 +00:00
organizationId,
phoneNumberId,
id: call.sid,
2021-07-31 14:33:18 +00:00
from: call.from,
to: call.to,
direction: translateDirection(call.direction),
status: translateStatus(call.status),
duration: call.duration,
createdAt: new Date(call.dateCreated),
}))
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
2021-07-31 14:33:18 +00:00
await db.phoneCall.createMany({ data: phoneCalls, skipDuplicates: true });
});
2021-07-31 14:33:18 +00:00
export default insertCallsQueue;
2021-07-31 14:33:18 +00:00
function translateDirection(direction: CallInstance["direction"]): Direction {
switch (direction) {
case "inbound":
return Direction.Inbound;
2021-07-31 14:33:18 +00:00
case "outbound":
default:
return Direction.Outbound;
2021-07-31 14:33:18 +00:00
}
}
function translateStatus(status: CallInstance["status"]): CallStatus {
switch (status) {
case "busy":
return CallStatus.Busy;
2021-07-31 14:33:18 +00:00
case "canceled":
return CallStatus.Canceled;
2021-07-31 14:33:18 +00:00
case "completed":
return CallStatus.Completed;
2021-07-31 14:33:18 +00:00
case "failed":
return CallStatus.Failed;
2021-07-31 14:33:18 +00:00
case "in-progress":
return CallStatus.InProgress;
2021-07-31 14:33:18 +00:00
case "no-answer":
return CallStatus.NoAnswer;
2021-07-31 14:33:18 +00:00
case "queued":
return CallStatus.Queued;
2021-07-31 14:33:18 +00:00
case "ringing":
return CallStatus.Ringing;
2021-07-31 14:33:18 +00:00
}
}