Merge branch 'master' into outgoing-calls
This commit is contained in:
@ -1,10 +1,17 @@
|
||||
import { resolver, NotFoundError } from "blitz";
|
||||
import { z } from "zod";
|
||||
import PhoneNumber from "awesome-phonenumber";
|
||||
|
||||
import db, { Direction, Message, Prisma } from "../../../db";
|
||||
import { decrypt } from "../../../db/_encryption";
|
||||
import { enforceSuperAdminIfNotCurrentOrganization, setDefaultOrganizationId } from "../../core/utils";
|
||||
|
||||
type Conversation = {
|
||||
recipient: string;
|
||||
formattedPhoneNumber: string;
|
||||
messages: Message[];
|
||||
};
|
||||
|
||||
export default resolver.pipe(
|
||||
resolver.zod(z.object({ organizationId: z.string().optional() })),
|
||||
resolver.authorize(),
|
||||
@ -25,7 +32,7 @@ export default resolver.pipe(
|
||||
orderBy: { sentAt: Prisma.SortOrder.desc },
|
||||
});
|
||||
|
||||
let conversations: Record<string, Message[]> = {};
|
||||
let conversations: Record<string, Conversation> = {};
|
||||
for (const message of messages) {
|
||||
let recipient: string;
|
||||
if (message.direction === Direction.Outbound) {
|
||||
@ -33,21 +40,28 @@ export default resolver.pipe(
|
||||
} else {
|
||||
recipient = message.from;
|
||||
}
|
||||
const formattedPhoneNumber = new PhoneNumber(recipient).getNumber("international");
|
||||
|
||||
if (!conversations[recipient]) {
|
||||
conversations[recipient] = [];
|
||||
conversations[recipient] = {
|
||||
recipient,
|
||||
formattedPhoneNumber,
|
||||
messages: [],
|
||||
};
|
||||
}
|
||||
|
||||
conversations[recipient]!.push({
|
||||
conversations[recipient]!.messages.push({
|
||||
...message,
|
||||
content: decrypt(message.content, organization.encryptionKey),
|
||||
});
|
||||
|
||||
conversations[recipient]!.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
|
||||
conversations[recipient]!.messages.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(),
|
||||
([, a], [, b]) =>
|
||||
b.messages[b.messages.length - 1]!.sentAt.getTime() -
|
||||
a.messages[a.messages.length - 1]!.sentAt.getTime(),
|
||||
),
|
||||
);
|
||||
|
||||
|
Reference in New Issue
Block a user