2022-05-17 23:54:06 +00:00
|
|
|
import { type ActionFunction, json } from "@remix-run/node";
|
|
|
|
import { badRequest } from "remix-utils";
|
|
|
|
import { z } from "zod";
|
|
|
|
|
|
|
|
import db from "~/utils/db.server";
|
|
|
|
import { type FormError, validate } from "~/utils/validation.server";
|
|
|
|
import { requireLoggedIn } from "~/utils/auth.server";
|
2022-05-21 19:33:23 +00:00
|
|
|
import setTwilioWebhooksQueue from "~/queues/set-twilio-webhooks.server";
|
2022-05-17 23:54:06 +00:00
|
|
|
|
|
|
|
type SetPhoneNumberFailureActionData = { errors: FormError<typeof bodySchema>; submitted?: never };
|
|
|
|
type SetPhoneNumberSuccessfulActionData = { errors?: never; submitted: true };
|
|
|
|
export type SetPhoneNumberActionData = SetPhoneNumberFailureActionData | SetPhoneNumberSuccessfulActionData;
|
|
|
|
|
|
|
|
const action: ActionFunction = async ({ request }) => {
|
2022-05-21 19:33:23 +00:00
|
|
|
const { organization } = await requireLoggedIn(request);
|
2022-05-17 23:54:06 +00:00
|
|
|
const formData = Object.fromEntries(await request.formData());
|
|
|
|
const validation = validate(bodySchema, formData);
|
|
|
|
if (validation.errors) {
|
|
|
|
return badRequest<SetPhoneNumberActionData>({ errors: validation.errors });
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
await db.phoneNumber.update({
|
|
|
|
where: { organizationId_isCurrent: { organizationId: organization.id, isCurrent: true } },
|
|
|
|
data: { isCurrent: false },
|
|
|
|
});
|
|
|
|
} catch (error: any) {
|
|
|
|
if (error.code !== "P2025") {
|
|
|
|
// if any error other than record not found
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
await db.phoneNumber.update({
|
|
|
|
where: { id: validation.data.phoneNumberSid },
|
|
|
|
data: { isCurrent: true },
|
|
|
|
});
|
2022-05-21 19:33:23 +00:00
|
|
|
await setTwilioWebhooksQueue.add(`set twilio webhooks for phoneNumberId=${validation.data.phoneNumberSid}`, {
|
|
|
|
phoneNumberId: validation.data.phoneNumberSid,
|
|
|
|
organizationId: organization.id,
|
|
|
|
});
|
|
|
|
console.log("queued");
|
2022-05-17 23:54:06 +00:00
|
|
|
|
|
|
|
return json<SetPhoneNumberActionData>({ submitted: true });
|
|
|
|
};
|
|
|
|
|
|
|
|
export default action;
|
|
|
|
|
|
|
|
const bodySchema = z.object({
|
|
|
|
phoneNumberSid: z
|
|
|
|
.string()
|
|
|
|
.refine((phoneNumberSid) => phoneNumberSid.startsWith("PN"), "Select a valid phone number"),
|
|
|
|
});
|