feat: implement comprehensive notification engine with policies, preferences, and automated dispatching services
This commit is contained in:
@@ -36,9 +36,18 @@ export type FindAppointmentsByCollaboratorPaginatedParams = FindAppointmentsByCo
|
||||
export enum APPOINTMENT_NOTIFICATION_TYPE {
|
||||
"CREATION" = "creation",
|
||||
"REMINDER" = "reminder",
|
||||
"CANCELLATION" = "cancellation",
|
||||
}
|
||||
|
||||
export type SendAppointmentNotificationParams = {
|
||||
appointmentId: string;
|
||||
sessionUser?: string;
|
||||
systemToken?: string;
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
channel?: "whatsapp" | "email";
|
||||
};
|
||||
|
||||
export type CreateImmediateAppointmentNotificationJobsParams = {
|
||||
appointmentId: string;
|
||||
sessionUser: string;
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
@@ -63,6 +72,7 @@ export type ChangeServiceParams = {
|
||||
export type SendWapSystemNotificationParams = {
|
||||
appointmentId: string;
|
||||
systemToken: string;
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
};
|
||||
|
||||
export type HeatMapConfig = {
|
||||
@@ -121,6 +131,7 @@ export type UpdateAppointmentParams = {
|
||||
export type DeleteAppointmentParams = {
|
||||
id: string;
|
||||
validation?: boolean;
|
||||
notification?: boolean;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
@@ -315,6 +326,7 @@ export interface IAppointmentsManager {
|
||||
getAvailableDates(data: GetAvailableDatesParams): Promise<GetAvailableDatesResult>;
|
||||
sendWapNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||
sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||
createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void>;
|
||||
sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void>;
|
||||
deleteAppointmentsByCompany(data: DeleteAppointmentsByCompanyParams): Promise<void>;
|
||||
changeEmployeeToOwner(data: ChangeEmployeeToOwnerParams): Promise<void>;
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
ChangeEmployeeToOwnerParams,
|
||||
CountAppointmentsByMonthParams,
|
||||
CreateAppointmentParams,
|
||||
CreateImmediateAppointmentNotificationJobsParams,
|
||||
DeleteAppointmentDiscountParams,
|
||||
DeleteAppointmentParams,
|
||||
DeleteAppointmentsByCompanyParams,
|
||||
@@ -76,6 +77,7 @@ import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled";
|
||||
import DiscountsEmail from "../DiscountsEmail/DiscountsEmail";
|
||||
import SchedulesOverridesList from "../SchedulesOverrides/SchedulesOverrides";
|
||||
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||
import { NotificationJobService } from "../NotificationPolicies/NotificationJobService";
|
||||
|
||||
dayjs.locale("es");
|
||||
dayjs.extend(isSameOrAfter);
|
||||
@@ -84,9 +86,11 @@ dayjs.extend(weekday);
|
||||
|
||||
class AppointmentManager implements IAppointmentsManager {
|
||||
Appointments: AppointmentsAdapterMongoose;
|
||||
private jobService: NotificationJobService;
|
||||
|
||||
constructor() {
|
||||
this.Appointments = new AppointmentsAdapterMongoose();
|
||||
this.jobService = new NotificationJobService();
|
||||
}
|
||||
|
||||
private isScheduleAvailableForService(schedule: ScheduleItem, serviceId?: string): boolean {
|
||||
@@ -526,36 +530,35 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
code: String((newAppointment as any)._id)
|
||||
});
|
||||
|
||||
//Intento enviar notificacion al cliente por Email
|
||||
try {
|
||||
if (newAppointment.id) {
|
||||
await this.sendEmailNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Error al enviar la notificacion por Email para ${companyCheck.name}(${companyCheck._id}):`,
|
||||
err
|
||||
);
|
||||
}
|
||||
//Create jobs for email and whatsapp notifications
|
||||
if (newAppointment.id) {
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
const clientPhoneNumber = await this.getOptionalClientWapNumber(checkClient);
|
||||
|
||||
//Intento enviar notificacion al cliente por Whatsapp
|
||||
try {
|
||||
if (newAppointment.id) {
|
||||
await this.sendWapNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Error al enviar la notificacion por Whatsapp para ${companyCheck.name}(${companyCheck._id}):`,
|
||||
err
|
||||
);
|
||||
await this.createCreationNotificationJobs({
|
||||
appointmentId: String(newAppointment.id),
|
||||
companyId: String(companyCheck._id),
|
||||
clientId: String(checkClient._id),
|
||||
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
clientEmail: checkClient.email,
|
||||
clientPhoneNumber,
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
companyName: companyCheck.name,
|
||||
appointmentStart: new Date(data.start),
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2070,36 +2073,18 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
code: String(checkAppointment._id)
|
||||
});
|
||||
|
||||
//Intento enviar notificacion al cliente por Email
|
||||
try {
|
||||
if (checkAppointment.id) {
|
||||
await this.sendEmailNotification({
|
||||
appointmentId: String(checkAppointment.id),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Error al enviar la notificacion por Email para ${companyCheck.name}(${companyCheck._id}):`,
|
||||
err
|
||||
);
|
||||
}
|
||||
//Cancel existing pending jobs before creating new ones for the rescheduled appointment
|
||||
if (checkAppointment.id) {
|
||||
await this.jobService.cancelByAppointment(String(checkAppointment.id));
|
||||
|
||||
//Intento enviar notificacion al cliente por Whatsapp
|
||||
try {
|
||||
if (checkAppointment.id) {
|
||||
await this.sendWapNotification({
|
||||
appointmentId: String(checkAppointment.id),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Error al enviar la notificacion por Whatsapp para ${companyCheck.name}(${companyCheck._id}):`,
|
||||
err
|
||||
);
|
||||
//Create jobs for email and whatsapp notifications
|
||||
await this.jobService.createJob({
|
||||
companyId: String(companyCheck._id),
|
||||
clientId: String(checkClient._id),
|
||||
appointmentId: String(checkAppointment.id),
|
||||
type: "update" as const,
|
||||
appointmentStart: new Date(data.start),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2155,8 +2140,89 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
return config;
|
||||
}
|
||||
|
||||
private async createCancellationNotificationJobs(data: {
|
||||
appointmentId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
clientUserId?: string;
|
||||
clientEmail?: string;
|
||||
clientPhoneNumber?: string;
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
emailMessage: string;
|
||||
wapMessage: string;
|
||||
}): Promise<void> {
|
||||
const systemSubject = `Turno cancelado en ${data.companyName}`;
|
||||
|
||||
await this.jobService.createJob({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "cancellation",
|
||||
scheduledAt: new Date(),
|
||||
payload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
subject: systemSubject,
|
||||
message: data.emailMessage,
|
||||
emailSubject: "TurnosXpress :: Turno cancelado",
|
||||
emailMessage: data.emailMessage,
|
||||
wapMessage: data.wapMessage,
|
||||
systemSubject,
|
||||
systemMessage: data.emailMessage,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async createCreationNotificationJobs(data: {
|
||||
appointmentId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
clientUserId?: string;
|
||||
clientEmail?: string;
|
||||
clientPhoneNumber?: string;
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
appointmentStart: Date;
|
||||
emailMessage: string;
|
||||
wapMessage: string;
|
||||
}): Promise<void> {
|
||||
const systemSubject = `Turno reservado en ${data.companyName}`;
|
||||
|
||||
await this.jobService.createJob({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "creation",
|
||||
appointmentStart: data.appointmentStart,
|
||||
payload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
subject: systemSubject,
|
||||
message: data.emailMessage,
|
||||
emailSubject: "TurnosXpress :: Alta de turno",
|
||||
emailMessage: data.emailMessage,
|
||||
wapMessage: data.wapMessage,
|
||||
systemSubject,
|
||||
systemMessage: data.emailMessage,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async getOptionalClientWapNumber(client: IClientDocument): Promise<string | undefined> {
|
||||
try {
|
||||
return await ClientsManager.getClientWapNumber(client);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async deleteAppointment(data: DeleteAppointmentParams): Promise<void> {
|
||||
const { validation = false } = data;
|
||||
const { validation = false, notification = false } = data;
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
});
|
||||
@@ -2234,23 +2300,41 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
try {
|
||||
const config = this.getHeatMapConfig(checkAppointment, serviceCheck.length);
|
||||
|
||||
// Cancel pending notification jobs for this appointment before deleting it
|
||||
await this.jobService.cancelByAppointment(String(checkAppointment._id));
|
||||
|
||||
if (notification) {
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(checkAppointment._id),
|
||||
sessionUser: data.sessionUser,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(checkAppointment._id),
|
||||
sessionUser: data.sessionUser,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await this.createCancellationNotificationJobs({
|
||||
companyId: String(checkAppointment.companyId),
|
||||
clientId: String(checkAppointment.clientId),
|
||||
appointmentId: String(checkAppointment._id),
|
||||
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
clientEmail: checkClient.email,
|
||||
clientPhoneNumber: await this.getOptionalClientWapNumber(checkClient),
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
companyName: companyCheck.name,
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
});
|
||||
}
|
||||
|
||||
await this.Appointments.AppointmentList.deleteOne({ _id: data.id });
|
||||
//Actualizar el heatmap.
|
||||
await this.updateHeatMap(config);
|
||||
|
||||
if (checkClient.userId) {
|
||||
//Enviamos la notificacion de cancelacion al cliente
|
||||
await NotificationsManager.sendSystemNotification({
|
||||
userId: String(checkClient.userId),
|
||||
subject: "Turno Cancelado",
|
||||
message: `Se ha cancelado el turno para el día ${dayjs(checkAppointment.start).format(
|
||||
"DD/MM/YYYY"
|
||||
)} a las ${dayjs(checkAppointment.start).format("HH:mm")}`,
|
||||
type: NotificationType.APPOINTMENT,
|
||||
code: String(checkAppointment._id)
|
||||
});
|
||||
}
|
||||
|
||||
//Enviamos la notificacion de cancelacion al profesional
|
||||
await NotificationsManager.sendSystemNotification({
|
||||
userId: String(employeeCheck.userId),
|
||||
@@ -2384,8 +2468,16 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
throw new Error("La compañia no existe");
|
||||
}
|
||||
|
||||
if (!(await EmployeesList.checkPermission(companyCheck, data.sessionUser, EmployeeRoles.ADMIN))) {
|
||||
throw new Error(NoPermissionMessage());
|
||||
const hasSystemToken = this.hasValidSystemToken(data.systemToken);
|
||||
|
||||
if (!hasSystemToken) {
|
||||
if (!data.sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
if (!(await EmployeesList.checkPermission(companyCheck, data.sessionUser, EmployeeRoles.ADMIN))) {
|
||||
throw new Error(NoPermissionMessage());
|
||||
}
|
||||
}
|
||||
|
||||
const checkClient = await ClientsManager.clients.findOne({
|
||||
@@ -2465,9 +2557,13 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
wapMessage = wapMessage.replaceAll("<---ORGANIZACION--->", companyCheck.name);
|
||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
||||
if (companyCheck.templateWapAltaId) {
|
||||
const templateId = data.channel === "email"
|
||||
? companyCheck.templateEmailAltaId || companyCheck.templateWapAltaId
|
||||
: companyCheck.templateWapAltaId;
|
||||
|
||||
if (templateId) {
|
||||
const template = await Templates.templates.findOne({
|
||||
id: String(companyCheck.templateWapAltaId),
|
||||
id: String(templateId),
|
||||
companyId: String(companyCheck._id),
|
||||
});
|
||||
|
||||
@@ -2477,7 +2573,9 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
}
|
||||
|
||||
if (!wapMessage) {
|
||||
wapMessage = process.env.WAP_ALTA ? process.env.WAP_ALTA : "";
|
||||
wapMessage = data.channel === "email"
|
||||
? process.env.EMAIL_NEW_APPOINTMENT || process.env.EMAIL_ALTA || process.env.WAP_ALTA || ""
|
||||
: process.env.WAP_ALTA || "";
|
||||
}
|
||||
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
@@ -2505,6 +2603,52 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
wapMessage = wapMessage.replaceAll("<---SERVICIO--->", checkService.name);
|
||||
wapMessage = wapMessage.replaceAll("<---PRECIO--->", formatCurrency(checkAppointment.price));
|
||||
|
||||
wapMessage = wapMessage.replaceAll("<---ORGANIZACION--->", companyCheck.name);
|
||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION) {
|
||||
const templateId = data.channel === "email"
|
||||
? companyCheck.templateEmailCancellationId || companyCheck.templateWapCancellationId
|
||||
: companyCheck.templateWapCancellationId;
|
||||
|
||||
if (templateId) {
|
||||
const template = await Templates.templates.findOne({
|
||||
id: String(templateId),
|
||||
companyId: String(companyCheck._id),
|
||||
});
|
||||
|
||||
if (template) {
|
||||
wapMessage = template.template;
|
||||
}
|
||||
}
|
||||
|
||||
if (!wapMessage) {
|
||||
wapMessage = data.channel === "email"
|
||||
? process.env.EMAIL_CANCELLATION || process.env.EMAIL_CANCELACION || process.env.WAP_CANCELLATION || process.env.WAP_CANCELACION || ""
|
||||
: process.env.WAP_CANCELLATION || process.env.WAP_CANCELACION || "";
|
||||
}
|
||||
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---CLIENTE--->",
|
||||
ClientsManager.getClientFullName(checkClient)
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---FECHA--->",
|
||||
dayjs(checkAppointment.start).format("DD/MM/YYYY")
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---HORARIO--->",
|
||||
dayjs(checkAppointment.start).format("HH:mm") + "hs."
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---DIRECCION--->",
|
||||
CompaniesManager.getCompanyAddress(companyCheck)
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---PROFESIONAL--->",
|
||||
UsersManager.getUserFullName(checkEmployeeUser)
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll("<---SERVICIO--->", checkService.name);
|
||||
wapMessage = wapMessage.replaceAll("<---PRECIO--->", formatCurrency(checkAppointment.price));
|
||||
wapMessage = wapMessage.replaceAll("<---ORGANIZACION--->", companyCheck.name);
|
||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||
}
|
||||
@@ -2517,15 +2661,24 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
}
|
||||
|
||||
public async sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void> {
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
});
|
||||
if (!this.hasValidSystemToken(data.systemToken)) {
|
||||
if (!data.sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
if (!sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
});
|
||||
|
||||
if (!sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
}
|
||||
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification(data);
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification({
|
||||
...data,
|
||||
channel: "email",
|
||||
});
|
||||
|
||||
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||
userId: String(companyCheck.ownerId),
|
||||
@@ -2548,6 +2701,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
subjectEmail = "TurnosXpress :: Recordatorio";
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
||||
subjectEmail = "TurnosXpress :: Alta de turno";
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION) {
|
||||
subjectEmail = "TurnosXpress :: Turno cancelado";
|
||||
}
|
||||
|
||||
//Enviar email...
|
||||
@@ -2558,7 +2713,66 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
public async createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void> {
|
||||
if (![APPOINTMENT_NOTIFICATION_TYPE.CREATION, APPOINTMENT_NOTIFICATION_TYPE.REMINDER].includes(data.type)) {
|
||||
throw new Error("El tipo de notificación no es válido para esta acción");
|
||||
}
|
||||
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.sessionUser,
|
||||
type: data.type,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.sessionUser,
|
||||
type: data.type,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
const checkAppointment = await this.Appointments.findOne({
|
||||
_id: data.appointmentId,
|
||||
});
|
||||
|
||||
if (!checkAppointment) {
|
||||
throw new Error("El turno no existe");
|
||||
}
|
||||
|
||||
const checkClient = emailContent.checkClient;
|
||||
const companyCheck = emailContent.companyCheck;
|
||||
const isCreation = data.type === APPOINTMENT_NOTIFICATION_TYPE.CREATION;
|
||||
const systemSubject = isCreation
|
||||
? `Turno reservado en ${companyCheck.name}`
|
||||
: `Recordatorio de turno en ${companyCheck.name}`;
|
||||
|
||||
await this.jobService.createImmediateJob({
|
||||
companyId: String(checkAppointment.companyId),
|
||||
clientId: String(checkAppointment.clientId),
|
||||
appointmentId: String(checkAppointment._id),
|
||||
type: data.type,
|
||||
scheduledAt: new Date(),
|
||||
payload: {
|
||||
email: checkClient.email,
|
||||
phoneNumber: await this.getOptionalClientWapNumber(checkClient),
|
||||
userId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
subject: systemSubject,
|
||||
message: emailContent.message,
|
||||
emailSubject: isCreation ? "TurnosXpress :: Alta de turno" : "TurnosXpress :: Recordatorio",
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
systemSubject,
|
||||
systemMessage: emailContent.message,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public async sendWapNotification(data: SendAppointmentNotificationParams): Promise<void> {
|
||||
if (!data.sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
});
|
||||
@@ -2567,7 +2781,10 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification(data);
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification({
|
||||
...data,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||
userId: String(companyCheck.ownerId),
|
||||
@@ -2593,13 +2810,7 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
}
|
||||
|
||||
public async sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void> {
|
||||
if (!data.systemToken || data.systemToken == "") {
|
||||
throw new Error("No tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
const systemToken = `${process.env.SYSTEM_KEY}`;
|
||||
|
||||
if (systemToken != data.systemToken) {
|
||||
if (!this.hasValidSystemToken(data.systemToken)) {
|
||||
throw new Error("No tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
@@ -2622,7 +2833,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: String(company.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
systemToken: data.systemToken,
|
||||
type: data.type,
|
||||
});
|
||||
|
||||
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||
@@ -2838,6 +3050,11 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
inRangeDates: [],
|
||||
} as GetAvailableDatesResult;
|
||||
}
|
||||
|
||||
private hasValidSystemToken(systemToken?: string): boolean {
|
||||
const expectedSystemToken = process.env.SYSTEM_KEY || process.env.API_KEY;
|
||||
return Boolean(systemToken && expectedSystemToken && systemToken === expectedSystemToken);
|
||||
}
|
||||
}
|
||||
|
||||
const AppointmentList = new AppointmentManager();
|
||||
|
||||
@@ -32,6 +32,7 @@ jest.mock("../../Companies/Companies", () => ({
|
||||
companies: {
|
||||
findOne: jest.fn(),
|
||||
},
|
||||
getCompanyAddress: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -41,6 +42,7 @@ jest.mock("../../Employees/Employee", () => ({
|
||||
employees: {
|
||||
findOne: jest.fn(),
|
||||
},
|
||||
checkPermission: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -151,6 +153,9 @@ jest.mock("../../../helpers/check", () => ({
|
||||
jest.mock("../../Templates/Templates", () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
templates: {
|
||||
findOne: jest.fn(),
|
||||
},
|
||||
sendEmail: jest.fn(),
|
||||
},
|
||||
}));
|
||||
@@ -180,6 +185,8 @@ import UsersManager from "../../Users/Users";
|
||||
import EmployeesList from "../../Employees/Employee";
|
||||
import ClientsManager from "../../Clients/Clients";
|
||||
import ServiceList from "../../Services/Service";
|
||||
import CompaniesManager from "../../Companies/Companies";
|
||||
import Templates from "../../Templates/Templates";
|
||||
|
||||
describe("getAppointmentEvent — historical read snapshot fallback", () => {
|
||||
let originalAdapter: any;
|
||||
@@ -385,3 +392,265 @@ describe("getAppointmentEvent — historical read snapshot fallback", () => {
|
||||
expect(result.collaboratorName).toBe("Jane Roe");
|
||||
});
|
||||
});
|
||||
|
||||
describe("cancellation notification jobs", () => {
|
||||
let originalAdapter: any;
|
||||
let originalJobService: any;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
originalAdapter = AppointmentsList.Appointments;
|
||||
originalJobService = (AppointmentsList as any).jobService;
|
||||
|
||||
(AppointmentsList as any).Appointments = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
_id: "appt-001",
|
||||
companyId: "company-001",
|
||||
clientId: "client-001",
|
||||
employeeId: "employee-001",
|
||||
serviceId: "service-001",
|
||||
start: new Date("2026-07-22T11:00:00.000Z"),
|
||||
price: 1500,
|
||||
}),
|
||||
};
|
||||
(AppointmentsList as any).jobService = {
|
||||
createJob: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "company-001",
|
||||
name: "clases llavallol",
|
||||
ownerId: "owner-001",
|
||||
templateEmailCancellationId: "email-template-001",
|
||||
templateWapCancellationId: "wap-template-001",
|
||||
address: "Av. Siempre Viva 123",
|
||||
});
|
||||
(CompaniesManager.getCompanyAddress as jest.Mock).mockReturnValue("Av. Siempre Viva 123");
|
||||
(ClientsManager.clients.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "client-001",
|
||||
userId: "client-user-001",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
email: "ada@example.com",
|
||||
});
|
||||
(ClientsManager.getClientFullName as jest.Mock).mockReturnValue("Ada Lovelace");
|
||||
(EmployeesList.employees.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "employee-001",
|
||||
userId: "employee-user-001",
|
||||
});
|
||||
(EmployeesList.checkPermission as jest.Mock | undefined)?.mockResolvedValue?.(true);
|
||||
(UsersManager.users.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "employee-user-001",
|
||||
firstName: "Grace",
|
||||
lastName: "Hopper",
|
||||
});
|
||||
(UsersManager.getUserFullName as jest.Mock).mockReturnValue("Grace Hopper");
|
||||
(ServiceList.services.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "service-001",
|
||||
name: "Contabilidad",
|
||||
});
|
||||
(Templates.templates.findOne as jest.Mock).mockImplementation(({ id }) => {
|
||||
if (id === "email-template-001") {
|
||||
return Promise.resolve({
|
||||
template: "EMAIL CANCEL <---CLIENTE---> <---SERVICIO---> <---ORGANIZACION---> <---FECHA---> <---HORARIO--->",
|
||||
});
|
||||
}
|
||||
|
||||
if (id === "wap-template-001") {
|
||||
return Promise.resolve({
|
||||
template: "WAP CANCEL <---CLIENTE---> <---SERVICIO---> <---ORGANIZACION---> <---FECHA---> <---HORARIO--->",
|
||||
});
|
||||
}
|
||||
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(AppointmentsList as any).Appointments = originalAdapter;
|
||||
(AppointmentsList as any).jobService = originalJobService;
|
||||
});
|
||||
|
||||
it("stores organization-rendered cancellation template content per channel", async () => {
|
||||
const emailContent = await (AppointmentsList as any).tryToSendNotification({
|
||||
appointmentId: "appt-001",
|
||||
sessionUser: "owner-001",
|
||||
type: "cancellation",
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await (AppointmentsList as any).tryToSendNotification({
|
||||
appointmentId: "appt-001",
|
||||
sessionUser: "owner-001",
|
||||
type: "cancellation",
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await (AppointmentsList as any).createCancellationNotificationJobs({
|
||||
appointmentId: "appt-001",
|
||||
companyId: "company-001",
|
||||
clientId: "client-001",
|
||||
clientUserId: "client-user-001",
|
||||
clientEmail: "ada@example.com",
|
||||
clientPhoneNumber: "5491112345678",
|
||||
companyOwnerId: "owner-001",
|
||||
companyName: "clases llavallol",
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
});
|
||||
|
||||
expect((AppointmentsList as any).jobService.createJob).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: "cancellation",
|
||||
payload: expect.objectContaining({
|
||||
emailSubject: "TurnosXpress :: Turno cancelado",
|
||||
emailMessage: "EMAIL CANCEL Ada Lovelace Contabilidad clases llavallol 22/07/2026 08:00hs.",
|
||||
wapMessage: "WAP CANCEL Ada Lovelace Contabilidad clases llavallol 22/07/2026 08:00hs.",
|
||||
systemSubject: "Turno cancelado en clases llavallol",
|
||||
systemMessage: "EMAIL CANCEL Ada Lovelace Contabilidad clases llavallol 22/07/2026 08:00hs.",
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("creation notification jobs", () => {
|
||||
let originalAdapter: any;
|
||||
let originalJobService: any;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
originalAdapter = AppointmentsList.Appointments;
|
||||
originalJobService = (AppointmentsList as any).jobService;
|
||||
|
||||
(AppointmentsList as any).Appointments = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
_id: "appt-001",
|
||||
companyId: "company-001",
|
||||
clientId: "client-001",
|
||||
employeeId: "employee-001",
|
||||
serviceId: "service-001",
|
||||
start: new Date("2026-07-22T11:00:00.000Z"),
|
||||
price: 1500,
|
||||
}),
|
||||
};
|
||||
(AppointmentsList as any).jobService = {
|
||||
createJob: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "company-001",
|
||||
name: "clases llavallol",
|
||||
ownerId: "owner-001",
|
||||
templateEmailAltaId: "email-alta-template-001",
|
||||
templateWapAltaId: "wap-alta-template-001",
|
||||
address: "Av. Siempre Viva 123",
|
||||
});
|
||||
(CompaniesManager.getCompanyAddress as jest.Mock).mockReturnValue("Av. Siempre Viva 123");
|
||||
(ClientsManager.clients.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "client-001",
|
||||
userId: "client-user-001",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
email: "ada@example.com",
|
||||
});
|
||||
(ClientsManager.getClientFullName as jest.Mock).mockReturnValue("Ada Lovelace");
|
||||
(EmployeesList.employees.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "employee-001",
|
||||
userId: "employee-user-001",
|
||||
});
|
||||
(EmployeesList.checkPermission as jest.Mock | undefined)?.mockResolvedValue?.(true);
|
||||
(UsersManager.users.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "employee-user-001",
|
||||
firstName: "Grace",
|
||||
lastName: "Hopper",
|
||||
});
|
||||
(UsersManager.getUserFullName as jest.Mock).mockReturnValue("Grace Hopper");
|
||||
(ServiceList.services.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "service-001",
|
||||
name: "Historia",
|
||||
});
|
||||
(Templates.templates.findOne as jest.Mock).mockImplementation(({ id }) => {
|
||||
if (id === "email-alta-template-001") {
|
||||
return Promise.resolve({
|
||||
template: "EMAIL ALTA <---CLIENTE---> <---SERVICIO---> <---ORGANIZACION---> <---FECHA---> <---HORARIO--->",
|
||||
});
|
||||
}
|
||||
|
||||
if (id === "wap-alta-template-001") {
|
||||
return Promise.resolve({
|
||||
template: "WAP ALTA <---CLIENTE---> <---SERVICIO---> <---ORGANIZACION---> <---FECHA---> <---HORARIO--->",
|
||||
});
|
||||
}
|
||||
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(AppointmentsList as any).Appointments = originalAdapter;
|
||||
(AppointmentsList as any).jobService = originalJobService;
|
||||
});
|
||||
|
||||
it("stores organization-rendered Alta template content per channel", async () => {
|
||||
const emailContent = await (AppointmentsList as any).tryToSendNotification({
|
||||
appointmentId: "appt-001",
|
||||
sessionUser: "owner-001",
|
||||
type: "creation",
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await (AppointmentsList as any).tryToSendNotification({
|
||||
appointmentId: "appt-001",
|
||||
sessionUser: "owner-001",
|
||||
type: "creation",
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await (AppointmentsList as any).createCreationNotificationJobs({
|
||||
appointmentId: "appt-001",
|
||||
companyId: "company-001",
|
||||
clientId: "client-001",
|
||||
clientUserId: "client-user-001",
|
||||
clientEmail: "ada@example.com",
|
||||
clientPhoneNumber: "5491112345678",
|
||||
companyOwnerId: "owner-001",
|
||||
companyName: "clases llavallol",
|
||||
appointmentStart: new Date("2026-07-22T11:00:00.000Z"),
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
});
|
||||
|
||||
expect((AppointmentsList as any).jobService.createJob).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: "creation",
|
||||
payload: expect.objectContaining({
|
||||
emailSubject: "TurnosXpress :: Alta de turno",
|
||||
emailMessage: "EMAIL ALTA Ada Lovelace Historia clases llavallol 22/07/2026 08:00hs.",
|
||||
wapMessage: "WAP ALTA Ada Lovelace Historia clases llavallol 22/07/2026 08:00hs.",
|
||||
systemSubject: "Turno reservado en clases llavallol",
|
||||
systemMessage: "EMAIL ALTA Ada Lovelace Historia clases llavallol 22/07/2026 08:00hs.",
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to organization WAP Alta template for email when email Alta is absent", async () => {
|
||||
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "company-001",
|
||||
name: "clases llavallol",
|
||||
ownerId: "owner-001",
|
||||
templateWapAltaId: "wap-alta-template-001",
|
||||
address: "Av. Siempre Viva 123",
|
||||
});
|
||||
|
||||
const emailContent = await (AppointmentsList as any).tryToSendNotification({
|
||||
appointmentId: "appt-001",
|
||||
sessionUser: "owner-001",
|
||||
type: "creation",
|
||||
channel: "email",
|
||||
});
|
||||
|
||||
expect(emailContent.message).toBe("WAP ALTA Ada Lovelace Historia clases llavallol 22/07/2026 08:00hs.");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -58,8 +58,10 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
|
||||
templateWapNotifId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateWapAltaId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateWapCancellationId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateEmailNotifId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateEmailAltaId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateEmailCancellationId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
onboardingStep: { type: Number, required: false, default: 0 },
|
||||
onboardingCompleted: { type: Boolean, required: false, default: false },
|
||||
|
||||
@@ -205,6 +207,10 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
updateCompany.templateWapAltaId = data.templateWapAltaId;
|
||||
}
|
||||
|
||||
if (data.templateWapCancellationId) {
|
||||
updateCompany.templateWapCancellationId = data.templateWapCancellationId;
|
||||
}
|
||||
|
||||
if (data.templateEmailNotifId) {
|
||||
updateCompany.templateEmailNotifId = data.templateEmailNotifId;
|
||||
}
|
||||
@@ -213,6 +219,10 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
updateCompany.templateEmailAltaId = data.templateEmailAltaId;
|
||||
}
|
||||
|
||||
if (data.templateEmailCancellationId) {
|
||||
updateCompany.templateEmailCancellationId = data.templateEmailCancellationId;
|
||||
}
|
||||
|
||||
if (data.onboardingStep !== undefined) {
|
||||
updateCompany.onboardingStep = data.onboardingStep;
|
||||
}
|
||||
|
||||
@@ -47,8 +47,10 @@ export type UpdateCompanyParams = {
|
||||
sessionUser: string;
|
||||
templateWapNotifId?: string;
|
||||
templateWapAltaId?: string;
|
||||
templateWapCancellationId?: string;
|
||||
templateEmailNotifId?: string;
|
||||
templateEmailAltaId?: string;
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
banned?: boolean;
|
||||
@@ -144,8 +146,10 @@ export interface ICompany {
|
||||
automaticNotifications?: boolean;
|
||||
templateWapNotifId?: string;
|
||||
templateWapAltaId?: string;
|
||||
templateWapCancellationId?: string;
|
||||
templateEmailNotifId?: string;
|
||||
templateEmailAltaId?: string;
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
fixedPostIds?: Array<string>;
|
||||
@@ -192,8 +196,10 @@ export interface MyOranizationsView {
|
||||
appointmentAlert?: string;
|
||||
templateWapNotifId?: string;
|
||||
templateWapAltaId?: string;
|
||||
templateWapCancellationId?: string;
|
||||
templateEmailNotifId?: string;
|
||||
templateEmailAltaId?: string;
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
banned?: boolean;
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { Document, Model, Schema, model } from "mongoose";
|
||||
import {
|
||||
CreateJobParams,
|
||||
INotificationJob,
|
||||
INotificationJobAdapter,
|
||||
NotificationJobStatus,
|
||||
} from "./NotificationJobs.Interface";
|
||||
|
||||
export interface INotificationJobDocument
|
||||
extends Omit<INotificationJob, "id">,
|
||||
Document {}
|
||||
|
||||
export class NotificationJobsAdapterMongoose implements INotificationJobAdapter {
|
||||
schema: Schema;
|
||||
notificationJobList: Model<INotificationJobDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema(
|
||||
{
|
||||
companyId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "Company",
|
||||
},
|
||||
appointmentId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "Appointment",
|
||||
},
|
||||
clientId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "Client",
|
||||
},
|
||||
channel: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: ["whatsapp", "email", "system"],
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: ["creation", "reminder", "update", "cancellation"],
|
||||
},
|
||||
scheduledAt: { type: Date, required: true },
|
||||
status: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: Object.values(NotificationJobStatus),
|
||||
default: NotificationJobStatus.PENDING,
|
||||
},
|
||||
attempts: { type: Number, required: true, default: 0 },
|
||||
maxAttempts: { type: Number, required: true, default: 3 },
|
||||
lastError: { type: String, required: false },
|
||||
nextRetryAt: { type: Date, required: false },
|
||||
providerResponse: { type: String, required: false },
|
||||
payload: { type: Schema.Types.Mixed, required: false },
|
||||
sentAt: { type: Date, required: false },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
this.schema.index({ status: 1, scheduledAt: 1 });
|
||||
this.schema.index({ companyId: 1, status: 1 });
|
||||
this.schema.index({ appointmentId: 1 });
|
||||
|
||||
this.notificationJobList = model<INotificationJobDocument>(
|
||||
"NotificationJob",
|
||||
this.schema
|
||||
);
|
||||
}
|
||||
|
||||
public async create(data: CreateJobParams): Promise<INotificationJob> {
|
||||
const doc = await this.notificationJobList.create({
|
||||
...data,
|
||||
status: NotificationJobStatus.PENDING,
|
||||
attempts: 0,
|
||||
maxAttempts: 3,
|
||||
});
|
||||
return doc.toObject() as INotificationJob;
|
||||
}
|
||||
|
||||
public async findPendingDue(now: Date): Promise<INotificationJob[]> {
|
||||
const docs = await this.notificationJobList
|
||||
.find({
|
||||
status: NotificationJobStatus.PENDING,
|
||||
scheduledAt: { $lte: now },
|
||||
})
|
||||
.sort({ scheduledAt: 1 })
|
||||
.exec();
|
||||
return docs.map((d) => d.toObject() as INotificationJob);
|
||||
}
|
||||
|
||||
public async updateStatus(
|
||||
jobId: string,
|
||||
status: NotificationJobStatus,
|
||||
data?: { lastError?: string; nextRetryAt?: Date; providerResponse?: string }
|
||||
): Promise<void> {
|
||||
const update: Record<string, unknown> = { status };
|
||||
if (status === NotificationJobStatus.SENT) {
|
||||
update.sentAt = new Date();
|
||||
}
|
||||
if (data?.lastError !== undefined) update.lastError = data.lastError;
|
||||
if (data?.nextRetryAt !== undefined) update.nextRetryAt = data.nextRetryAt;
|
||||
if (data?.providerResponse !== undefined)
|
||||
update.providerResponse = data.providerResponse;
|
||||
|
||||
await this.notificationJobList.updateOne({ _id: jobId }, { $set: update }).exec();
|
||||
}
|
||||
|
||||
public async cancelByAppointment(appointmentId: string): Promise<void> {
|
||||
await this.notificationJobList
|
||||
.updateMany(
|
||||
{
|
||||
appointmentId,
|
||||
status: NotificationJobStatus.PENDING,
|
||||
},
|
||||
{ $set: { status: NotificationJobStatus.CANCELLED } }
|
||||
)
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async findByAppointment(appointmentId: string): Promise<INotificationJob[]> {
|
||||
const docs = await this.notificationJobList
|
||||
.find({ appointmentId })
|
||||
.exec();
|
||||
return docs.map((d) => d.toObject() as INotificationJob);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
export enum NotificationJobStatus {
|
||||
PENDING = "pending",
|
||||
PROCESSING = "processing",
|
||||
SENT = "sent",
|
||||
FAILED = "failed",
|
||||
CANCELLED = "cancelled",
|
||||
}
|
||||
|
||||
export type NotificationChannel = "whatsapp" | "email" | "system";
|
||||
|
||||
export type NotificationJobType =
|
||||
| "creation"
|
||||
| "reminder"
|
||||
| "update"
|
||||
| "cancellation";
|
||||
|
||||
export interface NotificationJobPayload {
|
||||
email?: string;
|
||||
phoneNumber?: string;
|
||||
userId?: string;
|
||||
companyOwnerId?: string;
|
||||
subject?: string;
|
||||
message?: string;
|
||||
emailSubject?: string;
|
||||
emailMessage?: string;
|
||||
wapMessage?: string;
|
||||
systemSubject?: string;
|
||||
systemMessage?: string;
|
||||
}
|
||||
|
||||
export interface INotificationJob {
|
||||
id?: string;
|
||||
companyId: string;
|
||||
appointmentId: string;
|
||||
clientId: string;
|
||||
channel: NotificationChannel;
|
||||
type: NotificationJobType;
|
||||
scheduledAt: Date;
|
||||
status: NotificationJobStatus;
|
||||
attempts: number;
|
||||
maxAttempts: number;
|
||||
lastError?: string;
|
||||
nextRetryAt?: Date;
|
||||
providerResponse?: string;
|
||||
payload?: NotificationJobPayload;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
sentAt?: Date;
|
||||
}
|
||||
|
||||
export interface CreateJobParams {
|
||||
companyId: string;
|
||||
appointmentId: string;
|
||||
clientId: string;
|
||||
channel: NotificationChannel;
|
||||
type: NotificationJobType;
|
||||
scheduledAt: Date;
|
||||
payload?: NotificationJobPayload;
|
||||
}
|
||||
|
||||
export interface INotificationJobAdapter {
|
||||
create(data: CreateJobParams): Promise<INotificationJob>;
|
||||
findPendingDue(now: Date): Promise<INotificationJob[]>;
|
||||
updateStatus(
|
||||
jobId: string,
|
||||
status: NotificationJobStatus,
|
||||
data?: { lastError?: string; nextRetryAt?: Date; providerResponse?: string }
|
||||
): Promise<void>;
|
||||
cancelByAppointment(appointmentId: string): Promise<void>;
|
||||
findByAppointment(appointmentId: string): Promise<INotificationJob[]>;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {
|
||||
CreateJobParams,
|
||||
INotificationJob,
|
||||
} from "./NotificationJobs.Interface";
|
||||
import { NotificationJobsAdapterMongoose } from "./NotificationJobs.Adapter.Mongoose";
|
||||
|
||||
class NotificationJobManager {
|
||||
adapter: NotificationJobsAdapterMongoose;
|
||||
|
||||
constructor() {
|
||||
this.adapter = new NotificationJobsAdapterMongoose();
|
||||
}
|
||||
|
||||
public async createJob(data: CreateJobParams): Promise<INotificationJob> {
|
||||
return this.adapter.create(data);
|
||||
}
|
||||
|
||||
public async cancelByAppointment(appointmentId: string): Promise<void> {
|
||||
return this.adapter.cancelByAppointment(appointmentId);
|
||||
}
|
||||
|
||||
public async findByAppointment(appointmentId: string): Promise<INotificationJob[]> {
|
||||
return this.adapter.findByAppointment(appointmentId);
|
||||
}
|
||||
}
|
||||
|
||||
const NotificationJobsList = new NotificationJobManager();
|
||||
export default NotificationJobsList;
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { Document, Model, Schema, model, models } from "mongoose";
|
||||
import {
|
||||
FindClientCompanyOverrideParams,
|
||||
IClientCompanyNotificationOverride,
|
||||
IClientCompanyNotificationOverrideAdapter,
|
||||
} from "./ClientCompanyNotificationOverride.Interface";
|
||||
|
||||
export interface IClientCompanyNotificationOverrideDocument
|
||||
extends Omit<IClientCompanyNotificationOverride, "id">,
|
||||
Document {}
|
||||
|
||||
export class ClientCompanyNotificationOverrideAdapterMongoose
|
||||
implements IClientCompanyNotificationOverrideAdapter
|
||||
{
|
||||
schema: Schema;
|
||||
overrideList: Model<IClientCompanyNotificationOverrideDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema(
|
||||
{
|
||||
clientId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "Client",
|
||||
},
|
||||
companyId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "Company",
|
||||
},
|
||||
preferredChannels: {
|
||||
type: [String],
|
||||
required: true,
|
||||
default: ["whatsapp", "email", "system"],
|
||||
enum: ["whatsapp", "email", "system"],
|
||||
},
|
||||
mutedChannels: {
|
||||
type: [String],
|
||||
required: true,
|
||||
default: [],
|
||||
enum: ["whatsapp", "email", "system"],
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
this.schema.index({ clientId: 1, companyId: 1 }, { unique: true });
|
||||
|
||||
this.overrideList = models.ClientCompanyNotificationOverride ||
|
||||
model<IClientCompanyNotificationOverrideDocument>(
|
||||
"ClientCompanyNotificationOverride",
|
||||
this.schema
|
||||
);
|
||||
}
|
||||
|
||||
public async findOne(
|
||||
filters: FindClientCompanyOverrideParams
|
||||
): Promise<IClientCompanyNotificationOverride | null> {
|
||||
const doc = await this.overrideList.findOne(filters).exec();
|
||||
return doc ? (doc.toObject() as IClientCompanyNotificationOverride) : null;
|
||||
}
|
||||
|
||||
public async upsert(
|
||||
clientId: string,
|
||||
companyId: string,
|
||||
data: Partial<
|
||||
Omit<
|
||||
IClientCompanyNotificationOverride,
|
||||
"id" | "clientId" | "companyId" | "createdAt" | "updatedAt"
|
||||
>
|
||||
>
|
||||
): Promise<IClientCompanyNotificationOverride> {
|
||||
const doc = await this.overrideList
|
||||
.findOneAndUpdate(
|
||||
{ clientId, companyId },
|
||||
{ $set: data },
|
||||
{ upsert: true, new: true }
|
||||
)
|
||||
.exec();
|
||||
return doc.toObject() as IClientCompanyNotificationOverride;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NotificationChannel } from "../NotificationJobs/NotificationJobs.Interface";
|
||||
|
||||
export interface IClientCompanyNotificationOverride {
|
||||
id?: string;
|
||||
clientId: string;
|
||||
companyId: string;
|
||||
preferredChannels: NotificationChannel[];
|
||||
mutedChannels: NotificationChannel[];
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface FindClientCompanyOverrideParams {
|
||||
clientId?: string;
|
||||
companyId?: string;
|
||||
}
|
||||
|
||||
export interface IClientCompanyNotificationOverrideAdapter {
|
||||
findOne(
|
||||
filters: FindClientCompanyOverrideParams
|
||||
): Promise<IClientCompanyNotificationOverride | null>;
|
||||
upsert(
|
||||
clientId: string,
|
||||
companyId: string,
|
||||
data: Partial<
|
||||
Omit<
|
||||
IClientCompanyNotificationOverride,
|
||||
"id" | "clientId" | "companyId" | "createdAt" | "updatedAt"
|
||||
>
|
||||
>
|
||||
): Promise<IClientCompanyNotificationOverride>;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ClientCompanyNotificationOverrideAdapterMongoose } from "./ClientCompanyNotificationOverride.Adapter.Mongoose";
|
||||
import {
|
||||
IClientCompanyNotificationOverride,
|
||||
IClientCompanyNotificationOverrideAdapter,
|
||||
} from "./ClientCompanyNotificationOverride.Interface";
|
||||
import ClientsList from "../Clients/Clients";
|
||||
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
|
||||
|
||||
type FindClientCompanyOverrideParams = {
|
||||
clientId: string;
|
||||
companyId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
type UpsertClientCompanyOverrideParams = FindClientCompanyOverrideParams & {
|
||||
data: Partial<
|
||||
Omit<
|
||||
IClientCompanyNotificationOverride,
|
||||
"id" | "clientId" | "companyId" | "createdAt" | "updatedAt"
|
||||
>
|
||||
>;
|
||||
};
|
||||
|
||||
class ClientCompanyNotificationOverrideManager {
|
||||
overrides: IClientCompanyNotificationOverrideAdapter;
|
||||
|
||||
constructor() {
|
||||
this.overrides = new ClientCompanyNotificationOverrideAdapterMongoose();
|
||||
}
|
||||
|
||||
public async findOne(
|
||||
params: FindClientCompanyOverrideParams
|
||||
): Promise<IClientCompanyNotificationOverride | null> {
|
||||
await this.validateAccess(params);
|
||||
|
||||
return this.overrides.findOne({
|
||||
clientId: params.clientId,
|
||||
companyId: params.companyId,
|
||||
});
|
||||
}
|
||||
|
||||
public async upsert(
|
||||
params: UpsertClientCompanyOverrideParams
|
||||
): Promise<IClientCompanyNotificationOverride> {
|
||||
await this.validateAccess(params);
|
||||
|
||||
return this.overrides.upsert(params.clientId, params.companyId, params.data);
|
||||
}
|
||||
|
||||
private async validateAccess(params: FindClientCompanyOverrideParams): Promise<void> {
|
||||
await validateSessionUser({ sessionUser: params.sessionUser });
|
||||
await validatePermissionsByCompany({
|
||||
companyId: params.companyId,
|
||||
sessionUser: params.sessionUser,
|
||||
});
|
||||
|
||||
const client = await ClientsList.clients.findOne({ _id: params.clientId });
|
||||
|
||||
if (!client) {
|
||||
throw new Error("El cliente no existe");
|
||||
}
|
||||
|
||||
if (String(client.companyId) !== String(params.companyId)) {
|
||||
throw new Error("El cliente no pertenece a la organización");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ClientCompanyNotificationOverride = new ClientCompanyNotificationOverrideManager();
|
||||
|
||||
export default ClientCompanyNotificationOverride;
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { Document, Model, Schema, model, models } from "mongoose";
|
||||
import {
|
||||
FindClientPreferencesParams,
|
||||
IClientNotificationPreferences,
|
||||
IClientNotificationPreferencesAdapter,
|
||||
} from "./ClientNotificationPreferences.Interface";
|
||||
|
||||
export interface IClientNotificationPreferencesDocument
|
||||
extends Omit<IClientNotificationPreferences, "id">,
|
||||
Document {}
|
||||
|
||||
export class ClientNotificationPreferencesAdapterMongoose
|
||||
implements IClientNotificationPreferencesAdapter
|
||||
{
|
||||
schema: Schema;
|
||||
preferencesList: Model<IClientNotificationPreferencesDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema(
|
||||
{
|
||||
userId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
unique: true,
|
||||
ref: "User",
|
||||
},
|
||||
preferredChannels: {
|
||||
type: [String],
|
||||
required: true,
|
||||
default: ["whatsapp", "email", "system"],
|
||||
enum: ["whatsapp", "email", "system"],
|
||||
},
|
||||
mutedChannels: {
|
||||
type: [String],
|
||||
required: true,
|
||||
default: [],
|
||||
enum: ["whatsapp", "email", "system"],
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
this.preferencesList = models.ClientNotificationPreferences ||
|
||||
model<IClientNotificationPreferencesDocument>(
|
||||
"ClientNotificationPreferences",
|
||||
this.schema
|
||||
);
|
||||
}
|
||||
|
||||
public async findOne(
|
||||
filters: FindClientPreferencesParams
|
||||
): Promise<IClientNotificationPreferences | null> {
|
||||
const doc = await this.preferencesList.findOne(filters).exec();
|
||||
return doc ? (doc.toObject() as IClientNotificationPreferences) : null;
|
||||
}
|
||||
|
||||
public async upsert(
|
||||
userId: string,
|
||||
data: Partial<
|
||||
Omit<IClientNotificationPreferences, "id" | "userId" | "createdAt" | "updatedAt">
|
||||
>
|
||||
): Promise<IClientNotificationPreferences> {
|
||||
const doc = await this.preferencesList
|
||||
.findOneAndUpdate({ userId }, { $set: data }, { upsert: true, new: true })
|
||||
.exec();
|
||||
return doc.toObject() as IClientNotificationPreferences;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { NotificationChannel } from "../NotificationJobs/NotificationJobs.Interface";
|
||||
|
||||
export interface IClientNotificationPreferences {
|
||||
id?: string;
|
||||
userId: string;
|
||||
preferredChannels: NotificationChannel[];
|
||||
mutedChannels: NotificationChannel[];
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface FindClientPreferencesParams {
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
export interface IClientNotificationPreferencesAdapter {
|
||||
findOne(
|
||||
filters: FindClientPreferencesParams
|
||||
): Promise<IClientNotificationPreferences | null>;
|
||||
upsert(
|
||||
userId: string,
|
||||
data: Partial<
|
||||
Omit<IClientNotificationPreferences, "id" | "userId" | "createdAt" | "updatedAt">
|
||||
>
|
||||
): Promise<IClientNotificationPreferences>;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { ClientNotificationPreferencesAdapterMongoose } from "./ClientNotificationPreferences.Adapter.Mongoose";
|
||||
import {
|
||||
IClientNotificationPreferences,
|
||||
IClientNotificationPreferencesAdapter,
|
||||
} from "./ClientNotificationPreferences.Interface";
|
||||
import { validateSessionUser } from "../../helpers/check";
|
||||
|
||||
type FindClientPreferencesParams = {
|
||||
userId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
type UpsertClientPreferencesParams = FindClientPreferencesParams & {
|
||||
data: Partial<
|
||||
Omit<IClientNotificationPreferences, "id" | "userId" | "createdAt" | "updatedAt">
|
||||
>;
|
||||
};
|
||||
|
||||
class ClientNotificationPreferencesManager {
|
||||
preferences: IClientNotificationPreferencesAdapter;
|
||||
|
||||
constructor() {
|
||||
this.preferences = new ClientNotificationPreferencesAdapterMongoose();
|
||||
}
|
||||
|
||||
public async findOne(
|
||||
params: FindClientPreferencesParams
|
||||
): Promise<IClientNotificationPreferences | null> {
|
||||
await this.validateUserOwner(params);
|
||||
return this.preferences.findOne({ userId: params.userId });
|
||||
}
|
||||
|
||||
public async upsert(
|
||||
params: UpsertClientPreferencesParams
|
||||
): Promise<IClientNotificationPreferences> {
|
||||
await this.validateUserOwner(params);
|
||||
return this.preferences.upsert(params.userId, params.data);
|
||||
}
|
||||
|
||||
private async validateUserOwner(params: FindClientPreferencesParams): Promise<void> {
|
||||
await validateSessionUser({ sessionUser: params.sessionUser });
|
||||
|
||||
if (String(params.userId) !== String(params.sessionUser)) {
|
||||
throw new Error("No tienes permisos para modificar preferencias de otro usuario");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ClientNotificationPreferences = new ClientNotificationPreferencesManager();
|
||||
|
||||
export default ClientNotificationPreferences;
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Document, Model, Schema, model, models } from "mongoose";
|
||||
import {
|
||||
FindCompanyPolicyParams,
|
||||
ICompanyNotificationPolicy,
|
||||
ICompanyNotificationPolicyAdapter,
|
||||
} from "./CompanyNotificationPolicy.Interface";
|
||||
|
||||
export interface ICompanyNotificationPolicyDocument
|
||||
extends Omit<ICompanyNotificationPolicy, "id">,
|
||||
Document {}
|
||||
|
||||
export class CompanyNotificationPolicyAdapterMongoose
|
||||
implements ICompanyNotificationPolicyAdapter
|
||||
{
|
||||
schema: Schema;
|
||||
policyList: Model<ICompanyNotificationPolicyDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema(
|
||||
{
|
||||
companyId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
unique: true,
|
||||
ref: "Company",
|
||||
},
|
||||
defaultChannels: {
|
||||
type: [String],
|
||||
required: true,
|
||||
default: ["whatsapp", "email", "system"],
|
||||
enum: ["whatsapp", "email", "system"],
|
||||
},
|
||||
mutedChannels: {
|
||||
type: [String],
|
||||
required: false,
|
||||
default: [],
|
||||
enum: ["whatsapp", "email", "system"],
|
||||
},
|
||||
timezone: {
|
||||
type: String,
|
||||
required: true,
|
||||
default: "America/Argentina/Buenos_Aires",
|
||||
},
|
||||
quietHours: {
|
||||
from: { type: String, required: false },
|
||||
to: { type: String, required: false },
|
||||
},
|
||||
reminderRules: [
|
||||
{
|
||||
offset: { type: Number, required: true },
|
||||
enabled: { type: Boolean, required: true, default: true },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
this.policyList = models.CompanyNotificationPolicy ||
|
||||
model<ICompanyNotificationPolicyDocument>(
|
||||
"CompanyNotificationPolicy",
|
||||
this.schema
|
||||
);
|
||||
}
|
||||
|
||||
public async findOne(
|
||||
filters: FindCompanyPolicyParams
|
||||
): Promise<ICompanyNotificationPolicy | null> {
|
||||
const doc = await this.policyList.findOne(filters).exec();
|
||||
return doc ? (doc.toObject() as ICompanyNotificationPolicy) : null;
|
||||
}
|
||||
|
||||
public async upsert(
|
||||
companyId: string,
|
||||
data: Partial<Omit<ICompanyNotificationPolicy, "id" | "companyId" | "createdAt" | "updatedAt">>
|
||||
): Promise<ICompanyNotificationPolicy> {
|
||||
const doc = await this.policyList
|
||||
.findOneAndUpdate({ companyId }, { $set: data }, { upsert: true, new: true })
|
||||
.exec();
|
||||
return doc.toObject() as ICompanyNotificationPolicy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NotificationChannel } from "../NotificationJobs/NotificationJobs.Interface";
|
||||
|
||||
export interface QuietHours {
|
||||
from: string; // "HH:mm" format, e.g. "22:00"
|
||||
to: string; // "HH:mm" format, e.g. "07:00"
|
||||
}
|
||||
|
||||
export interface ReminderRules {
|
||||
offset: number; // minutes before appointment
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface ICompanyNotificationPolicy {
|
||||
id?: string;
|
||||
companyId: string;
|
||||
defaultChannels: NotificationChannel[];
|
||||
mutedChannels?: NotificationChannel[];
|
||||
timezone: string;
|
||||
quietHours?: QuietHours;
|
||||
reminderRules?: ReminderRules[];
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface FindCompanyPolicyParams {
|
||||
companyId?: string;
|
||||
}
|
||||
|
||||
export interface ICompanyNotificationPolicyAdapter {
|
||||
findOne(filters: FindCompanyPolicyParams): Promise<ICompanyNotificationPolicy | null>;
|
||||
upsert(
|
||||
companyId: string,
|
||||
data: Partial<Omit<ICompanyNotificationPolicy, "id" | "companyId" | "createdAt" | "updatedAt">>
|
||||
): Promise<ICompanyNotificationPolicy>;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { CompanyNotificationPolicyAdapterMongoose } from "./CompanyNotificationPolicy.Adapter.Mongoose";
|
||||
import {
|
||||
ICompanyNotificationPolicy,
|
||||
ICompanyNotificationPolicyAdapter,
|
||||
} from "./CompanyNotificationPolicy.Interface";
|
||||
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
|
||||
|
||||
type FindCompanyPolicyParams = {
|
||||
companyId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
type UpsertCompanyPolicyParams = FindCompanyPolicyParams & {
|
||||
data: Partial<
|
||||
Omit<ICompanyNotificationPolicy, "id" | "companyId" | "createdAt" | "updatedAt">
|
||||
>;
|
||||
};
|
||||
|
||||
class CompanyNotificationPolicyManager {
|
||||
policies: ICompanyNotificationPolicyAdapter;
|
||||
|
||||
constructor() {
|
||||
this.policies = new CompanyNotificationPolicyAdapterMongoose();
|
||||
}
|
||||
|
||||
public async findOne(
|
||||
params: FindCompanyPolicyParams
|
||||
): Promise<ICompanyNotificationPolicy | null> {
|
||||
await validateSessionUser({ sessionUser: params.sessionUser });
|
||||
await validatePermissionsByCompany({
|
||||
companyId: params.companyId,
|
||||
sessionUser: params.sessionUser,
|
||||
});
|
||||
|
||||
return this.policies.findOne({ companyId: params.companyId });
|
||||
}
|
||||
|
||||
public async upsert(params: UpsertCompanyPolicyParams): Promise<ICompanyNotificationPolicy> {
|
||||
await validateSessionUser({ sessionUser: params.sessionUser });
|
||||
await validatePermissionsByCompany({
|
||||
companyId: params.companyId,
|
||||
sessionUser: params.sessionUser,
|
||||
});
|
||||
|
||||
return this.policies.upsert(params.companyId, params.data);
|
||||
}
|
||||
}
|
||||
|
||||
const CompanyNotificationPolicy = new CompanyNotificationPolicyManager();
|
||||
|
||||
export default CompanyNotificationPolicy;
|
||||
@@ -0,0 +1,189 @@
|
||||
import {
|
||||
CreateJobParams,
|
||||
} from "../NotificationJobs/NotificationJobs.Interface";
|
||||
import { NotificationJobsAdapterMongoose } from "../NotificationJobs/NotificationJobs.Adapter.Mongoose";
|
||||
import { PolicyResolver, ResolvedPolicy } from "./PolicyResolver";
|
||||
import dayjs from "dayjs";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
dayjs.extend(utc);
|
||||
|
||||
export interface CreateJobServiceParams {
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
appointmentId: string;
|
||||
type: CreateJobParams["type"];
|
||||
scheduledAt?: Date;
|
||||
appointmentStart?: Date;
|
||||
payload?: CreateJobParams["payload"];
|
||||
}
|
||||
|
||||
export class NotificationJobService {
|
||||
private jobAdapter: NotificationJobsAdapterMongoose;
|
||||
private policyResolver: PolicyResolver;
|
||||
|
||||
constructor() {
|
||||
this.jobAdapter = new NotificationJobsAdapterMongoose();
|
||||
this.policyResolver = new PolicyResolver();
|
||||
}
|
||||
|
||||
async createJob(params: CreateJobServiceParams): Promise<any[]> {
|
||||
const resolvedPolicy = await this.policyResolver.resolve(
|
||||
params.companyId,
|
||||
params.clientId
|
||||
);
|
||||
|
||||
if (resolvedPolicy.channels.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const baseScheduledAt = params.scheduledAt || now;
|
||||
const adjustedScheduledAt = this.adjustForQuietHours(
|
||||
baseScheduledAt,
|
||||
resolvedPolicy
|
||||
);
|
||||
|
||||
const jobs: any[] = [];
|
||||
for (const channel of resolvedPolicy.channels) {
|
||||
const job = await this.jobAdapter.create({
|
||||
companyId: params.companyId,
|
||||
appointmentId: params.appointmentId,
|
||||
clientId: params.clientId,
|
||||
channel,
|
||||
type: params.type,
|
||||
scheduledAt: adjustedScheduledAt,
|
||||
payload: params.payload,
|
||||
});
|
||||
jobs.push(job);
|
||||
}
|
||||
|
||||
if (params.appointmentStart) {
|
||||
const enabledReminderRules = (resolvedPolicy.reminderRules || []).filter(
|
||||
(rule) => rule.enabled
|
||||
);
|
||||
|
||||
for (const rule of enabledReminderRules) {
|
||||
const reminderScheduledAt = this.adjustForQuietHours(
|
||||
dayjs(params.appointmentStart).subtract(rule.offset, "minute").toDate(),
|
||||
resolvedPolicy
|
||||
);
|
||||
|
||||
if (reminderScheduledAt < now || reminderScheduledAt >= params.appointmentStart) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const channel of resolvedPolicy.channels) {
|
||||
const job = await this.jobAdapter.create({
|
||||
companyId: params.companyId,
|
||||
appointmentId: params.appointmentId,
|
||||
clientId: params.clientId,
|
||||
channel,
|
||||
type: "reminder",
|
||||
scheduledAt: reminderScheduledAt,
|
||||
});
|
||||
jobs.push(job);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return jobs;
|
||||
}
|
||||
|
||||
async createImmediateJob(params: CreateJobServiceParams): Promise<any[]> {
|
||||
const resolvedPolicy = await this.policyResolver.resolve(
|
||||
params.companyId,
|
||||
params.clientId
|
||||
);
|
||||
|
||||
if (resolvedPolicy.channels.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const scheduledAt = params.scheduledAt || new Date();
|
||||
const jobs: any[] = [];
|
||||
|
||||
for (const channel of resolvedPolicy.channels) {
|
||||
const job = await this.jobAdapter.create({
|
||||
companyId: params.companyId,
|
||||
appointmentId: params.appointmentId,
|
||||
clientId: params.clientId,
|
||||
channel,
|
||||
type: params.type,
|
||||
scheduledAt,
|
||||
payload: params.payload,
|
||||
});
|
||||
jobs.push(job);
|
||||
}
|
||||
|
||||
return jobs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel all pending jobs for an appointment.
|
||||
* Called when an appointment is deleted or rescheduled.
|
||||
*/
|
||||
async cancelByAppointment(appointmentId: string): Promise<void> {
|
||||
return this.jobAdapter.cancelByAppointment(appointmentId);
|
||||
}
|
||||
|
||||
private adjustForQuietHours(scheduledAt: Date, policy: ResolvedPolicy): Date {
|
||||
if (!policy.quietHours?.from || !policy.quietHours?.to) {
|
||||
return scheduledAt;
|
||||
}
|
||||
|
||||
const scheduled = dayjs.utc(scheduledAt);
|
||||
const fromHour = parseInt(policy.quietHours.from.split(":")[0], 10);
|
||||
const fromMinute = parseInt(policy.quietHours.from.split(":")[1], 10);
|
||||
const toHour = parseInt(policy.quietHours.to.split(":")[0], 10);
|
||||
const toMinute = parseInt(policy.quietHours.to.split(":")[1], 10);
|
||||
|
||||
const scheduledHour = scheduled.hour();
|
||||
const scheduledMinute = scheduled.minute();
|
||||
|
||||
const isInsideQuietHours = this.isTimeInQuietHours(
|
||||
scheduledHour,
|
||||
scheduledMinute,
|
||||
fromHour,
|
||||
fromMinute,
|
||||
toHour,
|
||||
toMinute
|
||||
);
|
||||
|
||||
if (isInsideQuietHours) {
|
||||
// Shift to quiet hours end
|
||||
let adjusted = scheduled.hour(toHour).minute(toMinute).second(0);
|
||||
// If quiet hours cross midnight (e.g. 22:00-07:00) and end is before start,
|
||||
// the end is on the next day
|
||||
if (toHour < fromHour) {
|
||||
if (scheduledHour >= fromHour || scheduledHour < toHour) {
|
||||
adjusted = adjusted.add(1, "day");
|
||||
}
|
||||
}
|
||||
return adjusted.toDate();
|
||||
}
|
||||
|
||||
return scheduledAt;
|
||||
}
|
||||
|
||||
private isTimeInQuietHours(
|
||||
hour: number,
|
||||
minute: number,
|
||||
fromHour: number,
|
||||
fromMinute: number,
|
||||
toHour: number,
|
||||
toMinute: number
|
||||
): boolean {
|
||||
const currentMinutes = hour * 60 + minute;
|
||||
const fromMinutes = fromHour * 60 + fromMinute;
|
||||
const toMinutes = toHour * 60 + toMinute;
|
||||
|
||||
if (fromMinutes < toMinutes) {
|
||||
// Quiet hours within same day (e.g. 01:00-06:00)
|
||||
return currentMinutes >= fromMinutes && currentMinutes < toMinutes;
|
||||
} else {
|
||||
// Quiet hours cross midnight (e.g. 22:00-07:00)
|
||||
return currentMinutes >= fromMinutes || currentMinutes < toMinutes;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { NotificationChannel } from "../NotificationJobs/NotificationJobs.Interface";
|
||||
import { CompanyNotificationPolicyAdapterMongoose } from "./CompanyNotificationPolicy.Adapter.Mongoose";
|
||||
import { ClientNotificationPreferencesAdapterMongoose } from "./ClientNotificationPreferences.Adapter.Mongoose";
|
||||
import { ClientCompanyNotificationOverrideAdapterMongoose } from "./ClientCompanyNotificationOverride.Adapter.Mongoose";
|
||||
import { IClientNotificationPreferences } from "./ClientNotificationPreferences.Interface";
|
||||
import { IClientCompanyNotificationOverride } from "./ClientCompanyNotificationOverride.Interface";
|
||||
import { ICompanyNotificationPolicy } from "./CompanyNotificationPolicy.Interface";
|
||||
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
|
||||
import { PlanFeatures } from "../Plans/Plans.interface";
|
||||
import ClientsList from "../Clients/Clients";
|
||||
|
||||
const DEFAULT_TIMEZONE = "America/Argentina/Buenos_Aires";
|
||||
const SYSTEM_DEFAULT_CHANNELS: NotificationChannel[] = ["whatsapp", "email", "system"];
|
||||
|
||||
const PLAN_CHANNEL_MAP: Record<string, PlanFeatures> = {
|
||||
whatsapp: PlanFeatures.WAP_NOTIFICATIONS,
|
||||
email: PlanFeatures.MAIL_NOTIFICATIONS,
|
||||
};
|
||||
|
||||
export interface ResolvedPolicy {
|
||||
channels: NotificationChannel[];
|
||||
timezone: string;
|
||||
quietHours?: { from: string; to: string };
|
||||
reminderRules?: { offset: number; enabled: boolean }[];
|
||||
}
|
||||
|
||||
export class PolicyResolver {
|
||||
private companyPolicyAdapter: CompanyNotificationPolicyAdapterMongoose;
|
||||
private clientPreferencesAdapter: ClientNotificationPreferencesAdapterMongoose;
|
||||
private clientCompanyOverrideAdapter: ClientCompanyNotificationOverrideAdapterMongoose;
|
||||
|
||||
constructor() {
|
||||
this.companyPolicyAdapter = new CompanyNotificationPolicyAdapterMongoose();
|
||||
this.clientPreferencesAdapter = new ClientNotificationPreferencesAdapterMongoose();
|
||||
this.clientCompanyOverrideAdapter = new ClientCompanyNotificationOverrideAdapterMongoose();
|
||||
}
|
||||
|
||||
async resolve(companyId: string, clientId: string): Promise<ResolvedPolicy> {
|
||||
// Level 2: ClientCompanyNotificationOverride (per-client per-org)
|
||||
const override = await this.clientCompanyOverrideAdapter.findOne({
|
||||
clientId,
|
||||
companyId,
|
||||
});
|
||||
|
||||
const client = await ClientsList.clients.findOne({ _id: clientId });
|
||||
|
||||
// Level 3: ClientNotificationPreferences (user global)
|
||||
const clientPrefs = client?.userId
|
||||
? await this.clientPreferencesAdapter.findOne({ userId: String(client.userId) })
|
||||
: null;
|
||||
|
||||
// Level 4: CompanyNotificationPolicy (org defaults)
|
||||
const companyPolicy = await this.companyPolicyAdapter.findOne({ companyId });
|
||||
|
||||
// Determine channels from cascade
|
||||
let channels: NotificationChannel[];
|
||||
let timezone: string;
|
||||
let quietHours: ResolvedPolicy["quietHours"];
|
||||
let reminderRules: ResolvedPolicy["reminderRules"];
|
||||
|
||||
if (override) {
|
||||
channels = [...override.preferredChannels];
|
||||
} else if (clientPrefs) {
|
||||
channels = [...clientPrefs.preferredChannels];
|
||||
} else if (companyPolicy) {
|
||||
channels = [...companyPolicy.defaultChannels];
|
||||
} else {
|
||||
// Level 5: System defaults
|
||||
channels = [...SYSTEM_DEFAULT_CHANNELS];
|
||||
}
|
||||
|
||||
// Apply muted channels from the winning level only — do NOT merge across levels
|
||||
const mutedChannels = this.getMutedChannels(override, clientPrefs, companyPolicy);
|
||||
channels = channels.filter((ch) => !mutedChannels.includes(ch));
|
||||
|
||||
// Timezone and quiet hours from company policy
|
||||
if (companyPolicy) {
|
||||
timezone = companyPolicy.timezone;
|
||||
quietHours = companyPolicy.quietHours;
|
||||
reminderRules = companyPolicy.reminderRules;
|
||||
} else {
|
||||
timezone = DEFAULT_TIMEZONE;
|
||||
}
|
||||
|
||||
// Level 1: Plan limits — filter channels by plan features
|
||||
channels = await this.applyPlanLimits(companyId, channels);
|
||||
|
||||
return {
|
||||
channels,
|
||||
timezone,
|
||||
quietHours,
|
||||
reminderRules,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns muted channels from the winning cascade level only.
|
||||
* Per spec, muted channels are NOT merged across levels.
|
||||
* The level that determines preferredChannels also determines mutedChannels.
|
||||
*/
|
||||
private getMutedChannels(
|
||||
override: IClientCompanyNotificationOverride | null,
|
||||
clientPrefs: IClientNotificationPreferences | null,
|
||||
companyPolicy: ICompanyNotificationPolicy | null
|
||||
): NotificationChannel[] {
|
||||
if (override) {
|
||||
// Override wins — use only override's muted channels
|
||||
return override.mutedChannels || [];
|
||||
}
|
||||
if (clientPrefs) {
|
||||
// Client prefs wins — use only clientPrefs' muted channels
|
||||
return clientPrefs.mutedChannels || [];
|
||||
}
|
||||
if (companyPolicy) {
|
||||
// Company policy wins — use only companyPolicy' muted channels
|
||||
return companyPolicy.mutedChannels || [];
|
||||
}
|
||||
// System defaults — no muted channels
|
||||
return [];
|
||||
}
|
||||
|
||||
private async applyPlanLimits(
|
||||
companyId: string,
|
||||
channels: NotificationChannel[]
|
||||
): Promise<NotificationChannel[]> {
|
||||
// Resolve the company owner's userId for plan feature checks
|
||||
// Use lazy require to avoid circular dependency (PolicyResolver → CompaniesManager → Appointments → NotificationJobService → PolicyResolver)
|
||||
const CompaniesManager = require("../Companies/Companies").default;
|
||||
const company = await CompaniesManager.companies.findOne({ _id: companyId });
|
||||
if (!company) {
|
||||
// Company not found — return channels unchanged (fail-open)
|
||||
return channels;
|
||||
}
|
||||
|
||||
const ownerUserId = String(company.ownerId);
|
||||
const filtered: NotificationChannel[] = [];
|
||||
|
||||
for (const channel of channels) {
|
||||
const planFeature = PLAN_CHANNEL_MAP[channel];
|
||||
if (!planFeature) {
|
||||
// Channel has no plan restriction (e.g., system)
|
||||
filtered.push(channel);
|
||||
continue;
|
||||
}
|
||||
|
||||
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||
userId: ownerUserId,
|
||||
feature: planFeature,
|
||||
});
|
||||
|
||||
if (canSend) {
|
||||
filtered.push(channel);
|
||||
}
|
||||
}
|
||||
|
||||
return filtered;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
import { NotificationJobStatus } from "../../NotificationJobs/NotificationJobs.Interface";
|
||||
|
||||
// Mock all external dependencies
|
||||
jest.mock("../../NotificationJobs/NotificationJobs.Adapter.Mongoose", () => ({
|
||||
NotificationJobsAdapterMongoose: jest.fn().mockImplementation(() => ({
|
||||
create: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock("../PolicyResolver", () => ({
|
||||
PolicyResolver: jest.fn().mockImplementation(() => ({
|
||||
resolve: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock("../../PlanSubscriptions/PlanSubscriptons", () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
checkFeature: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { NotificationJobService } from "../NotificationJobService";
|
||||
import { ResolvedPolicy } from "../PolicyResolver";
|
||||
|
||||
describe("NotificationJobService.createJob", () => {
|
||||
let service: NotificationJobService;
|
||||
let mockJobCreate: jest.Mock;
|
||||
let mockResolverResolve: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.useRealTimers();
|
||||
|
||||
service = new NotificationJobService();
|
||||
|
||||
mockJobCreate = (service as any).jobAdapter.create as jest.Mock;
|
||||
mockResolverResolve = (service as any).policyResolver.resolve as jest.Mock;
|
||||
});
|
||||
|
||||
it("creates a job with resolved channels", async () => {
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["whatsapp", "email"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
mockJobCreate.mockResolvedValue({
|
||||
id: "job-1",
|
||||
status: NotificationJobStatus.PENDING,
|
||||
});
|
||||
|
||||
const result = await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
});
|
||||
|
||||
expect(mockResolverResolve).toHaveBeenCalledWith("company-1", "client-1");
|
||||
expect(mockJobCreate).toHaveBeenCalledTimes(2); // one per channel
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("creates reminder jobs for each enabled rule and resolved channel in addition to immediate jobs", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-21T14:00:00.000Z"));
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["system", "email"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
reminderRules: [
|
||||
{ offset: 2, enabled: true },
|
||||
{ offset: 5, enabled: true },
|
||||
],
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
mockJobCreate.mockResolvedValue({
|
||||
id: "job-1",
|
||||
status: NotificationJobStatus.PENDING,
|
||||
});
|
||||
|
||||
const result = await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
appointmentStart: new Date("2026-07-21T14:30:00.000Z"),
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
const immediateJobs = createCalls.filter((job) => job.type === "creation");
|
||||
const reminderJobs = createCalls.filter((job) => job.type === "reminder");
|
||||
|
||||
expect(mockJobCreate).toHaveBeenCalledTimes(6);
|
||||
expect(result).toHaveLength(6);
|
||||
expect(immediateJobs).toHaveLength(2);
|
||||
expect(reminderJobs).toHaveLength(4);
|
||||
expect(immediateJobs.map((job) => job.channel).sort()).toEqual(["email", "system"]);
|
||||
expect(immediateJobs.map((job) => job.scheduledAt.toISOString())).toEqual([
|
||||
"2026-07-21T14:00:00.000Z",
|
||||
"2026-07-21T14:00:00.000Z",
|
||||
]);
|
||||
expect(reminderJobs.map((job) => job.channel).sort()).toEqual([
|
||||
"email",
|
||||
"email",
|
||||
"system",
|
||||
"system",
|
||||
]);
|
||||
expect(reminderJobs.map((job) => job.scheduledAt.toISOString()).sort()).toEqual([
|
||||
"2026-07-21T14:25:00.000Z",
|
||||
"2026-07-21T14:25:00.000Z",
|
||||
"2026-07-21T14:28:00.000Z",
|
||||
"2026-07-21T14:28:00.000Z",
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips reminder jobs scheduled in the past", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-21T14:29:00.000Z"));
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["system", "email"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
reminderRules: [
|
||||
{ offset: 2, enabled: true },
|
||||
{ offset: 5, enabled: true },
|
||||
],
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
mockJobCreate.mockResolvedValue({ id: "job-1" });
|
||||
|
||||
await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
appointmentStart: new Date("2026-07-21T14:30:00.000Z"),
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
expect(createCalls.filter((job) => job.type === "creation")).toHaveLength(2);
|
||||
expect(createCalls.filter((job) => job.type === "reminder")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("skips reminder jobs adjusted by quiet hours after appointment start", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-21T20:00:00.000Z"));
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["system", "email"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
quietHours: { from: "22:00", to: "07:00" },
|
||||
reminderRules: [{ offset: 15, enabled: true }],
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
mockJobCreate.mockResolvedValue({ id: "job-1" });
|
||||
|
||||
await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
appointmentStart: new Date("2026-07-21T23:30:00.000Z"),
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
expect(createCalls.filter((job) => job.type === "creation")).toHaveLength(2);
|
||||
expect(createCalls.filter((job) => job.type === "reminder")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("creates no jobs when resolved channels are empty", async () => {
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: [],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
|
||||
const result = await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
});
|
||||
|
||||
expect(mockJobCreate).not.toHaveBeenCalled();
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("adjusts scheduledAt for quiet hours crossing midnight", async () => {
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["system"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
quietHours: { from: "22:00", to: "07:00" },
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
mockJobCreate.mockResolvedValue({ id: "job-1" });
|
||||
|
||||
// scheduledAt at 23:30 UTC — should be adjusted to 07:00 next day UTC
|
||||
const scheduledAt = new Date("2026-07-21T23:30:00.000Z");
|
||||
|
||||
await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
scheduledAt,
|
||||
});
|
||||
|
||||
const createCall = mockJobCreate.mock.calls[0][0];
|
||||
// 23:30 is inside quiet hours (22:00-07:00), adjusted to 07:00 next day
|
||||
expect(createCall.scheduledAt.getUTCHours()).toBe(7);
|
||||
expect(createCall.scheduledAt.getUTCDate()).toBe(22); // next day
|
||||
});
|
||||
|
||||
it("does not adjust scheduledAt when outside quiet hours", async () => {
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["system"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
quietHours: { from: "22:00", to: "07:00" },
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
mockJobCreate.mockResolvedValue({ id: "job-1" });
|
||||
|
||||
// scheduledAt at 14:00 UTC — outside quiet hours (22:00-07:00)
|
||||
const scheduledAt = new Date("2026-07-21T14:00:00.000Z");
|
||||
|
||||
await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
scheduledAt,
|
||||
});
|
||||
|
||||
const createCall = mockJobCreate.mock.calls[0][0];
|
||||
// 14:00 is outside quiet hours, should remain unchanged
|
||||
expect(createCall.scheduledAt.getUTCHours()).toBe(14);
|
||||
expect(createCall.scheduledAt.getUTCDate()).toBe(21);
|
||||
});
|
||||
|
||||
it("passes appointmentId and type to job creation", async () => {
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["system"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
mockJobCreate.mockResolvedValue({ id: "job-1" });
|
||||
|
||||
const scheduledAt = new Date("2026-07-21T15:00:00.000Z");
|
||||
|
||||
await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-42",
|
||||
type: "reminder",
|
||||
scheduledAt,
|
||||
});
|
||||
|
||||
const createCall = mockJobCreate.mock.calls[0][0];
|
||||
expect(createCall.appointmentId).toBe("appt-42");
|
||||
expect(createCall.type).toBe("reminder");
|
||||
expect(createCall.companyId).toBe("company-1");
|
||||
expect(createCall.clientId).toBe("client-1");
|
||||
});
|
||||
|
||||
it("creates immediate jobs without reminder offsets", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-21T14:00:00.000Z"));
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["system", "email"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
reminderRules: [{ offset: 30, enabled: true }],
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
mockJobCreate.mockResolvedValue({ id: "job-1" });
|
||||
|
||||
const result = await service.createImmediateJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "reminder",
|
||||
appointmentStart: new Date("2026-07-21T16:00:00.000Z"),
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(mockJobCreate).toHaveBeenCalledTimes(2);
|
||||
expect(createCalls).toEqual([
|
||||
expect.objectContaining({
|
||||
channel: "system",
|
||||
type: "reminder",
|
||||
scheduledAt: new Date("2026-07-21T14:00:00.000Z"),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
channel: "email",
|
||||
type: "reminder",
|
||||
scheduledAt: new Date("2026-07-21T14:00:00.000Z"),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates immediate cancellation jobs with snapshot payload for each resolved channel", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-21T14:00:00.000Z"));
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["system", "email"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
};
|
||||
const payload = {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Turno cancelado en Barber Shop",
|
||||
message: "Tu turno fue cancelado.",
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
mockJobCreate.mockResolvedValue({ id: "job-1" });
|
||||
|
||||
const result = await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "cancellation",
|
||||
scheduledAt: new Date(),
|
||||
payload,
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(createCalls).toEqual([
|
||||
expect.objectContaining({
|
||||
appointmentId: "appt-1",
|
||||
channel: "system",
|
||||
type: "cancellation",
|
||||
scheduledAt: new Date("2026-07-21T14:00:00.000Z"),
|
||||
payload,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
appointmentId: "appt-1",
|
||||
channel: "email",
|
||||
type: "cancellation",
|
||||
scheduledAt: new Date("2026-07-21T14:00:00.000Z"),
|
||||
payload,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,312 @@
|
||||
import { NotificationChannel } from "../../NotificationJobs/NotificationJobs.Interface";
|
||||
|
||||
// Mock all external dependencies before importing the module under test
|
||||
jest.mock("../../PlanSubscriptions/PlanSubscriptons", () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
checkFeature: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock("../CompanyNotificationPolicy.Adapter.Mongoose", () => ({
|
||||
CompanyNotificationPolicyAdapterMongoose: jest.fn().mockImplementation(() => ({
|
||||
findOne: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock("../ClientNotificationPreferences.Adapter.Mongoose", () => ({
|
||||
ClientNotificationPreferencesAdapterMongoose: jest.fn().mockImplementation(() => ({
|
||||
findOne: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock("../ClientCompanyNotificationOverride.Adapter.Mongoose", () => ({
|
||||
ClientCompanyNotificationOverrideAdapterMongoose: jest.fn().mockImplementation(() => ({
|
||||
findOne: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock("../../Companies/Companies", () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
companies: {
|
||||
findOne: jest.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock("../../Clients/Clients", () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
clients: {
|
||||
findOne: jest.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { PolicyResolver } from "../PolicyResolver";
|
||||
import PlanSubscriptionsList from "../../PlanSubscriptions/PlanSubscriptons";
|
||||
import CompaniesManager from "../../Companies/Companies";
|
||||
import ClientsList from "../../Clients/Clients";
|
||||
import { PlanFeatures } from "../../Plans/Plans.interface";
|
||||
|
||||
describe("PolicyResolver", () => {
|
||||
let resolver: PolicyResolver;
|
||||
let mockCompanyPolicyFindOne: jest.Mock;
|
||||
let mockClientPreferencesFindOne: jest.Mock;
|
||||
let mockOverrideFindOne: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
resolver = new PolicyResolver();
|
||||
|
||||
// Access the mocked adapter instances
|
||||
mockCompanyPolicyFindOne = (
|
||||
resolver as any
|
||||
).companyPolicyAdapter.findOne as jest.Mock;
|
||||
mockClientPreferencesFindOne = (
|
||||
resolver as any
|
||||
).clientPreferencesAdapter.findOne as jest.Mock;
|
||||
mockOverrideFindOne = (
|
||||
resolver as any
|
||||
).clientCompanyOverrideAdapter.findOne as jest.Mock;
|
||||
|
||||
// Mock CompaniesManager to return a company with an ownerId
|
||||
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "company-1",
|
||||
ownerId: "owner-user-1",
|
||||
});
|
||||
(ClientsList.clients.findOne as jest.Mock).mockResolvedValue({
|
||||
_id: "client-1",
|
||||
userId: "client-user-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns system defaults when no policies exist", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue(null);
|
||||
mockClientPreferencesFindOne.mockResolvedValue(null);
|
||||
mockOverrideFindOne.mockResolvedValue(null);
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.channels).toEqual(
|
||||
expect.arrayContaining(["whatsapp", "email", "system"])
|
||||
);
|
||||
expect(result.channels).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("uses company policy defaults when no client override exists", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: ["email" as NotificationChannel],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
});
|
||||
mockClientPreferencesFindOne.mockResolvedValue(null);
|
||||
mockOverrideFindOne.mockResolvedValue(null);
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.channels).toEqual(["email"]);
|
||||
});
|
||||
|
||||
it("client override wins over company default", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: ["email" as NotificationChannel],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
});
|
||||
mockClientPreferencesFindOne.mockResolvedValue(null);
|
||||
mockOverrideFindOne.mockResolvedValue({
|
||||
clientId: "client-1",
|
||||
companyId: "company-1",
|
||||
preferredChannels: ["whatsapp" as NotificationChannel],
|
||||
mutedChannels: [],
|
||||
});
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.channels).toEqual(["whatsapp"]);
|
||||
});
|
||||
|
||||
it("client global preferences used when no override exists", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: ["whatsapp" as NotificationChannel, "email" as NotificationChannel],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
});
|
||||
mockClientPreferencesFindOne.mockResolvedValue({
|
||||
userId: "client-user-1",
|
||||
preferredChannels: ["email" as NotificationChannel],
|
||||
mutedChannels: [],
|
||||
});
|
||||
mockOverrideFindOne.mockResolvedValue(null);
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.channels).toEqual(["email"]);
|
||||
});
|
||||
|
||||
it("excludes muted channels from override", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue(null);
|
||||
mockClientPreferencesFindOne.mockResolvedValue(null);
|
||||
mockOverrideFindOne.mockResolvedValue({
|
||||
clientId: "client-1",
|
||||
companyId: "company-1",
|
||||
preferredChannels: [
|
||||
"whatsapp" as NotificationChannel,
|
||||
"email" as NotificationChannel,
|
||||
],
|
||||
mutedChannels: ["whatsapp" as NotificationChannel],
|
||||
});
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.channels).toEqual(["email"]);
|
||||
expect(result.channels).not.toContain("whatsapp");
|
||||
});
|
||||
|
||||
it("excludes muted channels from client preferences", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue(null);
|
||||
mockClientPreferencesFindOne.mockResolvedValue({
|
||||
userId: "client-user-1",
|
||||
preferredChannels: [
|
||||
"whatsapp" as NotificationChannel,
|
||||
"email" as NotificationChannel,
|
||||
"system" as NotificationChannel,
|
||||
],
|
||||
mutedChannels: ["email" as NotificationChannel],
|
||||
});
|
||||
mockOverrideFindOne.mockResolvedValue(null);
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.channels).toEqual(
|
||||
expect.arrayContaining(["whatsapp", "system"])
|
||||
);
|
||||
expect(result.channels).not.toContain("email");
|
||||
});
|
||||
|
||||
it("loads global preferences by the appointment client's userId", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue(null);
|
||||
mockClientPreferencesFindOne.mockResolvedValue({
|
||||
userId: "client-user-1",
|
||||
preferredChannels: ["system" as NotificationChannel],
|
||||
mutedChannels: [],
|
||||
});
|
||||
mockOverrideFindOne.mockResolvedValue(null);
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(ClientsList.clients.findOne).toHaveBeenCalledWith({ _id: "client-1" });
|
||||
expect(mockClientPreferencesFindOne).toHaveBeenCalledWith({ userId: "client-user-1" });
|
||||
expect(result.channels).toEqual(["system"]);
|
||||
});
|
||||
|
||||
it("plan blocks WhatsApp when feature not available", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: [
|
||||
"whatsapp" as NotificationChannel,
|
||||
"email" as NotificationChannel,
|
||||
],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
});
|
||||
mockClientPreferencesFindOne.mockResolvedValue(null);
|
||||
mockOverrideFindOne.mockResolvedValue(null);
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockImplementation(
|
||||
async (params: { feature: string }) => {
|
||||
if (params.feature === PlanFeatures.WAP_NOTIFICATIONS) return false;
|
||||
return true;
|
||||
}
|
||||
);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.channels).not.toContain("whatsapp");
|
||||
expect(result.channels).toContain("email");
|
||||
});
|
||||
|
||||
it("plan blocks email when feature not available", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: [
|
||||
"whatsapp" as NotificationChannel,
|
||||
"email" as NotificationChannel,
|
||||
],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
});
|
||||
mockClientPreferencesFindOne.mockResolvedValue(null);
|
||||
mockOverrideFindOne.mockResolvedValue(null);
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockImplementation(
|
||||
async (params: { feature: string }) => {
|
||||
if (params.feature === PlanFeatures.MAIL_NOTIFICATIONS) return false;
|
||||
return true;
|
||||
}
|
||||
);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.channels).not.toContain("email");
|
||||
expect(result.channels).toContain("whatsapp");
|
||||
});
|
||||
|
||||
it("returns timezone from company policy", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: ["system" as NotificationChannel],
|
||||
timezone: "America/New_York",
|
||||
quietHours: { from: "22:00", to: "07:00" },
|
||||
});
|
||||
mockClientPreferencesFindOne.mockResolvedValue(null);
|
||||
mockOverrideFindOne.mockResolvedValue(null);
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.timezone).toBe("America/New_York");
|
||||
expect(result.quietHours).toEqual({ from: "22:00", to: "07:00" });
|
||||
});
|
||||
|
||||
it("returns default timezone when no company policy", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue(null);
|
||||
mockClientPreferencesFindOne.mockResolvedValue(null);
|
||||
mockOverrideFindOne.mockResolvedValue(null);
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.timezone).toBe("America/Argentina/Buenos_Aires");
|
||||
});
|
||||
|
||||
it("returns empty channels when all are muted via override", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue(null);
|
||||
mockClientPreferencesFindOne.mockResolvedValue(null);
|
||||
mockOverrideFindOne.mockResolvedValue({
|
||||
clientId: "client-1",
|
||||
companyId: "company-1",
|
||||
preferredChannels: [
|
||||
"whatsapp" as NotificationChannel,
|
||||
"email" as NotificationChannel,
|
||||
"system" as NotificationChannel,
|
||||
],
|
||||
mutedChannels: [
|
||||
"whatsapp" as NotificationChannel,
|
||||
"email" as NotificationChannel,
|
||||
"system" as NotificationChannel,
|
||||
],
|
||||
});
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolve("company-1", "client-1");
|
||||
|
||||
expect(result.channels).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -63,6 +63,11 @@ export type CreateSystemNotificationParams = {
|
||||
code?: string;
|
||||
};
|
||||
|
||||
export type CreateSystemNotificationBySystemParams = CreateSystemNotificationParams & {
|
||||
userId: string;
|
||||
systemToken: string;
|
||||
};
|
||||
|
||||
export type UpdateSystemNotificationParams = {
|
||||
id: string;
|
||||
readed: boolean;
|
||||
@@ -119,6 +124,7 @@ export interface ISystemNotificationsAdapter {
|
||||
export interface ISystemNotificationsManager {
|
||||
notifications: ISystemNotificationsAdapter;
|
||||
createNotification(data: CreateSystemNotificationParams): Promise<ISystemNotification>;
|
||||
createNotificationBySystem(data: CreateSystemNotificationBySystemParams): Promise<ISystemNotification>;
|
||||
updateNotification(data: UpdateSystemNotificationParams): Promise<void>;
|
||||
deleteNotification(data: DeleteSystemNotificationParams): Promise<void>;
|
||||
deleteConversationNotifications(data: DeleteSystemNotificationsByConversation): Promise<void>;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import CompaniesManager from "../Companies/Companies";
|
||||
import {
|
||||
CreateSystemNotificationParams,
|
||||
CreateSystemNotificationBySystemParams,
|
||||
DeleteNotificationsByDateParams,
|
||||
DeleteNotificationsByUserParams,
|
||||
DeleteSystemNotificationParams,
|
||||
@@ -108,6 +109,28 @@ class SystemNotificationsManager implements ISystemNotificationsManager {
|
||||
return newNotification;
|
||||
}
|
||||
|
||||
public async createNotificationBySystem(
|
||||
data: CreateSystemNotificationBySystemParams
|
||||
): Promise<ISystemNotification> {
|
||||
const expectedToken = process.env.SYSTEM_KEY || process.env.API_KEY;
|
||||
|
||||
if (!expectedToken || data.systemToken !== expectedToken) {
|
||||
throw new Error("Token de sistema inválido");
|
||||
}
|
||||
|
||||
const { systemToken, ...notificationData } = data;
|
||||
const notification = await this.createNotification(notificationData);
|
||||
|
||||
const countUnreadNotifications = await this.finUnreadNotifications({
|
||||
userId: data.userId,
|
||||
sessionUser: data.userId,
|
||||
});
|
||||
|
||||
io.to(`user:${data.userId}`).emit("new_system_notification", countUnreadNotifications);
|
||||
|
||||
return notification;
|
||||
}
|
||||
|
||||
public async updateNotification(data: UpdateSystemNotificationParams): Promise<void> {
|
||||
await validateSessionUser({
|
||||
sessionUser: data.sessionUser,
|
||||
|
||||
@@ -4,8 +4,10 @@ import { TextObjectFilterResult } from "../TextObjectFilter.model";
|
||||
export enum TemplateTypes {
|
||||
WAP_NEW_APPOINTMENT = "wap-new-appointment",
|
||||
WAP_REMINDER = "wap-reminder",
|
||||
WAP_CANCELLATION = "wap-cancellation",
|
||||
EMAIL_NEW_APPOINTMENT = "email-new-appointment",
|
||||
EMAIL_REMINDER = "email-reminder",
|
||||
EMAIL_CANCELLATION = "email-cancellation",
|
||||
}
|
||||
export interface ITemplate {
|
||||
id?: string;
|
||||
|
||||
@@ -215,12 +215,18 @@ export class TemplatesManager implements ITemplatesManager {
|
||||
case TemplateTypes.WAP_NEW_APPOINTMENT:
|
||||
defaultTemplate = `${process.env.WAP_ALTA}`;
|
||||
break;
|
||||
case TemplateTypes.WAP_CANCELLATION:
|
||||
defaultTemplate = `${process.env.WAP_CANCELLATION || process.env.WAP_CANCELACION || ""}`;
|
||||
break;
|
||||
case TemplateTypes.EMAIL_REMINDER:
|
||||
defaultTemplate = `${process.env.WAP_REMINDER}`;
|
||||
break;
|
||||
case TemplateTypes.EMAIL_NEW_APPOINTMENT:
|
||||
defaultTemplate = `${process.env.WAP_ALTA}`;
|
||||
break;
|
||||
case TemplateTypes.EMAIL_CANCELLATION:
|
||||
defaultTemplate = `${process.env.EMAIL_CANCELLATION || process.env.EMAIL_CANCELACION || process.env.WAP_CANCELLATION || process.env.WAP_CANCELACION || ""}`;
|
||||
break;
|
||||
}
|
||||
return defaultTemplate;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user