2021-08-03 13:03:10 +00:00
|
|
|
import { getConfig } from "blitz";
|
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 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
|
|
|
|
2021-08-03 13:03:10 +00:00
|
|
|
const { serverRuntimeConfig } = getConfig();
|
|
|
|
|
2021-08-01 14:03:49 +00:00
|
|
|
const setTwilioWebhooks = Queue<Payload>("api/queue/set-twilio-webhooks", 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;
|
|
|
|
}
|
|
|
|
|
|
|
|
const twimlApp = customer.twimlAppSid
|
|
|
|
? await twilio(customer.accountSid, customer.authToken).applications.get(customer.twimlAppSid).fetch()
|
|
|
|
: await twilio(customer.accountSid, customer.authToken).applications.create({
|
2021-08-03 13:03:10 +00:00
|
|
|
friendlyName: "Shellphone",
|
|
|
|
smsUrl: `https://${serverRuntimeConfig.app.baseUrl}/api/webhook/incoming-message`,
|
2021-08-01 14:03:49 +00:00
|
|
|
smsMethod: "POST",
|
2021-08-03 13:03:10 +00:00
|
|
|
voiceUrl: `https://${serverRuntimeConfig.app.baseUrl}/api/webhook/incoming-call`,
|
2021-08-01 14:03:49 +00:00
|
|
|
voiceMethod: "POST",
|
|
|
|
});
|
|
|
|
const twimlAppSid = twimlApp.sid;
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-01 14:03:49 +00:00
|
|
|
await Promise.all([
|
|
|
|
db.customer.update({
|
|
|
|
where: { id: customerId },
|
|
|
|
data: { twimlAppSid },
|
|
|
|
}),
|
2021-08-02 10:02:49 +00:00
|
|
|
twilio(customer.accountSid, customer.authToken).incomingPhoneNumbers.get(phoneNumber.phoneNumberSid).update({
|
|
|
|
smsApplicationSid: twimlAppSid,
|
|
|
|
voiceApplicationSid: twimlAppSid,
|
|
|
|
}),
|
2021-08-01 14:03:49 +00:00
|
|
|
]);
|
|
|
|
});
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
export default setTwilioWebhooks;
|