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 insertMessagesQueue from "./insert-messages";
|
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 fetchMessagesQueue = Queue<Payload>("api/queue/fetch-messages", async ({ customerId }) => {
|
2021-08-02 10:02:49 +00:00
|
|
|
const [customer, phoneNumber] = await Promise.all([
|
|
|
|
db.customer.findFirst({ where: { id: customerId } }),
|
|
|
|
db.phoneNumber.findFirst({ where: { customerId } }),
|
|
|
|
]);
|
|
|
|
if (!customer || !customer.accountSid || !customer.authToken || !phoneNumber) {
|
|
|
|
return;
|
|
|
|
}
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-01 14:01:51 +00:00
|
|
|
const [sent, received] = await Promise.all([
|
2021-08-02 10:02:49 +00:00
|
|
|
twilio(customer.accountSid, customer.authToken).messages.list({ from: phoneNumber.phoneNumber }),
|
|
|
|
twilio(customer.accountSid, customer.authToken).messages.list({ to: phoneNumber.phoneNumber }),
|
2021-07-31 15:57:43 +00:00
|
|
|
]);
|
2021-08-01 14:01:51 +00:00
|
|
|
const messagesSent = sent.filter((message) => message.direction.startsWith("outbound"));
|
|
|
|
const messagesReceived = received.filter((message) => message.direction === "inbound");
|
2021-07-31 14:33:18 +00:00
|
|
|
const messages = [...messagesSent, ...messagesReceived].sort(
|
2021-08-01 12:04:04 +00:00
|
|
|
(a, b) => a.dateCreated.getTime() - b.dateCreated.getTime(),
|
2021-07-31 15:57:43 +00:00
|
|
|
);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
await insertMessagesQueue.enqueue(
|
|
|
|
{
|
|
|
|
customerId,
|
|
|
|
messages,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
id: `insert-messages-${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 fetchMessagesQueue;
|