feat: implement comprehensive notification engine with policies, preferences, and automated dispatching services
This commit is contained in:
@@ -0,0 +1,20 @@
|
|||||||
|
module.exports = {
|
||||||
|
preset: "ts-jest",
|
||||||
|
testEnvironment: "node",
|
||||||
|
testMatch: ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"],
|
||||||
|
moduleNameMapper: {
|
||||||
|
"^(\\.{1,2}/.*)\\.js$": "$1",
|
||||||
|
},
|
||||||
|
transform: {
|
||||||
|
"^.+\\.tsx?$": [
|
||||||
|
"ts-jest",
|
||||||
|
{
|
||||||
|
useESM: false,
|
||||||
|
tsconfig: {
|
||||||
|
module: "CommonJS",
|
||||||
|
moduleResolution: "node",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
Generated
+4571
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,8 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "NODE_NO_WARNINGS=1 DOTENV_DISABLE_TELEMETRY=1 node --loader ts-node/esm src/index.ts",
|
"dev": "NODE_NO_WARNINGS=1 DOTENV_DISABLE_TELEMETRY=1 node --loader ts-node/esm src/index.ts",
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"start": "node dist/index.js"
|
"start": "node dist/index.js",
|
||||||
|
"test": "jest --config jest.config.cjs"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
@@ -14,8 +15,11 @@
|
|||||||
"description": "",
|
"description": "",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/axios": "^0.9.36",
|
"@types/axios": "^0.9.36",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
"@types/mongoose": "^5.11.96",
|
"@types/mongoose": "^5.11.96",
|
||||||
"@types/node": "^24.3.3",
|
"@types/node": "^24.3.3",
|
||||||
|
"jest": "^30.4.2",
|
||||||
|
"ts-jest": "^29.4.11",
|
||||||
"ts-node": "^10.9.2",
|
"ts-node": "^10.9.2",
|
||||||
"typescript": "^5.9.2"
|
"typescript": "^5.9.2"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,185 @@
|
|||||||
|
import { logDone, logError, logIntent } from "../../config/logger.js";
|
||||||
|
|
||||||
|
export interface DispatchResult {
|
||||||
|
success: boolean;
|
||||||
|
providerResponse?: string;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatResponseFailure(endpoint: string, data: unknown): string {
|
||||||
|
const serialized = JSON.stringify(data);
|
||||||
|
return `${endpoint} returned success=false${serialized && serialized !== "{}" ? ` data=${serialized}` : " without error details"}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getApiBaseUrl(): string {
|
||||||
|
const raw = process.env.API_URL || "";
|
||||||
|
|
||||||
|
if (!raw.trim()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return new URL(raw).origin;
|
||||||
|
} catch {
|
||||||
|
return raw.replace(/\/$/, "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildApiUrl(path: string): string {
|
||||||
|
return `${getApiBaseUrl()}${path}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDispatchError(error: unknown): string {
|
||||||
|
if (typeof error === "object" && error !== null && "isAxiosError" in error) {
|
||||||
|
const axiosError = error as {
|
||||||
|
message?: string;
|
||||||
|
response?: { status?: number; data?: unknown };
|
||||||
|
};
|
||||||
|
const details = [
|
||||||
|
axiosError.response?.status ? `status=${axiosError.response.status}` : undefined,
|
||||||
|
axiosError.response?.data !== undefined ? `data=${JSON.stringify(axiosError.response.data)}` : undefined,
|
||||||
|
axiosError.message ? `message=${axiosError.message}` : undefined,
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
return details.join(" ") || "Axios request failed without details";
|
||||||
|
}
|
||||||
|
|
||||||
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function dispatchWhatsApp(params: {
|
||||||
|
companyId: string;
|
||||||
|
appointmentId: string;
|
||||||
|
type: string;
|
||||||
|
systemToken: string;
|
||||||
|
phoneNumber: string;
|
||||||
|
message: string;
|
||||||
|
companyOwnerId: string;
|
||||||
|
}): Promise<DispatchResult> {
|
||||||
|
try {
|
||||||
|
if (!params.phoneNumber.trim() || !params.message.trim() || !params.companyOwnerId.trim()) {
|
||||||
|
return { success: false, error: "WhatsApp dispatch requires phoneNumber, message, and companyOwnerId" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send worker-rendered content directly so cancellation jobs survive appointment deletion.
|
||||||
|
const axios = (await import("axios")).default;
|
||||||
|
const response = await axios.post(
|
||||||
|
buildApiUrl("/notifications/send-wap"),
|
||||||
|
{
|
||||||
|
systemToken: params.systemToken,
|
||||||
|
phoneNumber: params.phoneNumber,
|
||||||
|
message: params.message,
|
||||||
|
companyId: params.companyId,
|
||||||
|
sessionUser: params.companyOwnerId,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
logDone(`WhatsApp dispatched for company ${params.companyId}`);
|
||||||
|
return { success: true, providerResponse: JSON.stringify(response.data) };
|
||||||
|
} catch (error) {
|
||||||
|
const msg = formatDispatchError(error);
|
||||||
|
logError(`WhatsApp dispatch failed for company ${params.companyId}:`, msg);
|
||||||
|
return { success: false, error: msg };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function dispatchEmail(params: {
|
||||||
|
appointmentId: string;
|
||||||
|
systemToken: string;
|
||||||
|
type: string;
|
||||||
|
email: string;
|
||||||
|
subject: string;
|
||||||
|
message: string;
|
||||||
|
}): Promise<DispatchResult> {
|
||||||
|
try {
|
||||||
|
if (!params.email.trim() || !params.subject.trim() || !params.message.trim()) {
|
||||||
|
return { success: false, error: "Email dispatch requires email, subject, and message" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send worker-rendered content directly so cancellation jobs survive appointment deletion.
|
||||||
|
const axios = (await import("axios")).default;
|
||||||
|
const response = await axios.post(
|
||||||
|
buildApiUrl("/notifications/send-email"),
|
||||||
|
{
|
||||||
|
systemToken: params.systemToken,
|
||||||
|
email: params.email,
|
||||||
|
subject: params.subject,
|
||||||
|
message: params.message,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const responseData = response.data as { success?: boolean };
|
||||||
|
if (responseData.success === false) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: formatResponseFailure("notifications/send-email", response.data),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
logDone(`Email dispatched to ${params.email}`);
|
||||||
|
return { success: true, providerResponse: JSON.stringify(response.data) };
|
||||||
|
} catch (error) {
|
||||||
|
const msg = formatDispatchError(error);
|
||||||
|
logError(`Email dispatch failed for ${params.email}:`, msg);
|
||||||
|
return { success: false, error: msg };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function dispatchSystem(params: {
|
||||||
|
systemToken: string;
|
||||||
|
userId: string;
|
||||||
|
subject: string;
|
||||||
|
message: string;
|
||||||
|
companyId?: string;
|
||||||
|
serviceId?: number;
|
||||||
|
conversationId?: string;
|
||||||
|
type?: string;
|
||||||
|
code?: string;
|
||||||
|
}): Promise<DispatchResult> {
|
||||||
|
try {
|
||||||
|
if (!params.userId.trim() || !params.subject.trim() || !params.message.trim()) {
|
||||||
|
return { success: false, error: "System dispatch requires userId, subject, and message" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delegate to the server API for system notification
|
||||||
|
const axios = (await import("axios")).default;
|
||||||
|
const response = await axios.post(
|
||||||
|
buildApiUrl("/systemnotifications/create"),
|
||||||
|
{
|
||||||
|
userId: params.userId,
|
||||||
|
subject: params.subject,
|
||||||
|
message: params.message,
|
||||||
|
companyId: params.companyId,
|
||||||
|
serviceId: params.serviceId,
|
||||||
|
conversationId: params.conversationId,
|
||||||
|
type: params.type,
|
||||||
|
code: params.code,
|
||||||
|
systemToken: params.systemToken,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const responseData = response.data as { success?: boolean };
|
||||||
|
if (responseData.success === false) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: formatResponseFailure("systemnotifications/create", response.data),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
logDone(`System notification dispatched to user ${params.userId}`);
|
||||||
|
return { success: true, providerResponse: JSON.stringify(response.data) };
|
||||||
|
} catch (error) {
|
||||||
|
const msg = formatDispatchError(error);
|
||||||
|
logError(`System notification dispatch failed for user ${params.userId}:`, msg);
|
||||||
|
return { success: false, error: msg };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
import { logDone, logError, logIntent } from "../../config/logger.js";
|
||||||
|
import { NotificationJobModel, INotificationJob } from "./NotificationJob.Adapter.Mongoose.js";
|
||||||
|
import { WhatsAppThrottleClass } from "./WhatsAppThrottle.js";
|
||||||
|
import { dispatchWhatsApp, dispatchEmail, dispatchSystem } from "./ChannelDispatchers.js";
|
||||||
|
import { resolveNotificationContent } from "./NotificationContentResolver.js";
|
||||||
|
|
||||||
|
const POLL_INTERVAL_MS = 5000;
|
||||||
|
const BASE_RETRY_DELAY_MS = 5000;
|
||||||
|
const MAX_JITTER_MS = 3000;
|
||||||
|
const THROTTLE_RETRY_DELAY_MS = 8000;
|
||||||
|
const SUPPORTED_APPOINTMENT_NOTIFICATION_TYPES = new Set(["creation", "reminder", "cancellation"]);
|
||||||
|
|
||||||
|
function resolveAppointmentNotificationType(type: unknown): string {
|
||||||
|
return typeof type === "string" && SUPPORTED_APPOINTMENT_NOTIFICATION_TYPES.has(type) ? type : "reminder";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPendingJobQuery(now: Date) {
|
||||||
|
return {
|
||||||
|
status: "pending",
|
||||||
|
scheduledAt: { $lte: now },
|
||||||
|
$or: [{ nextRetryAt: { $exists: false } }, { nextRetryAt: null }, { nextRetryAt: { $lte: now } }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function calculateNextRetryAt(attempt: number, now: Date): Date {
|
||||||
|
const delay = BASE_RETRY_DELAY_MS * Math.pow(2, attempt - 1);
|
||||||
|
const jitter = Math.floor(Math.random() * MAX_JITTER_MS);
|
||||||
|
return new Date(now.getTime() + delay + jitter);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getJobId(job: { id?: unknown; _id?: unknown; appointmentId?: unknown; channel?: unknown; get?: (path: string) => unknown }): string {
|
||||||
|
const value = job.id || job._id || job.get?.("_id");
|
||||||
|
if (value) return String(value);
|
||||||
|
|
||||||
|
const appointmentId = job.appointmentId || job.get?.("appointmentId");
|
||||||
|
const channel = job.channel || job.get?.("channel");
|
||||||
|
return appointmentId || channel ? `unknown appointment=${String(appointmentId || "n/a")} channel=${String(channel || "n/a")}` : "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
export class JobProcessor {
|
||||||
|
private jobModel: NotificationJobModel;
|
||||||
|
private throttle: WhatsAppThrottleClass;
|
||||||
|
private polling = false;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.jobModel = new NotificationJobModel();
|
||||||
|
this.throttle = new WhatsAppThrottleClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async startPolling(): Promise<void> {
|
||||||
|
if (this.polling) return;
|
||||||
|
this.polling = true;
|
||||||
|
logIntent("JobProcessor: starting poll loop");
|
||||||
|
this.poll();
|
||||||
|
}
|
||||||
|
|
||||||
|
public stopPolling(): void {
|
||||||
|
this.polling = false;
|
||||||
|
logIntent("JobProcessor: stopping poll loop");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async poll(): Promise<void> {
|
||||||
|
if (!this.polling) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const now = new Date();
|
||||||
|
const pendingJobs = await this.jobModel.notificationJobList
|
||||||
|
.find(buildPendingJobQuery(now))
|
||||||
|
.sort({ scheduledAt: 1 })
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
if (pendingJobs.length > 0) {
|
||||||
|
logIntent(`JobProcessor: found ${pendingJobs.length} pending jobs`);
|
||||||
|
await this.processJobs(pendingJobs);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logError("JobProcessor: poll error", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => this.poll(), POLL_INTERVAL_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async processJobs(jobs: any[]): Promise<void> {
|
||||||
|
// Group by companyId
|
||||||
|
const grouped = new Map<string, any[]>();
|
||||||
|
for (const job of jobs) {
|
||||||
|
const companyId = String(job.companyId);
|
||||||
|
if (!grouped.has(companyId)) {
|
||||||
|
grouped.set(companyId, []);
|
||||||
|
}
|
||||||
|
grouped.get(companyId)!.push(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [companyId, companyJobs] of grouped) {
|
||||||
|
for (const job of companyJobs) {
|
||||||
|
await this.processJob(job, companyId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async processJob(job: any, companyId: string): Promise<void> {
|
||||||
|
const now = new Date();
|
||||||
|
const jobId = getJobId(job);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Check throttle for WhatsApp
|
||||||
|
if (job.channel === "whatsapp") {
|
||||||
|
if (!this.throttle.canSend(companyId)) {
|
||||||
|
const nextRetryAt = new Date(now.getTime() + THROTTLE_RETRY_DELAY_MS);
|
||||||
|
await this.jobModel.notificationJobList.updateOne(
|
||||||
|
{ _id: job._id },
|
||||||
|
{ $set: { status: "pending", nextRetryAt } }
|
||||||
|
).exec();
|
||||||
|
logIntent(`JobProcessor: job ${jobId} throttled WhatsApp for company ${companyId}; retry at ${nextRetryAt.toISOString()}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextAttempt = job.attempts + 1;
|
||||||
|
await this.jobModel.notificationJobList.updateOne(
|
||||||
|
{ _id: job._id },
|
||||||
|
{ $set: { status: "processing", attempts: nextAttempt } }
|
||||||
|
).exec();
|
||||||
|
|
||||||
|
const dispatchJob = {
|
||||||
|
...job,
|
||||||
|
_id: job._id || job.get?.("_id"),
|
||||||
|
appointmentId: job.appointmentId || job.get?.("appointmentId"),
|
||||||
|
channel: job.channel || job.get?.("channel"),
|
||||||
|
attempts: nextAttempt,
|
||||||
|
};
|
||||||
|
const content = await resolveNotificationContent(job);
|
||||||
|
const appointmentNotificationType = resolveAppointmentNotificationType(job.type);
|
||||||
|
|
||||||
|
let result;
|
||||||
|
switch (job.channel) {
|
||||||
|
case "whatsapp":
|
||||||
|
result = await dispatchWhatsApp({
|
||||||
|
companyId,
|
||||||
|
appointmentId: String(job.appointmentId),
|
||||||
|
type: appointmentNotificationType,
|
||||||
|
systemToken: `${process.env.API_KEY}`,
|
||||||
|
phoneNumber: content.phoneNumber || "",
|
||||||
|
message: content.message,
|
||||||
|
companyOwnerId: content.companyOwnerId || "",
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "email":
|
||||||
|
result = await dispatchEmail({
|
||||||
|
appointmentId: String(job.appointmentId),
|
||||||
|
systemToken: `${process.env.API_KEY}`,
|
||||||
|
type: appointmentNotificationType,
|
||||||
|
email: content.email || "",
|
||||||
|
subject: content.subject,
|
||||||
|
message: content.message,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "system":
|
||||||
|
result = await dispatchSystem({
|
||||||
|
systemToken: `${process.env.API_KEY}`,
|
||||||
|
userId: content.userId || "",
|
||||||
|
subject: content.subject,
|
||||||
|
message: content.message,
|
||||||
|
companyId: String(job.companyId),
|
||||||
|
type: job.type,
|
||||||
|
code: String(job.appointmentId),
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
result = { success: false, error: `Unknown channel: ${job.channel}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
if (job.channel === "whatsapp") {
|
||||||
|
this.throttle.recordSent(companyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.jobModel.notificationJobList.updateOne(
|
||||||
|
{ _id: job._id },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: "sent",
|
||||||
|
sentAt: new Date(),
|
||||||
|
providerResponse: result.providerResponse,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
).exec();
|
||||||
|
logDone(`JobProcessor: job ${jobId} sent via ${job.channel}`);
|
||||||
|
} else {
|
||||||
|
await this.handleFailure(dispatchJob, result.error || "Unknown error");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const msg = error instanceof Error ? error.message : String(error);
|
||||||
|
await this.handleFailure({ ...job, attempts: job.attempts + 1 }, msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleFailure(job: any, errorMessage: string): Promise<void> {
|
||||||
|
const now = new Date();
|
||||||
|
const jobId = getJobId(job);
|
||||||
|
|
||||||
|
if (job.attempts >= job.maxAttempts) {
|
||||||
|
await this.jobModel.notificationJobList.updateOne(
|
||||||
|
{ _id: job._id },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: "failed",
|
||||||
|
lastError: errorMessage,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
).exec();
|
||||||
|
logError(`JobProcessor: job ${jobId} failed permanently after ${job.attempts} attempts`, errorMessage);
|
||||||
|
} else {
|
||||||
|
const nextRetryAt = calculateNextRetryAt(job.attempts, now);
|
||||||
|
await this.jobModel.notificationJobList.updateOne(
|
||||||
|
{ _id: job._id },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: "pending",
|
||||||
|
lastError: errorMessage,
|
||||||
|
nextRetryAt,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
).exec();
|
||||||
|
logError(`JobProcessor: job ${jobId} failed attempt ${job.attempts}/${job.maxAttempts}; retry at ${nextRetryAt.toISOString()}`, errorMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
import mongoose, { Model } from "mongoose";
|
||||||
|
import { INotificationJobDocument, NotificationJobType } from "./NotificationJob.Adapter.Mongoose.js";
|
||||||
|
|
||||||
|
const { Schema, model, models } = mongoose;
|
||||||
|
|
||||||
|
interface AppointmentDocument {
|
||||||
|
_id: unknown;
|
||||||
|
companyId: unknown;
|
||||||
|
serviceId?: unknown;
|
||||||
|
clientId?: unknown;
|
||||||
|
userId?: unknown;
|
||||||
|
start: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClientDocument {
|
||||||
|
_id: unknown;
|
||||||
|
userId?: unknown;
|
||||||
|
firstName?: string;
|
||||||
|
lastName?: string;
|
||||||
|
email?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserDocument {
|
||||||
|
_id: unknown;
|
||||||
|
email?: string;
|
||||||
|
firstName?: string;
|
||||||
|
lastName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ServiceDocument {
|
||||||
|
_id: unknown;
|
||||||
|
name?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CompanyDocument {
|
||||||
|
_id: unknown;
|
||||||
|
name?: string;
|
||||||
|
ownerId?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResolvedNotificationContent {
|
||||||
|
email?: string;
|
||||||
|
phoneNumber?: string;
|
||||||
|
userId?: string;
|
||||||
|
companyOwnerId?: string;
|
||||||
|
subject: string;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const appointmentSchema = new Schema(
|
||||||
|
{
|
||||||
|
companyId: { type: Schema.Types.ObjectId, required: true, ref: "Companie" },
|
||||||
|
serviceId: { type: Schema.Types.ObjectId, required: false, ref: "Service" },
|
||||||
|
clientId: { type: Schema.Types.ObjectId, required: false, ref: "Client" },
|
||||||
|
userId: { type: Schema.Types.ObjectId, required: false, ref: "User" },
|
||||||
|
start: { type: Date, required: true },
|
||||||
|
},
|
||||||
|
{ strict: false }
|
||||||
|
);
|
||||||
|
|
||||||
|
const clientSchema = new Schema(
|
||||||
|
{
|
||||||
|
userId: { type: Schema.Types.ObjectId, required: false, ref: "User" },
|
||||||
|
firstName: { type: String, required: false },
|
||||||
|
lastName: { type: String, required: false },
|
||||||
|
email: { type: String, required: false },
|
||||||
|
},
|
||||||
|
{ strict: false }
|
||||||
|
);
|
||||||
|
|
||||||
|
const userSchema = new Schema(
|
||||||
|
{
|
||||||
|
email: { type: String, required: false },
|
||||||
|
firstName: { type: String, required: false },
|
||||||
|
lastName: { type: String, required: false },
|
||||||
|
},
|
||||||
|
{ strict: false }
|
||||||
|
);
|
||||||
|
|
||||||
|
const serviceSchema = new Schema(
|
||||||
|
{
|
||||||
|
name: { type: String, required: false },
|
||||||
|
},
|
||||||
|
{ strict: false }
|
||||||
|
);
|
||||||
|
|
||||||
|
const companySchema = new Schema(
|
||||||
|
{
|
||||||
|
name: { type: String, required: false },
|
||||||
|
ownerId: { type: Schema.Types.ObjectId, required: false, ref: "User" },
|
||||||
|
},
|
||||||
|
{ strict: false }
|
||||||
|
);
|
||||||
|
|
||||||
|
const Appointment = (models.Appointment || model<AppointmentDocument>("Appointment", appointmentSchema)) as Model<AppointmentDocument>;
|
||||||
|
const Client = (models.Client || model<ClientDocument>("Client", clientSchema)) as Model<ClientDocument>;
|
||||||
|
const User = (models.User || model<UserDocument>("User", userSchema)) as Model<UserDocument>;
|
||||||
|
const Service = (models.Service || model<ServiceDocument>("Service", serviceSchema)) as Model<ServiceDocument>;
|
||||||
|
const Company = (models.Company || model<CompanyDocument>("Company", companySchema)) as Model<CompanyDocument>;
|
||||||
|
|
||||||
|
function compactName(...parts: Array<string | undefined>): string {
|
||||||
|
return parts.filter(Boolean).join(" ").trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateTime(value?: Date): string {
|
||||||
|
if (!value) return "fecha pendiente";
|
||||||
|
return new Intl.DateTimeFormat("es-AR", {
|
||||||
|
dateStyle: "short",
|
||||||
|
timeStyle: "short",
|
||||||
|
timeZone: "America/Argentina/Buenos_Aires",
|
||||||
|
}).format(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildNotificationText(params: {
|
||||||
|
type: NotificationJobType;
|
||||||
|
appointment?: AppointmentDocument | null;
|
||||||
|
client?: ClientDocument | null;
|
||||||
|
service?: ServiceDocument | null;
|
||||||
|
company?: CompanyDocument | null;
|
||||||
|
}): Pick<ResolvedNotificationContent, "subject" | "message"> {
|
||||||
|
const companyName = params.company?.name || "TurnosXpress";
|
||||||
|
const serviceName = params.service?.name || "tu turno";
|
||||||
|
const appointmentDate = formatDateTime(params.appointment?.start);
|
||||||
|
|
||||||
|
switch (params.type) {
|
||||||
|
case "creation":
|
||||||
|
return {
|
||||||
|
subject: `Alta de turno en ${companyName}`,
|
||||||
|
message: `Tu turno para ${serviceName} en ${companyName} fue confirmado para el ${appointmentDate}.`,
|
||||||
|
};
|
||||||
|
case "reminder":
|
||||||
|
return {
|
||||||
|
subject: `Recordatorio de turno en ${companyName}`,
|
||||||
|
message: `Te recordamos tu turno para ${serviceName} en ${companyName} el ${appointmentDate}.`,
|
||||||
|
};
|
||||||
|
case "update":
|
||||||
|
return {
|
||||||
|
subject: `Turno actualizado en ${companyName}`,
|
||||||
|
message: `Tu turno para ${serviceName} en ${companyName} fue actualizado. Nueva fecha: ${appointmentDate}.`,
|
||||||
|
};
|
||||||
|
case "cancellation":
|
||||||
|
return {
|
||||||
|
subject: `Turno cancelado en ${companyName}`,
|
||||||
|
message: `Tu turno para ${serviceName} en ${companyName} del ${appointmentDate} fue cancelado.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveNotificationContent(job: INotificationJobDocument): Promise<ResolvedNotificationContent> {
|
||||||
|
if ((job.type === "creation" || job.type === "reminder" || job.type === "cancellation") && job.payload) {
|
||||||
|
const { email, phoneNumber, userId, companyOwnerId } = job.payload;
|
||||||
|
const subject = job.channel === "email"
|
||||||
|
? job.payload.emailSubject
|
||||||
|
: job.channel === "system"
|
||||||
|
? job.payload.systemSubject
|
||||||
|
: job.payload.subject;
|
||||||
|
const message = job.channel === "whatsapp"
|
||||||
|
? job.payload.wapMessage
|
||||||
|
: job.channel === "email"
|
||||||
|
? job.payload.emailMessage
|
||||||
|
: job.payload.systemMessage;
|
||||||
|
const fallbackSubject = subject || job.payload.subject;
|
||||||
|
const fallbackMessage = message || job.payload.message;
|
||||||
|
if (fallbackSubject?.trim() && fallbackMessage?.trim()) {
|
||||||
|
return {
|
||||||
|
email: email?.trim(),
|
||||||
|
phoneNumber: phoneNumber?.trim(),
|
||||||
|
userId: userId ? String(userId) : undefined,
|
||||||
|
companyOwnerId: companyOwnerId ? String(companyOwnerId) : undefined,
|
||||||
|
subject: fallbackSubject.trim(),
|
||||||
|
message: fallbackMessage.trim(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const appointment = await Appointment.findOne({ _id: job.appointmentId }).lean().exec();
|
||||||
|
const client = await Client.findOne({ _id: job.clientId }).lean().exec();
|
||||||
|
const company = await Company.findOne({ _id: job.companyId }).lean().exec();
|
||||||
|
const service = appointment?.serviceId ? await Service.findOne({ _id: appointment.serviceId }).lean().exec() : null;
|
||||||
|
const userId = client?.userId || appointment?.userId || company?.ownerId;
|
||||||
|
const user = userId ? await User.findOne({ _id: userId }).lean().exec() : null;
|
||||||
|
const text = buildNotificationText({ type: job.type, appointment, client, service, company });
|
||||||
|
const email = client?.email || user?.email;
|
||||||
|
|
||||||
|
return {
|
||||||
|
email: email?.trim(),
|
||||||
|
userId: userId ? String(userId) : undefined,
|
||||||
|
subject: text.subject.trim(),
|
||||||
|
message: text.message.trim(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import mongoose, { Document, Model, Schema, model } from "mongoose";
|
||||||
|
|
||||||
|
export type NotificationChannel = "whatsapp" | "email" | "system";
|
||||||
|
export type NotificationJobStatus = "pending" | "processing" | "sent" | "failed" | "cancelled";
|
||||||
|
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 INotificationJobDocument extends Omit<INotificationJob, "_id">, Document {}
|
||||||
|
|
||||||
|
export class NotificationJobModel {
|
||||||
|
schema: Schema;
|
||||||
|
notificationJobList: Model<INotificationJobDocument>;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.schema = new Schema(
|
||||||
|
{
|
||||||
|
companyId: {
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
required: true,
|
||||||
|
ref: "Companie",
|
||||||
|
},
|
||||||
|
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: ["pending", "processing", "sent", "failed", "cancelled"],
|
||||||
|
default: "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({ status: 1, scheduledAt: 1, nextRetryAt: 1 });
|
||||||
|
this.schema.index({ companyId: 1, status: 1 });
|
||||||
|
this.schema.index({ appointmentId: 1 });
|
||||||
|
|
||||||
|
this.notificationJobList = model<INotificationJobDocument>(
|
||||||
|
"NotificationJob",
|
||||||
|
this.schema
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
const DEFAULT_MIN_INTERVAL_MS = 8000;
|
||||||
|
const JITTER_MAX_MS = 8000;
|
||||||
|
|
||||||
|
export class WhatsAppThrottleClass {
|
||||||
|
private lastSentAt: Map<string, number> = new Map();
|
||||||
|
private minIntervalMs: number;
|
||||||
|
|
||||||
|
constructor(minIntervalMs: number = DEFAULT_MIN_INTERVAL_MS) {
|
||||||
|
this.minIntervalMs = minIntervalMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
canSend(companyId: string): boolean {
|
||||||
|
const lastSent = this.lastSentAt.get(companyId);
|
||||||
|
if (!lastSent) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const elapsed = Date.now() - lastSent;
|
||||||
|
const jitter = Math.floor(Math.random() * JITTER_MAX_MS);
|
||||||
|
const requiredInterval = this.minIntervalMs + jitter;
|
||||||
|
|
||||||
|
return elapsed >= requiredInterval;
|
||||||
|
}
|
||||||
|
|
||||||
|
recordSent(companyId: string): void {
|
||||||
|
this.lastSentAt.set(companyId, Date.now());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import { dispatchEmail, dispatchWhatsApp } from "../ChannelDispatchers.js";
|
||||||
|
|
||||||
|
jest.mock("axios");
|
||||||
|
|
||||||
|
const mockedAxios = axios as jest.Mocked<typeof axios>;
|
||||||
|
|
||||||
|
describe("ChannelDispatchers", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
process.env.API_URL = "https://api.example.com/base";
|
||||||
|
process.env.API_KEY = "system-token";
|
||||||
|
mockedAxios.post.mockResolvedValue({
|
||||||
|
data: { success: true },
|
||||||
|
status: 200,
|
||||||
|
statusText: "OK",
|
||||||
|
headers: {},
|
||||||
|
config: { url: "" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends the job type in the email notification payload", async () => {
|
||||||
|
await dispatchEmail({
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
systemToken: "system-token",
|
||||||
|
type: "creation",
|
||||||
|
email: "client@example.com",
|
||||||
|
subject: "Appointment created",
|
||||||
|
message: "Creation message",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mockedAxios.post).toHaveBeenCalledWith(
|
||||||
|
"https://api.example.com/notifications/send-email",
|
||||||
|
{
|
||||||
|
systemToken: "system-token",
|
||||||
|
email: "client@example.com",
|
||||||
|
subject: "Appointment created",
|
||||||
|
message: "Creation message",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends the job type in the WhatsApp system notification payload", async () => {
|
||||||
|
await dispatchWhatsApp({
|
||||||
|
companyId: "company-1",
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
type: "creation",
|
||||||
|
systemToken: "system-token",
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
message: "Creation message",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mockedAxios.post).toHaveBeenCalledWith(
|
||||||
|
"https://api.example.com/notifications/send-wap",
|
||||||
|
{
|
||||||
|
systemToken: "system-token",
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
message: "Creation message",
|
||||||
|
companyId: "company-1",
|
||||||
|
sessionUser: "owner-1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
import { dispatchEmail, dispatchWhatsApp } from "../ChannelDispatchers.js";
|
||||||
|
import { buildPendingJobQuery, calculateNextRetryAt, JobProcessor } from "../JobProcessor.js";
|
||||||
|
import { resolveNotificationContent } from "../NotificationContentResolver.js";
|
||||||
|
|
||||||
|
jest.mock("../ChannelDispatchers.js", () => ({
|
||||||
|
dispatchWhatsApp: jest.fn(),
|
||||||
|
dispatchEmail: jest.fn(),
|
||||||
|
dispatchSystem: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock("../NotificationContentResolver.js", () => ({
|
||||||
|
resolveNotificationContent: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("JobProcessor", () => {
|
||||||
|
describe("calculateNextRetryAt", () => {
|
||||||
|
it("calculates exponential backoff for attempt 1", () => {
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
const result = calculateNextRetryAt(1, now);
|
||||||
|
|
||||||
|
const minExpected = now.getTime() + 5000;
|
||||||
|
const maxExpected = now.getTime() + 5000 + 3000;
|
||||||
|
|
||||||
|
expect(result.getTime()).toBeGreaterThanOrEqual(minExpected);
|
||||||
|
expect(result.getTime()).toBeLessThanOrEqual(maxExpected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calculates exponential backoff for attempt 2", () => {
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
const result = calculateNextRetryAt(2, now);
|
||||||
|
|
||||||
|
const minExpected = now.getTime() + 10000;
|
||||||
|
const maxExpected = now.getTime() + 10000 + 3000;
|
||||||
|
|
||||||
|
expect(result.getTime()).toBeGreaterThanOrEqual(minExpected);
|
||||||
|
expect(result.getTime()).toBeLessThanOrEqual(maxExpected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calculates exponential backoff for attempt 3", () => {
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
const result = calculateNextRetryAt(3, now);
|
||||||
|
|
||||||
|
const minExpected = now.getTime() + 20000;
|
||||||
|
const maxExpected = now.getTime() + 20000 + 3000;
|
||||||
|
|
||||||
|
expect(result.getTime()).toBeGreaterThanOrEqual(minExpected);
|
||||||
|
expect(result.getTime()).toBeLessThanOrEqual(maxExpected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns a Date in the future", () => {
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
const result = calculateNextRetryAt(1, now);
|
||||||
|
expect(result.getTime()).toBeGreaterThan(now.getTime());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses base delay for attempt 0 as fallback", () => {
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
const result = calculateNextRetryAt(1, now);
|
||||||
|
|
||||||
|
expect(result).toBeInstanceOf(Date);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("backoff math correctness", () => {
|
||||||
|
it("exponential growth doubles each attempt", () => {
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
|
||||||
|
const r1 = calculateNextRetryAt(1, now).getTime() - now.getTime();
|
||||||
|
const r2 = calculateNextRetryAt(2, now).getTime() - now.getTime();
|
||||||
|
const r3 = calculateNextRetryAt(3, now).getTime() - now.getTime();
|
||||||
|
|
||||||
|
// Without jitter: 5000, 10000, 20000
|
||||||
|
// With jitter up to 3000ms, the growth pattern should still hold
|
||||||
|
// Min possible: 5000, 10000, 20000
|
||||||
|
expect(r1).toBeGreaterThanOrEqual(5000);
|
||||||
|
expect(r2).toBeGreaterThanOrEqual(10000);
|
||||||
|
expect(r3).toBeGreaterThanOrEqual(20000);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildPendingJobQuery", () => {
|
||||||
|
it("only selects due jobs whose retry window is missing, null, or due", () => {
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
|
||||||
|
expect(buildPendingJobQuery(now)).toEqual({
|
||||||
|
status: "pending",
|
||||||
|
scheduledAt: { $lte: now },
|
||||||
|
$or: [
|
||||||
|
{ nextRetryAt: { $exists: false } },
|
||||||
|
{ nextRetryAt: null },
|
||||||
|
{ nextRetryAt: { $lte: now } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("WhatsApp dispatch", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
(resolveNotificationContent as jest.Mock).mockResolvedValue({
|
||||||
|
subject: "Appointment reminder",
|
||||||
|
message: "Reminder message",
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("passes the job appointmentId and type to the WhatsApp dispatcher", async () => {
|
||||||
|
const exec = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({ exec }));
|
||||||
|
const recordSent = jest.fn();
|
||||||
|
|
||||||
|
(dispatchWhatsApp as jest.Mock).mockResolvedValue({ success: true, providerResponse: "{}" });
|
||||||
|
|
||||||
|
await (JobProcessor.prototype as any).processJob.call(
|
||||||
|
{
|
||||||
|
jobModel: { notificationJobList: { updateOne } },
|
||||||
|
throttle: { canSend: jest.fn(() => true), recordSent },
|
||||||
|
handleFailure: jest.fn(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
_id: "job-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
channel: "whatsapp",
|
||||||
|
type: "creation",
|
||||||
|
attempts: 0,
|
||||||
|
maxAttempts: 3,
|
||||||
|
},
|
||||||
|
"company-1"
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(dispatchWhatsApp).toHaveBeenCalledWith({
|
||||||
|
companyId: "company-1",
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
type: "creation",
|
||||||
|
systemToken: `${process.env.API_KEY}`,
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
message: "Reminder message",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
});
|
||||||
|
expect(recordSent).toHaveBeenCalledWith("company-1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves cancellation WhatsApp job types", async () => {
|
||||||
|
const exec = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({ exec }));
|
||||||
|
|
||||||
|
(dispatchWhatsApp as jest.Mock).mockResolvedValue({ success: true, providerResponse: "{}" });
|
||||||
|
|
||||||
|
await (JobProcessor.prototype as any).processJob.call(
|
||||||
|
{
|
||||||
|
jobModel: { notificationJobList: { updateOne } },
|
||||||
|
throttle: { canSend: jest.fn(() => true), recordSent: jest.fn() },
|
||||||
|
handleFailure: jest.fn(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
_id: "job-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
channel: "whatsapp",
|
||||||
|
type: "cancellation",
|
||||||
|
attempts: 0,
|
||||||
|
maxAttempts: 3,
|
||||||
|
},
|
||||||
|
"company-1"
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(dispatchWhatsApp).toHaveBeenCalledWith({
|
||||||
|
companyId: "company-1",
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
type: "cancellation",
|
||||||
|
systemToken: `${process.env.API_KEY}`,
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
message: "Reminder message",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not record a WhatsApp send when dispatch fails", async () => {
|
||||||
|
const exec = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({ exec }));
|
||||||
|
const recordSent = jest.fn();
|
||||||
|
|
||||||
|
(dispatchWhatsApp as jest.Mock).mockResolvedValue({ success: false, error: "provider failed" });
|
||||||
|
|
||||||
|
await (JobProcessor.prototype as any).processJob.call(
|
||||||
|
{
|
||||||
|
jobModel: { notificationJobList: { updateOne } },
|
||||||
|
throttle: { canSend: jest.fn(() => true), recordSent },
|
||||||
|
handleFailure: jest.fn(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
_id: "job-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
channel: "whatsapp",
|
||||||
|
type: "reminder",
|
||||||
|
attempts: 0,
|
||||||
|
maxAttempts: 3,
|
||||||
|
},
|
||||||
|
"company-1"
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(recordSent).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Email dispatch", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
(resolveNotificationContent as jest.Mock).mockResolvedValue({
|
||||||
|
email: "client@example.com",
|
||||||
|
subject: "Appointment created",
|
||||||
|
message: "Creation message",
|
||||||
|
});
|
||||||
|
(dispatchEmail as jest.Mock).mockResolvedValue({ success: true, providerResponse: "{}" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("passes creation job type to the email dispatcher", async () => {
|
||||||
|
const exec = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({ exec }));
|
||||||
|
|
||||||
|
await (JobProcessor.prototype as any).processJob.call(
|
||||||
|
{
|
||||||
|
jobModel: { notificationJobList: { updateOne } },
|
||||||
|
throttle: { canSend: jest.fn(() => true), recordSent: jest.fn() },
|
||||||
|
handleFailure: jest.fn(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
_id: "job-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
channel: "email",
|
||||||
|
type: "creation",
|
||||||
|
attempts: 0,
|
||||||
|
maxAttempts: 3,
|
||||||
|
},
|
||||||
|
"company-1"
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(dispatchEmail).toHaveBeenCalledWith({
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
systemToken: `${process.env.API_KEY}`,
|
||||||
|
type: "creation",
|
||||||
|
email: "client@example.com",
|
||||||
|
subject: "Appointment created",
|
||||||
|
message: "Creation message",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
import mongoose from "mongoose";
|
||||||
|
import { buildNotificationText, resolveNotificationContent } from "../NotificationContentResolver.js";
|
||||||
|
|
||||||
|
describe("NotificationContentResolver", () => {
|
||||||
|
it("builds appointment creation subject and message as Alta de turno", () => {
|
||||||
|
const result = buildNotificationText({
|
||||||
|
type: "creation",
|
||||||
|
appointment: {
|
||||||
|
_id: "appointment-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
start: new Date("2026-07-22T15:30:00.000Z"),
|
||||||
|
},
|
||||||
|
service: { _id: "service-1", name: "Corte" },
|
||||||
|
company: { _id: "company-1", name: "Barber Shop" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.subject).toContain("Alta de turno");
|
||||||
|
expect(result.subject).toContain("Barber Shop");
|
||||||
|
expect(result.message).toContain("Corte");
|
||||||
|
expect(result.message).toContain("confirmado");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("builds meaningful appointment reminder subject and message", () => {
|
||||||
|
const result = buildNotificationText({
|
||||||
|
type: "reminder",
|
||||||
|
appointment: {
|
||||||
|
_id: "appointment-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
start: new Date("2026-07-22T15:30:00.000Z"),
|
||||||
|
},
|
||||||
|
service: { _id: "service-1", name: "Corte" },
|
||||||
|
company: { _id: "company-1", name: "Barber Shop" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.subject).toContain("Recordatorio");
|
||||||
|
expect(result.subject).toContain("Barber Shop");
|
||||||
|
expect(result.message).toContain("Corte");
|
||||||
|
expect(result.message).toContain("Barber Shop");
|
||||||
|
expect(result.subject.trim()).not.toBe("");
|
||||||
|
expect(result.message.trim()).not.toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses cancellation snapshot payload without requiring appointment lookup", async () => {
|
||||||
|
const result = await resolveNotificationContent({
|
||||||
|
appointmentId: "deleted-appointment-1",
|
||||||
|
clientId: "client-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
channel: "email",
|
||||||
|
type: "cancellation",
|
||||||
|
payload: {
|
||||||
|
email: "client@example.com",
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
userId: "user-1",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
subject: "Turno cancelado en Barber Shop",
|
||||||
|
message: "Tu turno para Corte fue cancelado.",
|
||||||
|
emailSubject: "Email cancellation subject",
|
||||||
|
emailMessage: "Email cancellation body.",
|
||||||
|
wapMessage: "WAP cancellation body.",
|
||||||
|
systemSubject: "System cancellation subject",
|
||||||
|
systemMessage: "System cancellation body.",
|
||||||
|
},
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
email: "client@example.com",
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
userId: "user-1",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
subject: "Email cancellation subject",
|
||||||
|
message: "Email cancellation body.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses creation snapshot payload content for email jobs", async () => {
|
||||||
|
const result = await resolveNotificationContent({
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
clientId: "client-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
channel: "email",
|
||||||
|
type: "creation",
|
||||||
|
payload: {
|
||||||
|
email: "client@example.com",
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
userId: "user-1",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
subject: "Turno reservado en Barber Shop",
|
||||||
|
message: "Generic creation body.",
|
||||||
|
emailSubject: "Email Alta subject",
|
||||||
|
emailMessage: "Email Alta body.",
|
||||||
|
wapMessage: "WAP Alta body.",
|
||||||
|
systemSubject: "System Alta subject",
|
||||||
|
systemMessage: "System Alta body.",
|
||||||
|
},
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
email: "client@example.com",
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
userId: "user-1",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
subject: "Email Alta subject",
|
||||||
|
message: "Email Alta body.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses creation snapshot payload content for WhatsApp jobs", async () => {
|
||||||
|
const result = await resolveNotificationContent({
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
clientId: "client-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
channel: "whatsapp",
|
||||||
|
type: "creation",
|
||||||
|
payload: {
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
subject: "Generic subject",
|
||||||
|
message: "Generic message.",
|
||||||
|
emailMessage: "Email Alta body.",
|
||||||
|
wapMessage: "WAP Alta body.",
|
||||||
|
},
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
expect(result.message).toBe("WAP Alta body.");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses reminder payload content without requiring appointment lookup", async () => {
|
||||||
|
const appointmentLookup = jest.spyOn(mongoose.models.Appointment, "findOne");
|
||||||
|
|
||||||
|
const result = await resolveNotificationContent({
|
||||||
|
appointmentId: "appointment-1",
|
||||||
|
clientId: "client-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
channel: "whatsapp",
|
||||||
|
type: "reminder",
|
||||||
|
payload: {
|
||||||
|
email: "client@example.com",
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
userId: "user-1",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
subject: "Generic reminder subject",
|
||||||
|
message: "Generic reminder body.",
|
||||||
|
emailSubject: "Email reminder subject",
|
||||||
|
emailMessage: "Email reminder body.",
|
||||||
|
wapMessage: "WAP reminder body.",
|
||||||
|
systemSubject: "System reminder subject",
|
||||||
|
systemMessage: "System reminder body.",
|
||||||
|
},
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
expect(appointmentLookup).not.toHaveBeenCalled();
|
||||||
|
expect(result).toEqual({
|
||||||
|
email: "client@example.com",
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
userId: "user-1",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
subject: "Generic reminder subject",
|
||||||
|
message: "WAP reminder body.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses WhatsApp cancellation payload content for WhatsApp jobs", async () => {
|
||||||
|
const result = await resolveNotificationContent({
|
||||||
|
appointmentId: "deleted-appointment-1",
|
||||||
|
clientId: "client-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
channel: "whatsapp",
|
||||||
|
type: "cancellation",
|
||||||
|
payload: {
|
||||||
|
phoneNumber: "5491112345678",
|
||||||
|
companyOwnerId: "owner-1",
|
||||||
|
subject: "Generic subject",
|
||||||
|
message: "Generic message.",
|
||||||
|
emailMessage: "Email cancellation body.",
|
||||||
|
wapMessage: "WAP cancellation body.",
|
||||||
|
},
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
expect(result.message).toBe("WAP cancellation body.");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses system cancellation payload content for system jobs", async () => {
|
||||||
|
const result = await resolveNotificationContent({
|
||||||
|
appointmentId: "deleted-appointment-1",
|
||||||
|
clientId: "client-1",
|
||||||
|
companyId: "company-1",
|
||||||
|
channel: "system",
|
||||||
|
type: "cancellation",
|
||||||
|
payload: {
|
||||||
|
userId: "user-1",
|
||||||
|
subject: "Generic subject",
|
||||||
|
message: "Generic message.",
|
||||||
|
systemSubject: "System cancellation subject",
|
||||||
|
systemMessage: "System cancellation body.",
|
||||||
|
},
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
expect(result.subject).toBe("System cancellation subject");
|
||||||
|
expect(result.message).toBe("System cancellation body.");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
describe("WhatsAppThrottle", () => {
|
||||||
|
let WhatsAppThrottle: typeof import("../WhatsAppThrottle.js").WhatsAppThrottleClass;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const mod = await import("../WhatsAppThrottle.js");
|
||||||
|
WhatsAppThrottle = mod.WhatsAppThrottleClass;
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows first send for a company immediately", () => {
|
||||||
|
const throttle = new WhatsAppThrottle(8000);
|
||||||
|
expect(throttle.canSend("company-1")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("blocks send within minimum interval", () => {
|
||||||
|
const throttle = new WhatsAppThrottle(8000);
|
||||||
|
throttle.recordSent("company-1");
|
||||||
|
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.setSystemTime(new Date("2026-07-21T12:00:03.000Z")); // 3s later
|
||||||
|
|
||||||
|
expect(throttle.canSend("company-1")).toBe(false);
|
||||||
|
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows send after maximum possible interval (base + jitter)", () => {
|
||||||
|
const throttle = new WhatsAppThrottle(8000);
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.setSystemTime(now);
|
||||||
|
|
||||||
|
throttle.recordSent("company-1");
|
||||||
|
|
||||||
|
// After 16s (max = 8s base + 8s jitter), should always be allowed
|
||||||
|
jest.setSystemTime(new Date("2026-07-21T12:00:16.000Z"));
|
||||||
|
|
||||||
|
expect(throttle.canSend("company-1")).toBe(true);
|
||||||
|
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tracks companies independently", () => {
|
||||||
|
const throttle = new WhatsAppThrottle(8000);
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.setSystemTime(now);
|
||||||
|
|
||||||
|
throttle.recordSent("company-1");
|
||||||
|
|
||||||
|
// company-2 should still be allowed
|
||||||
|
expect(throttle.canSend("company-2")).toBe(true);
|
||||||
|
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies jitter to minimum interval", () => {
|
||||||
|
const throttle = new WhatsAppThrottle(8000);
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.setSystemTime(now);
|
||||||
|
|
||||||
|
throttle.recordSent("company-1");
|
||||||
|
|
||||||
|
// At exactly 8s (base interval), it should still be blocked due to jitter
|
||||||
|
jest.setSystemTime(new Date("2026-07-21T12:00:08.000Z"));
|
||||||
|
expect(throttle.canSend("company-1")).toBe(false);
|
||||||
|
|
||||||
|
// At 16s (max interval = base + jitter), it should be allowed
|
||||||
|
jest.setSystemTime(new Date("2026-07-21T12:00:16.000Z"));
|
||||||
|
expect(throttle.canSend("company-1")).toBe(true);
|
||||||
|
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses default interval of 8000ms when not specified", () => {
|
||||||
|
const throttle = new WhatsAppThrottle();
|
||||||
|
const now = new Date("2026-07-21T12:00:00.000Z");
|
||||||
|
jest.useFakeTimers();
|
||||||
|
jest.setSystemTime(now);
|
||||||
|
|
||||||
|
throttle.recordSent("company-1");
|
||||||
|
|
||||||
|
// 7s should be blocked
|
||||||
|
jest.setSystemTime(new Date("2026-07-21T12:00:07.000Z"));
|
||||||
|
expect(throttle.canSend("company-1")).toBe(false);
|
||||||
|
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -42,7 +42,8 @@ export const logDone = (message: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const logError = (message: string, error: any) => {
|
export const logError = (message: string, error: any) => {
|
||||||
logger.info(`❌ ${bold}${message}${reset}\n\r`, error);
|
const details = error instanceof Error ? error.stack || error.message : String(error || "Unknown error");
|
||||||
|
logger.error(`❌ ${bold}${message}${reset}\n${details}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const logWarn = (message: string) => {
|
export const logWarn = (message: string) => {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import dotenv from "dotenv";
|
import dotenv from "dotenv";
|
||||||
import logger, { logDone, logError, logIntent } from "./config/logger.js";
|
import logger, { logDone, logError, logIntent } from "./config/logger.js";
|
||||||
import mongoose from "mongoose";
|
import mongoose from "mongoose";
|
||||||
import { Notifications } from "./Models/Notifications/Notifications.js";
|
import { JobProcessor } from "./Models/Jobs/JobProcessor.js";
|
||||||
|
|
||||||
logIntent("Iniciando Notification Sender.");
|
logIntent("Iniciando Notification Sender.");
|
||||||
|
|
||||||
@@ -28,10 +28,10 @@ mongoose
|
|||||||
.then(() => {
|
.then(() => {
|
||||||
const start = async () => {
|
const start = async () => {
|
||||||
logDone("Conexión a MongoDB establecida correctamente.");
|
logDone("Conexión a MongoDB establecida correctamente.");
|
||||||
logger.info("🚀 Notification Sender running");
|
logger.info("🚀 Notification Sender running (job-based polling)");
|
||||||
|
|
||||||
const worker = new Notifications();
|
const processor = new JobProcessor();
|
||||||
await worker.start();
|
await processor.startPolling();
|
||||||
};
|
};
|
||||||
|
|
||||||
start();
|
start();
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# Tasks: Notification Preferences UI
|
||||||
|
|
||||||
|
## Review Workload Forecast
|
||||||
|
|
||||||
|
| Field | Value |
|
||||||
|
|-------|-------|
|
||||||
|
| Estimated changed lines | 1000-1200 |
|
||||||
|
| 400-line budget risk | High |
|
||||||
|
| Chained PRs recommended | Yes |
|
||||||
|
| Suggested split | PR 1 → PR 2 → PR 3 → PR 4 |
|
||||||
|
| Delivery strategy | ask-on-risk |
|
||||||
|
| Chain strategy | pending |
|
||||||
|
|
||||||
|
Decision needed before apply: Yes
|
||||||
|
Chained PRs recommended: Yes
|
||||||
|
Chain strategy: pending
|
||||||
|
400-line budget risk: High
|
||||||
|
|
||||||
|
### Suggested Work Units
|
||||||
|
|
||||||
|
| Unit | Goal | Likely PR | Focused test command | Runtime harness | Rollback boundary |
|
||||||
|
|------|------|-----------|----------------------|-----------------|-------------------|
|
||||||
|
| 1 | Foundation: models, API service, store, validation | PR 1 | `npm run typecheck` | N/A — types only | Remove service, store, model files |
|
||||||
|
| 2 | Org policy page + navigation | PR 2 | Navigate to `/admin/org/profile/[id]/notifications` | Org profile page loads, toggles render | Remove org notifications page and layout |
|
||||||
|
| 3 | Client override page + navigation | PR 3 | Navigate to `/admin/org/[oid]/client/[clientId]/notifications` | Client profile page loads, toggles render | Remove client notifications page and layout |
|
||||||
|
| 4 | Client-facing page + tests | PR 4 | Navigate to `/user/profile/notifications` | Landing profile page loads, toggles render | Remove landing notifications page and tests |
|
||||||
|
|
||||||
|
## Phase 1: Foundation
|
||||||
|
|
||||||
|
- [x] 1.1 Create `txclient/src/Models/NotificationPreferences.model.ts` — TypeScript interfaces: NotificationChannel, QuietHours, ReminderRule, CompanyNotificationPolicy, ClientNotificationPreferences, ClientCompanyNotificationOverride, upsert params
|
||||||
|
- [x] 1.2 Create `txclient/src/services/Notifications.Service.ts` — 6 API functions using `ApiRequest.post<T>()`: getCompanyPolicy, upsertCompanyPolicy, getClientPreferences, upsertClientPreferences, getClientCompanyOverride, upsertClientCompanyOverride
|
||||||
|
- [x] 1.3 Create `txclient/src/Store/NotificationPreferences.Store.ts` — Zustand store with mode, form data, dirty flag; actions: setMode, updateFormData, resetForm
|
||||||
|
- [x] 1.4 Create `txclient/src/Models/NotificationPreferences.validation.ts` — Yup schemas: companyPolicySchema (channels min 1, timezone required, quietHours optional HH:mm, reminderRules max 5), clientPrefsSchema (preferredChannels, mutedChannels)
|
||||||
|
|
||||||
|
## Phase 2: Org Policy Page
|
||||||
|
|
||||||
|
- [x] 2.1 Create `txclient/src/app/admin/(organization-profile)/org/profile/[id]/notifications/layout.tsx` — Saveable wrapper loading company policy on mount, dispatching NEED_SAVE/SAVE events
|
||||||
|
- [x] 2.2 Create `txclient/src/app/admin/(organization-profile)/org/profile/[id]/notifications/page.tsx` — Org policy form: channel toggles (3x Switch), quiet hours (2x input time), timezone Textbox, reminder rules dynamic list (max 5) with add/remove buttons
|
||||||
|
- [x] 2.3 Modify `txclient/src/app/components/OrganizationHeader/OrganizationHeader.tsx` — Add "Notificaciones" menu item linking to `/admin/org/profile/[id]/notifications` with NotificationsIcon
|
||||||
|
|
||||||
|
## Phase 3: Client Override Page
|
||||||
|
|
||||||
|
- [x] 3.1 Create `txclient/src/app/admin/(client-profile)/org/[oid]/client/[clientId]/notifications/layout.tsx` — Saveable wrapper loading client company override on mount
|
||||||
|
- [x] 3.2 Create `txclient/src/app/admin/(client-profile)/org/[oid]/client/[clientId]/notifications/page.tsx` — Client override form: preferred channels (3x Switch), muted channels (3x Switch)
|
||||||
|
- [x] 3.3 Modify `txclient/src/app/admin/(client-profile)/org/[oid]/client/[clientId]/layout.tsx` — Add "Notificaciones" navigation link to client profile menu
|
||||||
|
|
||||||
|
## Phase 4: Client-Facing Page
|
||||||
|
|
||||||
|
- [x] 4.1 Create `txclient/src/app/user/profile/notifications-preferences/page.tsx` — Client preferences form: preferred channels (3x Switch), muted channels (3x Switch); wrapped in Secure component for auth gate
|
||||||
|
- [x] 4.2 Modify `txclient/src/app/user/profile/page.tsx` — Add "Preferencias de notificación" navigation link to user profile menu
|
||||||
|
|
||||||
|
## Phase 5: Testing
|
||||||
|
|
||||||
|
- [ ] 5.1 Create `txclient/src/Models/__tests__/NotificationPreferences.validation.test.ts` — Test Yup schemas: valid inputs pass, invalid channels rejected, timezone required, quietHours format validated, reminderRules max 5 enforced (BLOCKED: no test runner in txclient)
|
||||||
|
- [ ] 5.2 Create `txclient/src/services/__tests__/Notifications.Service.test.ts` — Mock ApiRequest.post, verify 6 functions call correct endpoints with correct params (BLOCKED: no test runner in txclient)
|
||||||
|
- [ ] 5.3 Create `txclient/src/Store/__tests__/NotificationPreferences.Store.test.ts` — Test store actions: setMode, updateFormData, resetForm, dirty flag transitions (BLOCKED: no test runner in txclient)
|
||||||
|
|
||||||
|
## Phase 6: Cleanup (if needed)
|
||||||
|
|
||||||
|
- [x] 6.1 Remove any temporary console.log statements added during development
|
||||||
|
- [x] 6.2 Verify all TypeScript types compile without errors
|
||||||
|
- [x] 6.3 Confirm navigation links work in all three contexts (org, client, landing)
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# Proposal: Notification System Redesign
|
||||||
|
|
||||||
|
## Intent
|
||||||
|
|
||||||
|
The current notification system has three critical limitations: (1) notifications are sent synchronously during appointment lifecycle operations, blocking the API response; (2) the notification-sender worker only handles today's appointments with a global delay (no per-company throttling for WhatsApp rate limits); and (3) there are no per-company or per-client notification preferences — notifications are either on or off for the entire company. This redesign decouples notification delivery from business operations into a job-based, multi-channel, policy-driven system.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
### In Scope
|
||||||
|
- New `NotificationJob` model: per-notification job records with status, channel, payload, retry state
|
||||||
|
- New `CompanyNotificationPolicy` model: org-level defaults for channels, scheduling windows, WhatsApp throttle config
|
||||||
|
- New `ClientNotificationPreferences` model: per-client opt-in/out per channel
|
||||||
|
- New `ClientCompanyNotificationOverride` model: per-client per-org overrides
|
||||||
|
- Policy resolution engine: Plan limits → Org override → Client prefs → Org default → System default
|
||||||
|
- Redesigned notification-sender worker: MongoDB polling, per-company WhatsApp throttle (8–16s), multi-channel dispatch
|
||||||
|
- Server integration: replace inline notification calls in `Appointments` with job creation
|
||||||
|
- Multi-channel support: WhatsApp (Baileys), Email (DonWeb), System (in-app + Socket.IO)
|
||||||
|
|
||||||
|
### Out of Scope
|
||||||
|
- SMS channel (plan feature exists but not implemented today)
|
||||||
|
- Notification templates / content builder
|
||||||
|
- Client-facing notification preferences UI
|
||||||
|
- Notification analytics / delivery reports
|
||||||
|
- Push notifications (mobile)
|
||||||
|
- Batch notification operations (e.g., "notify all clients about holiday")
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
- `notification-jobs`: Job creation, status tracking, retry logic, and lifecycle management for notification delivery
|
||||||
|
- `notification-policies`: Company and client notification preferences, policy resolution hierarchy, channel configuration
|
||||||
|
- `notification-worker`: Multi-channel job processor with per-company throttling and MongoDB polling
|
||||||
|
- `notification-integration`: Server-side hooks that create notification jobs from appointment lifecycle events
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
None — no existing specs in `openspec/specs/`.
|
||||||
|
|
||||||
|
## Approach
|
||||||
|
|
||||||
|
**Server (job creation):** Replace inline `NotificationsManager.send*()` calls in `Appointments.ts` with `NotificationJobService.createJob()`. The service resolves the effective policy, checks plan limits, and persists a `NotificationJob` document. This makes API calls non-blocking.
|
||||||
|
|
||||||
|
**notification-sender (worker):** Poll MongoDB for `status: "pending"` jobs. Process per-company with configurable WhatsApp throttle (default 8–16s between messages for same company). Email and System channels have no throttle. Failed jobs retry up to 3x with exponential backoff.
|
||||||
|
|
||||||
|
**Policy resolution:** Resolve in order: Plan feature flags → `ClientCompanyNotificationOverride` (per-client per-org) → `ClientNotificationPreferences` (client global) → `CompanyNotificationPolicy` (org default) → System defaults (all channels on).
|
||||||
|
|
||||||
|
**Migration:** No data migration needed — no pending notifications exist. New models are additive.
|
||||||
|
|
||||||
|
## Affected Areas
|
||||||
|
|
||||||
|
| Area | Impact | Description |
|
||||||
|
|------|--------|-------------|
|
||||||
|
| `notification-sender/src/` | New | Complete rewrite: job polling, multi-channel dispatch, throttle |
|
||||||
|
| `server/src/Models/Notifications/` | Modified | Add job creation service; existing adapters remain for direct sends |
|
||||||
|
| `server/src/Models/Appointments/Appointments.ts` | Modified | Replace inline sends with job creation calls |
|
||||||
|
| `server/src/Models/Plans/Plans.interface.ts` | Unchanged | Plan features already define channel support |
|
||||||
|
| New: `server/src/Models/NotificationJobs/` | New | NotificationJob model + adapter |
|
||||||
|
| New: `server/src/Models/NotificationPolicies/` | New | Company/Client policy models + resolution engine |
|
||||||
|
| New: `notification-sender/src/Models/Jobs/` | New | Job polling model for worker |
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
| Risk | Likelihood | Mitigation |
|
||||||
|
|------|------------|------------|
|
||||||
|
| WhatsApp rate limit hit during high-volume periods | High | Per-company throttle (8–16s), exponential backoff on failures |
|
||||||
|
| Job queue grows faster than worker processes | Medium | Monitor queue depth; add alerting on backlog threshold |
|
||||||
|
| Policy resolution adds latency to appointment creation | Low | Resolution is a simple DB query cascade; cache per-request |
|
||||||
|
| Breaking existing notification behavior during transition | Medium | Feature flag: keep inline sends as fallback during rollout |
|
||||||
|
|
||||||
|
## Rollback Plan
|
||||||
|
|
||||||
|
1. Disable job creation in server via feature flag (reverts to inline sends)
|
||||||
|
2. Stop notification-sender worker
|
||||||
|
3. Existing inline notification paths remain unchanged — no code removal needed until stable
|
||||||
|
4. Job collection can be truncated without data loss (jobs are ephemeral)
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- MongoDB (shared across all modules) — already available
|
||||||
|
- Baileys (txbot) — existing WhatsApp integration, no changes needed
|
||||||
|
- DonWeb email API — existing integration, no changes needed
|
||||||
|
- Socket.IO — existing in server, no changes needed
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- [ ] Appointment creation/update/delete returns within normal latency (< 200ms)
|
||||||
|
- [ ] WhatsApp messages for same company spaced ≥ 8s apart
|
||||||
|
- [ ] Failed notifications retry up to 3x with exponential backoff
|
||||||
|
- [ ] Policy resolution correctly cascades through hierarchy
|
||||||
|
- [ ] Zero missed notifications during 24h soak test
|
||||||
|
- [ ] notification-sender processes backlog within 5 minutes under normal load
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# SDD Configuration — turnosxpress
|
||||||
|
# Generated: 2026-07-21
|
||||||
|
|
||||||
|
context: |
|
||||||
|
Multi-module monorepo: Express+TypeScript server (tsoa, Mongoose, JWT),
|
||||||
|
Next.js 15 client (MUI, Zustand), WhatsApp bot (Baileys),
|
||||||
|
admin/sysadmin microservices, Android companion app.
|
||||||
|
MongoDB (Mongoose 8.x), OCI cloud storage, multi-region Docker deployment.
|
||||||
|
No workspace manager — independent modules.
|
||||||
|
|
||||||
|
strict_tdd: true
|
||||||
|
|
||||||
|
testing:
|
||||||
|
runner: jest
|
||||||
|
framework: Jest 30.x + ts-jest 29.x
|
||||||
|
command: "cd server && npx jest"
|
||||||
|
coverage: false
|
||||||
|
layers:
|
||||||
|
unit: true
|
||||||
|
integration: false
|
||||||
|
e2e: false
|
||||||
|
quality:
|
||||||
|
linter: "next lint (txclient), oxlint (sysadmin-cli)"
|
||||||
|
type_checker: tsc
|
||||||
|
formatter: none
|
||||||
|
|
||||||
|
phases:
|
||||||
|
proposal: mandatory
|
||||||
|
spec: mandatory
|
||||||
|
design: mandatory
|
||||||
|
tasks: mandatory
|
||||||
|
apply: mandatory
|
||||||
|
verify: mandatory
|
||||||
|
archive: mandatory
|
||||||
@@ -54,6 +54,7 @@ DONWEB_MAIL_API_KEY = eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE3NDYxMTc3N
|
|||||||
WAP_TIME_LIMIT = 5000
|
WAP_TIME_LIMIT = 5000
|
||||||
WAP_REMINDER = 🔔Hola <---CLIENTE---> <---BR---> 📌Te recuerdo que el <---FECHA---> te esperamos a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
WAP_REMINDER = 🔔Hola <---CLIENTE---> <---BR---> 📌Te recuerdo que el <---FECHA---> te esperamos a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
WAP_ALTA = 🔔Hola <---CLIENTE---> <---BR---> 📌Has realizado una reserva para el día <---FECHA---> a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
WAP_ALTA = 🔔Hola <---CLIENTE---> <---BR---> 📌Has realizado una reserva para el día <---FECHA---> a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
|
WAP_CANCELACION = 🔔Hola <---CLIENTE---> <---BR---> 📌Tu reserva para el día <---FECHA---> a las <---HORARIO---> fue cancelada. <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
|
|
||||||
GOOGLE_CLIENT_ID = 252287289364-bu8mquhttsaa282egh8su2sumvkjqe58.apps.googleusercontent.com
|
GOOGLE_CLIENT_ID = 252287289364-bu8mquhttsaa282egh8su2sumvkjqe58.apps.googleusercontent.com
|
||||||
|
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ DONWEB_MAIL_API_KEY = eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE3NDYxMTc3N
|
|||||||
WAP_TIME_LIMIT = 5000
|
WAP_TIME_LIMIT = 5000
|
||||||
WAP_REMINDER = 🔔Hola <---CLIENTE---> <---BR---> 📌Te recuerdo que el <---FECHA---> te esperamos a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
WAP_REMINDER = 🔔Hola <---CLIENTE---> <---BR---> 📌Te recuerdo que el <---FECHA---> te esperamos a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
WAP_ALTA = 🔔Hola <---CLIENTE---> <---BR---> 📌Has realizado una reserva para el día <---FECHA---> a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
WAP_ALTA = 🔔Hola <---CLIENTE---> <---BR---> 📌Has realizado una reserva para el día <---FECHA---> a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
|
WAP_CANCELACION = 🔔Hola <---CLIENTE---> <---BR---> 📌Tu reserva para el día <---FECHA---> a las <---HORARIO---> fue cancelada. <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
|
|
||||||
GOOGLE_CLIENT_ID = 252287289364-bu8mquhttsaa282egh8su2sumvkjqe58.apps.googleusercontent.com
|
GOOGLE_CLIENT_ID = 252287289364-bu8mquhttsaa282egh8su2sumvkjqe58.apps.googleusercontent.com
|
||||||
|
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ DONWEB_MAIL_API_KEY = eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE3NDYxMTc3N
|
|||||||
WAP_TIME_LIMIT = 5000
|
WAP_TIME_LIMIT = 5000
|
||||||
WAP_REMINDER = 🔔Hola <---CLIENTE---> <---BR---> 📌Te recuerdo que el <---FECHA---> te esperamos a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
WAP_REMINDER = 🔔Hola <---CLIENTE---> <---BR---> 📌Te recuerdo que el <---FECHA---> te esperamos a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
WAP_ALTA = 🔔Hola <---CLIENTE---> <---BR---> 📌Has realizado una reserva para el día <---FECHA---> a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
WAP_ALTA = 🔔Hola <---CLIENTE---> <---BR---> 📌Has realizado una reserva para el día <---FECHA---> a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
|
WAP_CANCELACION = 🔔Hola <---CLIENTE---> <---BR---> 📌Tu reserva para el día <---FECHA---> a las <---HORARIO---> fue cancelada. <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
|
|
||||||
GOOGLE_CLIENT_ID = 252287289364-bu8mquhttsaa282egh8su2sumvkjqe58.apps.googleusercontent.com
|
GOOGLE_CLIENT_ID = 252287289364-bu8mquhttsaa282egh8su2sumvkjqe58.apps.googleusercontent.com
|
||||||
|
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ WAP_TIME_LIMIT = 5000
|
|||||||
|
|
||||||
WAP_REMINDER = 🔔Hola <---CLIENTE---> <---BR---> 📌Te recuerdo que el <---FECHA---> te esperamos a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
WAP_REMINDER = 🔔Hola <---CLIENTE---> <---BR---> 📌Te recuerdo que el <---FECHA---> te esperamos a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
WAP_ALTA = 🔔Hola <---CLIENTE---> <---BR---> 📌Has realizado una reserva para el día <---FECHA---> a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
WAP_ALTA = 🔔Hola <---CLIENTE---> <---BR---> 📌Has realizado una reserva para el día <---FECHA---> a las <---HORARIO---> ⏰ <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR--->Precio: <---PRECIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
|
WAP_CANCELACION = 🔔Hola <---CLIENTE---> <---BR---> 📌Tu reserva para el día <---FECHA---> a las <---HORARIO---> fue cancelada. <---BR---> 🏫 En <---DIRECCION---> <---BR--->Con <---PROFESIONAL---> para <---SERVICIO---> <---BR---> *<---ORGANIZACION--->*
|
||||||
|
|
||||||
GOOGLE_CLIENT_ID = 252287289364-bu8mquhttsaa282egh8su2sumvkjqe58.apps.googleusercontent.com
|
GOOGLE_CLIENT_ID = 252287289364-bu8mquhttsaa282egh8su2sumvkjqe58.apps.googleusercontent.com
|
||||||
|
|
||||||
|
|||||||
@@ -36,9 +36,18 @@ export type FindAppointmentsByCollaboratorPaginatedParams = FindAppointmentsByCo
|
|||||||
export enum APPOINTMENT_NOTIFICATION_TYPE {
|
export enum APPOINTMENT_NOTIFICATION_TYPE {
|
||||||
"CREATION" = "creation",
|
"CREATION" = "creation",
|
||||||
"REMINDER" = "reminder",
|
"REMINDER" = "reminder",
|
||||||
|
"CANCELLATION" = "cancellation",
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SendAppointmentNotificationParams = {
|
export type SendAppointmentNotificationParams = {
|
||||||
|
appointmentId: string;
|
||||||
|
sessionUser?: string;
|
||||||
|
systemToken?: string;
|
||||||
|
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||||
|
channel?: "whatsapp" | "email";
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CreateImmediateAppointmentNotificationJobsParams = {
|
||||||
appointmentId: string;
|
appointmentId: string;
|
||||||
sessionUser: string;
|
sessionUser: string;
|
||||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||||
@@ -63,6 +72,7 @@ export type ChangeServiceParams = {
|
|||||||
export type SendWapSystemNotificationParams = {
|
export type SendWapSystemNotificationParams = {
|
||||||
appointmentId: string;
|
appointmentId: string;
|
||||||
systemToken: string;
|
systemToken: string;
|
||||||
|
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type HeatMapConfig = {
|
export type HeatMapConfig = {
|
||||||
@@ -121,6 +131,7 @@ export type UpdateAppointmentParams = {
|
|||||||
export type DeleteAppointmentParams = {
|
export type DeleteAppointmentParams = {
|
||||||
id: string;
|
id: string;
|
||||||
validation?: boolean;
|
validation?: boolean;
|
||||||
|
notification?: boolean;
|
||||||
sessionUser: string;
|
sessionUser: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -315,6 +326,7 @@ export interface IAppointmentsManager {
|
|||||||
getAvailableDates(data: GetAvailableDatesParams): Promise<GetAvailableDatesResult>;
|
getAvailableDates(data: GetAvailableDatesParams): Promise<GetAvailableDatesResult>;
|
||||||
sendWapNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
sendWapNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||||
sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||||
|
createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void>;
|
||||||
sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void>;
|
sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void>;
|
||||||
deleteAppointmentsByCompany(data: DeleteAppointmentsByCompanyParams): Promise<void>;
|
deleteAppointmentsByCompany(data: DeleteAppointmentsByCompanyParams): Promise<void>;
|
||||||
changeEmployeeToOwner(data: ChangeEmployeeToOwnerParams): Promise<void>;
|
changeEmployeeToOwner(data: ChangeEmployeeToOwnerParams): Promise<void>;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
ChangeEmployeeToOwnerParams,
|
ChangeEmployeeToOwnerParams,
|
||||||
CountAppointmentsByMonthParams,
|
CountAppointmentsByMonthParams,
|
||||||
CreateAppointmentParams,
|
CreateAppointmentParams,
|
||||||
|
CreateImmediateAppointmentNotificationJobsParams,
|
||||||
DeleteAppointmentDiscountParams,
|
DeleteAppointmentDiscountParams,
|
||||||
DeleteAppointmentParams,
|
DeleteAppointmentParams,
|
||||||
DeleteAppointmentsByCompanyParams,
|
DeleteAppointmentsByCompanyParams,
|
||||||
@@ -76,6 +77,7 @@ import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled";
|
|||||||
import DiscountsEmail from "../DiscountsEmail/DiscountsEmail";
|
import DiscountsEmail from "../DiscountsEmail/DiscountsEmail";
|
||||||
import SchedulesOverridesList from "../SchedulesOverrides/SchedulesOverrides";
|
import SchedulesOverridesList from "../SchedulesOverrides/SchedulesOverrides";
|
||||||
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
|
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||||
|
import { NotificationJobService } from "../NotificationPolicies/NotificationJobService";
|
||||||
|
|
||||||
dayjs.locale("es");
|
dayjs.locale("es");
|
||||||
dayjs.extend(isSameOrAfter);
|
dayjs.extend(isSameOrAfter);
|
||||||
@@ -84,9 +86,11 @@ dayjs.extend(weekday);
|
|||||||
|
|
||||||
class AppointmentManager implements IAppointmentsManager {
|
class AppointmentManager implements IAppointmentsManager {
|
||||||
Appointments: AppointmentsAdapterMongoose;
|
Appointments: AppointmentsAdapterMongoose;
|
||||||
|
private jobService: NotificationJobService;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.Appointments = new AppointmentsAdapterMongoose();
|
this.Appointments = new AppointmentsAdapterMongoose();
|
||||||
|
this.jobService = new NotificationJobService();
|
||||||
}
|
}
|
||||||
|
|
||||||
private isScheduleAvailableForService(schedule: ScheduleItem, serviceId?: string): boolean {
|
private isScheduleAvailableForService(schedule: ScheduleItem, serviceId?: string): boolean {
|
||||||
@@ -526,36 +530,35 @@ class AppointmentManager implements IAppointmentsManager {
|
|||||||
code: String((newAppointment as any)._id)
|
code: String((newAppointment as any)._id)
|
||||||
});
|
});
|
||||||
|
|
||||||
//Intento enviar notificacion al cliente por Email
|
//Create jobs for email and whatsapp notifications
|
||||||
try {
|
if (newAppointment.id) {
|
||||||
if (newAppointment.id) {
|
const emailContent = await this.tryToSendNotification({
|
||||||
await this.sendEmailNotification({
|
appointmentId: String(newAppointment.id),
|
||||||
appointmentId: String(newAppointment.id),
|
sessionUser: String(companyCheck.ownerId),
|
||||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||||
sessionUser: String(companyCheck.ownerId),
|
channel: "email",
|
||||||
});
|
});
|
||||||
}
|
const wapContent = await this.tryToSendNotification({
|
||||||
} catch (err) {
|
appointmentId: String(newAppointment.id),
|
||||||
console.log(
|
sessionUser: String(companyCheck.ownerId),
|
||||||
`Error al enviar la notificacion por Email para ${companyCheck.name}(${companyCheck._id}):`,
|
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||||
err
|
channel: "whatsapp",
|
||||||
);
|
});
|
||||||
}
|
const clientPhoneNumber = await this.getOptionalClientWapNumber(checkClient);
|
||||||
|
|
||||||
//Intento enviar notificacion al cliente por Whatsapp
|
await this.createCreationNotificationJobs({
|
||||||
try {
|
appointmentId: String(newAppointment.id),
|
||||||
if (newAppointment.id) {
|
companyId: String(companyCheck._id),
|
||||||
await this.sendWapNotification({
|
clientId: String(checkClient._id),
|
||||||
appointmentId: String(newAppointment.id),
|
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
clientEmail: checkClient.email,
|
||||||
sessionUser: String(companyCheck.ownerId),
|
clientPhoneNumber,
|
||||||
});
|
companyOwnerId: String(companyCheck.ownerId),
|
||||||
}
|
companyName: companyCheck.name,
|
||||||
} catch (err) {
|
appointmentStart: new Date(data.start),
|
||||||
console.log(
|
emailMessage: emailContent.message,
|
||||||
`Error al enviar la notificacion por Whatsapp para ${companyCheck.name}(${companyCheck._id}):`,
|
wapMessage: wapContent.message,
|
||||||
err
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2070,36 +2073,18 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
code: String(checkAppointment._id)
|
code: String(checkAppointment._id)
|
||||||
});
|
});
|
||||||
|
|
||||||
//Intento enviar notificacion al cliente por Email
|
//Cancel existing pending jobs before creating new ones for the rescheduled appointment
|
||||||
try {
|
if (checkAppointment.id) {
|
||||||
if (checkAppointment.id) {
|
await this.jobService.cancelByAppointment(String(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
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
//Intento enviar notificacion al cliente por Whatsapp
|
//Create jobs for email and whatsapp notifications
|
||||||
try {
|
await this.jobService.createJob({
|
||||||
if (checkAppointment.id) {
|
companyId: String(companyCheck._id),
|
||||||
await this.sendWapNotification({
|
clientId: String(checkClient._id),
|
||||||
appointmentId: String(checkAppointment.id),
|
appointmentId: String(checkAppointment.id),
|
||||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
type: "update" as const,
|
||||||
sessionUser: String(companyCheck.ownerId),
|
appointmentStart: new Date(data.start),
|
||||||
});
|
});
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.log(
|
|
||||||
`Error al enviar la notificacion por Whatsapp para ${companyCheck.name}(${companyCheck._id}):`,
|
|
||||||
err
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2155,8 +2140,89 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
return config;
|
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> {
|
public async deleteAppointment(data: DeleteAppointmentParams): Promise<void> {
|
||||||
const { validation = false } = data;
|
const { validation = false, notification = false } = data;
|
||||||
const sessionUser = await UsersManager.users.findOne({
|
const sessionUser = await UsersManager.users.findOne({
|
||||||
_id: data.sessionUser,
|
_id: data.sessionUser,
|
||||||
});
|
});
|
||||||
@@ -2234,23 +2300,41 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
try {
|
try {
|
||||||
const config = this.getHeatMapConfig(checkAppointment, serviceCheck.length);
|
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 });
|
await this.Appointments.AppointmentList.deleteOne({ _id: data.id });
|
||||||
//Actualizar el heatmap.
|
//Actualizar el heatmap.
|
||||||
await this.updateHeatMap(config);
|
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
|
//Enviamos la notificacion de cancelacion al profesional
|
||||||
await NotificationsManager.sendSystemNotification({
|
await NotificationsManager.sendSystemNotification({
|
||||||
userId: String(employeeCheck.userId),
|
userId: String(employeeCheck.userId),
|
||||||
@@ -2384,8 +2468,16 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
throw new Error("La compañia no existe");
|
throw new Error("La compañia no existe");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(await EmployeesList.checkPermission(companyCheck, data.sessionUser, EmployeeRoles.ADMIN))) {
|
const hasSystemToken = this.hasValidSystemToken(data.systemToken);
|
||||||
throw new Error(NoPermissionMessage());
|
|
||||||
|
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({
|
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("<---ORGANIZACION--->", companyCheck.name);
|
||||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
} 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({
|
const template = await Templates.templates.findOne({
|
||||||
id: String(companyCheck.templateWapAltaId),
|
id: String(templateId),
|
||||||
companyId: String(companyCheck._id),
|
companyId: String(companyCheck._id),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -2477,7 +2573,9 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!wapMessage) {
|
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(
|
wapMessage = wapMessage.replaceAll(
|
||||||
@@ -2505,6 +2603,52 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
wapMessage = wapMessage.replaceAll("<---SERVICIO--->", checkService.name);
|
wapMessage = wapMessage.replaceAll("<---SERVICIO--->", checkService.name);
|
||||||
wapMessage = wapMessage.replaceAll("<---PRECIO--->", formatCurrency(checkAppointment.price));
|
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("<---ORGANIZACION--->", companyCheck.name);
|
||||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||||
}
|
}
|
||||||
@@ -2517,15 +2661,24 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void> {
|
public async sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void> {
|
||||||
const sessionUser = await UsersManager.users.findOne({
|
if (!this.hasValidSystemToken(data.systemToken)) {
|
||||||
_id: data.sessionUser,
|
if (!data.sessionUser) {
|
||||||
});
|
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||||
|
}
|
||||||
|
|
||||||
if (!sessionUser) {
|
const sessionUser = await UsersManager.users.findOne({
|
||||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
_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({
|
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||||
userId: String(companyCheck.ownerId),
|
userId: String(companyCheck.ownerId),
|
||||||
@@ -2548,6 +2701,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
subjectEmail = "TurnosXpress :: Recordatorio";
|
subjectEmail = "TurnosXpress :: Recordatorio";
|
||||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
||||||
subjectEmail = "TurnosXpress :: Alta de turno";
|
subjectEmail = "TurnosXpress :: Alta de turno";
|
||||||
|
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION) {
|
||||||
|
subjectEmail = "TurnosXpress :: Turno cancelado";
|
||||||
}
|
}
|
||||||
|
|
||||||
//Enviar email...
|
//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> {
|
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({
|
const sessionUser = await UsersManager.users.findOne({
|
||||||
_id: data.sessionUser,
|
_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");
|
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({
|
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||||
userId: String(companyCheck.ownerId),
|
userId: String(companyCheck.ownerId),
|
||||||
@@ -2593,13 +2810,7 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void> {
|
public async sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void> {
|
||||||
if (!data.systemToken || data.systemToken == "") {
|
if (!this.hasValidSystemToken(data.systemToken)) {
|
||||||
throw new Error("No tiene permisos para realizar esta acción");
|
|
||||||
}
|
|
||||||
|
|
||||||
const systemToken = `${process.env.SYSTEM_KEY}`;
|
|
||||||
|
|
||||||
if (systemToken != data.systemToken) {
|
|
||||||
throw new Error("No tiene permisos para realizar esta acción");
|
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({
|
const { message, checkClient, companyCheck } = await this.tryToSendNotification({
|
||||||
appointmentId: data.appointmentId,
|
appointmentId: data.appointmentId,
|
||||||
sessionUser: String(company.ownerId),
|
sessionUser: String(company.ownerId),
|
||||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
systemToken: data.systemToken,
|
||||||
|
type: data.type,
|
||||||
});
|
});
|
||||||
|
|
||||||
const canSend = await PlanSubscriptionsList.checkFeature({
|
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||||
@@ -2838,6 +3050,11 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
|||||||
inRangeDates: [],
|
inRangeDates: [],
|
||||||
} as GetAvailableDatesResult;
|
} 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();
|
const AppointmentList = new AppointmentManager();
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ jest.mock("../../Companies/Companies", () => ({
|
|||||||
companies: {
|
companies: {
|
||||||
findOne: jest.fn(),
|
findOne: jest.fn(),
|
||||||
},
|
},
|
||||||
|
getCompanyAddress: jest.fn(),
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -41,6 +42,7 @@ jest.mock("../../Employees/Employee", () => ({
|
|||||||
employees: {
|
employees: {
|
||||||
findOne: jest.fn(),
|
findOne: jest.fn(),
|
||||||
},
|
},
|
||||||
|
checkPermission: jest.fn(),
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -151,6 +153,9 @@ jest.mock("../../../helpers/check", () => ({
|
|||||||
jest.mock("../../Templates/Templates", () => ({
|
jest.mock("../../Templates/Templates", () => ({
|
||||||
__esModule: true,
|
__esModule: true,
|
||||||
default: {
|
default: {
|
||||||
|
templates: {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
},
|
||||||
sendEmail: jest.fn(),
|
sendEmail: jest.fn(),
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
@@ -180,6 +185,8 @@ import UsersManager from "../../Users/Users";
|
|||||||
import EmployeesList from "../../Employees/Employee";
|
import EmployeesList from "../../Employees/Employee";
|
||||||
import ClientsManager from "../../Clients/Clients";
|
import ClientsManager from "../../Clients/Clients";
|
||||||
import ServiceList from "../../Services/Service";
|
import ServiceList from "../../Services/Service";
|
||||||
|
import CompaniesManager from "../../Companies/Companies";
|
||||||
|
import Templates from "../../Templates/Templates";
|
||||||
|
|
||||||
describe("getAppointmentEvent — historical read snapshot fallback", () => {
|
describe("getAppointmentEvent — historical read snapshot fallback", () => {
|
||||||
let originalAdapter: any;
|
let originalAdapter: any;
|
||||||
@@ -385,3 +392,265 @@ describe("getAppointmentEvent — historical read snapshot fallback", () => {
|
|||||||
expect(result.collaboratorName).toBe("Jane Roe");
|
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" },
|
templateWapNotifId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||||
templateWapAltaId: { 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" },
|
templateEmailNotifId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||||
templateEmailAltaId: { 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 },
|
onboardingStep: { type: Number, required: false, default: 0 },
|
||||||
onboardingCompleted: { type: Boolean, required: false, default: false },
|
onboardingCompleted: { type: Boolean, required: false, default: false },
|
||||||
|
|
||||||
@@ -205,6 +207,10 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
|||||||
updateCompany.templateWapAltaId = data.templateWapAltaId;
|
updateCompany.templateWapAltaId = data.templateWapAltaId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (data.templateWapCancellationId) {
|
||||||
|
updateCompany.templateWapCancellationId = data.templateWapCancellationId;
|
||||||
|
}
|
||||||
|
|
||||||
if (data.templateEmailNotifId) {
|
if (data.templateEmailNotifId) {
|
||||||
updateCompany.templateEmailNotifId = data.templateEmailNotifId;
|
updateCompany.templateEmailNotifId = data.templateEmailNotifId;
|
||||||
}
|
}
|
||||||
@@ -213,6 +219,10 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
|||||||
updateCompany.templateEmailAltaId = data.templateEmailAltaId;
|
updateCompany.templateEmailAltaId = data.templateEmailAltaId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (data.templateEmailCancellationId) {
|
||||||
|
updateCompany.templateEmailCancellationId = data.templateEmailCancellationId;
|
||||||
|
}
|
||||||
|
|
||||||
if (data.onboardingStep !== undefined) {
|
if (data.onboardingStep !== undefined) {
|
||||||
updateCompany.onboardingStep = data.onboardingStep;
|
updateCompany.onboardingStep = data.onboardingStep;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,8 +47,10 @@ export type UpdateCompanyParams = {
|
|||||||
sessionUser: string;
|
sessionUser: string;
|
||||||
templateWapNotifId?: string;
|
templateWapNotifId?: string;
|
||||||
templateWapAltaId?: string;
|
templateWapAltaId?: string;
|
||||||
|
templateWapCancellationId?: string;
|
||||||
templateEmailNotifId?: string;
|
templateEmailNotifId?: string;
|
||||||
templateEmailAltaId?: string;
|
templateEmailAltaId?: string;
|
||||||
|
templateEmailCancellationId?: string;
|
||||||
onboardingStep?: number;
|
onboardingStep?: number;
|
||||||
onboardingCompleted?: boolean;
|
onboardingCompleted?: boolean;
|
||||||
banned?: boolean;
|
banned?: boolean;
|
||||||
@@ -144,8 +146,10 @@ export interface ICompany {
|
|||||||
automaticNotifications?: boolean;
|
automaticNotifications?: boolean;
|
||||||
templateWapNotifId?: string;
|
templateWapNotifId?: string;
|
||||||
templateWapAltaId?: string;
|
templateWapAltaId?: string;
|
||||||
|
templateWapCancellationId?: string;
|
||||||
templateEmailNotifId?: string;
|
templateEmailNotifId?: string;
|
||||||
templateEmailAltaId?: string;
|
templateEmailAltaId?: string;
|
||||||
|
templateEmailCancellationId?: string;
|
||||||
onboardingStep?: number;
|
onboardingStep?: number;
|
||||||
onboardingCompleted?: boolean;
|
onboardingCompleted?: boolean;
|
||||||
fixedPostIds?: Array<string>;
|
fixedPostIds?: Array<string>;
|
||||||
@@ -192,8 +196,10 @@ export interface MyOranizationsView {
|
|||||||
appointmentAlert?: string;
|
appointmentAlert?: string;
|
||||||
templateWapNotifId?: string;
|
templateWapNotifId?: string;
|
||||||
templateWapAltaId?: string;
|
templateWapAltaId?: string;
|
||||||
|
templateWapCancellationId?: string;
|
||||||
templateEmailNotifId?: string;
|
templateEmailNotifId?: string;
|
||||||
templateEmailAltaId?: string;
|
templateEmailAltaId?: string;
|
||||||
|
templateEmailCancellationId?: string;
|
||||||
onboardingStep?: number;
|
onboardingStep?: number;
|
||||||
onboardingCompleted?: boolean;
|
onboardingCompleted?: boolean;
|
||||||
banned?: 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;
|
code?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type CreateSystemNotificationBySystemParams = CreateSystemNotificationParams & {
|
||||||
|
userId: string;
|
||||||
|
systemToken: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type UpdateSystemNotificationParams = {
|
export type UpdateSystemNotificationParams = {
|
||||||
id: string;
|
id: string;
|
||||||
readed: boolean;
|
readed: boolean;
|
||||||
@@ -119,6 +124,7 @@ export interface ISystemNotificationsAdapter {
|
|||||||
export interface ISystemNotificationsManager {
|
export interface ISystemNotificationsManager {
|
||||||
notifications: ISystemNotificationsAdapter;
|
notifications: ISystemNotificationsAdapter;
|
||||||
createNotification(data: CreateSystemNotificationParams): Promise<ISystemNotification>;
|
createNotification(data: CreateSystemNotificationParams): Promise<ISystemNotification>;
|
||||||
|
createNotificationBySystem(data: CreateSystemNotificationBySystemParams): Promise<ISystemNotification>;
|
||||||
updateNotification(data: UpdateSystemNotificationParams): Promise<void>;
|
updateNotification(data: UpdateSystemNotificationParams): Promise<void>;
|
||||||
deleteNotification(data: DeleteSystemNotificationParams): Promise<void>;
|
deleteNotification(data: DeleteSystemNotificationParams): Promise<void>;
|
||||||
deleteConversationNotifications(data: DeleteSystemNotificationsByConversation): Promise<void>;
|
deleteConversationNotifications(data: DeleteSystemNotificationsByConversation): Promise<void>;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import CompaniesManager from "../Companies/Companies";
|
import CompaniesManager from "../Companies/Companies";
|
||||||
import {
|
import {
|
||||||
CreateSystemNotificationParams,
|
CreateSystemNotificationParams,
|
||||||
|
CreateSystemNotificationBySystemParams,
|
||||||
DeleteNotificationsByDateParams,
|
DeleteNotificationsByDateParams,
|
||||||
DeleteNotificationsByUserParams,
|
DeleteNotificationsByUserParams,
|
||||||
DeleteSystemNotificationParams,
|
DeleteSystemNotificationParams,
|
||||||
@@ -108,6 +109,28 @@ class SystemNotificationsManager implements ISystemNotificationsManager {
|
|||||||
return newNotification;
|
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> {
|
public async updateNotification(data: UpdateSystemNotificationParams): Promise<void> {
|
||||||
await validateSessionUser({
|
await validateSessionUser({
|
||||||
sessionUser: data.sessionUser,
|
sessionUser: data.sessionUser,
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ import { TextObjectFilterResult } from "../TextObjectFilter.model";
|
|||||||
export enum TemplateTypes {
|
export enum TemplateTypes {
|
||||||
WAP_NEW_APPOINTMENT = "wap-new-appointment",
|
WAP_NEW_APPOINTMENT = "wap-new-appointment",
|
||||||
WAP_REMINDER = "wap-reminder",
|
WAP_REMINDER = "wap-reminder",
|
||||||
|
WAP_CANCELLATION = "wap-cancellation",
|
||||||
EMAIL_NEW_APPOINTMENT = "email-new-appointment",
|
EMAIL_NEW_APPOINTMENT = "email-new-appointment",
|
||||||
EMAIL_REMINDER = "email-reminder",
|
EMAIL_REMINDER = "email-reminder",
|
||||||
|
EMAIL_CANCELLATION = "email-cancellation",
|
||||||
}
|
}
|
||||||
export interface ITemplate {
|
export interface ITemplate {
|
||||||
id?: string;
|
id?: string;
|
||||||
|
|||||||
@@ -215,12 +215,18 @@ export class TemplatesManager implements ITemplatesManager {
|
|||||||
case TemplateTypes.WAP_NEW_APPOINTMENT:
|
case TemplateTypes.WAP_NEW_APPOINTMENT:
|
||||||
defaultTemplate = `${process.env.WAP_ALTA}`;
|
defaultTemplate = `${process.env.WAP_ALTA}`;
|
||||||
break;
|
break;
|
||||||
|
case TemplateTypes.WAP_CANCELLATION:
|
||||||
|
defaultTemplate = `${process.env.WAP_CANCELLATION || process.env.WAP_CANCELACION || ""}`;
|
||||||
|
break;
|
||||||
case TemplateTypes.EMAIL_REMINDER:
|
case TemplateTypes.EMAIL_REMINDER:
|
||||||
defaultTemplate = `${process.env.WAP_REMINDER}`;
|
defaultTemplate = `${process.env.WAP_REMINDER}`;
|
||||||
break;
|
break;
|
||||||
case TemplateTypes.EMAIL_NEW_APPOINTMENT:
|
case TemplateTypes.EMAIL_NEW_APPOINTMENT:
|
||||||
defaultTemplate = `${process.env.WAP_ALTA}`;
|
defaultTemplate = `${process.env.WAP_ALTA}`;
|
||||||
break;
|
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;
|
return defaultTemplate;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
AppointmentAdminByClientView,
|
AppointmentAdminByClientView,
|
||||||
AppointmentAdminByDateView,
|
AppointmentAdminByDateView,
|
||||||
CreateAppointmentParams,
|
CreateAppointmentParams,
|
||||||
|
CreateImmediateAppointmentNotificationJobsParams,
|
||||||
DeleteAppointmentParams,
|
DeleteAppointmentParams,
|
||||||
FindAppointmentsParams,
|
FindAppointmentsParams,
|
||||||
FindAppointmentSchedulesParams,
|
FindAppointmentSchedulesParams,
|
||||||
@@ -28,6 +29,7 @@ import { AppointmentService } from "./Appointments.Service";
|
|||||||
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
||||||
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
||||||
import { rateLimiter } from "../../middleware/ratelimiter";
|
import { rateLimiter } from "../../middleware/ratelimiter";
|
||||||
|
import { systemTokenMiddleware } from "../../middleware/systemToken";
|
||||||
|
|
||||||
@Route("appointments/create")
|
@Route("appointments/create")
|
||||||
@Middlewares(authenticateMiddleware)
|
@Middlewares(authenticateMiddleware)
|
||||||
@@ -294,7 +296,7 @@ export class SendWapNotificationContrnoller extends Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Route("appointments/send-wap-sys-notification")
|
@Route("appointments/send-wap-sys-notification")
|
||||||
@Middlewares(rateLimiter)
|
@Middlewares(systemTokenMiddleware)
|
||||||
export class SendWapSystemNotificationContrnoller extends Controller {
|
export class SendWapSystemNotificationContrnoller extends Controller {
|
||||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
@SuccessResponse(200, "Done")
|
@SuccessResponse(200, "Done")
|
||||||
@@ -319,7 +321,7 @@ export class SendWapSystemNotificationContrnoller extends Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Route("appointments/send-email-notification")
|
@Route("appointments/send-email-notification")
|
||||||
@Middlewares(rateLimiter)
|
@Middlewares([rateLimiter, systemTokenMiddleware])
|
||||||
export class SendEmailNotificationContrnoller extends Controller {
|
export class SendEmailNotificationContrnoller extends Controller {
|
||||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
@SuccessResponse(200, "Done")
|
@SuccessResponse(200, "Done")
|
||||||
@@ -342,6 +344,30 @@ export class SendEmailNotificationContrnoller extends Controller {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Route("appointments/create-immediate-notification-jobs")
|
||||||
|
@Middlewares(authenticateMiddleware)
|
||||||
|
export class CreateImmediateAppointmentNotificationJobsController extends Controller {
|
||||||
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
|
@SuccessResponse(200, "Done")
|
||||||
|
@Post()
|
||||||
|
public async createImmediateNotificationJobs(
|
||||||
|
@Body() requestBody: CreateImmediateAppointmentNotificationJobsParams
|
||||||
|
): Promise<ApiVoidResult | ApiValidationError> {
|
||||||
|
try {
|
||||||
|
await new AppointmentService().createImmediateNotificationJobs(requestBody);
|
||||||
|
this.setStatus(200);
|
||||||
|
return {
|
||||||
|
message: "Done",
|
||||||
|
success: true,
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
const errorOccurred: Error = e as Error; console.error("GET EVENT ERROR:", errorOccurred);
|
||||||
|
this.setStatus(500);
|
||||||
|
return new ApiValidationError(500, errorOccurred.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Route("appointments/apply-discount")
|
@Route("appointments/apply-discount")
|
||||||
@Middlewares(authenticateMiddleware)
|
@Middlewares(authenticateMiddleware)
|
||||||
export class ApplyAppointmentDiscountContrnoller extends Controller {
|
export class ApplyAppointmentDiscountContrnoller extends Controller {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
||||||
import AppointmentList from "../../Models/Appointments/Appointments";
|
import AppointmentList from "../../Models/Appointments/Appointments";
|
||||||
import {
|
import {
|
||||||
|
CreateImmediateAppointmentNotificationJobsParams,
|
||||||
AppointmentAdminByClientView,
|
AppointmentAdminByClientView,
|
||||||
AppointmentAdminByDateView,
|
AppointmentAdminByDateView,
|
||||||
CreateAppointmentParams,
|
CreateAppointmentParams,
|
||||||
@@ -161,6 +162,11 @@ export class AppointmentService {
|
|||||||
await AppointmentList.sendEmailNotification(data);
|
await AppointmentList.sendEmailNotification(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void> {
|
||||||
|
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||||
|
await AppointmentList.createImmediateNotificationJobs(data);
|
||||||
|
}
|
||||||
|
|
||||||
public async applyDiscount(data: ApplyAppointmentDiscountParams): Promise<void> {
|
public async applyDiscount(data: ApplyAppointmentDiscountParams): Promise<void> {
|
||||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||||
await AppointmentList.applyDiscount(data);
|
await AppointmentList.applyDiscount(data);
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
import { ApiValidationError } from "../../Models/Server.Error.model";
|
||||||
|
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
|
||||||
|
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||||
|
import {
|
||||||
|
NotificationPoliciesService,
|
||||||
|
FindCompanyPolicyParams,
|
||||||
|
UpsertCompanyPolicyParams,
|
||||||
|
FindClientPreferencesParams,
|
||||||
|
UpsertClientPreferencesParams,
|
||||||
|
FindClientCompanyOverrideParams,
|
||||||
|
UpsertClientCompanyOverrideParams,
|
||||||
|
} from "./NotificationPolicies.Service";
|
||||||
|
import { ICompanyNotificationPolicy } from "../../Models/NotificationPolicies/CompanyNotificationPolicy.Interface";
|
||||||
|
import { IClientNotificationPreferences } from "../../Models/NotificationPolicies/ClientNotificationPreferences.Interface";
|
||||||
|
import { IClientCompanyNotificationOverride } from "../../Models/NotificationPolicies/ClientCompanyNotificationOverride.Interface";
|
||||||
|
|
||||||
|
@Route("notifications/policy/find")
|
||||||
|
@Middlewares(authenticateMiddleware)
|
||||||
|
export class FindCompanyNotificationPolicyController extends Controller {
|
||||||
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
|
@SuccessResponse(200, "Política encontrada")
|
||||||
|
@Post()
|
||||||
|
public async findCompanyPolicy(
|
||||||
|
@Body() requestBody: FindCompanyPolicyParams
|
||||||
|
): Promise<ICompanyNotificationPolicy | ApiValidationError> {
|
||||||
|
try {
|
||||||
|
const policy = await new NotificationPoliciesService().getCompanyPolicy(requestBody);
|
||||||
|
this.setStatus(200);
|
||||||
|
if (!policy) {
|
||||||
|
return new ApiValidationError(404, "No se encontró una política de notificación para esta organización");
|
||||||
|
}
|
||||||
|
return policy;
|
||||||
|
} catch (e) {
|
||||||
|
const errorOccurred: Error = e as Error;
|
||||||
|
this.setStatus(500);
|
||||||
|
return new ApiValidationError(500, errorOccurred.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route("notifications/policy/save")
|
||||||
|
@Middlewares(authenticateMiddleware)
|
||||||
|
export class UpsertCompanyNotificationPolicyController extends Controller {
|
||||||
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
|
@SuccessResponse(200, "Política guardada con éxito")
|
||||||
|
@Post()
|
||||||
|
public async upsertCompanyPolicy(
|
||||||
|
@Body() requestBody: UpsertCompanyPolicyParams
|
||||||
|
): Promise<ICompanyNotificationPolicy | ApiValidationError> {
|
||||||
|
try {
|
||||||
|
const policy = await new NotificationPoliciesService().upsertCompanyPolicy(requestBody);
|
||||||
|
this.setStatus(200);
|
||||||
|
return policy;
|
||||||
|
} catch (e) {
|
||||||
|
const errorOccurred: Error = e as Error;
|
||||||
|
this.setStatus(500);
|
||||||
|
return new ApiValidationError(500, errorOccurred.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route("notifications/preferences/find")
|
||||||
|
@Middlewares(authenticateMiddleware)
|
||||||
|
export class FindClientNotificationPreferencesController extends Controller {
|
||||||
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
|
@SuccessResponse(200, "Preferencias encontradas")
|
||||||
|
@Post()
|
||||||
|
public async findClientPreferences(
|
||||||
|
@Body() requestBody: FindClientPreferencesParams
|
||||||
|
): Promise<IClientNotificationPreferences | ApiValidationError> {
|
||||||
|
try {
|
||||||
|
const preferences = await new NotificationPoliciesService().getClientPreferences(requestBody);
|
||||||
|
this.setStatus(200);
|
||||||
|
if (!preferences) {
|
||||||
|
return new ApiValidationError(404, "No se encontraron preferencias de notificación para este cliente");
|
||||||
|
}
|
||||||
|
return preferences;
|
||||||
|
} catch (e) {
|
||||||
|
const errorOccurred: Error = e as Error;
|
||||||
|
this.setStatus(500);
|
||||||
|
return new ApiValidationError(500, errorOccurred.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route("notifications/preferences/save")
|
||||||
|
@Middlewares(authenticateMiddleware)
|
||||||
|
export class UpsertClientNotificationPreferencesController extends Controller {
|
||||||
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
|
@SuccessResponse(200, "Preferencias guardadas con éxito")
|
||||||
|
@Post()
|
||||||
|
public async upsertClientPreferences(
|
||||||
|
@Body() requestBody: UpsertClientPreferencesParams
|
||||||
|
): Promise<IClientNotificationPreferences | ApiValidationError> {
|
||||||
|
try {
|
||||||
|
const preferences = await new NotificationPoliciesService().upsertClientPreferences(requestBody);
|
||||||
|
this.setStatus(200);
|
||||||
|
return preferences;
|
||||||
|
} catch (e) {
|
||||||
|
const errorOccurred: Error = e as Error;
|
||||||
|
this.setStatus(500);
|
||||||
|
return new ApiValidationError(500, errorOccurred.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route("notifications/override/find")
|
||||||
|
@Middlewares(authenticateMiddleware)
|
||||||
|
export class FindClientCompanyNotificationOverrideController extends Controller {
|
||||||
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
|
@SuccessResponse(200, "Override encontrado")
|
||||||
|
@Post()
|
||||||
|
public async findClientCompanyOverride(
|
||||||
|
@Body() requestBody: FindClientCompanyOverrideParams
|
||||||
|
): Promise<IClientCompanyNotificationOverride | ApiValidationError> {
|
||||||
|
try {
|
||||||
|
const override = await new NotificationPoliciesService().getClientCompanyOverride(requestBody);
|
||||||
|
this.setStatus(200);
|
||||||
|
if (!override) {
|
||||||
|
return new ApiValidationError(404, "No se encontró una preferencia específica para este cliente en esta organización");
|
||||||
|
}
|
||||||
|
return override;
|
||||||
|
} catch (e) {
|
||||||
|
const errorOccurred: Error = e as Error;
|
||||||
|
this.setStatus(500);
|
||||||
|
return new ApiValidationError(500, errorOccurred.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route("notifications/override/save")
|
||||||
|
@Middlewares(authenticateMiddleware)
|
||||||
|
export class UpsertClientCompanyNotificationOverrideController extends Controller {
|
||||||
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
|
@SuccessResponse(200, "Override guardado con éxito")
|
||||||
|
@Post()
|
||||||
|
public async upsertClientCompanyOverride(
|
||||||
|
@Body() requestBody: UpsertClientCompanyOverrideParams
|
||||||
|
): Promise<IClientCompanyNotificationOverride | ApiValidationError> {
|
||||||
|
try {
|
||||||
|
const override = await new NotificationPoliciesService().upsertClientCompanyOverride(requestBody);
|
||||||
|
this.setStatus(200);
|
||||||
|
return override;
|
||||||
|
} catch (e) {
|
||||||
|
const errorOccurred: Error = e as Error;
|
||||||
|
this.setStatus(500);
|
||||||
|
return new ApiValidationError(500, errorOccurred.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import { connect } from "mongoose";
|
||||||
|
import CompanyNotificationPolicy from "../../Models/NotificationPolicies/CompanyNotificationPolicy";
|
||||||
|
import ClientNotificationPreferences from "../../Models/NotificationPolicies/ClientNotificationPreferences";
|
||||||
|
import ClientCompanyNotificationOverride from "../../Models/NotificationPolicies/ClientCompanyNotificationOverride";
|
||||||
|
import {
|
||||||
|
ICompanyNotificationPolicy,
|
||||||
|
} from "../../Models/NotificationPolicies/CompanyNotificationPolicy.Interface";
|
||||||
|
import {
|
||||||
|
IClientNotificationPreferences,
|
||||||
|
} from "../../Models/NotificationPolicies/ClientNotificationPreferences.Interface";
|
||||||
|
import {
|
||||||
|
IClientCompanyNotificationOverride,
|
||||||
|
} from "../../Models/NotificationPolicies/ClientCompanyNotificationOverride.Interface";
|
||||||
|
import { NotificationChannel } from "../../Models/NotificationJobs/NotificationJobs.Interface";
|
||||||
|
|
||||||
|
export interface SessionUserParams {
|
||||||
|
sessionUser: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FindCompanyPolicyParams extends SessionUserParams {
|
||||||
|
companyId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpsertCompanyPolicyParams extends SessionUserParams {
|
||||||
|
companyId: string;
|
||||||
|
defaultChannels?: NotificationChannel[];
|
||||||
|
timezone?: string;
|
||||||
|
quietHours?: { from: string; to: string };
|
||||||
|
reminderRules?: { offset: number; enabled: boolean }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FindClientPreferencesParams extends SessionUserParams {
|
||||||
|
clientId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpsertClientPreferencesParams extends SessionUserParams {
|
||||||
|
clientId: string;
|
||||||
|
preferredChannels?: NotificationChannel[];
|
||||||
|
mutedChannels?: NotificationChannel[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FindClientCompanyOverrideParams extends SessionUserParams {
|
||||||
|
clientId: string;
|
||||||
|
companyId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpsertClientCompanyOverrideParams extends SessionUserParams {
|
||||||
|
clientId: string;
|
||||||
|
companyId: string;
|
||||||
|
preferredChannels?: NotificationChannel[];
|
||||||
|
mutedChannels?: NotificationChannel[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NotificationPoliciesService {
|
||||||
|
public async getCompanyPolicy(
|
||||||
|
params: FindCompanyPolicyParams
|
||||||
|
): Promise<ICompanyNotificationPolicy | null> {
|
||||||
|
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||||
|
return CompanyNotificationPolicy.findOne(params);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async upsertCompanyPolicy(
|
||||||
|
params: UpsertCompanyPolicyParams
|
||||||
|
): Promise<ICompanyNotificationPolicy> {
|
||||||
|
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||||
|
const data: Partial<
|
||||||
|
Omit<ICompanyNotificationPolicy, "id" | "companyId" | "createdAt" | "updatedAt">
|
||||||
|
> = {};
|
||||||
|
if (params.defaultChannels !== undefined) data.defaultChannels = params.defaultChannels;
|
||||||
|
if (params.timezone !== undefined) data.timezone = params.timezone;
|
||||||
|
if (params.quietHours !== undefined) data.quietHours = params.quietHours;
|
||||||
|
if (params.reminderRules !== undefined) data.reminderRules = params.reminderRules;
|
||||||
|
return CompanyNotificationPolicy.upsert({
|
||||||
|
companyId: params.companyId,
|
||||||
|
sessionUser: params.sessionUser,
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getClientPreferences(
|
||||||
|
params: FindClientPreferencesParams
|
||||||
|
): Promise<IClientNotificationPreferences | null> {
|
||||||
|
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||||
|
return ClientNotificationPreferences.findOne({
|
||||||
|
userId: params.clientId,
|
||||||
|
sessionUser: params.sessionUser,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async upsertClientPreferences(
|
||||||
|
params: UpsertClientPreferencesParams
|
||||||
|
): Promise<IClientNotificationPreferences> {
|
||||||
|
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||||
|
const data: Partial<
|
||||||
|
Omit<IClientNotificationPreferences, "id" | "userId" | "createdAt" | "updatedAt">
|
||||||
|
> = {};
|
||||||
|
if (params.preferredChannels !== undefined) data.preferredChannels = params.preferredChannels;
|
||||||
|
if (params.mutedChannels !== undefined) data.mutedChannels = params.mutedChannels;
|
||||||
|
return ClientNotificationPreferences.upsert({
|
||||||
|
userId: params.clientId,
|
||||||
|
sessionUser: params.sessionUser,
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getClientCompanyOverride(
|
||||||
|
params: FindClientCompanyOverrideParams
|
||||||
|
): Promise<IClientCompanyNotificationOverride | null> {
|
||||||
|
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||||
|
return ClientCompanyNotificationOverride.findOne(params);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async upsertClientCompanyOverride(
|
||||||
|
params: UpsertClientCompanyOverrideParams
|
||||||
|
): Promise<IClientCompanyNotificationOverride> {
|
||||||
|
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||||
|
const data: Partial<
|
||||||
|
Omit<
|
||||||
|
IClientCompanyNotificationOverride,
|
||||||
|
"id" | "clientId" | "companyId" | "createdAt" | "updatedAt"
|
||||||
|
>
|
||||||
|
> = {};
|
||||||
|
if (params.preferredChannels !== undefined) data.preferredChannels = params.preferredChannels;
|
||||||
|
if (params.mutedChannels !== undefined) data.mutedChannels = params.mutedChannels;
|
||||||
|
return ClientCompanyNotificationOverride.upsert({
|
||||||
|
clientId: params.clientId,
|
||||||
|
companyId: params.companyId,
|
||||||
|
sessionUser: params.sessionUser,
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { Body, Controller, Middlewares, Post, Route, SuccessResponse } from "tsoa";
|
||||||
|
import { rateLimiter } from "../../middleware/ratelimiter";
|
||||||
|
import { systemTokenMiddleware } from "../../middleware/systemToken";
|
||||||
|
import { NotificationsManager } from "../../Models/Notifications/Notifications";
|
||||||
|
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
||||||
|
|
||||||
|
interface SendEmailByContentParams {
|
||||||
|
systemToken: string;
|
||||||
|
email: string;
|
||||||
|
subject: string;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SendWapByContentParams {
|
||||||
|
systemToken: string;
|
||||||
|
phoneNumber: string;
|
||||||
|
message: string;
|
||||||
|
companyId: string;
|
||||||
|
sessionUser: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route("notifications/send-email")
|
||||||
|
@Middlewares([rateLimiter, systemTokenMiddleware])
|
||||||
|
export class SendEmailByContentController extends Controller {
|
||||||
|
@SuccessResponse(200, "Done")
|
||||||
|
@Post()
|
||||||
|
public async sendEmailByContent(@Body() requestBody: SendEmailByContentParams): Promise<ApiVoidResult> {
|
||||||
|
await NotificationsManager.sendEmail({
|
||||||
|
email: requestBody.email,
|
||||||
|
subject: requestBody.subject,
|
||||||
|
message: requestBody.message,
|
||||||
|
});
|
||||||
|
|
||||||
|
this.setStatus(200);
|
||||||
|
return {
|
||||||
|
message: "Done",
|
||||||
|
success: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route("notifications/send-wap")
|
||||||
|
@Middlewares([rateLimiter, systemTokenMiddleware])
|
||||||
|
export class SendWapByContentController extends Controller {
|
||||||
|
@SuccessResponse(200, "Done")
|
||||||
|
@Post()
|
||||||
|
public async sendWapByContent(@Body() requestBody: SendWapByContentParams): Promise<ApiVoidResult> {
|
||||||
|
await NotificationsManager.sendWap({
|
||||||
|
phoneNumber: requestBody.phoneNumber,
|
||||||
|
message: requestBody.message,
|
||||||
|
companyId: requestBody.companyId,
|
||||||
|
sessionUser: requestBody.sessionUser,
|
||||||
|
});
|
||||||
|
|
||||||
|
this.setStatus(200);
|
||||||
|
return {
|
||||||
|
message: "Done",
|
||||||
|
success: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import { authenticateMiddleware } from "../../middleware/authentication";
|
|||||||
import {
|
import {
|
||||||
DeleteNotificationsByDateParams,
|
DeleteNotificationsByDateParams,
|
||||||
DeleteSystemNotificationParams,
|
DeleteSystemNotificationParams,
|
||||||
|
CreateSystemNotificationBySystemParams,
|
||||||
|
ISystemNotification,
|
||||||
FindSystemNotificationsParams,
|
FindSystemNotificationsParams,
|
||||||
PaginateSystemNotificationsParams,
|
PaginateSystemNotificationsParams,
|
||||||
PaginateSystemNotificationsResults,
|
PaginateSystemNotificationsResults,
|
||||||
@@ -13,6 +15,7 @@ import {
|
|||||||
UpdateSystemNotificationParams,
|
UpdateSystemNotificationParams,
|
||||||
} from "../../Models/SystemNotifications/SystemNotification.Interface";
|
} from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||||
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
||||||
|
import { systemTokenMiddleware } from "../../middleware/systemToken";
|
||||||
|
|
||||||
@Route("systemnotifications/set-state")
|
@Route("systemnotifications/set-state")
|
||||||
@Middlewares(authenticateMiddleware)
|
@Middlewares(authenticateMiddleware)
|
||||||
@@ -151,3 +154,24 @@ export class DeleteSystemNotificationsByDateController extends Controller {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Route("systemnotifications/create")
|
||||||
|
@Middlewares(systemTokenMiddleware)
|
||||||
|
export class CreateSystemNotificationsBySystemController extends Controller {
|
||||||
|
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||||
|
@SuccessResponse(200, "Done")
|
||||||
|
@Post()
|
||||||
|
public async createSystemNotification(
|
||||||
|
@Body() requestBody: CreateSystemNotificationBySystemParams
|
||||||
|
): Promise<ISystemNotification | ApiValidationError> {
|
||||||
|
try {
|
||||||
|
const notification = await new SystemNotificationsService().createSystemNotification(requestBody);
|
||||||
|
this.setStatus(200);
|
||||||
|
return notification;
|
||||||
|
} catch (e) {
|
||||||
|
const errorOccurred: Error = e as Error;
|
||||||
|
this.setStatus(500);
|
||||||
|
return new ApiValidationError(500, errorOccurred.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import SystemNoficationsList from "../../Models/SystemNotifications/SystemNotifi
|
|||||||
import {
|
import {
|
||||||
DeleteNotificationsByDateParams,
|
DeleteNotificationsByDateParams,
|
||||||
DeleteSystemNotificationParams,
|
DeleteSystemNotificationParams,
|
||||||
|
CreateSystemNotificationBySystemParams,
|
||||||
|
ISystemNotification,
|
||||||
FindSystemNotificationsParams,
|
FindSystemNotificationsParams,
|
||||||
PaginateSystemNotificationsParams,
|
PaginateSystemNotificationsParams,
|
||||||
PaginateSystemNotificationsResults,
|
PaginateSystemNotificationsResults,
|
||||||
@@ -48,4 +50,12 @@ export class SystemNotificationsService {
|
|||||||
const notifications = await SystemNoficationsList.finUnreadNotifications(data);
|
const notifications = await SystemNoficationsList.finUnreadNotifications(data);
|
||||||
return notifications;
|
return notifications;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async createSystemNotification(
|
||||||
|
data: CreateSystemNotificationBySystemParams
|
||||||
|
): Promise<ISystemNotification> {
|
||||||
|
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||||
|
const notification = await SystemNoficationsList.createNotificationBySystem(data);
|
||||||
|
return notification;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { Request, Response } from "express";
|
||||||
|
import { systemTokenMiddleware } from "../systemToken";
|
||||||
|
|
||||||
|
describe("systemTokenMiddleware", () => {
|
||||||
|
const originalSystemKey = process.env.SYSTEM_KEY;
|
||||||
|
const originalApiKey = process.env.API_KEY;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.env.SYSTEM_KEY = originalSystemKey;
|
||||||
|
process.env.API_KEY = originalApiKey;
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
function createResponse(): Response {
|
||||||
|
return {
|
||||||
|
status: jest.fn().mockReturnThis(),
|
||||||
|
json: jest.fn().mockReturnThis(),
|
||||||
|
} as unknown as Response;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("allows requests with a valid system token", async () => {
|
||||||
|
process.env.SYSTEM_KEY = "system-token";
|
||||||
|
const request = { body: { systemToken: "system-token" } } as Request;
|
||||||
|
const response = createResponse();
|
||||||
|
const next = jest.fn();
|
||||||
|
|
||||||
|
await systemTokenMiddleware(request, response, next);
|
||||||
|
|
||||||
|
expect(next).toHaveBeenCalledTimes(1);
|
||||||
|
expect(response.status).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects requests without a valid system token", async () => {
|
||||||
|
process.env.SYSTEM_KEY = "system-token";
|
||||||
|
const request = { body: { systemToken: "wrong-token" } } as Request;
|
||||||
|
const response = createResponse();
|
||||||
|
const next = jest.fn();
|
||||||
|
|
||||||
|
await systemTokenMiddleware(request, response, next);
|
||||||
|
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
expect(response.status).toHaveBeenCalledWith(401);
|
||||||
|
expect(response.json).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ desc: "Token de sistema inválido" })
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects requests when no server-side system token is configured", async () => {
|
||||||
|
delete process.env.SYSTEM_KEY;
|
||||||
|
delete process.env.API_KEY;
|
||||||
|
const request = { body: { systemToken: "system-token" } } as Request;
|
||||||
|
const response = createResponse();
|
||||||
|
const next = jest.fn();
|
||||||
|
|
||||||
|
await systemTokenMiddleware(request, response, next);
|
||||||
|
|
||||||
|
expect(next).not.toHaveBeenCalled();
|
||||||
|
expect(response.status).toHaveBeenCalledWith(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { NextFunction, Request, Response } from "express";
|
||||||
|
import { ApiValidationError } from "../Models/Server.Error.model";
|
||||||
|
|
||||||
|
export async function systemTokenMiddleware(
|
||||||
|
request: Request,
|
||||||
|
response: Response,
|
||||||
|
next: NextFunction
|
||||||
|
): Promise<void | Response | ApiValidationError> {
|
||||||
|
const expectedSystemToken = process.env.SYSTEM_KEY || process.env.API_KEY;
|
||||||
|
const systemToken = request.body?.systemToken;
|
||||||
|
|
||||||
|
if (!expectedSystemToken || typeof systemToken !== "string" || systemToken !== expectedSystemToken) {
|
||||||
|
return response
|
||||||
|
.status(401)
|
||||||
|
.json(new ApiValidationError(401, "Token de sistema inválido"));
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
}
|
||||||
@@ -30,6 +30,7 @@ export type UpdateAppointmentParams = {
|
|||||||
export enum APPOINTMENT_NOTIFICATION_TYPE {
|
export enum APPOINTMENT_NOTIFICATION_TYPE {
|
||||||
"CREATION" = "creation",
|
"CREATION" = "creation",
|
||||||
"REMINDER" = "reminder",
|
"REMINDER" = "reminder",
|
||||||
|
"CANCELLATION" = "cancellation",
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SendAppointmentNotificationParams = {
|
export type SendAppointmentNotificationParams = {
|
||||||
@@ -41,6 +42,7 @@ export type SendAppointmentNotificationParams = {
|
|||||||
export type DeleteAppointmentParams = {
|
export type DeleteAppointmentParams = {
|
||||||
id: string;
|
id: string;
|
||||||
validation?: boolean;
|
validation?: boolean;
|
||||||
|
notification?: boolean;
|
||||||
sessionUser: string;
|
sessionUser: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -39,8 +39,10 @@ export interface MyOranizationsView {
|
|||||||
appointmentAlert: string;
|
appointmentAlert: string;
|
||||||
templateWapNotifId: string;
|
templateWapNotifId: string;
|
||||||
templateWapAltaId: string;
|
templateWapAltaId: string;
|
||||||
|
templateWapCancellationId: string;
|
||||||
templateEmailNotifId: string;
|
templateEmailNotifId: string;
|
||||||
templateEmailAltaId: string;
|
templateEmailAltaId: string;
|
||||||
|
templateEmailCancellationId: string;
|
||||||
onboardingStep?: number;
|
onboardingStep?: number;
|
||||||
onboardingCompleted?: boolean;
|
onboardingCompleted?: boolean;
|
||||||
}
|
}
|
||||||
@@ -85,8 +87,10 @@ export type UpdateCompanyParams = {
|
|||||||
sessionUser: string;
|
sessionUser: string;
|
||||||
templateWapNotifId?: string;
|
templateWapNotifId?: string;
|
||||||
templateWapAltaId?: string;
|
templateWapAltaId?: string;
|
||||||
|
templateWapCancellationId?: string;
|
||||||
templateEmailNotifId?: string;
|
templateEmailNotifId?: string;
|
||||||
templateEmailAltaId?: string;
|
templateEmailAltaId?: string;
|
||||||
|
templateEmailCancellationId?: string;
|
||||||
onboardingStep?: number;
|
onboardingStep?: number;
|
||||||
onboardingCompleted?: boolean;
|
onboardingCompleted?: boolean;
|
||||||
};
|
};
|
||||||
@@ -146,8 +150,10 @@ export interface ICompany {
|
|||||||
appointmentAlert?: string;
|
appointmentAlert?: string;
|
||||||
templateWapNotifId?: string;
|
templateWapNotifId?: string;
|
||||||
templateWapAltaId?: string;
|
templateWapAltaId?: string;
|
||||||
|
templateWapCancellationId?: string;
|
||||||
templateEmailNotifId?: string;
|
templateEmailNotifId?: string;
|
||||||
templateEmailAltaId?: string;
|
templateEmailAltaId?: string;
|
||||||
|
templateEmailCancellationId?: string;
|
||||||
onboardingStep?: number;
|
onboardingStep?: number;
|
||||||
onboardingCompleted?: boolean;
|
onboardingCompleted?: boolean;
|
||||||
fixedPostIds?: Array<string>;
|
fixedPostIds?: Array<string>;
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
export type NotificationChannel = "whatsapp" | "email" | "system";
|
||||||
|
|
||||||
|
export interface QuietHours {
|
||||||
|
from: string; // "HH:mm"
|
||||||
|
to: string; // "HH:mm"
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReminderRule {
|
||||||
|
offset: number; // minutes before appointment
|
||||||
|
enabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CompanyNotificationPolicy {
|
||||||
|
id?: string;
|
||||||
|
companyId: string;
|
||||||
|
defaultChannels: NotificationChannel[];
|
||||||
|
mutedChannels?: NotificationChannel[];
|
||||||
|
timezone: string;
|
||||||
|
quietHours?: QuietHours;
|
||||||
|
reminderRules?: ReminderRule[];
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClientNotificationPreferences {
|
||||||
|
id?: string;
|
||||||
|
userId: string;
|
||||||
|
preferredChannels: NotificationChannel[];
|
||||||
|
mutedChannels: NotificationChannel[];
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClientCompanyNotificationOverride {
|
||||||
|
id?: string;
|
||||||
|
clientId: string;
|
||||||
|
companyId: string;
|
||||||
|
preferredChannels: NotificationChannel[];
|
||||||
|
mutedChannels: NotificationChannel[];
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
// API params (match backend UpsertCompanyPolicyParams)
|
||||||
|
export interface UpsertCompanyPolicyParams {
|
||||||
|
defaultChannels?: NotificationChannel[];
|
||||||
|
timezone?: string;
|
||||||
|
quietHours?: QuietHours;
|
||||||
|
reminderRules?: ReminderRule[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpsertClientPreferencesParams {
|
||||||
|
preferredChannels?: NotificationChannel[];
|
||||||
|
mutedChannels?: NotificationChannel[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpsertClientCompanyOverrideParams {
|
||||||
|
preferredChannels?: NotificationChannel[];
|
||||||
|
mutedChannels?: NotificationChannel[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store mode
|
||||||
|
export type NotificationFormMode = "company-policy" | "client-override" | "client-preferences";
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import * as Yup from "yup";
|
||||||
|
|
||||||
|
const validChannels = ["whatsapp", "email", "system"] as const;
|
||||||
|
|
||||||
|
export const companyPolicySchema = Yup.object().shape({
|
||||||
|
defaultChannels: Yup.array()
|
||||||
|
.of(Yup.string().oneOf(validChannels))
|
||||||
|
.min(1, "Select at least one channel")
|
||||||
|
.required("Channels are required"),
|
||||||
|
timezone: Yup.string().required("Timezone is required"),
|
||||||
|
quietHours: Yup.object()
|
||||||
|
.shape({
|
||||||
|
from: Yup.string().matches(
|
||||||
|
/^([01]\d|2[0-3]):([0-5]\d)$/,
|
||||||
|
"Invalid time format (HH:mm)"
|
||||||
|
),
|
||||||
|
to: Yup.string().matches(
|
||||||
|
/^([01]\d|2[0-3]):([0-5]\d)$/,
|
||||||
|
"Invalid time format (HH:mm)"
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
|
reminderRules: Yup.array()
|
||||||
|
.of(
|
||||||
|
Yup.object().shape({
|
||||||
|
offset: Yup.number()
|
||||||
|
.min(5, "Minimum 5 minutes")
|
||||||
|
.max(10080, "Maximum 7 days (10080 minutes)")
|
||||||
|
.required("Offset is required"),
|
||||||
|
enabled: Yup.boolean().required()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.max(5, "Maximum 5 reminder rules")
|
||||||
|
.optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
export const clientPrefsSchema = Yup.object().shape({
|
||||||
|
preferredChannels: Yup.array()
|
||||||
|
.of(Yup.string().oneOf(validChannels))
|
||||||
|
.optional(),
|
||||||
|
mutedChannels: Yup.array()
|
||||||
|
.of(Yup.string().oneOf(validChannels))
|
||||||
|
.optional()
|
||||||
|
});
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
export enum TemplateTypes {
|
export enum TemplateTypes {
|
||||||
WAP_NEW_APPOINTMENT = "wap-new-appointment",
|
WAP_NEW_APPOINTMENT = "wap-new-appointment",
|
||||||
WAP_REMINDER = "wap-reminder",
|
WAP_REMINDER = "wap-reminder",
|
||||||
|
WAP_CANCELLATION = "wap-cancellation",
|
||||||
EMAIL_NEW_APPOINTMENT = "email-new-appointment",
|
EMAIL_NEW_APPOINTMENT = "email-new-appointment",
|
||||||
EMAIL_REMINDER = "email-reminder",
|
EMAIL_REMINDER = "email-reminder",
|
||||||
|
EMAIL_CANCELLATION = "email-cancellation",
|
||||||
}
|
}
|
||||||
|
|
||||||
export const refactorFields = (text: string) => {
|
export const refactorFields = (text: string) => {
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import ApiRequest from "@services/Api.Service";
|
||||||
|
import {
|
||||||
|
CompanyNotificationPolicy,
|
||||||
|
ClientNotificationPreferences,
|
||||||
|
ClientCompanyNotificationOverride,
|
||||||
|
UpsertCompanyPolicyParams,
|
||||||
|
UpsertClientPreferencesParams,
|
||||||
|
UpsertClientCompanyOverrideParams
|
||||||
|
} from "@models/NotificationPreferences.model";
|
||||||
|
|
||||||
|
export const getCompanyPolicy = (companyId: string, sessionUser: string): Promise<CompanyNotificationPolicy> =>
|
||||||
|
ApiRequest.post<CompanyNotificationPolicy>("notifications/policy/find", { companyId, sessionUser });
|
||||||
|
|
||||||
|
export const upsertCompanyPolicy = (companyId: string, sessionUser: string, data: UpsertCompanyPolicyParams): Promise<CompanyNotificationPolicy> =>
|
||||||
|
ApiRequest.post<CompanyNotificationPolicy>("notifications/policy/save", { companyId, sessionUser, ...data });
|
||||||
|
|
||||||
|
export const getClientPreferences = (userId: string, sessionUser: string): Promise<ClientNotificationPreferences> =>
|
||||||
|
ApiRequest.post<ClientNotificationPreferences>("notifications/preferences/find", { clientId: userId, sessionUser });
|
||||||
|
|
||||||
|
export const upsertClientPreferences = (userId: string, sessionUser: string, data: UpsertClientPreferencesParams): Promise<ClientNotificationPreferences> =>
|
||||||
|
ApiRequest.post<ClientNotificationPreferences>("notifications/preferences/save", { clientId: userId, sessionUser, ...data });
|
||||||
|
|
||||||
|
export const getClientCompanyOverride = (clientId: string, companyId: string, sessionUser: string): Promise<ClientCompanyNotificationOverride> =>
|
||||||
|
ApiRequest.post<ClientCompanyNotificationOverride>("notifications/override/find", { clientId, companyId, sessionUser });
|
||||||
|
|
||||||
|
export const upsertClientCompanyOverride = (clientId: string, companyId: string, sessionUser: string, data: UpsertClientCompanyOverrideParams): Promise<ClientCompanyNotificationOverride> =>
|
||||||
|
ApiRequest.post<ClientCompanyNotificationOverride>("notifications/override/save", { clientId, companyId, sessionUser, ...data });
|
||||||
@@ -1,12 +1,15 @@
|
|||||||
import { create } from "zustand";
|
import { create } from "zustand";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
interface IConfirmStore {
|
interface IConfirmStore {
|
||||||
visible: boolean;
|
visible: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
|
content?: ReactNode;
|
||||||
title: string;
|
title: string;
|
||||||
onConfirm: () => void;
|
onConfirm: () => void;
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
show: (message: string, onConfirm: () => void, onCancel: () => void) => void;
|
show: (message: string, onConfirm: () => void, onCancel: () => void) => void;
|
||||||
|
showContent: (message: string, content: ReactNode, onConfirm: () => void, onCancel: () => void) => void;
|
||||||
close: () => void;
|
close: () => void;
|
||||||
clear: () => void;
|
clear: () => void;
|
||||||
}
|
}
|
||||||
@@ -16,6 +19,7 @@ export type ConfirmState = IConfirmStore;
|
|||||||
const useConfirmStore = create<ConfirmState>()((set) => ({
|
const useConfirmStore = create<ConfirmState>()((set) => ({
|
||||||
visible: false,
|
visible: false,
|
||||||
message: "",
|
message: "",
|
||||||
|
content: undefined,
|
||||||
title: "",
|
title: "",
|
||||||
onConfirm: () => {},
|
onConfirm: () => {},
|
||||||
onCancel: () => {},
|
onCancel: () => {},
|
||||||
@@ -23,6 +27,16 @@ const useConfirmStore = create<ConfirmState>()((set) => ({
|
|||||||
set(() => ({
|
set(() => ({
|
||||||
visible: true,
|
visible: true,
|
||||||
message: message,
|
message: message,
|
||||||
|
content: undefined,
|
||||||
|
onConfirm: onConfirm,
|
||||||
|
onCancel: onCancel,
|
||||||
|
title: "Atención",
|
||||||
|
})),
|
||||||
|
showContent: (message: string, content: ReactNode, onConfirm: () => void, onCancel: () => void) =>
|
||||||
|
set(() => ({
|
||||||
|
visible: true,
|
||||||
|
message: message,
|
||||||
|
content: content,
|
||||||
onConfirm: onConfirm,
|
onConfirm: onConfirm,
|
||||||
onCancel: onCancel,
|
onCancel: onCancel,
|
||||||
title: "Atención",
|
title: "Atención",
|
||||||
@@ -31,6 +45,7 @@ const useConfirmStore = create<ConfirmState>()((set) => ({
|
|||||||
set(() => ({
|
set(() => ({
|
||||||
visible: false,
|
visible: false,
|
||||||
message: "",
|
message: "",
|
||||||
|
content: undefined,
|
||||||
onConfirm: () => {},
|
onConfirm: () => {},
|
||||||
onCancel: () => {},
|
onCancel: () => {},
|
||||||
title: "",
|
title: "",
|
||||||
@@ -39,6 +54,7 @@ const useConfirmStore = create<ConfirmState>()((set) => ({
|
|||||||
set(() => ({
|
set(() => ({
|
||||||
visible: false,
|
visible: false,
|
||||||
message: "",
|
message: "",
|
||||||
|
content: undefined,
|
||||||
onConfirm: () => {},
|
onConfirm: () => {},
|
||||||
onCancel: () => {},
|
onCancel: () => {},
|
||||||
title: "",
|
title: "",
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
import {
|
||||||
|
NotificationFormMode,
|
||||||
|
CompanyNotificationPolicy,
|
||||||
|
ClientNotificationPreferences,
|
||||||
|
ClientCompanyNotificationOverride
|
||||||
|
} from "@models/NotificationPreferences.model";
|
||||||
|
|
||||||
|
interface NotificationPreferencesState {
|
||||||
|
mode: NotificationFormMode;
|
||||||
|
companyId: string;
|
||||||
|
clientId: string;
|
||||||
|
companyPolicy: CompanyNotificationPolicy | null;
|
||||||
|
clientPreferences: ClientNotificationPreferences | null;
|
||||||
|
clientOverride: ClientCompanyNotificationOverride | null;
|
||||||
|
formData: {
|
||||||
|
defaultChannels: string[];
|
||||||
|
preferredChannels: string[];
|
||||||
|
mutedChannels: string[];
|
||||||
|
timezone: string;
|
||||||
|
quietHours: { from: string; to: string } | null;
|
||||||
|
reminderRules: { offset: number; enabled: boolean }[];
|
||||||
|
};
|
||||||
|
isDirty: boolean;
|
||||||
|
loading: boolean;
|
||||||
|
setMode: (mode: NotificationFormMode) => void;
|
||||||
|
setCompanyId: (companyId: string) => void;
|
||||||
|
setClientId: (clientId: string) => void;
|
||||||
|
setCompanyPolicy: (policy: CompanyNotificationPolicy | null) => void;
|
||||||
|
setClientPreferences: (preferences: ClientNotificationPreferences | null) => void;
|
||||||
|
setClientOverride: (override: ClientCompanyNotificationOverride | null) => void;
|
||||||
|
updateFormData: (data: Partial<NotificationPreferencesState["formData"]>) => void;
|
||||||
|
setDirty: (dirty: boolean) => void;
|
||||||
|
setLoading: (loading: boolean) => void;
|
||||||
|
resetForm: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const initialFormData = {
|
||||||
|
defaultChannels: [],
|
||||||
|
preferredChannels: [],
|
||||||
|
mutedChannels: [],
|
||||||
|
timezone: "America/Argentina/Buenos_Aires",
|
||||||
|
quietHours: null,
|
||||||
|
reminderRules: []
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useNotificationPreferencesStore = create<NotificationPreferencesState>()((set) => ({
|
||||||
|
mode: "company-policy",
|
||||||
|
companyId: "",
|
||||||
|
clientId: "",
|
||||||
|
companyPolicy: null,
|
||||||
|
clientPreferences: null,
|
||||||
|
clientOverride: null,
|
||||||
|
formData: { ...initialFormData },
|
||||||
|
isDirty: false,
|
||||||
|
loading: false,
|
||||||
|
setMode: (mode) => set({ mode }),
|
||||||
|
setCompanyId: (companyId) => set({ companyId }),
|
||||||
|
setClientId: (clientId) => set({ clientId }),
|
||||||
|
setCompanyPolicy: (policy) => set({ companyPolicy: policy }),
|
||||||
|
setClientPreferences: (preferences) => set({ clientPreferences: preferences }),
|
||||||
|
setClientOverride: (override) => set({ clientOverride: override }),
|
||||||
|
updateFormData: (data) =>
|
||||||
|
set((state) => ({
|
||||||
|
formData: { ...state.formData, ...data },
|
||||||
|
isDirty: true
|
||||||
|
})),
|
||||||
|
setDirty: (dirty) => set({ isDirty: dirty }),
|
||||||
|
setLoading: (loading) => set({ loading }),
|
||||||
|
resetForm: () =>
|
||||||
|
set({
|
||||||
|
formData: { ...initialFormData },
|
||||||
|
isDirty: false
|
||||||
|
})
|
||||||
|
}));
|
||||||
+17
@@ -91,6 +91,23 @@ export const sendEmailNotification = async (
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const createImmediateNotificationJobs = async (
|
||||||
|
data: SendAppointmentNotificationParams
|
||||||
|
): Promise<ApiVoidResult> => {
|
||||||
|
return new Promise<ApiVoidResult>((resolve, reject) => {
|
||||||
|
schemaSendWapNotification
|
||||||
|
.validate(data, { abortEarly: true })
|
||||||
|
.then(() => {
|
||||||
|
resolve(
|
||||||
|
ApiRequest.post<ApiVoidResult>("appointments/create-immediate-notification-jobs", data)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
reject(new ApiError(500, error.message));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const schemaApplyDiscount = Yup.object().shape({
|
const schemaApplyDiscount = Yup.object().shape({
|
||||||
appointmentId: Yup.string().required("Debe seleccionar un turno."),
|
appointmentId: Yup.string().required("Debe seleccionar un turno."),
|
||||||
companyId: Yup.string().required("Organización no seleccionada."),
|
companyId: Yup.string().required("Organización no seleccionada."),
|
||||||
|
|||||||
+27
-66
@@ -9,11 +9,10 @@ import { useParams } from "next/navigation";
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import {
|
import {
|
||||||
applyAppointmentDiscount,
|
applyAppointmentDiscount,
|
||||||
|
createImmediateNotificationJobs,
|
||||||
deleteAppointment,
|
deleteAppointment,
|
||||||
deleteAppointmentDiscount,
|
deleteAppointmentDiscount,
|
||||||
findAppointmentsAdminByClient,
|
findAppointmentsAdminByClient,
|
||||||
sendEmailNotification,
|
|
||||||
sendWapNotification,
|
|
||||||
updateAppointment,
|
updateAppointment,
|
||||||
} from "../Appointments.Service";
|
} from "../Appointments.Service";
|
||||||
import {
|
import {
|
||||||
@@ -26,8 +25,7 @@ import {
|
|||||||
import { ChangeServiceParams } from "@models/Appointments.model";
|
import { ChangeServiceParams } from "@models/Appointments.model";
|
||||||
import Textbox from "@core/app/components/Textbox/Textbox";
|
import Textbox from "@core/app/components/Textbox/Textbox";
|
||||||
import { useMenuStore } from "@core/Store/Menu.Store";
|
import { useMenuStore } from "@core/Store/Menu.Store";
|
||||||
import WhatsAppIcon from "@mui/icons-material/WhatsApp";
|
import NotificationsActiveOutlinedIcon from "@mui/icons-material/NotificationsActiveOutlined";
|
||||||
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
|
|
||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
|
|
||||||
import Switch from "@mui/material/Switch";
|
import Switch from "@mui/material/Switch";
|
||||||
@@ -54,6 +52,8 @@ import filterObjects from "@components/TextObjectFilter/Filter.Service";
|
|||||||
|
|
||||||
import DialogWindow from "@core/app/components/DialogWindow/DialogWindow";
|
import DialogWindow from "@core/app/components/DialogWindow/DialogWindow";
|
||||||
import { DialogActions, DialogContent } from "@mui/material";
|
import { DialogActions, DialogContent } from "@mui/material";
|
||||||
|
import Checkbox from "@mui/material/Checkbox";
|
||||||
|
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||||
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
|
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
|
||||||
import { FindDiscountsParams } from "@core/Models/Discounts.model";
|
import { FindDiscountsParams } from "@core/Models/Discounts.model";
|
||||||
import DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
|
import DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
|
||||||
@@ -312,71 +312,19 @@ export default function ClientAppointment() {
|
|||||||
menu.clear();
|
menu.clear();
|
||||||
|
|
||||||
menu.add({
|
menu.add({
|
||||||
text: "Enviar recordatorio por Whatsapp",
|
text: "Enviar notificación de alta",
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
if (!appointmentId) {
|
if (!appointmentId) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
sendWapNotification({
|
createImmediateNotificationJobs({
|
||||||
appointmentId: appointmentId.toString(),
|
|
||||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
|
||||||
sessionUser: SessionUser.userId,
|
|
||||||
})
|
|
||||||
.then(() => {
|
|
||||||
alert.showSuccess("La notificatión fue enviada con éxito");
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
alert.showError(error.format());
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
icon: <WhatsAppIcon />,
|
|
||||||
});
|
|
||||||
|
|
||||||
menu.add({
|
|
||||||
text: "Enviar recordatorio por Email",
|
|
||||||
onClick: () => {
|
|
||||||
if (!appointmentId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
|
||||||
sendEmailNotification({
|
|
||||||
appointmentId: appointmentId.toString(),
|
|
||||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
|
||||||
sessionUser: SessionUser.userId,
|
|
||||||
})
|
|
||||||
.then(() => {
|
|
||||||
alert.showSuccess("La notificatión fue enviada con éxito");
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
alert.showError(error.format());
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
icon: <EmailOutlinedIcon />,
|
|
||||||
});
|
|
||||||
|
|
||||||
menu.divider();
|
|
||||||
|
|
||||||
menu.add({
|
|
||||||
text: "Enviar alta de turno por Whatsapp",
|
|
||||||
onClick: () => {
|
|
||||||
if (!appointmentId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
|
||||||
sendWapNotification({
|
|
||||||
appointmentId: appointmentId.toString(),
|
appointmentId: appointmentId.toString(),
|
||||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||||
sessionUser: SessionUser.userId,
|
sessionUser: SessionUser.userId,
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
alert.showSuccess("La notificatión fue enviada con éxito");
|
alert.showSuccess("La notificación fue encolada con éxito");
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
alert.showError(error.format());
|
alert.showError(error.format());
|
||||||
@@ -385,23 +333,23 @@ export default function ClientAppointment() {
|
|||||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
icon: <WhatsAppIcon />,
|
icon: <NotificationsActiveOutlinedIcon />,
|
||||||
});
|
});
|
||||||
|
|
||||||
menu.add({
|
menu.add({
|
||||||
text: "Enviar alta de turno por Email",
|
text: "Enviar recordatorio",
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
if (!appointmentId) {
|
if (!appointmentId) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
sendEmailNotification({
|
createImmediateNotificationJobs({
|
||||||
appointmentId: appointmentId.toString(),
|
appointmentId: appointmentId.toString(),
|
||||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||||
sessionUser: SessionUser.userId,
|
sessionUser: SessionUser.userId,
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
alert.showSuccess("La notificatión fue enviada con éxito");
|
alert.showSuccess("La notificación fue encolada con éxito");
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
alert.showError(error.format());
|
alert.showError(error.format());
|
||||||
@@ -410,7 +358,7 @@ export default function ClientAppointment() {
|
|||||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
icon: <EmailOutlinedIcon />,
|
icon: <NotificationsActiveOutlinedIcon />,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (showQuitDiscount) {
|
if (showQuitDiscount) {
|
||||||
@@ -593,12 +541,25 @@ export default function ClientAppointment() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
confirm.show(
|
let sendNotification = false;
|
||||||
|
|
||||||
|
confirm.showContent(
|
||||||
"Estas seguro que queres cancelar el turno?",
|
"Estas seguro que queres cancelar el turno?",
|
||||||
|
<FormControlLabel
|
||||||
|
control={
|
||||||
|
<Checkbox
|
||||||
|
onChange={(event) => {
|
||||||
|
sendNotification = event.target.checked;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
label="Enviar notificación al cliente"
|
||||||
|
/>,
|
||||||
() => {
|
() => {
|
||||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
deleteAppointment({
|
deleteAppointment({
|
||||||
id: appointmentId?.toString(),
|
id: appointmentId?.toString(),
|
||||||
|
notification: sendNotification,
|
||||||
sessionUser: SessionUser.userId,
|
sessionUser: SessionUser.userId,
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
|
|||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
.container {
|
||||||
|
margin-top: 32px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
width: min(100%, 900px);
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.channels {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(220px, 1fr) minmax(360px, 1fr);
|
||||||
|
gap: 16px;
|
||||||
|
align-items: center;
|
||||||
|
padding: 16px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
background-color: var(--bg-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.channelTitle {
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.channelDescription {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 13px;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.options {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.optionButton {
|
||||||
|
cursor: pointer;
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
background-color: var(--bg-primary);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 14px;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.optionButtonActive {
|
||||||
|
border-color: var(--primary-color);
|
||||||
|
background-color: rgba(25, 118, 210, 0.12);
|
||||||
|
color: var(--primary-color);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.card {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.container {
|
||||||
|
margin-top: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
padding: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.options {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
+82
@@ -0,0 +1,82 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useParams } from "next/navigation";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import Saveable from "@components/Saveable/Saveable";
|
||||||
|
import { useNotificationPreferencesStore } from "@store/NotificationPreferences.Store";
|
||||||
|
import { useSessionStore } from "@store/Sesion.Store";
|
||||||
|
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
|
||||||
|
import { useAlert } from "@store/Alert.Store";
|
||||||
|
import { getClientCompanyOverride, upsertClientCompanyOverride } from "@services/Notifications.Service";
|
||||||
|
import { NotificationChannel } from "@models/NotificationPreferences.model";
|
||||||
|
|
||||||
|
type UrlData = {
|
||||||
|
oid: string;
|
||||||
|
clientId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function NotificationsLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
const data = useParams<UrlData>();
|
||||||
|
const oid = data.oid;
|
||||||
|
const clientId = data.clientId;
|
||||||
|
const store = useNotificationPreferencesStore();
|
||||||
|
const SessionInfo = useSessionStore();
|
||||||
|
const eventHandler = useEventHandlerStore();
|
||||||
|
const alert = useAlert();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!SessionInfo.userId || !oid || !clientId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
store.setCompanyId(oid);
|
||||||
|
store.setClientId(clientId);
|
||||||
|
store.setMode("client-override");
|
||||||
|
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
|
getClientCompanyOverride(clientId, oid, SessionInfo.userId)
|
||||||
|
.then((override) => {
|
||||||
|
store.setClientOverride(override);
|
||||||
|
store.updateFormData({
|
||||||
|
preferredChannels: override.preferredChannels || [],
|
||||||
|
mutedChannels: override.mutedChannels || []
|
||||||
|
});
|
||||||
|
store.setDirty(false);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert.showError(error.format());
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
|
});
|
||||||
|
}, [SessionInfo.userId, oid, clientId]);
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
|
upsertClientCompanyOverride(clientId, oid, SessionInfo.userId, {
|
||||||
|
preferredChannels: store.formData.preferredChannels as NotificationChannel[],
|
||||||
|
mutedChannels: store.formData.mutedChannels as NotificationChannel[]
|
||||||
|
})
|
||||||
|
.then((override) => {
|
||||||
|
store.setClientOverride(override);
|
||||||
|
store.setDirty(false);
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert.showError(error.format());
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (store.isDirty) {
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||||
|
}
|
||||||
|
}, [store.isDirty]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Saveable onClick={handleSave}>
|
||||||
|
{children}
|
||||||
|
</Saveable>
|
||||||
|
);
|
||||||
|
}
|
||||||
+139
@@ -0,0 +1,139 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useParams } from "next/navigation";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import Location from "@components/Location/Location";
|
||||||
|
import { useLocationStore } from "@store/Location.Store";
|
||||||
|
import { useNotificationPreferencesStore } from "@store/NotificationPreferences.Store";
|
||||||
|
import { NotificationChannel } from "@models/NotificationPreferences.model";
|
||||||
|
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
|
||||||
|
import ClientsIcon from "@mui/icons-material/AccountBoxOutlined";
|
||||||
|
import NotificationsIcon from "@mui/icons-material/NotificationsOutlined";
|
||||||
|
import MaterialAlert from "@mui/material/Alert";
|
||||||
|
import styles from "./NotificationsPage.module.css";
|
||||||
|
|
||||||
|
type UrlData = {
|
||||||
|
oid: string;
|
||||||
|
clientId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CHANNELS: { key: NotificationChannel; label: string }[] = [
|
||||||
|
{ key: "whatsapp", label: "WhatsApp" },
|
||||||
|
{ key: "email", label: "Email" },
|
||||||
|
{ key: "system", label: "Sistema" }
|
||||||
|
];
|
||||||
|
|
||||||
|
type ChannelPreference = "default" | "preferred" | "muted";
|
||||||
|
|
||||||
|
export default function NotificationsPage() {
|
||||||
|
const data = useParams<UrlData>();
|
||||||
|
const oid = data.oid;
|
||||||
|
const clientId = data.clientId;
|
||||||
|
const location = useLocationStore();
|
||||||
|
const store = useNotificationPreferencesStore();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
location.clear();
|
||||||
|
|
||||||
|
location.add({
|
||||||
|
url: "/admin/org",
|
||||||
|
title: "Organizaciones",
|
||||||
|
icon: null
|
||||||
|
});
|
||||||
|
|
||||||
|
location.add({
|
||||||
|
url: "/admin/org/profile/" + oid,
|
||||||
|
title: "Organización",
|
||||||
|
icon: <StorefrontOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||||
|
});
|
||||||
|
|
||||||
|
location.add({
|
||||||
|
url: "/admin/org/" + oid + "/client/" + clientId + "/profile",
|
||||||
|
title: "Cliente",
|
||||||
|
icon: <ClientsIcon sx={{ fontSize: "32px", mr: "10px" }} />
|
||||||
|
});
|
||||||
|
|
||||||
|
location.add({
|
||||||
|
url: "",
|
||||||
|
title: "Notificaciones",
|
||||||
|
icon: <NotificationsIcon sx={{ fontSize: "32px", mr: "10px" }} />
|
||||||
|
});
|
||||||
|
}, [oid, clientId]);
|
||||||
|
|
||||||
|
const getChannelPreference = (channel: NotificationChannel): ChannelPreference => {
|
||||||
|
if (store.formData.mutedChannels.includes(channel)) {
|
||||||
|
return "muted";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (store.formData.preferredChannels.includes(channel)) {
|
||||||
|
return "preferred";
|
||||||
|
}
|
||||||
|
|
||||||
|
return "default";
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectPreference = (channel: NotificationChannel, preference: ChannelPreference) => {
|
||||||
|
store.updateFormData({
|
||||||
|
preferredChannels:
|
||||||
|
preference === "preferred"
|
||||||
|
? [...store.formData.preferredChannels.filter((c) => c !== channel), channel]
|
||||||
|
: store.formData.preferredChannels.filter((c) => c !== channel),
|
||||||
|
mutedChannels:
|
||||||
|
preference === "muted"
|
||||||
|
? [...store.formData.mutedChannels.filter((c) => c !== channel), channel]
|
||||||
|
: store.formData.mutedChannels.filter((c) => c !== channel)
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Location />
|
||||||
|
|
||||||
|
<div className={styles.container}>
|
||||||
|
<MaterialAlert severity="info" sx={{ marginBottom: "0" }}>
|
||||||
|
<b>Preferencias del cliente:</b> Configure cómo esta organización debe comunicarse con este cliente. Si deja un canal en estándar, se usará la política general de la organización.
|
||||||
|
</MaterialAlert>
|
||||||
|
|
||||||
|
<div className={styles.channels}>
|
||||||
|
{CHANNELS.map((channel) => {
|
||||||
|
const selectedPreference = getChannelPreference(channel.key);
|
||||||
|
return (
|
||||||
|
<div key={channel.key} className={styles.card}>
|
||||||
|
<div>
|
||||||
|
<div className={styles.channelTitle}>{channel.label}</div>
|
||||||
|
<div className={styles.channelDescription}>
|
||||||
|
{selectedPreference === "preferred" && "Priorizar este canal para el cliente."}
|
||||||
|
{selectedPreference === "muted" && "No enviar notificaciones por este canal."}
|
||||||
|
{selectedPreference === "default" && "Usar la configuración general de la organización."}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className={styles.options}>
|
||||||
|
{[
|
||||||
|
{ key: "default" as ChannelPreference, label: "Estándar" },
|
||||||
|
{ key: "preferred" as ChannelPreference, label: "Preferido" },
|
||||||
|
{ key: "muted" as ChannelPreference, label: "Silenciado" }
|
||||||
|
].map((option) => {
|
||||||
|
const isSelected = selectedPreference === option.key;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={option.key}
|
||||||
|
type="button"
|
||||||
|
onClick={() => selectPreference(channel.key, option.key)}
|
||||||
|
className={`${styles.optionButton} ${isSelected ? styles.optionButtonActive : ""}`}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ marginBottom: "40px" }}> </div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import ButtonOption from "@components/ButtonOption/ButtonOption";
|
|||||||
import Location from "@components/Location/Location";
|
import Location from "@components/Location/Location";
|
||||||
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
|
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
|
||||||
import ClientsIcon from "@mui/icons-material/AccountBoxOutlined";
|
import ClientsIcon from "@mui/icons-material/AccountBoxOutlined";
|
||||||
|
import NotificationsIcon from "@mui/icons-material/Notifications";
|
||||||
import { useLocationStore } from "@store/Location.Store";
|
import { useLocationStore } from "@store/Location.Store";
|
||||||
import { useNavigation } from "@hooks/goto";
|
import { useNavigation } from "@hooks/goto";
|
||||||
import { useParams } from "next/navigation";
|
import { useParams } from "next/navigation";
|
||||||
@@ -120,6 +121,19 @@ export default function ClientProfile() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<ButtonOption
|
||||||
|
text="Notificaciones"
|
||||||
|
icon="/notifications-icon.svg"
|
||||||
|
onClick={() =>
|
||||||
|
goTo(
|
||||||
|
"/admin/org/" +
|
||||||
|
oid +
|
||||||
|
"/client/" +
|
||||||
|
clientId +
|
||||||
|
"/notifications"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -148,6 +148,10 @@ export default function OrganizationEdit() {
|
|||||||
TextObjectFilterResult[]
|
TextObjectFilterResult[]
|
||||||
>([]);
|
>([]);
|
||||||
const [templateWapAltaId, setTemplateWapAltaId] = useState<string>("");
|
const [templateWapAltaId, setTemplateWapAltaId] = useState<string>("");
|
||||||
|
const [templateWapCancellationFilterData, setTemplateWapCancellationFilterData] = useState<
|
||||||
|
TextObjectFilterResult[]
|
||||||
|
>([]);
|
||||||
|
const [templateWapCancellationId, setTemplateWapCancellationId] = useState<string>("");
|
||||||
|
|
||||||
const loadTemplatesCombos = () => {
|
const loadTemplatesCombos = () => {
|
||||||
if (!SessionInfo.userId) return;
|
if (!SessionInfo.userId) return;
|
||||||
@@ -168,6 +172,7 @@ export default function OrganizationEdit() {
|
|||||||
};
|
};
|
||||||
filterObjects<FindTemplatesParams>("templates/filter-all", filter).then((res) => {
|
filterObjects<FindTemplatesParams>("templates/filter-all", filter).then((res) => {
|
||||||
setTemplateWapAltaFilterData(res);
|
setTemplateWapAltaFilterData(res);
|
||||||
|
setTemplateWapCancellationFilterData(res);
|
||||||
setCombosLoaded(true);
|
setCombosLoaded(true);
|
||||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
});
|
});
|
||||||
@@ -222,6 +227,7 @@ export default function OrganizationEdit() {
|
|||||||
requestAnimationFrame(() => {
|
requestAnimationFrame(() => {
|
||||||
setTemplateWapNotifId(response.templateWapNotifId);
|
setTemplateWapNotifId(response.templateWapNotifId);
|
||||||
setTemplateWapAltaId(response.templateWapAltaId);
|
setTemplateWapAltaId(response.templateWapAltaId);
|
||||||
|
setTemplateWapCancellationId(response.templateWapCancellationId);
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
@@ -263,6 +269,7 @@ export default function OrganizationEdit() {
|
|||||||
phoneNumber: phone,
|
phoneNumber: phone,
|
||||||
templateWapNotifId: templateWapNotifId === "" ? undefined : templateWapNotifId,
|
templateWapNotifId: templateWapNotifId === "" ? undefined : templateWapNotifId,
|
||||||
templateWapAltaId: templateWapAltaId === "" ? undefined : templateWapAltaId,
|
templateWapAltaId: templateWapAltaId === "" ? undefined : templateWapAltaId,
|
||||||
|
templateWapCancellationId: templateWapCancellationId === "" ? undefined : templateWapCancellationId,
|
||||||
};
|
};
|
||||||
|
|
||||||
const schema = Yup.object().shape({
|
const schema = Yup.object().shape({
|
||||||
@@ -317,8 +324,10 @@ export default function OrganizationEdit() {
|
|||||||
.positive("El Plazo Mínimo de Cancelación debe ser un número positivo."),
|
.positive("El Plazo Mínimo de Cancelación debe ser un número positivo."),
|
||||||
templateWapNotifId: Yup.string().optional().default(""),
|
templateWapNotifId: Yup.string().optional().default(""),
|
||||||
templateWapAltaId: Yup.string().optional().default(""),
|
templateWapAltaId: Yup.string().optional().default(""),
|
||||||
|
templateWapCancellationId: Yup.string().optional().default(""),
|
||||||
templateEmailNotifId: Yup.string().optional().default(""),
|
templateEmailNotifId: Yup.string().optional().default(""),
|
||||||
templateEmailAltaId: Yup.string().optional().default(""),
|
templateEmailAltaId: Yup.string().optional().default(""),
|
||||||
|
templateEmailCancellationId: Yup.string().optional().default(""),
|
||||||
});
|
});
|
||||||
|
|
||||||
schema
|
schema
|
||||||
@@ -603,6 +612,17 @@ export default function OrganizationEdit() {
|
|||||||
selectedId={templateWapAltaId}
|
selectedId={templateWapAltaId}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<TextObjectFilter
|
||||||
|
placeholder="Cancelación de Reservas"
|
||||||
|
content={templateWapAltaFilterContent}
|
||||||
|
data={templateWapCancellationFilterData}
|
||||||
|
onChange={(id) => {
|
||||||
|
setTemplateWapCancellationId(id);
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||||
|
}}
|
||||||
|
selectedId={templateWapCancellationId}
|
||||||
|
/>
|
||||||
|
|
||||||
<div style={{ marginBottom: "10px" }}> </div>
|
<div style={{ marginBottom: "10px" }}> </div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
+83
@@ -0,0 +1,83 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useParams } from "next/navigation";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import Saveable from "@components/Saveable/Saveable";
|
||||||
|
import { useNotificationPreferencesStore } from "@store/NotificationPreferences.Store";
|
||||||
|
import { useSessionStore } from "@store/Sesion.Store";
|
||||||
|
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
|
||||||
|
import { useAlert } from "@store/Alert.Store";
|
||||||
|
import { getCompanyPolicy, upsertCompanyPolicy } from "@services/Notifications.Service";
|
||||||
|
import { NotificationChannel } from "@models/NotificationPreferences.model";
|
||||||
|
|
||||||
|
type UrlData = {
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function NotificationsLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
const data = useParams<UrlData>();
|
||||||
|
const id = data.id;
|
||||||
|
const store = useNotificationPreferencesStore();
|
||||||
|
const SessionInfo = useSessionStore();
|
||||||
|
const eventHandler = useEventHandlerStore();
|
||||||
|
const alert = useAlert();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!SessionInfo.userId || !id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
store.setCompanyId(id);
|
||||||
|
store.setMode("company-policy");
|
||||||
|
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
|
getCompanyPolicy(id, SessionInfo.userId)
|
||||||
|
.then((policy) => {
|
||||||
|
store.setCompanyPolicy(policy);
|
||||||
|
store.updateFormData({
|
||||||
|
defaultChannels: policy.defaultChannels || [],
|
||||||
|
mutedChannels: policy.mutedChannels || [],
|
||||||
|
quietHours: policy.quietHours || null,
|
||||||
|
reminderRules: policy.reminderRules || []
|
||||||
|
});
|
||||||
|
store.setDirty(false);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert.showError(error.format());
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
|
});
|
||||||
|
}, [SessionInfo.userId, id]);
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
|
upsertCompanyPolicy(id, SessionInfo.userId, {
|
||||||
|
defaultChannels: store.formData.defaultChannels as NotificationChannel[],
|
||||||
|
timezone: "America/Argentina/Buenos_Aires",
|
||||||
|
quietHours: store.formData.quietHours || undefined,
|
||||||
|
reminderRules: store.formData.reminderRules
|
||||||
|
})
|
||||||
|
.then((policy) => {
|
||||||
|
store.setCompanyPolicy(policy);
|
||||||
|
store.setDirty(false);
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert.showError(error.format());
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (store.isDirty) {
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||||
|
}
|
||||||
|
}, [store.isDirty]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Saveable onClick={handleSave}>
|
||||||
|
{children}
|
||||||
|
</Saveable>
|
||||||
|
);
|
||||||
|
}
|
||||||
+215
@@ -0,0 +1,215 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useParams } from "next/navigation";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import Location from "@components/Location/Location";
|
||||||
|
import TextTime from "@components/TextTime/TextTime";
|
||||||
|
import { useLocationStore } from "@store/Location.Store";
|
||||||
|
import { useNotificationPreferencesStore } from "@store/NotificationPreferences.Store";
|
||||||
|
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
|
||||||
|
import { NotificationChannel } from "@models/NotificationPreferences.model";
|
||||||
|
import Switch from "@core/app/components/Switch/Switch";
|
||||||
|
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
|
||||||
|
import NotificationsIcon from "@mui/icons-material/NotificationsOutlined";
|
||||||
|
import MaterialAlert from "@mui/material/Alert";
|
||||||
|
import dayjs from "dayjs";
|
||||||
|
|
||||||
|
type UrlData = {
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CHANNELS: { key: NotificationChannel; label: string }[] = [
|
||||||
|
{ key: "whatsapp", label: "WhatsApp" },
|
||||||
|
{ key: "email", label: "Email" },
|
||||||
|
{ key: "system", label: "Sistema" }
|
||||||
|
];
|
||||||
|
|
||||||
|
const REMINDER_PRESETS: { minutes: number; label: string }[] = [
|
||||||
|
{ minutes: 2, label: "2 minutos antes" },
|
||||||
|
{ minutes: 5, label: "5 minutos antes" },
|
||||||
|
{ minutes: 10, label: "10 minutos antes" }
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function NotificationsPage() {
|
||||||
|
const data = useParams<UrlData>();
|
||||||
|
const id = data.id;
|
||||||
|
const location = useLocationStore();
|
||||||
|
const store = useNotificationPreferencesStore();
|
||||||
|
const eventHandler = useEventHandlerStore();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
location.clear();
|
||||||
|
|
||||||
|
location.add({
|
||||||
|
url: "/admin/org",
|
||||||
|
title: "Organizaciones",
|
||||||
|
icon: null
|
||||||
|
});
|
||||||
|
|
||||||
|
location.add({
|
||||||
|
url: "/admin/org/profile/" + id,
|
||||||
|
title: "Perfil",
|
||||||
|
icon: <StorefrontOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />
|
||||||
|
});
|
||||||
|
|
||||||
|
location.add({
|
||||||
|
url: "/admin/org/profile/" + id + "/notifications",
|
||||||
|
title: "Notificaciones",
|
||||||
|
icon: <NotificationsIcon sx={{ fontSize: "32px", mr: "10px" }} />
|
||||||
|
});
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
const toggleChannel = (channel: NotificationChannel) => {
|
||||||
|
const current = store.formData.defaultChannels;
|
||||||
|
const updated = current.includes(channel)
|
||||||
|
? current.filter((c) => c !== channel)
|
||||||
|
: [...current, channel];
|
||||||
|
store.updateFormData({ defaultChannels: updated });
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateQuietHours = (field: "from" | "to", value: string) => {
|
||||||
|
const current = store.formData.quietHours || { from: "00:00", to: "00:00" };
|
||||||
|
store.updateFormData({
|
||||||
|
quietHours: { ...current, [field]: value }
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const quietHourValue = (value: string | undefined, fallback: string) => {
|
||||||
|
const [hour, minute] = (value || fallback).split(":").map(Number);
|
||||||
|
return dayjs(new Date()).hour(hour).minute(minute || 0).second(0).millisecond(0);
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleQuietHours = () => {
|
||||||
|
store.updateFormData({
|
||||||
|
quietHours: store.formData.quietHours ? null : { from: "22:00", to: "08:00" }
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleReminder = (minutes: number) => {
|
||||||
|
const exists = store.formData.reminderRules.some((r) => r.offset === minutes);
|
||||||
|
if (exists) {
|
||||||
|
const updated = store.formData.reminderRules.filter((r) => r.offset !== minutes);
|
||||||
|
store.updateFormData({ reminderRules: updated });
|
||||||
|
} else {
|
||||||
|
store.updateFormData({
|
||||||
|
reminderRules: [...store.formData.reminderRules, { offset: minutes, enabled: true }]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Location />
|
||||||
|
|
||||||
|
<div style={{ marginTop: "20px" }}>
|
||||||
|
{/* Channel Toggles Section */}
|
||||||
|
<MaterialAlert severity="info" sx={{ marginBottom: "20px" }}>
|
||||||
|
<b>Canales de notificación:</b> Seleccione los canales por los cuales se enviarán las notificaciones automáticas.
|
||||||
|
</MaterialAlert>
|
||||||
|
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: "8px", marginBottom: "30px" }}>
|
||||||
|
{CHANNELS.map((channel) => (
|
||||||
|
<div
|
||||||
|
key={channel.key}
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
|
padding: "12px 16px",
|
||||||
|
borderRadius: "4px",
|
||||||
|
border: "1px solid var(--border-color)",
|
||||||
|
backgroundColor: "var(--bg-primary)"
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ color: "var(--text-primary)", fontWeight: "500" }}>{channel.label}</span>
|
||||||
|
<Switch
|
||||||
|
checked={store.formData.defaultChannels.includes(channel.key)}
|
||||||
|
onChange={() => toggleChannel(channel.key)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Quiet Hours Section */}
|
||||||
|
<MaterialAlert severity="info" sx={{ marginBottom: "20px" }}>
|
||||||
|
<b>Horario silencioso:</b> Las notificaciones no se enviarán durante este rango horario.
|
||||||
|
</MaterialAlert>
|
||||||
|
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
|
padding: "12px 16px",
|
||||||
|
borderRadius: "8px",
|
||||||
|
border: "1px solid var(--border-color)",
|
||||||
|
backgroundColor: "var(--bg-primary)",
|
||||||
|
marginBottom: "16px"
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ color: "var(--text-primary)", fontWeight: "500" }}>
|
||||||
|
Activar horario silencioso
|
||||||
|
</span>
|
||||||
|
<Switch
|
||||||
|
checked={Boolean(store.formData.quietHours)}
|
||||||
|
onChange={toggleQuietHours}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{store.formData.quietHours && (
|
||||||
|
<div style={{ display: "flex", gap: "16px", alignItems: "flex-end", marginBottom: "30px" }}>
|
||||||
|
<div style={{ flex: 1 }}>
|
||||||
|
<TextTime
|
||||||
|
placeholder="Desde"
|
||||||
|
width="100%"
|
||||||
|
value={quietHourValue(store.formData.quietHours.from, "22:00")}
|
||||||
|
onChange={(value) => updateQuietHours("from", value.format("HH:mm"))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div style={{ flex: 1 }}>
|
||||||
|
<TextTime
|
||||||
|
placeholder="Hasta"
|
||||||
|
width="100%"
|
||||||
|
value={quietHourValue(store.formData.quietHours.to, "08:00")}
|
||||||
|
onChange={(value) => updateQuietHours("to", value.format("HH:mm"))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Reminder Rules Section */}
|
||||||
|
<MaterialAlert severity="info" sx={{ marginBottom: "20px" }}>
|
||||||
|
<b>Reglas de recordatorio:</b> Active los momentos en los que desea enviar recordatorios antes del turno.
|
||||||
|
</MaterialAlert>
|
||||||
|
|
||||||
|
<div style={{ display: "flex", flexWrap: "wrap", gap: "10px" }}>
|
||||||
|
{REMINDER_PRESETS.map((preset) => {
|
||||||
|
const isActive = store.formData.reminderRules.some((r) => r.offset === preset.minutes);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={preset.minutes}
|
||||||
|
type="button"
|
||||||
|
onClick={() => toggleReminder(preset.minutes)}
|
||||||
|
style={{
|
||||||
|
cursor: "pointer",
|
||||||
|
padding: "10px 16px",
|
||||||
|
borderRadius: "999px",
|
||||||
|
border: `1px solid ${isActive ? "var(--primary-color)" : "var(--border-color)"}`,
|
||||||
|
backgroundColor: isActive ? "rgba(25, 118, 210, 0.12)" : "var(--bg-primary)",
|
||||||
|
color: isActive ? "var(--primary-color)" : "var(--text-secondary)",
|
||||||
|
fontWeight: isActive ? "600" : "500",
|
||||||
|
fontSize: "14px",
|
||||||
|
transition: "all 0.2s ease"
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{preset.label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ marginBottom: "40px" }}> </div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -20,6 +20,7 @@ import CashIcon from "@mui/icons-material/AccountBalanceOutlined";
|
|||||||
import DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
|
import DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
|
||||||
import TemplatesIcon from "@mui/icons-material/SpeakerNotesOutlined";
|
import TemplatesIcon from "@mui/icons-material/SpeakerNotesOutlined";
|
||||||
import AssistanceIcon from "@mui/icons-material/HeadsetMicOutlined";
|
import AssistanceIcon from "@mui/icons-material/HeadsetMicOutlined";
|
||||||
|
import NotificationsOutlinedIcon from "@mui/icons-material/NotificationsOutlined";
|
||||||
import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
|
import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
|
||||||
import Dialog from "@mui/material/Dialog";
|
import Dialog from "@mui/material/Dialog";
|
||||||
import DialogContent from "@mui/material/DialogContent";
|
import DialogContent from "@mui/material/DialogContent";
|
||||||
@@ -88,6 +89,11 @@ export default function OrganizationProfile() {
|
|||||||
text: "WhatsApp",
|
text: "WhatsApp",
|
||||||
onClick: () => goTo("/admin/org/profile/" + id + "/wap"),
|
onClick: () => goTo("/admin/org/profile/" + id + "/wap"),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
icon: <NotificationsOutlinedIcon />,
|
||||||
|
text: "Notificaciones",
|
||||||
|
onClick: () => goTo("/admin/org/profile/" + id + "/notifications"),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
icon: <CategoryOutlinedIcon />,
|
icon: <CategoryOutlinedIcon />,
|
||||||
text: "Servicios",
|
text: "Servicios",
|
||||||
|
|||||||
+2
-1
@@ -197,7 +197,7 @@ export default function TemplateCreate() {
|
|||||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
getDefaultTemplate({
|
getDefaultTemplate({
|
||||||
companyId: id,
|
companyId: id,
|
||||||
type: type,
|
type: typeRef.current,
|
||||||
sessionUser: SessionInfo.userId,
|
sessionUser: SessionInfo.userId,
|
||||||
})
|
})
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
@@ -267,6 +267,7 @@ export default function TemplateCreate() {
|
|||||||
data={[
|
data={[
|
||||||
{ id: TemplateTypes.WAP_REMINDER, text: "WhatsApp - Recordatorio" },
|
{ id: TemplateTypes.WAP_REMINDER, text: "WhatsApp - Recordatorio" },
|
||||||
{ id: TemplateTypes.WAP_NEW_APPOINTMENT, text: "WhatsApp - Nueva reserva" },
|
{ id: TemplateTypes.WAP_NEW_APPOINTMENT, text: "WhatsApp - Nueva reserva" },
|
||||||
|
{ id: TemplateTypes.WAP_CANCELLATION, text: "WhatsApp - Cancelación" },
|
||||||
]}
|
]}
|
||||||
setSelectedValue={(value) => {
|
setSelectedValue={(value) => {
|
||||||
setType(value as TemplateTypes);
|
setType(value as TemplateTypes);
|
||||||
|
|||||||
@@ -37,10 +37,14 @@ export default function TemplatesGrid() {
|
|||||||
return "WhatsApp - Nueva reserva";
|
return "WhatsApp - Nueva reserva";
|
||||||
case TemplateTypes.WAP_REMINDER:
|
case TemplateTypes.WAP_REMINDER:
|
||||||
return "WhatsApp - Recordatorio";
|
return "WhatsApp - Recordatorio";
|
||||||
|
case TemplateTypes.WAP_CANCELLATION:
|
||||||
|
return "WhatsApp - Cancelación";
|
||||||
case TemplateTypes.EMAIL_NEW_APPOINTMENT:
|
case TemplateTypes.EMAIL_NEW_APPOINTMENT:
|
||||||
return "Email - Nueva reserva";
|
return "Email - Nueva reserva";
|
||||||
case TemplateTypes.EMAIL_REMINDER:
|
case TemplateTypes.EMAIL_REMINDER:
|
||||||
return "Email - Recordatorio";
|
return "Email - Recordatorio";
|
||||||
|
case TemplateTypes.EMAIL_CANCELLATION:
|
||||||
|
return "Email - Cancelación";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ export default function ConfirmDialog() {
|
|||||||
<DialogContentText id="alert-dialog-description">
|
<DialogContentText id="alert-dialog-description">
|
||||||
{confirm.message}
|
{confirm.message}
|
||||||
</DialogContentText>
|
</DialogContentText>
|
||||||
|
{confirm.content}
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={handleCancell}>Cancelar</Button>
|
<Button onClick={handleCancell}>Cancelar</Button>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
useOrganizationHeaderStore,
|
useOrganizationHeaderStore,
|
||||||
} from "@store/OrganizationHeader.Store";
|
} from "@store/OrganizationHeader.Store";
|
||||||
import SettingsIcon from "@mui/icons-material/Settings";
|
import SettingsIcon from "@mui/icons-material/Settings";
|
||||||
|
import NotificationsIcon from "@mui/icons-material/Notifications";
|
||||||
import classNames from "classnames";
|
import classNames from "classnames";
|
||||||
import { useNavigation } from "@core/app/hooks/goto";
|
import { useNavigation } from "@core/app/hooks/goto";
|
||||||
|
|
||||||
@@ -68,6 +69,14 @@ export default function OrganizationHeader(props: OrganizationHeaderParams): Rea
|
|||||||
icon: <ShareOutlinedIcon />,
|
icon: <ShareOutlinedIcon />,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
menu.add({
|
||||||
|
text: "Notificaciones",
|
||||||
|
onClick: () => {
|
||||||
|
goTo("/admin/org/profile/" + props.data.id + "/notifications");
|
||||||
|
},
|
||||||
|
icon: <NotificationsIcon />,
|
||||||
|
});
|
||||||
|
|
||||||
menu.divider();
|
menu.divider();
|
||||||
|
|
||||||
menu.add({
|
menu.add({
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ export default function OrganizationPublicProfile() {
|
|||||||
const data: DeleteAppointmentParams = {
|
const data: DeleteAppointmentParams = {
|
||||||
id: aid,
|
id: aid,
|
||||||
validation: true,
|
validation: true,
|
||||||
|
notification: true,
|
||||||
sessionUser: SessionInfo.userId,
|
sessionUser: SessionInfo.userId,
|
||||||
};
|
};
|
||||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
|
|||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
.container {
|
||||||
|
margin-top: 32px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
width: min(100%, 900px);
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.channels {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(220px, 1fr) minmax(360px, 1fr);
|
||||||
|
gap: 16px;
|
||||||
|
align-items: center;
|
||||||
|
padding: 16px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
background-color: var(--bg-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.channelTitle {
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.channelDescription {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 13px;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.options {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.optionButton {
|
||||||
|
cursor: pointer;
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
background-color: var(--bg-primary);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 14px;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.optionButtonActive {
|
||||||
|
border-color: var(--primary-color);
|
||||||
|
background-color: rgba(25, 118, 210, 0.12);
|
||||||
|
color: var(--primary-color);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.saveButton {
|
||||||
|
align-self: flex-end;
|
||||||
|
padding: 12px 24px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: none;
|
||||||
|
background-color: var(--primary-color);
|
||||||
|
color: white;
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.card {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.container {
|
||||||
|
margin-top: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
padding: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.options {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.saveButton {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Saveable from "@components/Saveable/Saveable";
|
||||||
|
|
||||||
|
export default function NotificationsPreferencesLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return <Saveable>{children}</Saveable>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import Location from "@components/Location/Location";
|
||||||
|
import { useLocationStore } from "@store/Location.Store";
|
||||||
|
import { useNotificationPreferencesStore } from "@store/NotificationPreferences.Store";
|
||||||
|
import { useSessionStore } from "@store/Sesion.Store";
|
||||||
|
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
|
||||||
|
import { useAlert } from "@store/Alert.Store";
|
||||||
|
import { getClientPreferences, upsertClientPreferences } from "@services/Notifications.Service";
|
||||||
|
import { NotificationChannel } from "@models/NotificationPreferences.model";
|
||||||
|
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
|
||||||
|
import NotificationsIcon from "@mui/icons-material/NotificationsOutlined";
|
||||||
|
import MaterialAlert from "@mui/material/Alert";
|
||||||
|
import styles from "./NotificationsPreferencesPage.module.css";
|
||||||
|
|
||||||
|
const CHANNELS: { key: NotificationChannel; label: string }[] = [
|
||||||
|
{ key: "whatsapp", label: "WhatsApp" },
|
||||||
|
{ key: "email", label: "Email" },
|
||||||
|
{ key: "system", label: "Sistema" }
|
||||||
|
];
|
||||||
|
|
||||||
|
type ChannelPreference = "default" | "preferred" | "muted";
|
||||||
|
|
||||||
|
export default function NotificationsPreferencesPage() {
|
||||||
|
const location = useLocationStore();
|
||||||
|
const store = useNotificationPreferencesStore();
|
||||||
|
const SessionInfo = useSessionStore();
|
||||||
|
const eventHandler = useEventHandlerStore();
|
||||||
|
const alert = useAlert();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
location.clear();
|
||||||
|
|
||||||
|
location.add({
|
||||||
|
url: "/user/profile",
|
||||||
|
title: "Perfil de usuario",
|
||||||
|
icon: <AccountCircleOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />
|
||||||
|
});
|
||||||
|
|
||||||
|
location.add({
|
||||||
|
url: "",
|
||||||
|
title: "Preferencias de notificación",
|
||||||
|
icon: <NotificationsIcon sx={{ fontSize: "32px", mr: "10px" }} />
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!SessionInfo.userId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
store.setClientId(SessionInfo.userId);
|
||||||
|
store.setMode("client-preferences");
|
||||||
|
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
|
getClientPreferences(SessionInfo.userId, SessionInfo.userId)
|
||||||
|
.then((preferences) => {
|
||||||
|
store.setClientPreferences(preferences);
|
||||||
|
store.updateFormData({
|
||||||
|
preferredChannels: preferences.preferredChannels || [],
|
||||||
|
mutedChannels: preferences.mutedChannels || []
|
||||||
|
});
|
||||||
|
store.setDirty(false);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert.showError(error.format());
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
|
});
|
||||||
|
}, [SessionInfo.userId]);
|
||||||
|
|
||||||
|
const getChannelPreference = (channel: NotificationChannel): ChannelPreference => {
|
||||||
|
if (store.formData.mutedChannels.includes(channel)) {
|
||||||
|
return "muted";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (store.formData.preferredChannels.includes(channel)) {
|
||||||
|
return "preferred";
|
||||||
|
}
|
||||||
|
|
||||||
|
return "default";
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectPreference = (channel: NotificationChannel, preference: ChannelPreference) => {
|
||||||
|
store.updateFormData({
|
||||||
|
preferredChannels:
|
||||||
|
preference === "preferred"
|
||||||
|
? [...store.formData.preferredChannels.filter((c) => c !== channel), channel]
|
||||||
|
: store.formData.preferredChannels.filter((c) => c !== channel),
|
||||||
|
mutedChannels:
|
||||||
|
preference === "muted"
|
||||||
|
? [...store.formData.mutedChannels.filter((c) => c !== channel), channel]
|
||||||
|
: store.formData.mutedChannels.filter((c) => c !== channel)
|
||||||
|
});
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||||
|
upsertClientPreferences(SessionInfo.userId, SessionInfo.userId, {
|
||||||
|
preferredChannels: store.formData.preferredChannels as NotificationChannel[],
|
||||||
|
mutedChannels: store.formData.mutedChannels as NotificationChannel[]
|
||||||
|
})
|
||||||
|
.then((preferences) => {
|
||||||
|
store.setClientPreferences(preferences);
|
||||||
|
store.setDirty(false);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert.showError(error.format());
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (eventHandler.eventType === EVENT_TYPES.SAVE) {
|
||||||
|
handleSave();
|
||||||
|
}
|
||||||
|
}, [eventHandler.eventType]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Location />
|
||||||
|
|
||||||
|
<div className={styles.container}>
|
||||||
|
<MaterialAlert severity="info" sx={{ marginBottom: "0" }}>
|
||||||
|
<b>Preferencias globales:</b> Configure cómo prefiere recibir notificaciones. Si deja un canal en estándar, cada organización podrá usar su configuración general.
|
||||||
|
</MaterialAlert>
|
||||||
|
|
||||||
|
<div className={styles.channels}>
|
||||||
|
{CHANNELS.map((channel) => {
|
||||||
|
const selectedPreference = getChannelPreference(channel.key);
|
||||||
|
return (
|
||||||
|
<div key={channel.key} className={styles.card}>
|
||||||
|
<div>
|
||||||
|
<div className={styles.channelTitle}>{channel.label}</div>
|
||||||
|
<div className={styles.channelDescription}>
|
||||||
|
{selectedPreference === "preferred" && "Priorizar este canal para tus notificaciones."}
|
||||||
|
{selectedPreference === "muted" && "No recibir notificaciones por este canal."}
|
||||||
|
{selectedPreference === "default" && "Usar la configuración estándar de cada organización."}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className={styles.options}>
|
||||||
|
{[
|
||||||
|
{ key: "default" as ChannelPreference, label: "Estándar" },
|
||||||
|
{ key: "preferred" as ChannelPreference, label: "Preferido" },
|
||||||
|
{ key: "muted" as ChannelPreference, label: "Silenciado" }
|
||||||
|
].map((option) => {
|
||||||
|
const isSelected = selectedPreference === option.key;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={option.key}
|
||||||
|
type="button"
|
||||||
|
onClick={() => selectPreference(channel.key, option.key)}
|
||||||
|
className={`${styles.optionButton} ${isSelected ? styles.optionButtonActive : ""}`}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{store.isDirty && (
|
||||||
|
<button onClick={handleSave} className={styles.saveButton}>
|
||||||
|
Guardar preferencias
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ marginBottom: "40px" }}> </div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import Location from "@components/Location/Location";
|
|||||||
import { useLocationStore } from "@store/Location.Store";
|
import { useLocationStore } from "@store/Location.Store";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
|
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
|
||||||
|
import NotificationsIcon from "@mui/icons-material/Notifications";
|
||||||
import { useBottomToolbarStore } from "@core/Store/BottomToolbar.Store";
|
import { useBottomToolbarStore } from "@core/Store/BottomToolbar.Store";
|
||||||
|
|
||||||
export default function Profile() {
|
export default function Profile() {
|
||||||
@@ -52,6 +53,11 @@ export default function Profile() {
|
|||||||
icon="/notifications-icon.svg"
|
icon="/notifications-icon.svg"
|
||||||
onClick={() => goTo("/user/profile/notifications")}
|
onClick={() => goTo("/user/profile/notifications")}
|
||||||
/>
|
/>
|
||||||
|
<ButtonOption
|
||||||
|
text="Preferencias de notificación"
|
||||||
|
icon="/notifications-icon.svg"
|
||||||
|
onClick={() => goTo("/user/profile/notifications-preferences")}
|
||||||
|
/>
|
||||||
<ButtonOption
|
<ButtonOption
|
||||||
text="Avanzado"
|
text="Avanzado"
|
||||||
icon="/services-icon.svg"
|
icon="/services-icon.svg"
|
||||||
|
|||||||
Reference in New Issue
Block a user