2021-07-31 15:57:43 +00:00
|
|
|
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-30 12:53:21 +00:00
|
|
|
import db from "../../../../db";
|
|
|
|
import { translateCallDirection, translateCallStatus } from "../../../../integrations/twilio";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
type Payload = {
|
2021-08-05 17:07:15 +00:00
|
|
|
organizationId: string;
|
|
|
|
phoneNumberId: string;
|
2021-07-31 15:57:43 +00:00
|
|
|
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,
|
2021-08-30 12:53:21 +00:00
|
|
|
direction: translateCallDirection(call.direction),
|
|
|
|
status: translateCallStatus(call.status),
|
2021-07-31 14:33:18 +00:00
|
|
|
duration: call.duration,
|
|
|
|
createdAt: new Date(call.dateCreated),
|
|
|
|
}))
|
2021-07-31 15:57:43 +00:00
|
|
|
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-13 17:15:35 +00:00
|
|
|
await db.phoneCall.createMany({ data: phoneCalls, skipDuplicates: true });
|
2021-09-24 23:07:40 +00:00
|
|
|
|
|
|
|
const processingState = await db.processingPhoneNumber.findFirst({ where: { organizationId, phoneNumberId } });
|
|
|
|
if (!processingState) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (processingState.hasFetchedMessages) {
|
|
|
|
await db.processingPhoneNumber.delete({
|
|
|
|
where: { organizationId_phoneNumberId: { organizationId, phoneNumberId } },
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
await db.processingPhoneNumber.update({
|
|
|
|
where: { organizationId_phoneNumberId: { organizationId, phoneNumberId } },
|
|
|
|
data: { hasFetchedCalls: true },
|
|
|
|
});
|
|
|
|
}
|
2021-07-31 15:57:43 +00:00
|
|
|
});
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
export default insertCallsQueue;
|