feat: implement comprehensive notification engine with policies, preferences, and automated dispatching services
This commit is contained in:
+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([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user