import { getFilterObject, getSortObject, PageQueryParams } from "../pagination"; import { notificationFields, notificationModel, UpdateNotificationInput, } from "./notification.schema"; export async function updateNotification( notifId: string, input: UpdateNotificationInput, tenantId: string ) { return await notificationModel.findOneAndUpdate( { $and: [{ tenantId: tenantId }, { pid: notifId }] }, { ...input, updatedAt: new Date(), }, { new: true } ); } export async function listNotifications( params: PageQueryParams, tenantId: string ) { const page = params.page || 1; const pageSize = params.pageSize || 10; const sortObj = getSortObject(params, notificationFields); const filterObj = getFilterObject(params, notificationFields); const notifications = await notificationModel.aggregate([ { $match: { $and: [{ tenantId: tenantId }, ...filterObj] } }, { $lookup: { from: "organizations", localField: "county", foreignField: "_id", as: "countyRec", }, }, { $lookup: { from: "organizations", localField: "client", foreignField: "_id", as: "clientRec", }, }, { $project: { _id: 1, pid: 1, permitNumber: 1, permitLink: 1, status: 1, changes: 1, createdAt: 1, county: { $let: { vars: { county: { $arrayElemAt: ["$countyRec", 0] } }, in: { _id: "$$county._id", pid: "$$county.pid", name: "$$county.name", type: "$$county.type", avatar: "$$county.avatar", }, }, }, client: { $let: { vars: { client: { $arrayElemAt: ["$clientRec", 0] } }, in: { _id: "$$client._id", pid: "$$client.pid", name: "$$client.name", type: "$$client.type", avatar: "$$client.avatar", }, }, }, }, }, { $facet: { metadata: [{ $count: "count" }], data: [ { $skip: (page - 1) * pageSize }, { $limit: pageSize }, { $sort: sortObj }, ], }, }, ]); if (notifications[0].data.length === 0) return { notifications: [], metadata: { count: 0, page, pageSize } }; return { notifications: notifications[0].data, metadata: { count: notifications[0].metadata[0].count, page, pageSize, }, }; }