2021-08-02 13:43:27 +00:00
|
|
|
import { resolver, NotFoundError } 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-08-02 10:02:49 +00:00
|
|
|
if (!customer) {
|
2021-08-02 13:43:27 +00:00
|
|
|
throw new NotFoundError();
|
2021-08-02 10:02:49 +00:00
|
|
|
}
|
|
|
|
|
2021-07-31 14:33:18 +00:00
|
|
|
const messages = await db.message.findMany({
|
2021-08-02 10:02:49 +00:00
|
|
|
where: { customerId: customer.id },
|
2021-07-31 14:33:18 +00:00
|
|
|
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,
|
2021-08-02 10:02:49 +00:00
|
|
|
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(
|
2021-08-01 12:04:04 +00:00
|
|
|
([, 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;
|
|
|
|
});
|