2021-07-31 15:57:43 +00:00
|
|
|
import { Queue } from "quirrel/blitz";
|
|
|
|
import twilio from "twilio";
|
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-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
type Payload = {
|
2021-07-31 15:57:43 +00:00
|
|
|
customerId: string;
|
|
|
|
};
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
const fetchCallsQueue = Queue<Payload>("api/queue/fetch-calls", async ({ customerId }) => {
|
2021-07-31 15:57:43 +00:00
|
|
|
const customer = await db.customer.findFirst({ where: { id: customerId } });
|
|
|
|
const phoneNumber = await db.phoneNumber.findFirst({ where: { customerId } });
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
const [callsSent, callsReceived] = await Promise.all([
|
|
|
|
twilio(customer!.accountSid!, customer!.authToken!).calls.list({
|
|
|
|
from: phoneNumber!.phoneNumber,
|
|
|
|
}),
|
|
|
|
twilio(customer!.accountSid!, customer!.authToken!).calls.list({
|
|
|
|
to: phoneNumber!.phoneNumber,
|
|
|
|
}),
|
2021-07-31 15:57:43 +00:00
|
|
|
]);
|
2021-08-01 14:03:49 +00:00
|
|
|
const calls = [...callsSent, ...callsReceived].sort((a, b) => a.dateCreated.getTime() - b.dateCreated.getTime());
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
await insertCallsQueue.enqueue(
|
|
|
|
{
|
|
|
|
customerId,
|
|
|
|
calls,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
id: `insert-calls-${customerId}`,
|
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;
|