got {messages,phone calls} {fetching,display} working

This commit is contained in:
m5r 2022-05-18 01:54:06 +02:00
parent 7dc9c403d8
commit 9c9b4a5af4
22 changed files with 543 additions and 133 deletions

View File

@ -13,7 +13,7 @@ export default function MissingTwilioCredentials() {
</p> </p>
<div className="mt-6"> <div className="mt-6">
<Link <Link
to="/settings/account" to="/settings/phone"
className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-primary-500 focus:outline-none focus:ring-2 focus:ring-offset-2" className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-primary-500 focus:outline-none focus:ring-2 focus:ring-offset-2"
> >
<IoSettings className="-ml-1 mr-2 h-5 w-5" aria-hidden="true" /> <IoSettings className="-ml-1 mr-2 h-5 w-5" aria-hidden="true" />

View File

@ -1,7 +1,6 @@
import type { FunctionComponent } from "react"; import type { FunctionComponent } from "react";
import { useRef } from "react"; import { useRef } from "react";
import { useNavigate } from "@remix-run/react"; import { Link, useNavigate } from "@remix-run/react";
import { Link } from "react-router-dom";
import Modal, { ModalTitle } from "~/features/core/components/modal"; import Modal, { ModalTitle } from "~/features/core/components/modal";

View File

@ -1,5 +1,6 @@
import { Suspense, useEffect, useMemo, useRef } from "react"; import { Suspense, useEffect, useMemo, useRef } from "react";
import { useLoaderData, useParams } from "@remix-run/react"; import { useParams } from "@remix-run/react";
import { useLoaderData } from "superjson-remix";
import clsx from "clsx"; import clsx from "clsx";
import { Direction } from "@prisma/client"; import { Direction } from "@prisma/client";
@ -73,9 +74,7 @@ export default function Conversation() {
})} })}
</ul> </ul>
</div> </div>
<Suspense fallback={null}>
<NewMessageArea recipient={recipient} /> <NewMessageArea recipient={recipient} />
</Suspense>
</> </>
); );
} }

View File

@ -1,4 +1,5 @@
import { Link, useLoaderData } from "@remix-run/react"; import { Link } from "@remix-run/react";
import { useLoaderData } from "superjson-remix";
import { IoChevronForward } from "react-icons/io5"; import { IoChevronForward } from "react-icons/io5";
import { formatRelativeDate } from "~/features/core/helpers/date-formatter"; import { formatRelativeDate } from "~/features/core/helpers/date-formatter";

View File

@ -1,4 +1,5 @@
import { Link, useLoaderData } from "@remix-run/react"; import { Link } from "@remix-run/react";
import { useLoaderData } from "superjson-remix";
import { HiPhoneMissedCall, HiPhoneIncoming, HiPhoneOutgoing } from "react-icons/hi"; import { HiPhoneMissedCall, HiPhoneIncoming, HiPhoneOutgoing } from "react-icons/hi";
import clsx from "clsx"; import clsx from "clsx";
import { Direction, CallStatus } from "@prisma/client"; import { Direction, CallStatus } from "@prisma/client";

View File

@ -0,0 +1,48 @@
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";
type SetPhoneNumberFailureActionData = { errors: FormError<typeof bodySchema>; submitted?: never };
type SetPhoneNumberSuccessfulActionData = { errors?: never; submitted: true };
export type SetPhoneNumberActionData = SetPhoneNumberFailureActionData | SetPhoneNumberSuccessfulActionData;
const action: ActionFunction = async ({ request }) => {
const { organizations } = await requireLoggedIn(request);
const organization = organizations[0];
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 },
});
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"),
});

View File

@ -14,17 +14,16 @@ const HelpModal: FunctionComponent<Props> = ({ isHelpModalOpen, closeModal }) =>
<Modal initialFocus={modalCloseButtonRef} isOpen={isHelpModalOpen} onClose={closeModal}> <Modal initialFocus={modalCloseButtonRef} isOpen={isHelpModalOpen} onClose={closeModal}>
<div className="md:flex md:items-start"> <div className="md:flex md:items-start">
<div className="mt-3 text-center md:mt-0 md:ml-4 md:text-left"> <div className="mt-3 text-center md:mt-0 md:ml-4 md:text-left">
<ModalTitle>Need help finding your Twilio credentials?</ModalTitle> <ModalTitle>Need some help?</ModalTitle>
<div className="mt-6 space-y-3 text-gray-500"> <div className="mt-6 space-y-3 text-gray-500">
<p> <p>
You can check out our{" "} Try{" "}
<a className="underline" href="https://docs.shellphone.app/guide/getting-started"> <a className="underline" href="https://www.twilio.com/authorize/CN01675d385a9ee79e6aa58adf54abe3b3">
getting started reconnecting your Twilio account
</a>{" "} </a> to refresh the phone numbers.
guide to set up your account with your Twilio credentials.
</p> </p>
<p> <p>
If you feel stuck, pick a date & time on{" "} If you are stuck, pick a date & time on{" "}
<a className="underline" href="https://calendly.com/shellphone-onboarding"> <a className="underline" href="https://calendly.com/shellphone-onboarding">
our calendly our calendly
</a>{" "} </a>{" "}

View File

