2021-07-31 15:57:43 +00:00
|
|
|
import { resolver } from "blitz";
|
|
|
|
import { z } from "zod";
|
2021-08-08 04:34:29 +00:00
|
|
|
import twilio from "twilio";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
import db from "../../../db";
|
2021-08-05 17:07:15 +00:00
|
|
|
import getCurrentUser from "../../users/queries/get-current-user";
|
2021-08-01 10:46:10 +00:00
|
|
|
import setTwilioWebhooks from "../api/queue/set-twilio-webhooks";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
const Body = z.object({
|
|
|
|
phoneNumberSid: z.string(),
|
2021-07-31 15:57:43 +00:00
|
|
|
});
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-01 14:01:51 +00:00
|
|
|
export default resolver.pipe(resolver.zod(Body), resolver.authorize(), async ({ phoneNumberSid }, context) => {
|
2021-08-05 17:07:15 +00:00
|
|
|
const user = await getCurrentUser(null, context);
|
|
|
|
const organization = user?.memberships[0]!.organization;
|
2021-08-08 04:34:29 +00:00
|
|
|
if (!user || !organization || !organization.twilioAccountSid || !organization.twilioAuthToken) {
|
2021-08-02 10:02:49 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-08-08 04:34:29 +00:00
|
|
|
const phoneNumbers = await twilio(
|
|
|
|
organization.twilioAccountSid,
|
|
|
|
organization.twilioAuthToken,
|
|
|
|
).incomingPhoneNumbers.list();
|
2021-08-01 14:01:51 +00:00
|
|
|
const phoneNumber = phoneNumbers.find((phoneNumber) => phoneNumber.sid === phoneNumberSid)!;
|
2021-08-05 17:07:15 +00:00
|
|
|
const organizationId = organization.id;
|
2021-08-01 14:01:51 +00:00
|
|
|
await db.phoneNumber.create({
|
|
|
|
data: {
|
2021-08-05 17:07:15 +00:00
|
|
|
organizationId,
|
|
|
|
id: phoneNumberSid,
|
|
|
|
number: phoneNumber.phoneNumber,
|
2021-08-01 14:01:51 +00:00
|
|
|
},
|
|
|
|
});
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-08 05:34:15 +00:00
|
|
|
const mainTwilioClient = twilio(organization.twilioAccountSid, organization.twilioAuthToken);
|
|
|
|
const apiKey = await mainTwilioClient.newKeys.create({ friendlyName: "Shellphone API key" });
|
|
|
|
await db.organization.update({
|
|
|
|
where: { id: organizationId },
|
|
|
|
data: {
|
|
|
|
twilioApiKey: apiKey.sid,
|
|
|
|
twilioApiSecret: apiKey.secret,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2021-08-05 17:07:15 +00:00
|
|
|
const phoneNumberId = phoneNumberSid;
|
2021-08-01 14:01:51 +00:00
|
|
|
await Promise.all([
|
2021-08-05 17:07:15 +00:00
|
|
|
setTwilioWebhooks.enqueue(
|
|
|
|
{ organizationId, phoneNumberId },
|
|
|
|
{ id: `set-twilio-webhooks-${organizationId}-${phoneNumberId}` },
|
|
|
|
),
|
2021-08-01 14:01:51 +00:00
|
|
|
]);
|
|
|
|
});
|