shellphone.app/app/messages/mutations/send-message.ts

81 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-08-05 17:07:15 +00:00
import { NotFoundError, resolver } from "blitz";
import { z } from "zod";
2021-07-31 14:33:18 +00:00
import db, { Direction, MessageStatus, SubscriptionStatus } from "../../../db";
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";
import getTwilioClient from "../../../integrations/twilio";
2021-08-01 07:40:18 +00:00
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 14:33:18 +00:00
2021-08-01 14:03:49 +00:00
export default resolver.pipe(resolver.zod(Body), resolver.authorize(), async ({ content, to }, context) => {
2021-08-05 17:07:15 +00:00
const organizationId = context.session.orgId;
const organization = await db.organization.findFirst({
where: { id: organizationId },
include: { phoneNumbers: true },
});
if (!organization) {
throw new NotFoundError();
}
const twilioClient = getTwilioClient(organization);
2021-08-01 14:03:49 +00:00
try {
await twilioClient.lookups.v1.phoneNumbers(to).fetch();
2021-08-27 18:05:44 +00:00
} catch (error: any) {
2021-08-01 14:03:49 +00:00
logger.error(error);
return;
}
2021-08-01 07:40:18 +00:00
const phoneNumber = organization.phoneNumbers[0]; // TODO: use the active number, not the first one
2021-08-05 17:07:15 +00:00
if (!phoneNumber) {
throw new NotFoundError();
}
2021-07-31 14:33:18 +00:00
const subscription = await db.subscription.findFirst({
where: {
organizationId,
OR: [
{ status: { not: SubscriptionStatus.deleted } },
{ status: SubscriptionStatus.deleted, cancellationEffectiveDate: { gt: new Date() } },
],
},
});
const hasOngoingSubscription = Boolean(subscription);
const messageBody = hasOngoingSubscription
? content
: content + "\n\nSent from Shellphone (https://www.shellphone.app)";
2021-08-05 17:07:15 +00:00
const phoneNumberId = phoneNumber.id;
2021-08-01 14:03:49 +00:00
const message = await db.message.create({
data: {
2021-08-05 17:07:15 +00:00
organizationId,
phoneNumberId,
2021-08-01 14:03:49 +00:00
to,
2021-08-05 17:07:15 +00:00
from: phoneNumber.number,
2021-08-01 14:03:49 +00:00
direction: Direction.Outbound,
status: MessageStatus.Queued,
content: encrypt(messageBody, organization.encryptionKey),
2021-08-01 14:03:49 +00:00
sentAt: new Date(),
},
});
2021-07-31 14:33:18 +00:00
2021-08-01 14:03:49 +00:00
await sendMessageQueue.enqueue(
{
id: message.id,
2021-08-05 17:07:15 +00:00
organizationId,
phoneNumberId,
2021-08-01 14:03:49 +00:00
to,
content: messageBody,
2021-08-01 14:03:49 +00:00
},
{
2021-08-05 17:07:15 +00:00
id: `insert-${message.id}-${organizationId}-${phoneNumberId}`,
2021-08-01 14:03:49 +00:00
},
);
});