2021-07-31 15:57:43 +00:00
|
|
|
import { resolver } from "blitz";
|
|
|
|
import { z } from "zod";
|
2021-08-01 07:40:18 +00:00
|
|
|
import twilio from "twilio";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
import db, { Direction, MessageStatus } from "../../../db";
|
|
|
|
import getCurrentCustomer from "../../customers/queries/get-current-customer";
|
|
|
|
import getCustomerPhoneNumber from "../../phone-numbers/queries/get-customer-phone-number";
|
|
|
|
import { encrypt } from "../../../db/_encryption";
|
2021-08-01 10:46:10 +00:00
|
|
|
import sendMessageQueue from "../../messages/api/queue/send-message";
|
2021-08-01 07:40:18 +00:00
|
|
|
import appLogger from "../../../integrations/logger";
|
|
|
|
|
|
|
|
const logger = appLogger.child({ mutation: "send-message" });
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
const Body = z.object({
|
|
|
|
content: z.string(),
|
|
|
|
to: z.string(),
|
2021-07-31 15:57:43 +00:00
|
|
|
});
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
export default resolver.pipe(
|
|
|
|
resolver.zod(Body),
|
|
|
|
resolver.authorize(),
|
|
|
|
async ({ content, to }, context) => {
|
2021-07-31 15:57:43 +00:00
|
|
|
const customer = await getCurrentCustomer(null, context);
|
2021-08-01 07:40:18 +00:00
|
|
|
try {
|
|
|
|
await twilio(customer!.accountSid!, customer!.authToken!)
|
|
|
|
.lookups.v1.phoneNumbers(to)
|
|
|
|
.fetch();
|
|
|
|
} catch (error) {
|
|
|
|
logger.error(error);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
const customerId = customer!.id;
|
|
|
|
const customerPhoneNumber = await getCustomerPhoneNumber({ customerId }, context);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
const message = await db.message.create({
|
|
|
|
data: {
|
|
|
|
customerId,
|
|
|
|
to,
|
|
|
|
from: customerPhoneNumber!.phoneNumber,
|
|
|
|
direction: Direction.Outbound,
|
|
|
|
status: MessageStatus.Queued,
|
|
|
|
content: encrypt(content, customer!.encryptionKey),
|
|
|
|
sentAt: new Date(),
|
|
|
|
},
|
2021-07-31 15:57:43 +00:00
|
|
|
});
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
await sendMessageQueue.enqueue(
|
|
|
|
{
|
|
|
|
id: message.id,
|
|
|
|
customerId,
|
|
|
|
to,
|
|
|
|
content,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
id: message.id,
|
2021-08-01 12:04:04 +00:00
|
|
|
},
|
2021-07-31 15:57:43 +00:00
|
|
|
);
|
2021-08-01 12:04:04 +00:00
|
|
|
},
|
2021-07-31 15:57:43 +00:00
|
|
|
);
|