2021-07-31 15:57:43 +00:00
|
|
|
import { resolver } from "blitz";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
import db, { Direction, Message, Prisma } from "../../../db";
|
|
|
|
import getCurrentCustomer from "../../customers/queries/get-current-customer";
|
|
|
|
import { decrypt } from "../../../db/_encryption";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
export default resolver.pipe(resolver.authorize(), async (_ = null, context) => {
|
2021-07-31 15:57:43 +00:00
|
|
|
const customer = await getCurrentCustomer(null, context);
|
2021-07-31 14:33:18 +00:00
|
|
|
const messages = await db.message.findMany({
|
|
|
|
where: { customerId: customer!.id },
|
|
|
|
orderBy: { sentAt: Prisma.SortOrder.asc },
|
2021-07-31 15:57:43 +00:00
|
|
|
});
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
let conversations: Record<string, Message[]> = {};
|
2021-07-31 14:33:18 +00:00
|
|
|
for (const message of messages) {
|
2021-07-31 15:57:43 +00:00
|
|
|
let recipient: string;
|
2021-07-31 14:33:18 +00:00
|
|
|
if (message.direction === Direction.Outbound) {
|
2021-07-31 15:57:43 +00:00
|
|
|
recipient = message.to;
|
2021-07-31 14:33:18 +00:00
|
|
|
} else {
|
2021-07-31 15:57:43 +00:00
|
|
|
recipient = message.from;
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!conversations[recipient]) {
|
2021-07-31 15:57:43 +00:00
|
|
|
conversations[recipient] = [];
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
conversations[recipient]!.push({
|
|
|
|
...message,
|
|
|
|
content: decrypt(message.content, customer!.encryptionKey),
|
2021-07-31 15:57:43 +00:00
|
|
|
});
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
conversations[recipient]!.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|
|
|
|
conversations = Object.fromEntries(
|
|
|
|
Object.entries(conversations).sort(
|
|
|
|
([, a], [, b]) => b[b.length - 1]!.sentAt.getTime() - a[a.length - 1]!.sentAt.getTime()
|
|
|
|
)
|
2021-07-31 15:57:43 +00:00
|
|
|
);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
return conversations;
|
|
|
|
});
|