2021-07-31 15:57:43 +00:00
|
|
|
import { Queue } from "quirrel/blitz";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-01 10:46:10 +00:00
|
|
|
import db from "../../../../db";
|
2021-07-31 15:57:43 +00:00
|
|
|
import insertCallsQueue from "./insert-calls";
|
2021-08-08 04:28:19 +00:00
|
|
|
import getTwilioClient from "../../../../integrations/twilio";
|
2021-08-30 20:13:40 +00:00
|
|
|
import appLogger from "../../../../integrations/logger";
|
|
|
|
|
|
|
|
const logger = appLogger.child({ queue: "fetch-calls" });
|
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
|
|
|
};
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-05 17:07:15 +00:00
|
|
|
const fetchCallsQueue = Queue<Payload>("api/queue/fetch-calls", async ({ organizationId, phoneNumberId }) => {
|
|
|
|
const phoneNumber = await db.phoneNumber.findFirst({
|
|
|
|
where: { id: phoneNumberId, organizationId },
|
|
|
|
include: { organization: true },
|
|
|
|
});
|
|
|
|
if (!phoneNumber) {
|
2021-08-30 20:13:40 +00:00
|
|
|
logger.warn(`No phone number found with id=${phoneNumberId}, organizationId=${organizationId}`);
|
2021-08-05 17:07:15 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const organization = phoneNumber.organization;
|
2021-08-08 04:28:19 +00:00
|
|
|
const twilioClient = getTwilioClient(organization);
|
2021-07-31 14:33:18 +00:00
|
|
|
const [callsSent, callsReceived] = await Promise.all([
|
2021-08-08 04:28:19 +00:00
|
|
|
twilioClient.calls.list({ from: phoneNumber.number }),
|
|
|
|
twilioClient.calls.list({ to: phoneNumber.number }),
|
2021-07-31 15:57:43 +00:00
|
|
|
]);
|
2021-10-03 19:31:26 +00:00
|
|
|
const calls = [...callsSent, ...callsReceived];
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
await insertCallsQueue.enqueue(
|
|
|
|
{
|
2021-08-05 17:07:15 +00:00
|
|
|
organizationId,
|
|
|
|
phoneNumberId,
|
2021-07-31 14:33:18 +00:00
|
|
|
calls,
|
|
|
|
},
|
|
|
|
{
|
2021-08-05 17:07:15 +00:00
|
|
|
id: `insert-calls-${organizationId}-${phoneNumberId}`,
|
2021-08-01 12:04:04 +00:00
|
|
|
},
|
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 fetchCallsQueue;
|