2022-05-17 23:54:06 +00:00
|
|
|
import type { CallInstance } from "twilio/lib/rest/api/v2010/account/call";
|
2022-05-21 23:17:43 +00:00
|
|
|
import { type PhoneCall, Direction } from "@prisma/client";
|
2022-05-17 23:54:06 +00:00
|
|
|
|
|
|
|
import { Queue } from "~/utils/queue.server";
|
|
|
|
import db from "~/utils/db.server";
|
|
|
|
import { translateCallDirection, translateCallStatus } from "~/utils/twilio.server";
|
|
|
|
import logger from "~/utils/logger.server";
|
|
|
|
|
|
|
|
type Payload = {
|
|
|
|
phoneNumberId: string;
|
|
|
|
calls: CallInstance[];
|
|
|
|
};
|
|
|
|
|
|
|
|
export default Queue<Payload>("insert phone calls", async ({ data }) => {
|
|
|
|
const { calls, phoneNumberId } = data;
|
2022-07-01 23:49:34 +00:00
|
|
|
logger.info(`Inserting ${calls.length} phone calls for phone number with id=${phoneNumberId}`);
|
2022-06-11 00:09:37 +00:00
|
|
|
const phoneNumber = await db.phoneNumber.findUnique({ where: { id: phoneNumberId } });
|
2022-05-17 23:54:06 +00:00
|
|
|
if (!phoneNumber) {
|
2022-07-01 23:49:34 +00:00
|
|
|
logger.warn(`No phone number found with id=${phoneNumberId}`);
|
2022-05-17 23:54:06 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const phoneCalls = calls
|
2022-05-21 23:17:43 +00:00
|
|
|
.map<PhoneCall>((call) => {
|
|
|
|
const direction = translateCallDirection(call.direction);
|
|
|
|
const status = translateCallStatus(call.status);
|
|
|
|
return {
|
|
|
|
phoneNumberId,
|
|
|
|
id: call.sid,
|
|
|
|
recipient: direction === Direction.Outbound ? call.to : call.from,
|
|
|
|
from: call.from,
|
|
|
|
to: call.to,
|
|
|
|
direction,
|
|
|
|
status,
|
|
|
|
duration: call.duration,
|
|
|
|
createdAt: new Date(call.dateCreated),
|
|
|
|
};
|
|
|
|
})
|
2022-05-17 23:54:06 +00:00
|
|
|
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
|
|
|
|
2022-06-11 00:09:37 +00:00
|
|
|
const { count } = await db.phoneCall.createMany({ data: phoneCalls, skipDuplicates: true });
|
2022-07-01 23:49:34 +00:00
|
|
|
logger.info(`Inserted ${count} new phone calls for phone number with id=${phoneNumberId}`);
|
2022-05-17 23:54:06 +00:00
|
|
|
|
|
|
|
if (!phoneNumber.isFetchingCalls) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
await db.phoneNumber.update({
|
|
|
|
where: { id: phoneNumberId },
|
|
|
|
data: { isFetchingCalls: null },
|
|
|
|
});
|
|
|
|
});
|