shellphone.app/app/messages/queries/get-conversations.ts

57 lines
1.6 KiB
TypeScript
Raw Normal View History

import { resolver, NotFoundError } from "blitz";
2021-08-05 17:07:15 +00:00
import { z } from "zod";
2021-07-31 14:33:18 +00:00
import db, { Direction, Message, Prisma } from "../../../db";
import { decrypt } from "../../../db/_encryption";
2021-08-05 17:07:15 +00:00
import { enforceSuperAdminIfNotCurrentOrganization, setDefaultOrganizationId } from "../../core/utils";
export default resolver.pipe(
resolver.zod(z.object({ organizationId: z.string().optional() })),
resolver.authorize(),
setDefaultOrganizationId,
enforceSuperAdminIfNotCurrentOrganization,
async ({ organizationId }) => {
const organization = await db.organization.findFirst({
where: { id: organizationId },
include: { phoneNumbers: true },
});
if (!organization) {
throw new NotFoundError();
2021-07-31 14:33:18 +00:00
}
2021-08-05 17:07:15 +00:00
const phoneNumberId = organization.phoneNumbers[0]!.id;
const messages = await db.message.findMany({
where: { organizationId, phoneNumberId },
2021-08-13 15:54:13 +00:00
orderBy: { sentAt: Prisma.SortOrder.desc },
});
2021-07-31 14:33:18 +00:00
2021-08-05 17:07:15 +00:00
let conversations: Record<string, Message[]> = {};
for (const message of messages) {
let recipient: string;
if (message.direction === Direction.Outbound) {
recipient = message.to;
} else {
recipient = message.from;
}
if (!conversations[recipient]) {
conversations[recipient] = [];
}
conversations[recipient]!.push({
...message,
content: decrypt(message.content, organization.encryptionKey),
});
conversations[recipient]!.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
}
conversations = Object.fromEntries(
Object.entries(conversations).sort(
([, a], [, b]) => b[b.length - 1]!.sentAt.getTime() - a[a.length - 1]!.sentAt.getTime(),
),
);
return conversations;
},
);