@ -1,47 +1,45 @@
import { useActionData, useCatch, useLoaderData, useTransition } from "@remix-run/react"; import { Form, useActionData, useCatch, useLoaderData, useTransition } from "@remix-run/react";
import Button from "../button"; import Button from "../button";
import SettingsSection from "../settings-section"; import SettingsSection from "../settings-section";
import Alert from "~/features/core/components/alert"; import Alert from "~/features/core/components/alert";
import useSession from "~/features/core/hooks/use-session"; import useSession from "~/features/core/hooks/use-session";
import { PhoneSettingsLoaderData } from "~/routes/__app/settings/phone"; import type { PhoneSettingsLoaderData } from "~/routes/__app/settings/phone";
import type { SetPhoneNumberActionData } from "~/features/settings/actions/phone";
export default function PhoneNumberForm() { export default function PhoneNumberForm() {
const transition = useTransition(); const transition = useTransition();
const actionData = useActionData(); const actionData = useActionData<SetPhoneNumberActionData>();
const { currentOrganization } = useSession(); const { currentOrganization } = useSession();
const availablePhoneNumbers = useLoaderData<PhoneSettingsLoaderData>().phoneNumbers;
const isSubmitting = transition.state === "submitting"; const isSubmitting = transition.state === "submitting";
const isSuccess = actionData?.submitted === true; const isSuccess = actionData?.submitted === true;
const error = actionData?.error; const errors = actionData?.errors;
const isError = !!error; const topErrorMessage = errors?.general ?? errors?.phoneNumberSid;
const isError = typeof topErrorMessage !== "undefined";
const currentPhoneNumber = availablePhoneNumbers.find(phoneNumber => phoneNumber.isCurrent === true);
const hasFilledTwilioCredentials = Boolean(currentOrganization.twilioAccountSid) const hasFilledTwilioCredentials = Boolean(currentOrganization.twilioAccountSid)
const availablePhoneNumbers = useLoaderData<PhoneSettingsLoaderData>().phoneNumbers;
const onSubmit = async () => {
// await setPhoneNumberMutation({ phoneNumberSid }); // TODO
};
if (!hasFilledTwilioCredentials) { if (!hasFilledTwilioCredentials) {
return null; return null;
} }
return ( return (
<form onSubmit={onSubmit} className="flex flex-col gap-6"> <Form method="post" className="flex flex-col gap-6">
<SettingsSection <SettingsSection
className="relative" className="relative"
footer={ footer={
<div className="px-4 py-3 bg-gray-50 text-right text-sm font-medium sm:px-6"> <div className="px-4 py-3 bg-gray-50 text-right text-sm font-medium sm:px-6">
<Button variant="default" type="submit" isDisabled={isSubmitting}> <Button variant="default" type="submit" isDisabled={isSubmitting}>
{isSubmitting ? "Saving..." : "Save"} Save
</Button> </Button>
</div> </div>
} }
> >
{isError ? ( {isError ? (
<div className="mb-8"> <div className="mb-8">
<Alert title="Oops, there was an issue" message={error} variant="error" /> <Alert title="Oops, there was an issue" message={topErrorMessage} variant="error" />
</div> </div>
) : null} ) : null}
@ -58,16 +56,17 @@ export default function PhoneNumberForm() {
id="phoneNumberSid" id="phoneNumberSid"
name="phoneNumberSid" name="phoneNumberSid"
className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md" className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
defaultValue={currentPhoneNumber?.id}
> >
<option value="none" /> <option value="none" />
{availablePhoneNumbers?.map(({ sid, phoneNumber }) => ( {availablePhoneNumbers.map(({ id, number }) => (
<option value={sid} key={sid}> <option value={id} key={id}>
{phoneNumber} {number}
</option> </option>
))} ))}
</select> </select>
</SettingsSection> </SettingsSection>
</form> </Form>
); );
} }

View File

@ -11,12 +11,12 @@ export default function TwilioConnect() {
return ( return (
<> <>
<section className="flex flex-col gap-6"> <SettingsSection className="flex flex-col relative">
<SettingsSection className="relative"> <section>
<button onClick={() => setIsHelpModalOpen(true)} className="absolute top-2 right-2"> <button onClick={() => setIsHelpModalOpen(true)} className="absolute top-2 right-2">
<IoHelpCircle className="w-6 h-6 text-primary-700" /> <IoHelpCircle className="w-6 h-6 text-primary-700" />
</button> </button>
<article> <article className="mb-6">
Shellphone needs to connect to your Twilio account to securely use your phone numbers. Shellphone needs to connect to your Twilio account to securely use your phone numbers.
</article> </article>
@ -31,8 +31,8 @@ export default function TwilioConnect() {
) : ( ) : (
<p className="text-green-700"> Your Twilio account is connected to Shellphone.</p> <p className="text-green-700"> Your Twilio account is connected to Shellphone.</p>
)} )}
</SettingsSection>
</section> </section>
</SettingsSection>
<HelpModal closeModal={() => setIsHelpModalOpen(false)} isHelpModalOpen={isHelpModalOpen} /> <HelpModal closeModal={() => setIsHelpModalOpen(false)} isHelpModalOpen={isHelpModalOpen} />
</> </>

View File

@ -0,0 +1,36 @@
import { Queue } from "~/utils/queue.server";
import db from "~/utils/db.server";
import logger from "~/utils/logger.server";
import getTwilioClient from "~/utils/twilio.server";
import insertMessagesQueue from "./insert-messages.server";
type Payload = {
phoneNumberId: string;
};
export default Queue<Payload>("fetch messages", async ({ data }) => {
const { phoneNumberId } = data;
const phoneNumber = await db.phoneNumber.findUnique({
where: { id: phoneNumberId },
include: { organization: true },
});
if (!phoneNumber) {
logger.warn(`No phone number found with id=${phoneNumberId}`);
return;
}
const organization = phoneNumber.organization;
const twilioClient = getTwilioClient(organization);
const [sent, received] = await Promise.all([
twilioClient.messages.list({ from: phoneNumber.number }),
twilioClient.messages.list({ to: phoneNumber.number }),
]);
const messagesSent = sent.filter((message) => message.direction.startsWith("outbound"));
const messagesReceived = received.filter((message) => message.direction === "inbound");
const messages = [...messagesSent, ...messagesReceived];
await insertMessagesQueue.add(`insert messages of id=${phoneNumberId}`, {
phoneNumberId,
messages,
});
});

View File

@ -0,0 +1,34 @@
import { Queue } from "~/utils/queue.server";
import db from "~/utils/db.server";
import logger from "~/utils/logger.server";
import getTwilioClient from "~/utils/twilio.server";
import insertCallsQueue from "./insert-phone-calls.server";
type Payload = {
phoneNumberId: string;
};
export default Queue<Payload>("fetch phone calls", async ({ data }) => {
const { phoneNumberId } = data;
const phoneNumber = await db.phoneNumber.findUnique({
where: { id: phoneNumberId },
include: { organization: true },
});
if (!phoneNumber) {
logger.warn(`No phone number found with id=${phoneNumberId}`);
return;
}
const organization = phoneNumber.organization;
const twilioClient = getTwilioClient(organization);
const [callsSent, callsReceived] = await Promise.all([
twilioClient.calls.list({ from: phoneNumber.number }),
twilioClient.calls.list({ to: phoneNumber.number }),
]);
const calls = [...callsSent, ...callsReceived];
await insertCallsQueue.add(`insert calls of id=${phoneNumberId}`, {
phoneNumberId,
calls,
});
});

View File

@ -1,3 +1,13 @@
import deleteUserDataQueue from "./delete-user-data.server"; import deleteUserDataQueue from "./delete-user-data.server";
import fetchPhoneCallsQueue from "./fetch-phone-calls.server";
import insertPhoneCallsQueue from "./insert-phone-calls.server";
import fetchMessagesQueue from "./fetch-messages.server";
import insertMessagesQueue from "./insert-messages.server";
export default [deleteUserDataQueue]; export default [
deleteUserDataQueue,
fetchPhoneCallsQueue,
insertPhoneCallsQueue,
fetchMessagesQueue,
insertMessagesQueue,
];

View File

@ -0,0 +1,48 @@
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message";
import type { Message } from "@prisma/client";
import { Queue } from "~/utils/queue.server";
import db from "~/utils/db.server";
import { translateMessageDirection, translateMessageStatus } from "~/utils/twilio.server";
import logger from "~/utils/logger.server";
type Payload = {
phoneNumberId: string;
messages: MessageInstance[];
};
export default Queue<Payload>("insert messages", async ({ data }) => {
const { messages, phoneNumberId } = data;
const phoneNumber = await db.phoneNumber.findUnique({
where: { id: phoneNumberId },
include: { organization: true },
});
if (!phoneNumber) {
return;
}
const sms = messages
.map<Message>((message) => ({
id: message.sid,
phoneNumberId: phoneNumber.id,
content: message.body,
from: message.from,
to: message.to,
status: translateMessageStatus(message.status),
direction: translateMessageDirection(message.direction),
sentAt: new Date(message.dateCreated),
}))
.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
const { count } = await db.message.createMany({ data: sms, skipDuplicates: true });
logger.info(`inserted ${count} new messages for phoneNumberId=${phoneNumberId}`)
if (!phoneNumber.isFetchingMessages) {
return;
}
await db.phoneNumber.update({
where: { id: phoneNumberId },
data: { isFetchingMessages: null },
});
});

View File

@ -0,0 +1,48 @@
import type { CallInstance } from "twilio/lib/rest/api/v2010/account/call";
import type { PhoneCall } from "@prisma/client";
import { Queue } from "~/utils/queue.server";
import db from "~/utils/db.server";
import { translateCallDirection, translateCallStatus } from "~/utils/twilio.server";
import logger from "~/utils/logger.server";
type Payload = {
phoneNumberId: string;
calls: CallInstance[];
};
export default Queue<Payload>("insert phone calls", async ({ data }) => {
const { calls, phoneNumberId } = data;
const phoneNumber = await db.phoneNumber.findUnique({
where: { id: phoneNumberId },
include: { organization: true },
});
if (!phoneNumber) {
return;
}
const phoneCalls = calls
.map<PhoneCall>((call) => ({
phoneNumberId,
id: call.sid,
from: call.from,
to: call.to,
direction: translateCallDirection(call.direction),
status: translateCallStatus(call.status),
duration: call.duration,
createdAt: new Date(call.dateCreated),
}))
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
const ddd = await db.phoneCall.createMany({ data: phoneCalls, skipDuplicates: true });
logger.info(`inserted ${ddd.count || "no"} new phone calls for phoneNumberId=${phoneNumberId}`);
if (!phoneNumber.isFetchingCalls) {
return;
}
await db.phoneNumber.update({
where: { id: phoneNumberId },
data: { isFetchingCalls: null },
});
});

View File

@ -1,6 +1,8 @@
import { Suspense } from "react"; import { Suspense } from "react";
import { type PhoneCall, Prisma } from "@prisma/client"; import { type PhoneCall, Prisma } from "@prisma/client";
import { type LoaderFunction, json } from "@remix-run/node"; import { type LoaderFunction } from "@remix-run/node";
import { json, useLoaderData } from "superjson-remix";
import { parsePhoneNumber } from "awesome-phonenumber";
import MissingTwilioCredentials from "~/features/core/components/missing-twilio-credentials"; import MissingTwilioCredentials from "~/features/core/components/missing-twilio-credentials";
import PageTitle from "~/features/core/components/page-title"; import PageTitle from "~/features/core/components/page-title";
@ -9,30 +11,46 @@ import InactiveSubscription from "~/features/core/components/inactive-subscripti
import PhoneCallsList from "~/features/phone-calls/components/phone-calls-list"; import PhoneCallsList from "~/features/phone-calls/components/phone-calls-list";
import { requireLoggedIn } from "~/utils/auth.server"; import { requireLoggedIn } from "~/utils/auth.server";
import db from "~/utils/db.server"; import db from "~/utils/db.server";
import { parsePhoneNumber } from "awesome-phonenumber";
type PhoneCallMeta = { type PhoneCallMeta = {
formattedPhoneNumber: string; formattedPhoneNumber: string;
country: string | "unknown"; country: string | "unknown";
}; };
export type PhoneCallsLoaderData = { phoneCalls: (PhoneCall & { toMeta: PhoneCallMeta; fromMeta: PhoneCallMeta })[] }; export type PhoneCallsLoaderData = {
user: {
hasOngoingSubscription: boolean;
hasPhoneNumber: boolean;
};
phoneCalls: (PhoneCall & { toMeta: PhoneCallMeta; fromMeta: PhoneCallMeta })[] | undefined;
};
export const loader: LoaderFunction = async ({ request }) => { export const loader: LoaderFunction = async ({ request }) => {
const { organizations } = await requireLoggedIn(request); const { organizations } = await requireLoggedIn(request);
const organizationId = organizations[0].id; const organizationId = organizations[0].id;
const phoneNumberId = ""; const phoneNumber = await db.phoneNumber.findUnique({
const phoneNumber = await db.phoneNumber.findFirst({ where: { organizationId, id: phoneNumberId } }); where: { organizationId_isCurrent: { organizationId, isCurrent: true } },
if (phoneNumber?.isFetchingCalls) { });
return; if (!phoneNumber || phoneNumber.isFetchingCalls) {
return json<PhoneCallsLoaderData>({
user: {
hasOngoingSubscription: true, // TODO
hasPhoneNumber: Boolean(phoneNumber),
},
phoneCalls: undefined,
});
} }
const phoneCalls = await db.phoneCall.findMany({ const phoneCalls = await db.phoneCall.findMany({
where: { phoneNumberId }, where: { phoneNumberId: phoneNumber.id },
orderBy: { createdAt: Prisma.SortOrder.desc }, orderBy: { createdAt: Prisma.SortOrder.desc },
}); });
return json<PhoneCallsLoaderData>({ return json<PhoneCallsLoaderData>({
user: {
hasOngoingSubscription: true, // TODO
hasPhoneNumber: Boolean(phoneNumber),
},
phoneCalls: phoneCalls.map((phoneCall) => ({ phoneCalls: phoneCalls.map((phoneCall) => ({
...phoneCall, ...phoneCall,
fromMeta: getPhoneNumberMeta(phoneCall.from), fromMeta: getPhoneNumberMeta(phoneCall.from),
@ -299,13 +317,9 @@ export const loader: LoaderFunction = async ({ request }) => {
}; };
export default function PhoneCalls() { export default function PhoneCalls() {
const { hasFilledTwilioCredentials, hasPhoneNumber, hasOngoingSubscription } = { const { hasPhoneNumber, hasOngoingSubscription } = useLoaderData<PhoneCallsLoaderData>().user;
hasFilledTwilioCredentials: false,
hasPhoneNumber: false,
hasOngoingSubscription: false,
};
if (!hasFilledTwilioCredentials || !hasPhoneNumber) { if (!hasPhoneNumber) {
return ( return (
<> <>
<MissingTwilioCredentials /> <MissingTwilioCredentials />
@ -334,10 +348,10 @@ export default function PhoneCalls() {
<> <>
<PageTitle className="pl-12" title="Calls" /> <PageTitle className="pl-12" title="Calls" />
<section className="flex flex-grow flex-col"> <section className="flex flex-grow flex-col">
<Suspense fallback={<Spinner />}> {/*<Suspense fallback={<Spinner />}>*/}
{/* TODO: skeleton phone calls list */} {/* TODO: skeleton phone calls list */}
<PhoneCallsList /> <PhoneCallsList />
</Suspense> {/*</Suspense>*/}
</section> </section>
</> </>
); );

View File

@ -1,6 +1,7 @@
import { Suspense } from "react"; import { Suspense } from "react";
import { json, type LoaderFunction, type MetaFunction } from "@remix-run/node"; import type { LoaderFunction, MetaFunction } from "@remix-run/node";
import { useLoaderData, useNavigate, useParams } from "@remix-run/react"; import { useNavigate, useParams } from "@remix-run/react";
import { json, useLoaderData } from "superjson-remix";
import { IoCall, IoChevronBack, IoInformationCircle } from "react-icons/io5"; import { IoCall, IoChevronBack, IoInformationCircle } from "react-icons/io5";
import { type Message, Prisma } from "@prisma/client"; import { type Message, Prisma } from "@prisma/client";
@ -38,32 +39,21 @@ export const loader: LoaderFunction = async ({ request, params }) => {
return json<ConversationLoaderData>({ conversation }); return json<ConversationLoaderData>({ conversation });
async function getConversation(recipient: string): Promise<ConversationType> { async function getConversation(recipient: string): Promise<ConversationType> {
/*if (!hasFilledTwilioCredentials) {
return;
}*/
const organizationId = organizations[0].id; const organizationId = organizations[0].id;
const organization = await db.organization.findFirst({ const phoneNumber = await db.phoneNumber.findUnique({
where: { id: organizationId }, where: { organizationId_isCurrent: { organizationId, isCurrent: true } },
include: { phoneNumbers: true },
}); });
if (!organization || !organization.phoneNumbers[0]) { if (!phoneNumber || phoneNumber.isFetchingMessages) {
throw new Error("Not found"); throw new Error("unreachable");
}
const phoneNumber = organization.phoneNumbers[0]; // TODO: use the active number, not the first one
const phoneNumberId = phoneNumber.id;
if (organization.phoneNumbers[0].isFetchingMessages) {
throw new Error("Not found");
} }
const formattedPhoneNumber = parsePhoneNumber(recipient).getNumber("international"); const formattedPhoneNumber = parsePhoneNumber(recipient).getNumber("international");
const messages = await db.message.findMany({ const messages = await db.message.findMany({
where: { where: {
phoneNumberId, phoneNumberId: phoneNumber.id,
OR: [{ from: recipient }, { to: recipient }], OR: [{ from: recipient }, { to: recipient }],
}, },
orderBy: { sentAt: Prisma.SortOrder.desc }, orderBy: { sentAt: Prisma.SortOrder.asc },
}); });
return { return {
recipient, recipient,
@ -91,9 +81,9 @@ export default function ConversationPage() {
<IoInformationCircle className="h-8 w-8" /> <IoInformationCircle className="h-8 w-8" />
</span> </span>
</header> </header>
<Suspense fallback={<div className="pt-12">Loading messages with {recipient}</div>}> {/*<Suspense fallback={<div className="pt-12">Loading messages with {recipient}</div>}>*/}
<Conversation /> <Conversation />
</Suspense> {/*</Suspense>*/}
</> </>
); );
} }

View File

@ -1,6 +1,6 @@
import { type LoaderFunction, json } from "@remix-run/node"; import { type LoaderFunction } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react"; import { json, useLoaderData } from "superjson-remix";
import { type Message, Prisma, Direction } from "@prisma/client"; import { type Message, Prisma, Direction, SubscriptionStatus } from "@prisma/client";
import { parsePhoneNumber } from "awesome-phonenumber"; import { parsePhoneNumber } from "awesome-phonenumber";
import PageTitle from "~/features/core/components/page-title"; import PageTitle from "~/features/core/components/page-title";
@ -11,7 +11,6 @@ import { requireLoggedIn } from "~/utils/auth.server";
export type MessagesLoaderData = { export type MessagesLoaderData = {
user: { user: {
hasFilledTwilioCredentials: boolean;
hasPhoneNumber: boolean; hasPhoneNumber: boolean;
}; };
conversations: Record<string, Conversation> | undefined; conversations: Record<string, Conversation> | undefined;
@ -25,7 +24,7 @@ type Conversation = {
export const loader: LoaderFunction = async ({ request }) => { export const loader: LoaderFunction = async ({ request }) => {
const { id, organizations } = await requireLoggedIn(request); const { id, organizations } = await requireLoggedIn(request);
/*const user = await db.user.findFirst({ const user = await db.user.findFirst({
where: { id }, where: { id },
select: { select: {
id: true, id: true,
@ -54,12 +53,9 @@ export const loader: LoaderFunction = async ({ request }) => {
}, },
}, },
}); });
const organization = user!.memberships[0]!.organization; const organization = user!.memberships[0].organization;
const hasFilledTwilioCredentials = Boolean(organization?.twilioAccountSid && organization?.twilioAuthToken);*/ const phoneNumber = await db.phoneNumber.findUnique({
const hasFilledTwilioCredentials = false; where: { organizationId_isCurrent: { organizationId: organization.id, isCurrent: true } },
const phoneNumber = await db.phoneNumber.findFirst({
// TODO: use the active number, not the first one
where: { organizationId: organizations[0].id },
select: { select: {
id: true, id: true,
organizationId: true, organizationId: true,
@ -69,34 +65,21 @@ export const loader: LoaderFunction = async ({ request }) => {
const conversations = await getConversations(); const conversations = await getConversations();
return json<MessagesLoaderData>({ return json<MessagesLoaderData>({
user: { user: { hasPhoneNumber: Boolean(phoneNumber) },
hasFilledTwilioCredentials,
hasPhoneNumber: Boolean(phoneNumber),
},
conversations, conversations,
}); });
async function getConversations() { async function getConversations() {
if (!hasFilledTwilioCredentials) {
return;
}
const organizationId = organizations[0].id; const organizationId = organizations[0].id;
const organization = await db.organization.findFirst({ const phoneNumber = await db.phoneNumber.findUnique({
where: { id: organizationId }, where: { organizationId_isCurrent: { organizationId, isCurrent: true } },
include: { phoneNumbers: true },
}); });
if (!organization || !organization.phoneNumbers[0]) { if (!phoneNumber || phoneNumber.isFetchingMessages) {
throw new Error("Not found");
}
const phoneNumberId = organization.phoneNumbers[0].id; // TODO: use the active number, not the first one
if (organization.phoneNumbers[0].isFetchingMessages) {
return; return;
} }
const messages = await db.message.findMany({ const messages = await db.message.findMany({
where: { phoneNumberId }, where: { phoneNumberId: phoneNumber.id },
orderBy: { sentAt: Prisma.SortOrder.desc }, orderBy: { sentAt: Prisma.SortOrder.desc },
}); });
@ -118,7 +101,7 @@ export const loader: LoaderFunction = async ({ request }) => {
}; };
} }
if (conversations[recipient].lastMessage.sentAt > message.sentAt) { if (message.sentAt > conversations[recipient].lastMessage.sentAt) {
conversations[recipient].lastMessage = message; conversations[recipient].lastMessage = message;
} }
/*conversations[recipient]!.messages.push({ /*conversations[recipient]!.messages.push({
@ -129,13 +112,12 @@ export const loader: LoaderFunction = async ({ request }) => {
return conversations; return conversations;
} }
}; };
export default function MessagesPage() { export default function MessagesPage() {
const { user } = useLoaderData<MessagesLoaderData>(); const { user } = useLoaderData<MessagesLoaderData>();
if (!user.hasFilledTwilioCredentials || !user.hasPhoneNumber) { if (!user.hasPhoneNumber) {
return ( return (
<> <>
<MissingTwilioCredentials /> <MissingTwilioCredentials />

View File

@ -1,31 +1,36 @@
import { type LoaderFunction, json } from "@remix-run/node"; import { type LoaderFunction, json } from "@remix-run/node";
import { type PhoneNumber, Prisma } from "@prisma/client";
import { requireLoggedIn } from "~/utils/auth.server";
import settingsPhoneAction from "~/features/settings/actions/phone";
import TwilioConnect from "~/features/settings/components/phone/twilio-connect"; import TwilioConnect from "~/features/settings/components/phone/twilio-connect";
import PhoneNumberForm from "~/features/settings/components/phone/phone-number-form"; import PhoneNumberForm from "~/features/settings/components/phone/phone-number-form";
import { requireLoggedIn } from "~/utils/auth.server"; import logger from "~/utils/logger.server";
import getTwilioClient from "~/utils/twilio.server"; import db from "~/utils/db.server";
export type PhoneSettingsLoaderData = { export type PhoneSettingsLoaderData = {
phoneNumbers: { phoneNumbers: Pick<PhoneNumber, "id" | "number" | "isCurrent">[];
phoneNumber: string; };
sid: string;
}[];
}
export const loader: LoaderFunction = async ({ request }) => { export const loader: LoaderFunction = async ({ request }) => {
const { organizations } = await requireLoggedIn(request); const { organizations } = await requireLoggedIn(request);
const organization = organizations[0]; const organization = organizations[0];
if (!organization.twilioAccountSid) { if (!organization.twilioAccountSid) {
throw new Error("Twilio account is not connected"); logger.warn("Twilio account is not connected");
return json<PhoneSettingsLoaderData>({ phoneNumbers: [] });
} }
const twilioClient = getTwilioClient(organization); const phoneNumbers = await db.phoneNumber.findMany({
const incomingPhoneNumbers = await twilioClient.incomingPhoneNumbers.list(); where: { organizationId: organization.id },
const phoneNumbers = incomingPhoneNumbers.map(({ phoneNumber, sid }) => ({ phoneNumber, sid })); select: { id: true, number: true, isCurrent: true },
orderBy: { id: Prisma.SortOrder.desc },
});
return json<PhoneSettingsLoaderData>({ phoneNumbers }); return json<PhoneSettingsLoaderData>({ phoneNumbers });
}; };
export const action = settingsPhoneAction;
function PhoneSettings() { function PhoneSettings() {
return ( return (
<div className="flex flex-col space-y-6"> <div className="flex flex-col space-y-6">

View File

@ -1,26 +1,65 @@
import { type LoaderFunction, redirect } from "@remix-run/node"; import { type LoaderFunction, redirect } from "@remix-run/node";
import { refreshSessionData, requireLoggedIn } from "~/utils/auth.server";
import db from "~/utils/db.server";
import { commitSession } from "~/utils/session.server";
import twilio from "twilio"; import twilio from "twilio";
import { refreshSessionData, requireLoggedIn } from "~/utils/auth.server";
import { commitSession } from "~/utils/session.server";
import db from "~/utils/db.server";
import serverConfig from "~/config/config.server"; import serverConfig from "~/config/config.server";
import getTwilioClient from "~/utils/twilio.server";
import fetchPhoneCallsQueue from "~/queues/fetch-phone-calls.server";
import fetchMessagesQueue from "~/queues/fetch-messages.server";
export const loader: LoaderFunction = async ({ request }) => { export const loader: LoaderFunction = async ({ request }) => {
const user = await requireLoggedIn(request); const user = await requireLoggedIn(request);
const organization = user.organizations[0];
const url = new URL(request.url); const url = new URL(request.url);
const twilioSubAccountSid = url.searchParams.get("AccountSid"); const twilioSubAccountSid = url.searchParams.get("AccountSid");
if (!twilioSubAccountSid) { if (!twilioSubAccountSid) {
throw new Error("unreachable"); throw new Error("unreachable");
} }
const twilioClient = twilio(twilioSubAccountSid, serverConfig.twilio.authToken); let twilioClient = twilio(twilioSubAccountSid, serverConfig.twilio.authToken);
const twilioSubAccount = await twilioClient.api.accounts(twilioSubAccountSid).fetch(); const twilioSubAccount = await twilioClient.api.accounts(twilioSubAccountSid).fetch();
const twilioAccountSid = twilioSubAccount.ownerAccountSid; const twilioAccountSid = twilioSubAccount.ownerAccountSid;
await db.organization.update({ await db.organization.update({
where: { id: user.organizations[0].id }, where: { id: organization.id },
data: { twilioSubAccountSid, twilioAccountSid }, data: { twilioSubAccountSid, twilioAccountSid },
}); });
twilioClient = getTwilioClient({ twilioAccountSid, twilioSubAccountSid });
const phoneNumbers = await twilioClient.incomingPhoneNumbers.list();
await Promise.all(
phoneNumbers.map(async (phoneNumber) => {
const phoneNumberId = phoneNumber.sid;
try {
await db.phoneNumber.create({
data: {
id: phoneNumberId,
organizationId: organization.id,
number: phoneNumber.phoneNumber,
isCurrent: false,
isFetchingCalls: true,
isFetchingMessages: true,
},
});
await Promise.all([
fetchPhoneCallsQueue.add(`fetch calls of id=${phoneNumberId}`, {
phoneNumberId,
}),
fetchMessagesQueue.add(`fetch messages of id=${phoneNumberId}`, {
phoneNumberId,
}),
]);
} catch (error: any) {
if (error.code !== "P2002") {
// if it's not a duplicate, it's a real error we need to handle
throw error;
}
}
}),
);
const { session } = await refreshSessionData(request); const { session } = await refreshSessionData(request);
return redirect("/settings/phone", { return redirect("/settings/phone", {
headers: { headers: {

View File

@ -1,16 +1,92 @@
import twilio from "twilio"; import twilio from "twilio";
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message";
import type { CallInstance } from "twilio/lib/rest/api/v2010/account/call";
import { type Organization, CallStatus, Direction, MessageStatus } from "@prisma/client";
import type { Organization } from "@prisma/client";
import serverConfig from "~/config/config.server"; import serverConfig from "~/config/config.server";
type MinimalOrganization = Pick<Organization, "twilioSubAccountSid" | "twilioAccountSid">; type MinimalOrganization = Pick<Organization, "twilioSubAccountSid" | "twilioAccountSid">;
export default function getTwilioClient(organization: MinimalOrganization): twilio.Twilio { export default function getTwilioClient({ twilioAccountSid, twilioSubAccountSid }: MinimalOrganization): twilio.Twilio {
if (!organization || !organization.twilioSubAccountSid || !organization.twilioAccountSid) { if (!twilioSubAccountSid || !twilioAccountSid) {
throw new Error("unreachable"); throw new Error("unreachable");
} }
return twilio(organization.twilioSubAccountSid, serverConfig.twilio.authToken, { return twilio(twilioSubAccountSid, serverConfig.twilio.authToken, {
accountSid: organization.twilioAccountSid, accountSid: twilioAccountSid,
}); });
} }
export function translateMessageStatus(status: MessageInstance["status"]): MessageStatus {
switch (status) {
case "accepted":
return MessageStatus.Accepted;
case "canceled":
return MessageStatus.Canceled;
case "delivered":
return MessageStatus.Delivered;
case "failed":
return MessageStatus.Failed;
case "partially_delivered":
return MessageStatus.PartiallyDelivered;
case "queued":
return MessageStatus.Queued;
case "read":
return MessageStatus.Read;
case "received":
return MessageStatus.Received;
case "receiving":
return MessageStatus.Receiving;
case "scheduled":
return MessageStatus.Scheduled;
case "sending":
return MessageStatus.Sending;
case "sent":
return MessageStatus.Sent;
case "undelivered":
return MessageStatus.Undelivered;
}
}
export function translateMessageDirection(direction: MessageInstance["direction"]): Direction {
switch (direction) {
case "inbound":
return Direction.Inbound;
case "outbound-api":
case "outbound-call":
case "outbound-reply":
default:
return Direction.Outbound;
}
}
export function translateCallStatus(status: CallInstance["status"]): CallStatus {
switch (status) {
case "busy":
return CallStatus.Busy;
case "canceled":
return CallStatus.Canceled;
case "completed":
return CallStatus.Completed;
case "failed":
return CallStatus.Failed;
case "in-progress":
return CallStatus.InProgress;
case "no-answer":
return CallStatus.NoAnswer;
case "queued":
return CallStatus.Queued;
case "ringing":
return CallStatus.Ringing;
}
}
export function translateCallDirection(direction: CallInstance["direction"]): Direction {
switch (direction) {
case "inbound":
return Direction.Inbound;
case "outbound":
default:
return Direction.Outbound;
}
}

81
package-lock.json generated
View File

@ -41,6 +41,7 @@
"remix-utils": "3.2.0", "remix-utils": "3.2.0",
"secure-password": "4.0.0", "secure-password": "4.0.0",
"stripe": "9.1.0", "stripe": "9.1.0",
"superjson-remix": "0.1.2",
"tiny-invariant": "1.2.0", "tiny-invariant": "1.2.0",
"tslog": "3.3.3", "tslog": "3.3.3",
"twilio": "3.77.0", "twilio": "3.77.0",
@ -6898,6 +6899,20 @@
"node": ">=6.6.0" "node": ">=6.6.0"
} }
}, },
"node_modules/copy-anything": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-3.0.2.tgz",
"integrity": "sha512-CzATjGXzUQ0EvuvgOCI6A4BGOo2bcVx8B+eC2nF862iv9fopnPQwlrbACakNCHRIJbCSBj+J/9JeDf60k64MkA==",
"dependencies": {
"is-what": "^4.1.6"
},
"engines": {
"node": ">=12.13"
},
"funding": {
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/copy-descriptor": { "node_modules/copy-descriptor": {
"version": "0.1.1", "version": "0.1.1",
"resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz",
@ -11947,6 +11962,17 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/is-what": {
"version": "4.1.7",
"resolved": "https://registry.npmjs.org/is-what/-/is-what-4.1.7.tgz",
"integrity": "sha512-DBVOQNiPKnGMxRMLIYSwERAS5MVY1B7xYiGnpgctsOFvVDz9f9PFXXxMcTOHuoqYp4NK9qFYQaIC1NRRxLMpBQ==",
"engines": {
"node": ">=12.13"
},
"funding": {
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/is-whitespace": { "node_modules/is-whitespace": {
"version": "0.3.0", "version": "0.3.0",
"resolved": "https://registry.npmjs.org/is-whitespace/-/is-whitespace-0.3.0.tgz", "resolved": "https://registry.npmjs.org/is-whitespace/-/is-whitespace-0.3.0.tgz",
@ -19751,6 +19777,32 @@
"postcss": "^8.2.15" "postcss": "^8.2.15"
} }
}, },
"node_modules/superjson": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/superjson/-/superjson-1.9.1.tgz",
"integrity": "sha512-oT3HA2nPKlU1+5taFgz/HDy+GEaY+CWEbLzaRJVD4gZ7zMVVC4GDNFdgvAZt6/VuIk6D2R7RtPAiCHwmdzlMmg==",
"dependencies": {
"copy-anything": "^3.0.2"
},
"engines": {
"node": ">=10"
}
},
"node_modules/superjson-remix": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/superjson-remix/-/superjson-remix-0.1.2.tgz",
"integrity": "sha512-NkJd+V0zOMCUbwnaKsxNs1FXMWTAHppqaCTd9IKXDOoPtRkjxU8/7duQeJ9yC8L3J9eJ47CShkIS+NEhzlY6IQ==",
"hasInstallScript": true,
"dependencies": {
"superjson": "^1.8.1"
},
"engines": {
"node": ">=10"
},
"peerDependencies": {
"remix": ">=1.2.3"
}
},
"node_modules/supports-color": { "node_modules/supports-color": {
"version": "7.2.0", "version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
@ -26805,6 +26857,14 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.0.tgz", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.0.tgz",
"integrity": "sha512-R0BOPfLGTitaKhgKROKZQN6iyq2iDQcH1DOF8nJoaWapguX5bC2w+Q/I9NmmM5lfcvEarnLZr+cCvmEYYSXvYA==" "integrity": "sha512-R0BOPfLGTitaKhgKROKZQN6iyq2iDQcH1DOF8nJoaWapguX5bC2w+Q/I9NmmM5lfcvEarnLZr+cCvmEYYSXvYA=="
}, },
"copy-anything": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-3.0.2.tgz",
"integrity": "sha512-CzATjGXzUQ0EvuvgOCI6A4BGOo2bcVx8B+eC2nF862iv9fopnPQwlrbACakNCHRIJbCSBj+J/9JeDf60k64MkA==",
"requires": {
"is-what": "^4.1.6"
}
},
"copy-descriptor": { "copy-descriptor": {
"version": "0.1.1", "version": "0.1.1",
"resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz",
@ -30493,6 +30553,11 @@
"call-bind": "^1.0.2" "call-bind": "^1.0.2"
} }
}, },
"is-what": {
"version": "4.1.7",
"resolved": "https://registry.npmjs.org/is-what/-/is-what-4.1.7.tgz",
"integrity": "sha512-DBVOQNiPKnGMxRMLIYSwERAS5MVY1B7xYiGnpgctsOFvVDz9f9PFXXxMcTOHuoqYp4NK9qFYQaIC1NRRxLMpBQ=="
},
"is-whitespace": { "is-whitespace": {
"version": "0.3.0", "version": "0.3.0",
"resolved": "https://registry.npmjs.org/is-whitespace/-/is-whitespace-0.3.0.tgz", "resolved": "https://registry.npmjs.org/is-whitespace/-/is-whitespace-0.3.0.tgz",
@ -36394,6 +36459,22 @@
"postcss-selector-parser": "^6.0.4" "postcss-selector-parser": "^6.0.4"
} }
}, },
"superjson": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/superjson/-/superjson-1.9.1.tgz",
"integrity": "sha512-oT3HA2nPKlU1+5taFgz/HDy+GEaY+CWEbLzaRJVD4gZ7zMVVC4GDNFdgvAZt6/VuIk6D2R7RtPAiCHwmdzlMmg==",
"requires": {
"copy-anything": "^3.0.2"
}
},
"superjson-remix": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/superjson-remix/-/superjson-remix-0.1.2.tgz",
"integrity": "sha512-NkJd+V0zOMCUbwnaKsxNs1FXMWTAHppqaCTd9IKXDOoPtRkjxU8/7duQeJ9yC8L3J9eJ47CShkIS+NEhzlY6IQ==",
"requires": {
"superjson": "^1.8.1"
}
},
"supports-color": { "supports-color": {
"version": "7.2.0", "version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",

View File

@ -82,6 +82,7 @@
"remix-utils": "3.2.0", "remix-utils": "3.2.0",
"secure-password": "4.0.0", "secure-password": "4.0.0",
"stripe": "9.1.0", "stripe": "9.1.0",
"superjson-remix": "0.1.2",
"tiny-invariant": "1.2.0", "tiny-invariant": "1.2.0",
"tslog": "3.3.3", "tslog": "3.3.3",
"twilio": "3.77.0", "twilio": "3.77.0",