Compare commits
19 Commits
40090cdec5
...
scoring
| Author | SHA1 | Date | |
|---|---|---|---|
| c77d479344 | |||
| 0a285776c7 | |||
| f39ba44f59 | |||
| ece3879c8d | |||
| 68d98e8b40 | |||
| dc020d94d2 | |||
| 20b0363767 | |||
| 6c75929e21 | |||
| e6662aac18 | |||
| 4029566063 | |||
| 3988e328eb | |||
| dd3e07311d | |||
| 279e1b54cc | |||
| da3c3abb52 | |||
| 383a5bc6b4 | |||
| b26c3e58d1 | |||
| 98f0ec3102 | |||
| aac53e13cc | |||
| 10ca449f88 |
@@ -0,0 +1,86 @@
|
||||
---
|
||||
name: tx-admin-endpoint
|
||||
description: "Trigger: crear colección, nueva colección, crear endpoint, nuevo endpoint, Models, api, turnosxpress admin. Reglas para crear colecciones y endpoints del backend admin de turnosxpress."
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: gentleman-programming
|
||||
version: "1.0"
|
||||
---
|
||||
|
||||
## Activation Contract
|
||||
|
||||
Load this skill when creating a new collection or a new endpoint in the `server` backend of the turnosxpress admin (the API consumed by admins/employees, not the public client app). Applies to both the data layer (`server/src/Models`) and the HTTP layer (`server/src/api`). Example to imitate: `Clients`, `Posts`, `SchedulesDisabled`.
|
||||
|
||||
## Hard Rules
|
||||
|
||||
- Use the ACTUAL paths: collections live in `server/src/Models/<Name>/`, endpoints in `server/src/api/<Name>/`. The folder name is the collection name (e.g. `Clients`, `Posts`).
|
||||
- A collection is ALWAYS exactly 3 files with separated responsibilities (never collapse them):
|
||||
|
||||
| File | Owns | Forbidden here |
|
||||
|------|------|-----------------|
|
||||
| `<Name>.Interface.ts` | All TS types: `*Params` (Create/Update/Delete/Find), `IX`, `IXDocument` re-export, `IXAdapter`, `IXManager`, view/result types. | No Mongoose, no business logic. |
|
||||
| `<Name>.Adapter.Mongoose.ts` | Mongoose ONLY: `Schema`, `IXDocument extends IX & Document`, `model()`, and pure DB ops (`create`, `delete`, `find`, `findOne`, `paginate`). Implements `IXAdapter`. | No business rules, NO security checks. |
|
||||
| `<Name>.ts` | Business rules AND security. A `<Name>Manager implements IXManager` class that instantiates the adapter in the constructor; exported as a singleton (`const XList = new ...Manager(); export default XList;`). | No Schema, no `model()`. |
|
||||
|
||||
- SECURITY STANDARD (mandatory, even though `Clients.ts` inlines it — that is legacy): use the shared helpers from `server/src/helpers/check.ts`:
|
||||
- `validateSessionUser({ sessionUser })` — confirm the session user exists. Call FIRST in any method that receives `sessionUser`.
|
||||
- `validatePermissionsByCompany({ companyId, sessionUser })` — confirm the company exists AND the session user has ADMIN role. Call whenever a `companyId` is involved.
|
||||
- Modern reference: `server/src/Models/Posts/Posts.ts`, `server/src/Models/SchedulesDisabled/SchedulesDisabled.ts`.
|
||||
- Role checks beyond ADMIN (EMPLOYEE, etc.) go through `EmployeesList.checkPermission` / `checkRoleById`.
|
||||
- An endpoint is ALWAYS 2 files:
|
||||
- `<Name>.Controller.ts` — tsoa decorators. One controller class per `@Route("resource/action")`. Each handler `@Post()`, takes `@Body()`, sets status, wraps in try/catch and returns `new ApiValidationError(500, message)` on error. Import `ApiValidationError` from `../../Models/Server.Error.model`.
|
||||
- `<Name>.Service.ts` — thin: each method `await connect(process.env.DATABASE_CONNECTION)` then delegates to the manager singleton. No business logic here.
|
||||
- `authenticationMiddleware` (from `server/src/middleware/authentication.ts`) MUST be applied with `@Middlewares(authenticateMiddleware)` on EVERY controller, UNLESS the endpoint is intentionally public. Never omit it without explicit confirmation (see Ask Before Building).
|
||||
- 99% of endpoints use `@Post()`. Default to POST; use GET/other only with a concrete, justified reason.
|
||||
- After adding/changing controllers, regenerate the tsoa routes/spec: `npm run routes` (binds `tsoa spec-and-routes`); compile with `npm run build`.
|
||||
|
||||
## Decision Gates
|
||||
|
||||
| Situation | Decision |
|
||||
|-----------|----------|
|
||||
| Does the method take `sessionUser`? | Call `validateSessionUser` first. |
|
||||
| Does the method act on a `companyId`? | Then `validatePermissionsByCompany`. |
|
||||
| Endpoint exposed in the admin backend? | Default: `@Middlewares(authenticateMiddleware)`. |
|
||||
| Endpoint hits WhatsApp notification / public recovery / ratings or another abuse-prone path? | Consider `rateLimiter` (or `ratingRateLimiter`) from `server/src/middleware/ratelimiter.ts`. When both apply: `@Middlewares([rateLimiter, authenticateMiddleware])`. |
|
||||
| Internal/system-only endpoint? | Use `systemTokenMiddleware` instead of/with the above. |
|
||||
| Doubt about middleware, role, or method? | STOP and ask. See Ask Before Building. |
|
||||
|
||||
## Ask Before Building (HARD — security first)
|
||||
|
||||
STOP and ask the user BEFORE writing security or middleware code whenever there is ANY doubt. Never guess on these:
|
||||
|
||||
1. Which validations/roles/plan features the new method requires (ADMIN vs EMPLOYEE vs extra feature gates).
|
||||
2. Whether the endpoint should be public (no `authenticateMiddleware`) or authenticated. A missing auth middleware is a security hole — when unsure, default to KEEPING `authenticateMiddleware` and confirm.
|
||||
3. Whether `rateLimiter` should be applied to a given endpoint. Do NOT add it by default; ask when the endpoint could be abuse-prone.
|
||||
4. Whether a non-POST method is genuinely needed.
|
||||
|
||||
Ask at most a couple of focused questions, then wait. Do not proceed by assumption on security.
|
||||
|
||||
## Execution Steps
|
||||
|
||||
Creating a collection:
|
||||
|
||||
1. Create `server/src/Models/<Name>/<Name>.Interface.ts` — define all params, `IX`, `IXAdapter`, `IXManager`, view/result types.
|
||||
2. Create `server/src/Models/<Name>/<Name>.Adapter.Mongoose.ts` — schema, `IXDocument`, `model()`, pure DB ops implementing `IXAdapter`.
|
||||
3. Create `server/src/Models/<Name>/<Name>.ts` — `<Name>Manager implements IXManager`; instantiate the adapter in the constructor; put business rules; call `validateSessionUser` / `validatePermissionsByCompany` at the top of each secured method; export a singleton default.
|
||||
4. Re-check Ask Before Building for any unconfirmed security requirement.
|
||||
|
||||
Creating an endpoint:
|
||||
|
||||
1. Create `server/src/api/<Name>/<Name>.Service.ts` — one method per action, `connect(process.env.DATABASE_CONNECTION)` then delegate to the manager singleton.
|
||||
2. Create `server/src/api/<Name>/<Name>.Controller.ts` — one controller class per `@Route`; `@Middlewares(authenticateMiddleware)` unless confirmed public; `@Post()` + `@Body()`; try/catch returning `ApiValidationError`.
|
||||
3. Apply Decision Gates (rateLimiter? system token? method?).
|
||||
4. Regenerate routes: `npm run routes` then `npm run build`.
|
||||
|
||||
## Output Contract
|
||||
|
||||
Return: files created, the singletons/middlewares wired, any security decision that was confirmed with the user, and whether `npm run routes` / `npm run build` were run.
|
||||
|
||||
## References
|
||||
|
||||
- `server/src/Models/Clients/Clients.ts`, `Clients.Interface.ts`, `Clients.Adapter.Mongoose.ts` — canonical 3-file collection example (note: Clients inlines security; do NOT copy that part).
|
||||
- `server/src/Models/Posts/Posts.ts` — modern security pattern using the shared helpers.
|
||||
- `server/src/helpers/check.ts` — `validateSessionUser`, `validatePermissionsByCompany`, `validatePermissionsByClient`.
|
||||
- `server/src/api/Clients/Clients.Controller.ts`, `Clients.Service.ts` — endpoint pattern (Controller + Service).
|
||||
- `server/src/middleware/authentication.ts`, `server/src/middleware/ratelimiter.ts` — middleware sources.
|
||||
- `server/tsoa.json`, `server/package.json` (`npm run routes`) — route generation.
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
DATABASE_CONNECTION = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
|
||||
DATABASE_CONNECTION = mongodb://horacio:frx8us2w@localhost:20215/turnosxpress
|
||||
DATABASE_CONNECTION_ATLAS = mongodb+srv://horacio:frx8us2w@reservar.a2cgd.mongodb.net/reservar
|
||||
DATABASE_CONNECTION_LOCAL = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
|
||||
|
||||
|
||||
@@ -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": {
|
||||
"dev": "NODE_NO_WARNINGS=1 DOTENV_DISABLE_TELEMETRY=1 node --loader ts-node/esm src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js"
|
||||
"start": "node dist/index.js",
|
||||
"test": "jest --config jest.config.cjs"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
@@ -14,8 +15,11 @@
|
||||
"description": "",
|
||||
"devDependencies": {
|
||||
"@types/axios": "^0.9.36",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/mongoose": "^5.11.96",
|
||||
"@types/node": "^24.3.3",
|
||||
"jest": "^30.4.2",
|
||||
"ts-jest": "^29.4.11",
|
||||
"ts-node": "^10.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,270 @@
|
||||
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 DEFAULT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
|
||||
const SUPPORTED_APPOINTMENT_NOTIFICATION_TYPES = new Set(["creation", "reminder", "cancellation"]);
|
||||
|
||||
function resolveCleanupIntervalMs(): number {
|
||||
const raw = process.env.NOTIFICATION_JOB_CLEANUP_INTERVAL_MS;
|
||||
if (!raw) return DEFAULT_CLEANUP_INTERVAL_MS;
|
||||
|
||||
const parsed = Number(raw);
|
||||
return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_CLEANUP_INTERVAL_MS;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function buildStartOfDay(date: Date): Date {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
}
|
||||
|
||||
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;
|
||||
private cleanupTimeout?: NodeJS.Timeout;
|
||||
private cleanupIntervalMs: number;
|
||||
|
||||
constructor() {
|
||||
this.jobModel = new NotificationJobModel();
|
||||
this.throttle = new WhatsAppThrottleClass();
|
||||
this.cleanupIntervalMs = resolveCleanupIntervalMs();
|
||||
}
|
||||
|
||||
public async startPolling(): Promise<void> {
|
||||
if (this.polling) return;
|
||||
this.polling = true;
|
||||
logIntent("JobProcessor: starting poll loop");
|
||||
await this.cleanupOldJobs();
|
||||
this.scheduleCleanup();
|
||||
this.poll();
|
||||
}
|
||||
|
||||
public stopPolling(): void {
|
||||
this.polling = false;
|
||||
if (this.cleanupTimeout) {
|
||||
clearTimeout(this.cleanupTimeout);
|
||||
this.cleanupTimeout = undefined;
|
||||
}
|
||||
logIntent("JobProcessor: stopping poll loop");
|
||||
}
|
||||
|
||||
private scheduleCleanup(): void {
|
||||
if (!this.polling || this.cleanupIntervalMs <= 0) return;
|
||||
|
||||
this.cleanupTimeout = setTimeout(async () => {
|
||||
await this.cleanupOldJobs();
|
||||
this.scheduleCleanup();
|
||||
}, this.cleanupIntervalMs);
|
||||
}
|
||||
|
||||
private async cleanupOldJobs(now = new Date()): Promise<void> {
|
||||
const cutoff = buildStartOfDay(now);
|
||||
|
||||
try {
|
||||
const deletedCount = await this.jobModel.deleteBeforeScheduledAt(cutoff);
|
||||
logDone(`JobProcessor: cleaned ${deletedCount} old notification jobs before ${cutoff.toISOString()}`);
|
||||
} catch (error) {
|
||||
logError(`JobProcessor: cleanup error before ${cutoff.toISOString()}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
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,113 @@
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
async deleteBeforeScheduledAt(cutoff: Date): Promise<number> {
|
||||
const result = await this.notificationJobList.deleteMany({
|
||||
scheduledAt: { $lt: cutoff },
|
||||
}).exec();
|
||||
|
||||
return result.deletedCount || 0;
|
||||
}
|
||||
}
|
||||
@@ -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,274 @@
|
||||
import { dispatchEmail, dispatchWhatsApp } from "../ChannelDispatchers.js";
|
||||
import { buildPendingJobQuery, buildStartOfDay, 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("buildStartOfDay", () => {
|
||||
it("returns the start of the local day", () => {
|
||||
const result = buildStartOfDay(new Date(2026, 6, 21, 15, 30, 45, 123));
|
||||
|
||||
expect(result).toEqual(new Date(2026, 6, 21, 0, 0, 0, 0));
|
||||
});
|
||||
});
|
||||
|
||||
describe("old job cleanup", () => {
|
||||
it("deletes jobs scheduled before the start of the current day", async () => {
|
||||
const deleteBeforeScheduledAt = jest.fn().mockResolvedValue(3);
|
||||
const now = new Date(2026, 6, 21, 15, 30, 0, 0);
|
||||
|
||||
await (JobProcessor.prototype as any).cleanupOldJobs.call(
|
||||
{ jobModel: { deleteBeforeScheduledAt } },
|
||||
now
|
||||
);
|
||||
|
||||
expect(deleteBeforeScheduledAt).toHaveBeenCalledWith(new Date(2026, 6, 21, 0, 0, 0, 0));
|
||||
});
|
||||
});
|
||||
|
||||
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) => {
|
||||
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) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import dotenv from "dotenv";
|
||||
import logger, { logDone, logError, logIntent } from "./config/logger.js";
|
||||
import mongoose from "mongoose";
|
||||
import { Notifications } from "./Models/Notifications/Notifications.js";
|
||||
import { JobProcessor } from "./Models/Jobs/JobProcessor.js";
|
||||
|
||||
logIntent("Iniciando Notification Sender.");
|
||||
|
||||
@@ -28,10 +28,10 @@ mongoose
|
||||
.then(() => {
|
||||
const start = async () => {
|
||||
logDone("Conexión a MongoDB establecida correctamente.");
|
||||
logger.info("🚀 Notification Sender running");
|
||||
logger.info("🚀 Notification Sender running (job-based polling)");
|
||||
|
||||
const worker = new Notifications();
|
||||
await worker.start();
|
||||
const processor = new JobProcessor();
|
||||
await processor.startPolling();
|
||||
};
|
||||
|
||||
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
|
||||
@@ -0,0 +1,274 @@
|
||||
# TurnosXpress — contenido actualizado para tríptico
|
||||
|
||||
## 1. Mensaje principal
|
||||
|
||||
**TurnosXpress es una plataforma para gestionar turnos, clientes, servicios, pagos y comunicación desde un solo lugar.**
|
||||
|
||||
Pensada para profesionales, equipos y negocios que trabajan con reservas, permite ordenar la agenda diaria, publicar servicios online y facilitar que los clientes soliciten turnos desde cualquier dispositivo.
|
||||
|
||||
### Frases sugeridas
|
||||
|
||||
- **Tu agenda online, simple y organizada.**
|
||||
- **Reservá, administrá y comunicá mejor tus turnos.**
|
||||
- **Menos mensajes sueltos. Más control sobre tu agenda.**
|
||||
- **Turnos online para negocios que quieren trabajar mejor.**
|
||||
|
||||
## 2. Qué es TurnosXpress
|
||||
|
||||
TurnosXpress ayuda a negocios y profesionales a administrar sus reservas sin depender todo el tiempo del teléfono, los mensajes manuales o una agenda en papel.
|
||||
|
||||
Con la plataforma, el negocio puede:
|
||||
|
||||
- Crear su perfil público.
|
||||
- Publicar servicios.
|
||||
- Configurar días y horarios disponibles.
|
||||
- Administrar turnos por fecha, servicio, cliente y profesional.
|
||||
- Organizar clientes, pagos, caja y cuenta corriente.
|
||||
- Configurar notificaciones y comunicación por WhatsApp según el plan disponible.
|
||||
- Trabajar con colaboradores o profesionales dentro de una misma organización.
|
||||
- Mostrar información pública, opiniones, puntajes y profesionales cuando corresponda.
|
||||
|
||||
El objetivo es que cada negocio tenga una agenda digital clara, una presencia online más profesional y herramientas de administración que acompañen el crecimiento.
|
||||
|
||||
## 3. Público al que está dirigido
|
||||
|
||||
TurnosXpress está pensado para cualquier actividad que trabaje con citas, reservas o atención por horarios.
|
||||
|
||||
Ejemplos de rubros posibles:
|
||||
|
||||
- Centros de estética y belleza.
|
||||
- Peluquerías y barberías.
|
||||
- Consultorios y profesionales independientes.
|
||||
- Clases particulares, talleres y capacitaciones.
|
||||
- Estudios, centros de bienestar y servicios personalizados.
|
||||
- Equipos con varios colaboradores que necesitan coordinar agendas.
|
||||
|
||||
La plataforma sirve tanto para profesionales que trabajan solos como para organizaciones que necesitan distribuir servicios, horarios y turnos entre varias personas.
|
||||
|
||||
## 4. Propuesta de valor
|
||||
|
||||
### Reservas online para tus clientes
|
||||
|
||||
Tus clientes pueden encontrar tus servicios y solicitar turnos desde el celular, la computadora o cualquier dispositivo conectado.
|
||||
|
||||
### Agenda digital siempre ordenada
|
||||
|
||||
Centralizá los turnos del negocio en una agenda clara, consultable por fecha, cliente, servicio y profesional.
|
||||
|
||||
### Menos coordinación manual
|
||||
|
||||
Reducí llamadas, mensajes repetidos y cruces de horarios. El sistema muestra disponibilidad según la configuración del negocio.
|
||||
|
||||
### Administración del negocio
|
||||
|
||||
Además de los turnos, TurnosXpress permite gestionar clientes, pagos, caja, descuentos y cuenta corriente.
|
||||
|
||||
### Comunicación por WhatsApp
|
||||
|
||||
La plataforma cuenta con herramientas para conectar WhatsApp y configurar avisos o notificaciones según las funciones disponibles en cada plan.
|
||||
|
||||
### Presencia pública configurable
|
||||
|
||||
Cada negocio puede publicar su perfil, servicios e información visible para clientes. También puede configurar la visibilidad de opiniones, puntajes y profesionales cuando el plan y la configuración lo permiten.
|
||||
|
||||
### Planes para distintas etapas
|
||||
|
||||
TurnosXpress ofrece un plan gratuito/base para comenzar y planes pagos para negocios que necesitan más capacidad, más herramientas o funciones avanzadas.
|
||||
|
||||
## 5. Funciones principales
|
||||
|
||||
### Agenda y turnos
|
||||
|
||||
- Agenda digital por día.
|
||||
- Creación, edición, cancelación y movimiento de turnos.
|
||||
- Turnos asociados a clientes, servicios y profesionales.
|
||||
- Consulta de turnos próximos e históricos.
|
||||
- Soporte para turnos recurrentes según el plan disponible.
|
||||
|
||||
### Servicios
|
||||
|
||||
- Publicación de servicios con nombre, descripción, duración y precio.
|
||||
- Servicios públicos o privados.
|
||||
- Imagen, color y datos de ubicación.
|
||||
- Configuración de cupos o límites cuando corresponde.
|
||||
|
||||
### Horarios y disponibilidad
|
||||
|
||||
- Configuración de días y rangos horarios.
|
||||
- Horarios por organización o por colaborador/profesional.
|
||||
- Disponibilidad por servicio.
|
||||
- Control para que los clientes reserven dentro de los horarios habilitados.
|
||||
|
||||
### Clientes
|
||||
|
||||
- Registro y administración de clientes.
|
||||
- Historial de turnos por cliente.
|
||||
- Datos de contacto y preferencias.
|
||||
- Cuenta corriente y movimientos asociados.
|
||||
|
||||
### Pagos, caja y cuenta corriente
|
||||
|
||||
- Registro de pagos vinculados a turnos.
|
||||
- Estados de pago: pendiente, aprobado o rechazado.
|
||||
- Métodos como efectivo, transferencia, crédito, débito, cuenta corriente u otros.
|
||||
- Caja con movimientos, filtros y balance.
|
||||
- Cuenta corriente para controlar saldos y movimientos de clientes.
|
||||
|
||||
### Colaboradores y profesionales
|
||||
|
||||
- Administración de colaboradores dentro de una organización.
|
||||
- Roles y permisos.
|
||||
- Horarios y servicios asignados por profesional.
|
||||
- Visibilidad pública de profesionales cuando corresponde.
|
||||
|
||||
### Notificaciones y WhatsApp
|
||||
|
||||
- Configuración de notificaciones del negocio.
|
||||
- Preferencias generales y por cliente.
|
||||
- WhatsApp como canal principal para automatizar avisos según el plan y la configuración.
|
||||
- Asistente guiado para conectar y administrar WhatsApp.
|
||||
|
||||
> Nota comercial: conviene comunicar WhatsApp como herramienta de conexión y avisos de la plataforma, no como integración oficial de WhatsApp Business API.
|
||||
|
||||
### Opiniones y reputación
|
||||
|
||||
- Opiniones verificadas vinculadas a organización, servicio o profesional.
|
||||
- Configuración para mostrar u ocultar opiniones y puntajes.
|
||||
- Herramientas para fortalecer la presencia pública del negocio.
|
||||
|
||||
### Planes y MercadoPago
|
||||
|
||||
- Plan gratuito/base para comenzar.
|
||||
- Planes pagos con mayor capacidad y funciones avanzadas.
|
||||
- Gestión de contratación o actualización de plan.
|
||||
- Pagos de planes procesados con MercadoPago.
|
||||
|
||||
> Nota comercial: MercadoPago está confirmado para pagos de planes/suscripciones. No prometer cobro online de turnos a clientes salvo que se verifique esa funcionalidad para la campaña específica.
|
||||
|
||||
## 6. Cómo empezar
|
||||
|
||||
### Paso 1 — Registrate
|
||||
|
||||
Creá tu cuenta en TurnosXpress y accedé al panel para comenzar a configurar tu negocio.
|
||||
|
||||
URL sugerida:
|
||||
|
||||
`https://turnosxpress.com.ar/landing/signup`
|
||||
|
||||
### Paso 2 — Elegí tu plan
|
||||
|
||||
Podés comenzar con el plan gratuito/base o elegir un plan pago según el tamaño y las necesidades de tu negocio.
|
||||
|
||||
URL sugerida:
|
||||
|
||||
`https://turnosxpress.com.ar/landing/pricing`
|
||||
|
||||
### Paso 3 — Configurá tu negocio
|
||||
|
||||
Creá el perfil de tu organización, cargá tus servicios, definí horarios y configurá colaboradores si trabajás con un equipo.
|
||||
|
||||
### Paso 4 — Compartí tu enlace
|
||||
|
||||
Publicá tu perfil o compartí el enlace de reserva para que tus clientes puedan solicitar turnos online.
|
||||
|
||||
### Paso 5 — Administrá todo desde el panel
|
||||
|
||||
Consultá la agenda, gestioná clientes, registrá pagos, revisá caja, configurá notificaciones y mantené el negocio organizado.
|
||||
|
||||
## 7. Flujo de uso resumido
|
||||
|
||||
1. El profesional o negocio se registra.
|
||||
2. Selecciona un plan.
|
||||
3. Crea el perfil de la organización.
|
||||
4. Carga servicios, horarios y colaboradores.
|
||||
5. Comparte su enlace o publica su perfil.
|
||||
6. El cliente elige servicio, día y horario disponible.
|
||||
7. El turno queda registrado en la agenda.
|
||||
8. El negocio administra la atención, los pagos y la comunicación desde el panel.
|
||||
|
||||
## 8. Contenido sugerido para cara exterior del tríptico
|
||||
|
||||
### Portada
|
||||
|
||||
**TurnosXpress**
|
||||
|
||||
**Tu agenda online, simple y organizada.**
|
||||
|
||||
Gestioná turnos, clientes, servicios, pagos y comunicación desde una plataforma pensada para negocios que trabajan con reservas.
|
||||
|
||||
**Probá TurnosXpress y empezá a ordenar tu agenda hoy.**
|
||||
|
||||
### Panel de beneficios
|
||||
|
||||
**Reservas online**
|
||||
Tus clientes pueden solicitar turnos desde cualquier dispositivo.
|
||||
|
||||
**Agenda digital**
|
||||
Visualizá y administrá tus turnos de forma clara.
|
||||
|
||||
**Clientes y pagos**
|
||||
Centralizá información, movimientos, caja y cuenta corriente.
|
||||
|
||||
**WhatsApp y notificaciones**
|
||||
Configurá avisos y comunicación según tu plan.
|
||||
|
||||
**Perfil público**
|
||||
Mostrá tus servicios, profesionales, opiniones y puntajes cuando corresponda.
|
||||
|
||||
### Llamado a la acción
|
||||
|
||||
**Empezá gratis y configurá tu negocio en pocos pasos.**
|
||||
|
||||
Sitio web: `https://turnosxpress.com.ar`
|
||||
Email: `info@turnosxpress.com.ar`
|
||||
Teléfono: `11-2390-2059`
|
||||
|
||||
## 9. Contenido sugerido para cara interior del tríptico
|
||||
|
||||
### Título interior
|
||||
|
||||
**Todo lo que necesitás para administrar tus turnos en un solo lugar**
|
||||
|
||||
### Bloque 1 — Configurá tu negocio
|
||||
|
||||
Creá tu organización, cargá los servicios que ofrecés, definí duración, precio, ubicación y horarios disponibles.
|
||||
|
||||
### Bloque 2 — Publicá y recibí reservas
|
||||
|
||||
Compartí tu perfil o enlace de reserva para que tus clientes puedan elegir un servicio y solicitar un turno online.
|
||||
|
||||
### Bloque 3 — Administrá tu día a día
|
||||
|
||||
Consultá la agenda, gestioná clientes, registrá pagos, revisá caja y mantené el historial del negocio ordenado.
|
||||
|
||||
### Bloque 4 — Sumá comunicación y visibilidad
|
||||
|
||||
Configurá WhatsApp, notificaciones, opiniones, puntajes y profesionales visibles según el plan y la configuración de tu organización.
|
||||
|
||||
### Bloque 5 — Crecé con planes flexibles
|
||||
|
||||
Comenzá con el plan gratuito/base y pasá a un plan superior cuando necesites más capacidad o funciones avanzadas.
|
||||
|
||||
## 10. Llamados a la acción recomendados
|
||||
|
||||
- **Probá TurnosXpress gratis.**
|
||||
- **Creá tu agenda online hoy.**
|
||||
- **Compartí tus servicios y empezá a recibir reservas.**
|
||||
- **Ordená turnos, clientes y pagos desde un solo panel.**
|
||||
- **Digitalizá tu negocio sin complicarte.**
|
||||
|
||||
## 11. Mensajes que conviene evitar o matizar
|
||||
|
||||
- Evitar prometer SMS como función disponible actualmente.
|
||||
- Evitar decir “automatización multicanal completa” sin aclarar alcance por plan y configuración.
|
||||
- Evitar presentar WhatsApp como integración oficial de WhatsApp Business API.
|
||||
- Evitar prometer cobro online de turnos con MercadoPago si la campaña no verifica esa función específica.
|
||||
- Evitar enfocar el folleto en herramientas internas de sysadmin; no son beneficios directos para el negocio final.
|
||||
|
||||
## 12. Resumen comercial
|
||||
|
||||
TurnosXpress ya no es solamente una agenda online. Es una plataforma de gestión para negocios con turnos: permite publicar servicios, organizar disponibilidad, recibir reservas, administrar clientes, registrar pagos, controlar caja, trabajar con colaboradores y mejorar la comunicación con herramientas como WhatsApp y notificaciones configurables.
|
||||
|
||||
El mensaje actualizado debe transmitir una idea central:
|
||||
|
||||
**TurnosXpress ayuda a que el negocio trabaje más ordenado, atienda mejor y dependa menos de la coordinación manual.**
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 53 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
@@ -54,6 +54,7 @@ DONWEB_MAIL_API_KEY = eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE3NDYxMTc3N
|
||||
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_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
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ DONWEB_MAIL_API_KEY = eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE3NDYxMTc3N
|
||||
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_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
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ DONWEB_MAIL_API_KEY = eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE3NDYxMTc3N
|
||||
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_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
|
||||
|
||||
|
||||
@@ -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_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
|
||||
|
||||
|
||||
@@ -36,9 +36,19 @@ export type FindAppointmentsByCollaboratorPaginatedParams = FindAppointmentsByCo
|
||||
export enum APPOINTMENT_NOTIFICATION_TYPE {
|
||||
"CREATION" = "creation",
|
||||
"REMINDER" = "reminder",
|
||||
"UPDATE" = "update",
|
||||
"CANCELLATION" = "cancellation",
|
||||
}
|
||||
|
||||
export type SendAppointmentNotificationParams = {
|
||||
appointmentId: string;
|
||||
sessionUser?: string;
|
||||
systemToken?: string;
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
channel?: "whatsapp" | "email";
|
||||
};
|
||||
|
||||
export type CreateImmediateAppointmentNotificationJobsParams = {
|
||||
appointmentId: string;
|
||||
sessionUser: string;
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
@@ -63,6 +73,7 @@ export type ChangeServiceParams = {
|
||||
export type SendWapSystemNotificationParams = {
|
||||
appointmentId: string;
|
||||
systemToken: string;
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
};
|
||||
|
||||
export type HeatMapConfig = {
|
||||
@@ -121,6 +132,7 @@ export type UpdateAppointmentParams = {
|
||||
export type DeleteAppointmentParams = {
|
||||
id: string;
|
||||
validation?: boolean;
|
||||
notification?: boolean;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
@@ -315,6 +327,7 @@ export interface IAppointmentsManager {
|
||||
getAvailableDates(data: GetAvailableDatesParams): Promise<GetAvailableDatesResult>;
|
||||
sendWapNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||
sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||
createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void>;
|
||||
sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void>;
|
||||
deleteAppointmentsByCompany(data: DeleteAppointmentsByCompanyParams): Promise<void>;
|
||||
changeEmployeeToOwner(data: ChangeEmployeeToOwnerParams): Promise<void>;
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
ChangeEmployeeToOwnerParams,
|
||||
CountAppointmentsByMonthParams,
|
||||
CreateAppointmentParams,
|
||||
CreateImmediateAppointmentNotificationJobsParams,
|
||||
DeleteAppointmentDiscountParams,
|
||||
DeleteAppointmentParams,
|
||||
DeleteAppointmentsByCompanyParams,
|
||||
@@ -76,6 +77,7 @@ import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled";
|
||||
import DiscountsEmail from "../DiscountsEmail/DiscountsEmail";
|
||||
import SchedulesOverridesList from "../SchedulesOverrides/SchedulesOverrides";
|
||||
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||
import { NotificationJobService } from "../NotificationPolicies/NotificationJobService";
|
||||
|
||||
dayjs.locale("es");
|
||||
dayjs.extend(isSameOrAfter);
|
||||
@@ -84,9 +86,11 @@ dayjs.extend(weekday);
|
||||
|
||||
class AppointmentManager implements IAppointmentsManager {
|
||||
Appointments: AppointmentsAdapterMongoose;
|
||||
private jobService: NotificationJobService;
|
||||
|
||||
constructor() {
|
||||
this.Appointments = new AppointmentsAdapterMongoose();
|
||||
this.jobService = new NotificationJobService();
|
||||
}
|
||||
|
||||
private isScheduleAvailableForService(schedule: ScheduleItem, serviceId?: string): boolean {
|
||||
@@ -525,38 +529,51 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
type: NotificationType.APPOINTMENT,
|
||||
code: String((newAppointment as any)._id)
|
||||
});
|
||||
}
|
||||
|
||||
//Intento enviar notificacion al cliente por Email
|
||||
try {
|
||||
if (newAppointment.id) {
|
||||
await this.sendEmailNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Error al enviar la notificacion por Email para ${companyCheck.name}(${companyCheck._id}):`,
|
||||
err
|
||||
);
|
||||
}
|
||||
//Create jobs for email and whatsapp notifications
|
||||
if (notification && newAppointment.id) {
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
const clientPhoneNumber = await this.getOptionalClientWapNumber(checkClient);
|
||||
const reminderEmailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "email",
|
||||
});
|
||||
const reminderWapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
//Intento enviar notificacion al cliente por Whatsapp
|
||||
try {
|
||||
if (newAppointment.id) {
|
||||
await this.sendWapNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Error al enviar la notificacion por Whatsapp para ${companyCheck.name}(${companyCheck._id}):`,
|
||||
err
|
||||
);
|
||||
}
|
||||
await this.createCreationNotificationJobs({
|
||||
appointmentId: String(newAppointment.id),
|
||||
companyId: String(companyCheck._id),
|
||||
clientId: String(checkClient._id),
|
||||
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
clientEmail: checkClient.email,
|
||||
clientPhoneNumber,
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
companyName: companyCheck.name,
|
||||
appointmentStart: new Date(data.start),
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
reminderEmailMessage: reminderEmailContent.message,
|
||||
reminderWapMessage: reminderWapContent.message,
|
||||
});
|
||||
}
|
||||
|
||||
//Envio la notificacion al profesional.
|
||||
@@ -2070,36 +2087,50 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
code: String(checkAppointment._id)
|
||||
});
|
||||
|
||||
//Intento enviar notificacion al cliente por Email
|
||||
try {
|
||||
if (checkAppointment.id) {
|
||||
await this.sendEmailNotification({
|
||||
appointmentId: String(checkAppointment.id),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Error al enviar la notificacion por Email para ${companyCheck.name}(${companyCheck._id}):`,
|
||||
err
|
||||
);
|
||||
}
|
||||
//Cancel existing pending jobs before creating new ones for the rescheduled appointment
|
||||
if (checkAppointment.id) {
|
||||
await this.jobService.cancelByAppointment(String(checkAppointment.id));
|
||||
|
||||
//Intento enviar notificacion al cliente por Whatsapp
|
||||
try {
|
||||
if (checkAppointment.id) {
|
||||
await this.sendWapNotification({
|
||||
appointmentId: String(checkAppointment.id),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Error al enviar la notificacion por Whatsapp para ${companyCheck.name}(${companyCheck._id}):`,
|
||||
err
|
||||
);
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(checkAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.UPDATE,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(checkAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.UPDATE,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
const reminderEmailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(checkAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "email",
|
||||
});
|
||||
const reminderWapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(checkAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await this.createUpdateNotificationJobs({
|
||||
appointmentId: String(checkAppointment.id),
|
||||
companyId: String(companyCheck._id),
|
||||
clientId: String(checkClient._id),
|
||||
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
clientEmail: checkClient.email,
|
||||
clientPhoneNumber: await this.getOptionalClientWapNumber(checkClient),
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
companyName: companyCheck.name,
|
||||
appointmentStart: new Date(data.start),
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
reminderEmailMessage: reminderEmailContent.message,
|
||||
reminderWapMessage: reminderWapContent.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2155,8 +2186,167 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
return config;
|
||||
}
|
||||
|
||||
private async createCancellationNotificationJobs(data: {
|
||||
appointmentId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
clientUserId?: string;
|
||||
clientEmail?: string;
|
||||
clientPhoneNumber?: string;
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
emailMessage: string;
|
||||
wapMessage: string;
|
||||
}): Promise<void> {
|
||||
const systemSubject = `Turno cancelado en ${data.companyName}`;
|
||||
|
||||
await this.jobService.createJob({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "cancellation",
|
||||
scheduledAt: new Date(),
|
||||
payload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
subject: systemSubject,
|
||||
message: data.emailMessage,
|
||||
emailSubject: "TurnosXpress :: Turno cancelado",
|
||||
emailMessage: data.emailMessage,
|
||||
wapMessage: data.wapMessage,
|
||||
systemSubject,
|
||||
systemMessage: data.emailMessage,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async createCreationNotificationJobs(data: {
|
||||
appointmentId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
clientUserId?: string;
|
||||
clientEmail?: string;
|
||||
clientPhoneNumber?: string;
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
appointmentStart: Date;
|
||||
emailMessage: string;
|
||||
wapMessage: string;
|
||||
reminderEmailMessage: string;
|
||||
reminderWapMessage: string;
|
||||
}): Promise<void> {
|
||||
const systemSubject = `Turno reservado en ${data.companyName}`;
|
||||
const reminderSystemSubject = `Recordatorio de turno en ${data.companyName}`;
|
||||
|
||||
const 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,
|
||||
};
|
||||
|
||||
await this.jobService.createMandatoryCreationJob({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "creation",
|
||||
payload,
|
||||
});
|
||||
|
||||
await this.jobService.createReminderJobs({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "reminder",
|
||||
appointmentStart: data.appointmentStart,
|
||||
reminderPayload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
subject: reminderSystemSubject,
|
||||
message: data.reminderEmailMessage,
|
||||
emailSubject: "TurnosXpress :: Recordatorio",
|
||||
emailMessage: data.reminderEmailMessage,
|
||||
wapMessage: data.reminderWapMessage,
|
||||
systemSubject: reminderSystemSubject,
|
||||
systemMessage: data.reminderEmailMessage,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async createUpdateNotificationJobs(data: {
|
||||
appointmentId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
clientUserId?: string;
|
||||
clientEmail?: string;
|
||||
clientPhoneNumber?: string;
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
appointmentStart: Date;
|
||||
emailMessage: string;
|
||||
wapMessage: string;
|
||||
reminderEmailMessage: string;
|
||||
reminderWapMessage: string;
|
||||
}): Promise<void> {
|
||||
const systemSubject = `Turno actualizado en ${data.companyName}`;
|
||||
const reminderSystemSubject = `Recordatorio de turno en ${data.companyName}`;
|
||||
|
||||
await this.jobService.createJob({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "update",
|
||||
appointmentStart: data.appointmentStart,
|
||||
payload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
subject: systemSubject,
|
||||
message: data.emailMessage,
|
||||
emailSubject: "TurnosXpress :: Turno actualizado",
|
||||
emailMessage: data.emailMessage,
|
||||
wapMessage: data.wapMessage,
|
||||
systemSubject,
|
||||
systemMessage: data.emailMessage,
|
||||
},
|
||||
reminderPayload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
subject: reminderSystemSubject,
|
||||
message: data.reminderEmailMessage,
|
||||
emailSubject: "TurnosXpress :: Recordatorio",
|
||||
emailMessage: data.reminderEmailMessage,
|
||||
wapMessage: data.reminderWapMessage,
|
||||
systemSubject: reminderSystemSubject,
|
||||
systemMessage: data.reminderEmailMessage,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async getOptionalClientWapNumber(client: IClientDocument): Promise<string | undefined> {
|
||||
try {
|
||||
return await ClientsManager.getClientWapNumber(client);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async deleteAppointment(data: DeleteAppointmentParams): Promise<void> {
|
||||
const { validation = false } = data;
|
||||
const { validation = false, notification = false } = data;
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
});
|
||||
@@ -2234,23 +2424,41 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
try {
|
||||
const config = this.getHeatMapConfig(checkAppointment, serviceCheck.length);
|
||||
|
||||
// Cancel pending notification jobs for this appointment before deleting it
|
||||
await this.jobService.cancelByAppointment(String(checkAppointment._id));
|
||||
|
||||
if (notification) {
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(checkAppointment._id),
|
||||
sessionUser: data.sessionUser,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(checkAppointment._id),
|
||||
sessionUser: data.sessionUser,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await this.createCancellationNotificationJobs({
|
||||
companyId: String(checkAppointment.companyId),
|
||||
clientId: String(checkAppointment.clientId),
|
||||
appointmentId: String(checkAppointment._id),
|
||||
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
clientEmail: checkClient.email,
|
||||
clientPhoneNumber: await this.getOptionalClientWapNumber(checkClient),
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
companyName: companyCheck.name,
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
});
|
||||
}
|
||||
|
||||
await this.Appointments.AppointmentList.deleteOne({ _id: data.id });
|
||||
//Actualizar el heatmap.
|
||||
await this.updateHeatMap(config);
|
||||
|
||||
if (checkClient.userId) {
|
||||
//Enviamos la notificacion de cancelacion al cliente
|
||||
await NotificationsManager.sendSystemNotification({
|
||||
userId: String(checkClient.userId),
|
||||
subject: "Turno Cancelado",
|
||||
message: `Se ha cancelado el turno para el día ${dayjs(checkAppointment.start).format(
|
||||
"DD/MM/YYYY"
|
||||
)} a las ${dayjs(checkAppointment.start).format("HH:mm")}`,
|
||||
type: NotificationType.APPOINTMENT,
|
||||
code: String(checkAppointment._id)
|
||||
});
|
||||
}
|
||||
|
||||
//Enviamos la notificacion de cancelacion al profesional
|
||||
await NotificationsManager.sendSystemNotification({
|
||||
userId: String(employeeCheck.userId),
|
||||
@@ -2384,8 +2592,16 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
throw new Error("La compañia no existe");
|
||||
}
|
||||
|
||||
if (!(await EmployeesList.checkPermission(companyCheck, data.sessionUser, EmployeeRoles.ADMIN))) {
|
||||
throw new Error(NoPermissionMessage());
|
||||
const hasSystemToken = this.hasValidSystemToken(data.systemToken);
|
||||
|
||||
if (!hasSystemToken) {
|
||||
if (!data.sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
if (!(await EmployeesList.checkPermission(companyCheck, data.sessionUser, EmployeeRoles.ADMIN))) {
|
||||
throw new Error(NoPermissionMessage());
|
||||
}
|
||||
}
|
||||
|
||||
const checkClient = await ClientsManager.clients.findOne({
|
||||
@@ -2465,9 +2681,13 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
wapMessage = wapMessage.replaceAll("<---ORGANIZACION--->", companyCheck.name);
|
||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
||||
if (companyCheck.templateWapAltaId) {
|
||||
const templateId = data.channel === "email"
|
||||
? companyCheck.templateEmailAltaId || companyCheck.templateWapAltaId
|
||||
: companyCheck.templateWapAltaId;
|
||||
|
||||
if (templateId) {
|
||||
const template = await Templates.templates.findOne({
|
||||
id: String(companyCheck.templateWapAltaId),
|
||||
id: String(templateId),
|
||||
companyId: String(companyCheck._id),
|
||||
});
|
||||
|
||||
@@ -2477,7 +2697,9 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
}
|
||||
|
||||
if (!wapMessage) {
|
||||
wapMessage = process.env.WAP_ALTA ? process.env.WAP_ALTA : "";
|
||||
wapMessage = data.channel === "email"
|
||||
? process.env.EMAIL_NEW_APPOINTMENT || process.env.EMAIL_ALTA || process.env.WAP_ALTA || ""
|
||||
: process.env.WAP_ALTA || "";
|
||||
}
|
||||
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
@@ -2505,6 +2727,61 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
wapMessage = wapMessage.replaceAll("<---SERVICIO--->", checkService.name);
|
||||
wapMessage = wapMessage.replaceAll("<---PRECIO--->", formatCurrency(checkAppointment.price));
|
||||
|
||||
wapMessage = wapMessage.replaceAll("<---ORGANIZACION--->", companyCheck.name);
|
||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION || data.type == APPOINTMENT_NOTIFICATION_TYPE.UPDATE) {
|
||||
const isUpdate = data.type == APPOINTMENT_NOTIFICATION_TYPE.UPDATE;
|
||||
const templateId = data.channel === "email"
|
||||
? isUpdate
|
||||
? companyCheck.templateEmailAltaId || companyCheck.templateWapAltaId
|
||||
: companyCheck.templateEmailCancellationId || companyCheck.templateWapCancellationId
|
||||
: isUpdate
|
||||
? companyCheck.templateWapAltaId
|
||||
: 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"
|
||||
? isUpdate
|
||||
? process.env.EMAIL_NEW_APPOINTMENT || process.env.EMAIL_ALTA || process.env.WAP_ALTA || ""
|
||||
: process.env.EMAIL_CANCELLATION || process.env.EMAIL_CANCELACION || process.env.WAP_CANCELLATION || process.env.WAP_CANCELACION || ""
|
||||
: isUpdate
|
||||
? process.env.WAP_ALTA || ""
|
||||
: process.env.WAP_CANCELLATION || process.env.WAP_CANCELACION || "";
|
||||
}
|
||||
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---CLIENTE--->",
|
||||
ClientsManager.getClientFullName(checkClient)
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---FECHA--->",
|
||||
dayjs(checkAppointment.start).format("DD/MM/YYYY")
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---HORARIO--->",
|
||||
dayjs(checkAppointment.start).format("HH:mm") + "hs."
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---DIRECCION--->",
|
||||
CompaniesManager.getCompanyAddress(companyCheck)
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll(
|
||||
"<---PROFESIONAL--->",
|
||||
UsersManager.getUserFullName(checkEmployeeUser)
|
||||
);
|
||||
wapMessage = wapMessage.replaceAll("<---SERVICIO--->", checkService.name);
|
||||
wapMessage = wapMessage.replaceAll("<---PRECIO--->", formatCurrency(checkAppointment.price));
|
||||
wapMessage = wapMessage.replaceAll("<---ORGANIZACION--->", companyCheck.name);
|
||||
wapMessage = wapMessage.replaceAll("<---BR--->", "\r\n");
|
||||
}
|
||||
@@ -2517,15 +2794,24 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
}
|
||||
|
||||
public async sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void> {
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
});
|
||||
if (!this.hasValidSystemToken(data.systemToken)) {
|
||||
if (!data.sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
if (!sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
});
|
||||
|
||||
if (!sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
}
|
||||
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification(data);
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification({
|
||||
...data,
|
||||
channel: "email",
|
||||
});
|
||||
|
||||
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||
userId: String(companyCheck.ownerId),
|
||||
@@ -2548,6 +2834,10 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
subjectEmail = "TurnosXpress :: Recordatorio";
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
||||
subjectEmail = "TurnosXpress :: Alta de turno";
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.CANCELLATION) {
|
||||
subjectEmail = "TurnosXpress :: Turno cancelado";
|
||||
} else if (data.type == APPOINTMENT_NOTIFICATION_TYPE.UPDATE) {
|
||||
subjectEmail = "TurnosXpress :: Turno actualizado";
|
||||
}
|
||||
|
||||
//Enviar email...
|
||||
@@ -2558,7 +2848,66 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
public async createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void> {
|
||||
if (![APPOINTMENT_NOTIFICATION_TYPE.CREATION, APPOINTMENT_NOTIFICATION_TYPE.REMINDER].includes(data.type)) {
|
||||
throw new Error("El tipo de notificación no es válido para esta acción");
|
||||
}
|
||||
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.sessionUser,
|
||||
type: data.type,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.sessionUser,
|
||||
type: data.type,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
const checkAppointment = await this.Appointments.findOne({
|
||||
_id: data.appointmentId,
|
||||
});
|
||||
|
||||
if (!checkAppointment) {
|
||||
throw new Error("El turno no existe");
|
||||
}
|
||||
|
||||
const checkClient = emailContent.checkClient;
|
||||
const companyCheck = emailContent.companyCheck;
|
||||
const isCreation = data.type === APPOINTMENT_NOTIFICATION_TYPE.CREATION;
|
||||
const systemSubject = isCreation
|
||||
? `Turno reservado en ${companyCheck.name}`
|
||||
: `Recordatorio de turno en ${companyCheck.name}`;
|
||||
|
||||
await this.jobService.createImmediateJob({
|
||||
companyId: String(checkAppointment.companyId),
|
||||
clientId: String(checkAppointment.clientId),
|
||||
appointmentId: String(checkAppointment._id),
|
||||
type: data.type,
|
||||
scheduledAt: new Date(),
|
||||
payload: {
|
||||
email: checkClient.email,
|
||||
phoneNumber: await this.getOptionalClientWapNumber(checkClient),
|
||||
userId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
subject: systemSubject,
|
||||
message: emailContent.message,
|
||||
emailSubject: isCreation ? "TurnosXpress :: Alta de turno" : "TurnosXpress :: Recordatorio",
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
systemSubject,
|
||||
systemMessage: emailContent.message,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public async sendWapNotification(data: SendAppointmentNotificationParams): Promise<void> {
|
||||
if (!data.sessionUser) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
});
|
||||
@@ -2567,7 +2916,10 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification(data);
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification({
|
||||
...data,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||
userId: String(companyCheck.ownerId),
|
||||
@@ -2593,13 +2945,7 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
}
|
||||
|
||||
public async sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void> {
|
||||
if (!data.systemToken || data.systemToken == "") {
|
||||
throw new Error("No tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
const systemToken = `${process.env.SYSTEM_KEY}`;
|
||||
|
||||
if (systemToken != data.systemToken) {
|
||||
if (!this.hasValidSystemToken(data.systemToken)) {
|
||||
throw new Error("No tiene permisos para realizar esta acción");
|
||||
}
|
||||
|
||||
@@ -2622,7 +2968,8 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
const { message, checkClient, companyCheck } = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: String(company.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
systemToken: data.systemToken,
|
||||
type: data.type,
|
||||
});
|
||||
|
||||
const canSend = await PlanSubscriptionsList.checkFeature({
|
||||
@@ -2838,6 +3185,11 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
inRangeDates: [],
|
||||
} as GetAvailableDatesResult;
|
||||
}
|
||||
|
||||
private hasValidSystemToken(systemToken?: string): boolean {
|
||||
const expectedSystemToken = process.env.SYSTEM_KEY || process.env.API_KEY;
|
||||
return Boolean(systemToken && expectedSystemToken && systemToken === expectedSystemToken);
|
||||
}
|
||||
}
|
||||
|
||||
const AppointmentList = new AppointmentManager();
|
||||
|
||||
@@ -32,6 +32,7 @@ jest.mock("../../Companies/Companies", () => ({
|
||||
companies: {
|
||||
findOne: jest.fn(),
|
||||
},
|
||||
getCompanyAddress: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -41,6 +42,7 @@ jest.mock("../../Employees/Employee", () => ({
|
||||
employees: {
|
||||
findOne: jest.fn(),
|
||||
},
|
||||
checkPermission: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -103,6 +105,7 @@ jest.mock("../../Notifications/Notifications", () => ({
|
||||
NotificationsManager: {
|
||||
sendSystemNotification: jest.fn(),
|
||||
sendPushNotification: jest.fn(),
|
||||
sendEmail: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -117,6 +120,7 @@ jest.mock("../../PlanSubscriptions/PlanSubscriptons", () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
findOne: jest.fn(),
|
||||
checkFeature: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -151,6 +155,9 @@ jest.mock("../../../helpers/check", () => ({
|
||||
jest.mock("../../Templates/Templates", () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
templates: {
|
||||
findOne: jest.fn(),
|
||||
},
|
||||
sendEmail: jest.fn(),
|
||||
},
|
||||
}));
|
||||
@@ -180,6 +187,11 @@ import UsersManager from "../../Users/Users";
|
||||
import EmployeesList from "../../Employees/Employee";
|
||||
import ClientsManager from "../../Clients/Clients";
|
||||
import ServiceList from "../../Services/Service";
|
||||
import CompaniesManager from "../../Companies/Companies";
|
||||
import Templates from "../../Templates/Templates";
|
||||
import PlanSubscriptionsList from "../../PlanSubscriptions/PlanSubscriptons";
|
||||
import { NotificationsManager } from "../../Notifications/Notifications";
|
||||
import { APPOINTMENT_NOTIFICATION_TYPE } from "../Appointments.Interface";
|
||||
|
||||
describe("getAppointmentEvent — historical read snapshot fallback", () => {
|
||||
let originalAdapter: any;
|
||||
@@ -385,3 +397,364 @@ describe("getAppointmentEvent — historical read snapshot fallback", () => {
|
||||
expect(result.collaboratorName).toBe("Jane Roe");
|
||||
});
|
||||
});
|
||||
|
||||
describe("cancellation notification jobs", () => {
|
||||
let originalAdapter: any;
|
||||
let originalJobService: any;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
originalAdapter = AppointmentsList.Appointments;
|
||||
originalJobService = (AppointmentsList as any).jobService;
|
||||
|
||||
(AppointmentsList as any).Appointments = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
_id: "appt-001",
|
||||
companyId: "company-001",
|
||||
clientId: "client-001",
|
||||
employeeId: "employee-001",
|
||||
serviceId: "service-001",
|
||||
start: new Date("2026-07-22T11:00:00.000Z"),
|
||||
price: 1500,
|
||||
}),
|
||||
};
|
||||
(AppointmentsList as any).jobService = {
|
||||
createJob: jest.fn().mockResolvedValue([]),
|
||||
createMandatoryCreationJob: jest.fn().mockResolvedValue([]),
|
||||
createReminderJobs: 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({
|
||||
email: "ada@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "client-user-001",
|
||||
companyOwnerId: "owner-001",
|
||||
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.",
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("sends update email notifications with a non-empty subject", async () => {
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
await (AppointmentsList as any).sendEmailNotification({
|
||||
appointmentId: "appt-001",
|
||||
sessionUser: "owner-001",
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.UPDATE,
|
||||
});
|
||||
|
||||
expect(NotificationsManager.sendEmail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
email: "ada@example.com",
|
||||
subject: "TurnosXpress :: Turno actualizado",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
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([]),
|
||||
createMandatoryCreationJob: jest.fn().mockResolvedValue([]),
|
||||
createReminderJobs: 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,
|
||||
reminderEmailMessage: "EMAIL REMINDER Ada Lovelace",
|
||||
reminderWapMessage: "WAP REMINDER Ada Lovelace",
|
||||
});
|
||||
|
||||
expect((AppointmentsList as any).jobService.createMandatoryCreationJob).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.",
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect((AppointmentsList as any).jobService.createReminderJobs).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: "reminder",
|
||||
reminderPayload: expect.objectContaining({
|
||||
email: "ada@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "client-user-001",
|
||||
companyOwnerId: "owner-001",
|
||||
emailSubject: "TurnosXpress :: Recordatorio",
|
||||
emailMessage: "EMAIL REMINDER Ada Lovelace",
|
||||
wapMessage: "WAP REMINDER Ada Lovelace",
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
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.");
|
||||
});
|
||||
|
||||
it("stores organization-rendered update template content with contact snapshot fields", async () => {
|
||||
const emailContent = await (AppointmentsList as any).tryToSendNotification({
|
||||
appointmentId: "appt-001",
|
||||
sessionUser: "owner-001",
|
||||
type: "update",
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await (AppointmentsList as any).tryToSendNotification({
|
||||
appointmentId: "appt-001",
|
||||
sessionUser: "owner-001",
|
||||
type: "update",
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await (AppointmentsList as any).createUpdateNotificationJobs({
|
||||
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,
|
||||
reminderEmailMessage: "EMAIL REMINDER Ada Lovelace",
|
||||
reminderWapMessage: "WAP REMINDER Ada Lovelace",
|
||||
});
|
||||
|
||||
expect((AppointmentsList as any).jobService.createJob).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: "update",
|
||||
appointmentStart: new Date("2026-07-22T11:00:00.000Z"),
|
||||
payload: expect.objectContaining({
|
||||
email: "ada@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "client-user-001",
|
||||
companyOwnerId: "owner-001",
|
||||
emailSubject: "TurnosXpress :: Turno actualizado",
|
||||
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 actualizado en clases llavallol",
|
||||
systemMessage: "EMAIL ALTA Ada Lovelace Historia clases llavallol 22/07/2026 08:00hs.",
|
||||
}),
|
||||
reminderPayload: expect.objectContaining({
|
||||
email: "ada@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "client-user-001",
|
||||
companyOwnerId: "owner-001",
|
||||
emailSubject: "TurnosXpress :: Recordatorio",
|
||||
emailMessage: "EMAIL REMINDER Ada Lovelace",
|
||||
wapMessage: "WAP REMINDER Ada Lovelace",
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -58,13 +58,18 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
|
||||
templateWapNotifId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateWapAltaId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateWapCancellationId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateEmailNotifId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateEmailAltaId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
templateEmailCancellationId: { type: Schema.Types.ObjectId, required: false, ref: "Template" },
|
||||
onboardingStep: { type: Number, required: false, default: 0 },
|
||||
onboardingCompleted: { type: Boolean, required: false, default: false },
|
||||
|
||||
fixedPostIds: { type: Array, required: false },
|
||||
banned: { type: Boolean, required: false, default: false },
|
||||
showPublicScores: { type: Boolean, required: false, default: true },
|
||||
showPublicOpinions: { type: Boolean, required: false, default: true },
|
||||
showPublicProfessionals: { type: Boolean, required: false, default: true },
|
||||
});
|
||||
|
||||
this.companyList = model<ICompanyDocument>("Company", this.schema);
|
||||
@@ -205,6 +210,10 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
updateCompany.templateWapAltaId = data.templateWapAltaId;
|
||||
}
|
||||
|
||||
if (data.templateWapCancellationId) {
|
||||
updateCompany.templateWapCancellationId = data.templateWapCancellationId;
|
||||
}
|
||||
|
||||
if (data.templateEmailNotifId) {
|
||||
updateCompany.templateEmailNotifId = data.templateEmailNotifId;
|
||||
}
|
||||
@@ -213,6 +222,10 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
updateCompany.templateEmailAltaId = data.templateEmailAltaId;
|
||||
}
|
||||
|
||||
if (data.templateEmailCancellationId) {
|
||||
updateCompany.templateEmailCancellationId = data.templateEmailCancellationId;
|
||||
}
|
||||
|
||||
if (data.onboardingStep !== undefined) {
|
||||
updateCompany.onboardingStep = data.onboardingStep;
|
||||
}
|
||||
@@ -225,6 +238,18 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
updateCompany.banned = data.banned;
|
||||
}
|
||||
|
||||
if (data.showPublicScores !== undefined) {
|
||||
updateCompany.showPublicScores = data.showPublicScores;
|
||||
}
|
||||
|
||||
if (data.showPublicOpinions !== undefined) {
|
||||
updateCompany.showPublicOpinions = data.showPublicOpinions;
|
||||
}
|
||||
|
||||
if (data.showPublicProfessionals !== undefined) {
|
||||
updateCompany.showPublicProfessionals = data.showPublicProfessionals;
|
||||
}
|
||||
|
||||
updateCompany.save();
|
||||
|
||||
//actualizo los campos correspondientes a la localizacion de los servicios de la organizacion.
|
||||
|
||||
@@ -47,11 +47,16 @@ export type UpdateCompanyParams = {
|
||||
sessionUser: string;
|
||||
templateWapNotifId?: string;
|
||||
templateWapAltaId?: string;
|
||||
templateWapCancellationId?: string;
|
||||
templateEmailNotifId?: string;
|
||||
templateEmailAltaId?: string;
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
};
|
||||
|
||||
export type SetCompanyFileParams = {
|
||||
@@ -144,12 +149,17 @@ export interface ICompany {
|
||||
automaticNotifications?: boolean;
|
||||
templateWapNotifId?: string;
|
||||
templateWapAltaId?: string;
|
||||
templateWapCancellationId?: string;
|
||||
templateEmailNotifId?: string;
|
||||
templateEmailAltaId?: string;
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
fixedPostIds?: Array<string>;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
}
|
||||
|
||||
export interface MyOranizationsView {
|
||||
@@ -192,11 +202,16 @@ export interface MyOranizationsView {
|
||||
appointmentAlert?: string;
|
||||
templateWapNotifId?: string;
|
||||
templateWapAltaId?: string;
|
||||
templateWapCancellationId?: string;
|
||||
templateEmailNotifId?: string;
|
||||
templateEmailAltaId?: string;
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
}
|
||||
|
||||
export interface ClientOrganizationView {
|
||||
|
||||
@@ -67,6 +67,17 @@ class CompaniesManager implements ICompaniesManager {
|
||||
this.companies = new CompaniesAdapterMongoose();
|
||||
}
|
||||
|
||||
private async validatePublicRatingFlagsPlan(ownerId: string): Promise<void> {
|
||||
const { default: PlanSubscriptionsList } = await import("../PlanSubscriptions/PlanSubscriptons");
|
||||
const subscription = await PlanSubscriptionsList.getSubscriptionByUser({
|
||||
sessionUser: ownerId,
|
||||
});
|
||||
|
||||
if (!subscription || subscription.plan.price === 0) {
|
||||
throw new Error("Esta configuración está disponible solo para planes pagos.");
|
||||
}
|
||||
}
|
||||
|
||||
public async toggleFixedPost(data: FixCompanyPostParams): Promise<void> {
|
||||
await validateSessionUser({
|
||||
sessionUser: data.sessionUser,
|
||||
@@ -489,6 +500,14 @@ class CompaniesManager implements ICompaniesManager {
|
||||
throw new Error(NoPermissionMessage());
|
||||
}
|
||||
|
||||
if (
|
||||
data.showPublicScores !== undefined ||
|
||||
data.showPublicOpinions !== undefined ||
|
||||
data.showPublicProfessionals !== undefined
|
||||
) {
|
||||
await this.validatePublicRatingFlagsPlan(String(companyCheck.ownerId));
|
||||
}
|
||||
|
||||
let updateData = {
|
||||
...data,
|
||||
};
|
||||
@@ -597,6 +616,9 @@ class CompaniesManager implements ICompaniesManager {
|
||||
templateEmailAltaId: isNull<string>(company.templateEmailAltaId, ""),
|
||||
onboardingStep: company.onboardingStep,
|
||||
onboardingCompleted: company.onboardingCompleted,
|
||||
showPublicScores: company.showPublicScores ?? true,
|
||||
showPublicOpinions: company.showPublicOpinions ?? true,
|
||||
showPublicProfessionals: company.showPublicProfessionals ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -660,7 +682,11 @@ class CompaniesManager implements ICompaniesManager {
|
||||
continue;
|
||||
}
|
||||
|
||||
const isAdmin = await EmployeesList.checkPermission(companyDoc, employ.id, EmployeeRoles.ADMIN);
|
||||
const isAdmin = await EmployeesList.checkPermission(
|
||||
companyDoc,
|
||||
data.sessionUser,
|
||||
EmployeeRoles.ADMIN
|
||||
);
|
||||
|
||||
returnData.push({
|
||||
id: isNull<string>(company.id, ""),
|
||||
@@ -716,6 +742,9 @@ class CompaniesManager implements ICompaniesManager {
|
||||
templateEmailAltaId: isNull<string>(company.templateEmailAltaId, ""),
|
||||
onboardingStep: company.onboardingStep,
|
||||
onboardingCompleted: company.onboardingCompleted,
|
||||
showPublicScores: company.showPublicScores ?? true,
|
||||
showPublicOpinions: company.showPublicOpinions ?? true,
|
||||
showPublicProfessionals: company.showPublicProfessionals ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -786,6 +815,9 @@ class CompaniesManager implements ICompaniesManager {
|
||||
templateEmailAltaId: isNull<string>(company.templateEmailAltaId, ""),
|
||||
onboardingStep: company.onboardingStep,
|
||||
onboardingCompleted: company.onboardingCompleted,
|
||||
showPublicScores: company.showPublicScores ?? true,
|
||||
showPublicOpinions: company.showPublicOpinions ?? true,
|
||||
showPublicProfessionals: company.showPublicProfessionals ?? true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
PaginateEmployeesParams,
|
||||
PaginateEmployeesResults,
|
||||
CompanyEmployeesView,
|
||||
PublicCompanyEmployeeView,
|
||||
FindPublicEmployeeParams,
|
||||
PublicEmployeeView,
|
||||
FindEmployeesParams,
|
||||
FindEmployeesByIdParams,
|
||||
UpdateEmployeeRolesParams,
|
||||
@@ -442,6 +445,71 @@ class EmployeeManager implements IEmployeesManager {
|
||||
return view;
|
||||
}
|
||||
|
||||
public async findPublicByCompanyId(
|
||||
data: FindEmployeesParams
|
||||
): Promise<PublicCompanyEmployeeView[]> {
|
||||
const employees = await this.employees.find({
|
||||
companyId: data.companyId,
|
||||
guestOk: true,
|
||||
hostOk: true,
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
const view = await Promise.all(
|
||||
employees.map(async (employee) => {
|
||||
const userData = await UsersManager.users.findOne({ _id: employee.userId });
|
||||
|
||||
if (!userData) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const strFirstName = isNull<string>(userData.firstName, "");
|
||||
const strLastName = isNull<string>(userData.lastName, "");
|
||||
const strFullName = joinStrings([strFirstName, strLastName], " ");
|
||||
|
||||
return {
|
||||
employeeId: isNull<string>(employee.id, ""),
|
||||
userId: employee.userId,
|
||||
firstName: strFirstName,
|
||||
lastName: strLastName,
|
||||
avatarUrl: getAvatar(userData.id, userData.avatar, strFullName),
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return view.filter((employee): employee is PublicCompanyEmployeeView => employee !== null);
|
||||
}
|
||||
|
||||
public async findPublicByEmployeeId(data: FindPublicEmployeeParams): Promise<PublicEmployeeView> {
|
||||
const employee = await this.employees.findOne({
|
||||
_id: data.employeeId,
|
||||
guestOk: true,
|
||||
hostOk: true,
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
if (!employee) {
|
||||
throw new Error("El colaborador no existe");
|
||||
}
|
||||
|
||||
const userData = await UsersManager.users.findOne({ _id: employee.userId });
|
||||
|
||||
if (!userData) {
|
||||
throw new Error("El colaborador no existe");
|
||||
}
|
||||
|
||||
const strFirstName = isNull<string>(userData.firstName, "");
|
||||
const strLastName = isNull<string>(userData.lastName, "");
|
||||
const strFullName = joinStrings([strFirstName, strLastName], " ");
|
||||
|
||||
return {
|
||||
employeeId: isNull<string>(employee.id, ""),
|
||||
firstName: strFirstName,
|
||||
lastName: strLastName,
|
||||
avatarUrl: getAvatar(userData.id, userData.avatar, strFullName),
|
||||
};
|
||||
}
|
||||
|
||||
public async findById(data: FindEmployeesByIdParams): Promise<CompanyEmployeesView> {
|
||||
const employee = await this.employees.findOne({ _id: data.id });
|
||||
|
||||
|
||||
@@ -119,6 +119,25 @@ export interface CompanyEmployeesView {
|
||||
};
|
||||
}
|
||||
|
||||
export interface PublicCompanyEmployeeView {
|
||||
employeeId: string;
|
||||
userId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatarUrl: string;
|
||||
}
|
||||
|
||||
export interface FindPublicEmployeeParams {
|
||||
employeeId: string;
|
||||
}
|
||||
|
||||
export interface PublicEmployeeView {
|
||||
employeeId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatarUrl: string;
|
||||
}
|
||||
|
||||
export interface IncompleteCollaboratorView {
|
||||
employeeId: string;
|
||||
companyId: string;
|
||||
@@ -143,6 +162,8 @@ export interface IEmployeesManager {
|
||||
updateEmployeeRoles(data: UpdateEmployeeRolesParams): Promise<void>;
|
||||
update(data: UpdateEmployeeParams): Promise<void>;
|
||||
findByCompanyId(data: FindEmployeesParams): Promise<CompanyEmployeesView[]>;
|
||||
findPublicByCompanyId(data: FindEmployeesParams): Promise<PublicCompanyEmployeeView[]>;
|
||||
findPublicByEmployeeId(data: FindPublicEmployeeParams): Promise<PublicEmployeeView>;
|
||||
findById(data: FindEmployeesByIdParams): Promise<CompanyEmployeesView>;
|
||||
textObjectFilter(data: FindEmployeesParams): Promise<TextObjectFilterResult[]>;
|
||||
deleteEmployeesByCompany(data: DeleteEmployeesByCompany): Promise<void>;
|
||||
|
||||
@@ -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,280 @@
|
||||
import {
|
||||
CreateJobParams,
|
||||
NotificationChannel,
|
||||
} 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"];
|
||||
reminderPayload?: 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,
|
||||
payload: params.reminderPayload,
|
||||
});
|
||||
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;
|
||||
}
|
||||
|
||||
async createMandatoryCreationJob(params: CreateJobServiceParams): Promise<any[]> {
|
||||
const payloadChannels = this.getPayloadChannels(params.payload);
|
||||
const channels = await this.policyResolver.resolveAvailableChannels(
|
||||
params.companyId,
|
||||
payloadChannels
|
||||
);
|
||||
|
||||
if (channels.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const scheduledAt = params.scheduledAt || new Date();
|
||||
const jobs: any[] = [];
|
||||
|
||||
for (const channel of channels) {
|
||||
const job = await this.jobAdapter.create({
|
||||
companyId: params.companyId,
|
||||
appointmentId: params.appointmentId,
|
||||
clientId: params.clientId,
|
||||
channel,
|
||||
type: "creation",
|
||||
scheduledAt,
|
||||
payload: params.payload,
|
||||
});
|
||||
jobs.push(job);
|
||||
}
|
||||
|
||||
return jobs;
|
||||
}
|
||||
|
||||
async createReminderJobs(params: CreateJobServiceParams): Promise<any[]> {
|
||||
const resolvedPolicy = await this.policyResolver.resolve(
|
||||
params.companyId,
|
||||
params.clientId
|
||||
);
|
||||
|
||||
if (!params.appointmentStart || resolvedPolicy.channels.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const jobs: any[] = [];
|
||||
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,
|
||||
payload: params.reminderPayload,
|
||||
});
|
||||
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, only the pre-midnight segment ends next day.
|
||||
if (toHour < fromHour && scheduledHour >= fromHour) {
|
||||
adjusted = adjusted.add(1, "day");
|
||||
}
|
||||
return adjusted.toDate();
|
||||
}
|
||||
|
||||
return scheduledAt;
|
||||
}
|
||||
|
||||
private getPayloadChannels(payload?: CreateJobParams["payload"]): NotificationChannel[] {
|
||||
const channels: NotificationChannel[] = [];
|
||||
|
||||
if (payload?.email) {
|
||||
channels.push("email");
|
||||
}
|
||||
|
||||
if (payload?.phoneNumber) {
|
||||
channels.push("whatsapp");
|
||||
}
|
||||
|
||||
if (payload?.userId) {
|
||||
channels.push("system");
|
||||
}
|
||||
|
||||
return channels;
|
||||
}
|
||||
|
||||
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,173 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
async resolveAvailableChannels(
|
||||
companyId: string,
|
||||
channels: NotificationChannel[]
|
||||
): Promise<NotificationChannel[]> {
|
||||
const companyPolicy = await this.companyPolicyAdapter.findOne({ companyId });
|
||||
const enabledChannels = companyPolicy
|
||||
? companyPolicy.defaultChannels
|
||||
: SYSTEM_DEFAULT_CHANNELS;
|
||||
const companyEnabledChannels = channels.filter((channel) =>
|
||||
enabledChannels.includes(channel)
|
||||
);
|
||||
|
||||
return this.applyPlanLimits(companyId, companyEnabledChannels);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,511 @@
|
||||
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(),
|
||||
resolveAvailableChannels: 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;
|
||||
let mockResolveAvailableChannels: 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;
|
||||
mockResolveAvailableChannels = (service as any).policyResolver.resolveAvailableChannels 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("passes reminder snapshot payload to scheduled reminder jobs", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-21T14:00:00.000Z"));
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: ["whatsapp", "email"],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
reminderRules: [{ offset: 30, enabled: true }],
|
||||
};
|
||||
const payload = { message: "Creation body" };
|
||||
const reminderPayload = {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
companyOwnerId: "owner-1",
|
||||
emailMessage: "Reminder email body",
|
||||
wapMessage: "Reminder WAP body",
|
||||
};
|
||||
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-21T15:00:00.000Z"),
|
||||
payload,
|
||||
reminderPayload,
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
expect(createCalls.filter((job) => job.type === "creation")).toEqual([
|
||||
expect.objectContaining({ channel: "whatsapp", payload }),
|
||||
expect.objectContaining({ channel: "email", payload }),
|
||||
]);
|
||||
expect(createCalls.filter((job) => job.type === "reminder")).toEqual([
|
||||
expect.objectContaining({ channel: "whatsapp", payload: reminderPayload }),
|
||||
expect.objectContaining({ channel: "email", payload: reminderPayload }),
|
||||
]);
|
||||
});
|
||||
|
||||
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("creates mandatory creation jobs from available payload destinations without resolving reminder policy", async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-21T14:00:00.000Z"));
|
||||
mockJobCreate.mockResolvedValue({ id: "job-1" });
|
||||
mockResolveAvailableChannels.mockResolvedValue(["email", "whatsapp"]);
|
||||
const payload = {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
companyOwnerId: "owner-1",
|
||||
emailMessage: "Alta email",
|
||||
wapMessage: "Alta WAP",
|
||||
};
|
||||
|
||||
const result = await service.createMandatoryCreationJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
payload,
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
expect(mockResolverResolve).not.toHaveBeenCalled();
|
||||
expect(mockResolveAvailableChannels).toHaveBeenCalledWith("company-1", [
|
||||
"email",
|
||||
"whatsapp",
|
||||
]);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(createCalls).toEqual([
|
||||
expect.objectContaining({
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: new Date("2026-07-21T14:00:00.000Z"),
|
||||
payload,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
channel: "whatsapp",
|
||||
type: "creation",
|
||||
scheduledAt: new Date("2026-07-21T14:00:00.000Z"),
|
||||
payload,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not create mandatory creation jobs for channels missing destination data", async () => {
|
||||
mockResolveAvailableChannels.mockResolvedValue([]);
|
||||
|
||||
await service.createMandatoryCreationJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
payload: {
|
||||
companyOwnerId: "owner-1",
|
||||
emailMessage: "Alta email",
|
||||
wapMessage: "Alta WAP",
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockResolverResolve).not.toHaveBeenCalled();
|
||||
expect(mockResolveAvailableChannels).toHaveBeenCalledWith("company-1", []);
|
||||
expect(mockJobCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not create mandatory creation jobs for unavailable channels", async () => {
|
||||
mockResolveAvailableChannels.mockResolvedValue(["email"]);
|
||||
const payload = {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
companyOwnerId: "owner-1",
|
||||
};
|
||||
|
||||
const result = await service.createMandatoryCreationJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
payload,
|
||||
});
|
||||
|
||||
const createCalls = mockJobCreate.mock.calls.map((call) => call[0]);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(createCalls).toEqual([
|
||||
expect.objectContaining({ channel: "email", type: "creation", payload }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps reminder jobs policy-aware when resolved channels are empty", async () => {
|
||||
const resolvedPolicy: ResolvedPolicy = {
|
||||
channels: [],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
reminderRules: [{ offset: 30, enabled: true }],
|
||||
};
|
||||
mockResolverResolve.mockResolvedValue(resolvedPolicy);
|
||||
|
||||
const result = await service.createReminderJobs({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "reminder",
|
||||
appointmentStart: new Date("2026-07-21T15:00:00.000Z"),
|
||||
reminderPayload: { email: "client@example.com" },
|
||||
});
|
||||
|
||||
expect(mockResolverResolve).toHaveBeenCalledWith("company-1", "client-1");
|
||||
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("adjusts early morning quiet hours crossing midnight to the same day", 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" });
|
||||
|
||||
await service.createJob({
|
||||
companyId: "company-1",
|
||||
clientId: "client-1",
|
||||
appointmentId: "appt-1",
|
||||
type: "creation",
|
||||
scheduledAt: new Date("2026-07-21T05:00:00.000Z"),
|
||||
});
|
||||
|
||||
const createCall = mockJobCreate.mock.calls[0][0];
|
||||
expect(createCall.scheduledAt.toISOString()).toBe("2026-07-21T07:00:00.000Z");
|
||||
});
|
||||
|
||||
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,351 @@
|
||||
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([]);
|
||||
});
|
||||
|
||||
it("resolves available channels from company defaults and plan limits without client preferences", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: ["whatsapp" as NotificationChannel, "email" as NotificationChannel],
|
||||
mutedChannels: ["email" as NotificationChannel],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
});
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
const result = await resolver.resolveAvailableChannels("company-1", [
|
||||
"whatsapp",
|
||||
"email",
|
||||
"system",
|
||||
]);
|
||||
|
||||
expect(result).toEqual(["whatsapp", "email"]);
|
||||
expect(mockClientPreferencesFindOne).not.toHaveBeenCalled();
|
||||
expect(mockOverrideFindOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes available channels disallowed by the owner plan", async () => {
|
||||
mockCompanyPolicyFindOne.mockResolvedValue({
|
||||
companyId: "company-1",
|
||||
defaultChannels: ["whatsapp" as NotificationChannel, "email" as NotificationChannel],
|
||||
timezone: "America/Argentina/Buenos_Aires",
|
||||
});
|
||||
(PlanSubscriptionsList.checkFeature as jest.Mock).mockImplementation(
|
||||
async (params: { feature: string }) =>
|
||||
params.feature !== PlanFeatures.WAP_NOTIFICATIONS
|
||||
);
|
||||
|
||||
const result = await resolver.resolveAvailableChannels("company-1", [
|
||||
"whatsapp",
|
||||
"email",
|
||||
]);
|
||||
|
||||
expect(result).toEqual(["email"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import { Document, Model, Schema, Types, model, models } from "mongoose";
|
||||
import getAvatar from "../../helpers/getAvatar";
|
||||
import { joinStrings } from "../../helpers/String";
|
||||
import {
|
||||
FindRatingsParams,
|
||||
IRating,
|
||||
IRatingsAdapter,
|
||||
RATING_COMMENT_MAX_LENGTH,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
RatingTargetType,
|
||||
} from "./Ratings.Interface";
|
||||
|
||||
export interface IRatingDocument extends Omit<IRating, "id">, Document {
|
||||
_id: Types.ObjectId;
|
||||
}
|
||||
|
||||
type RatingReviewDocument = IRatingDocument & {
|
||||
userId?: {
|
||||
_id: Types.ObjectId;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
avatar?: string;
|
||||
};
|
||||
};
|
||||
|
||||
const GENERIC_REVIEW_AUTHOR = "Cliente verificado";
|
||||
|
||||
export class RatingsAdapterMongoose implements IRatingsAdapter {
|
||||
schema: Schema;
|
||||
ratingsList: Model<IRatingDocument>;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema(
|
||||
{
|
||||
appointmentId: { type: Schema.Types.ObjectId, required: true, ref: "Appointment" },
|
||||
userId: { type: Schema.Types.ObjectId, required: true, ref: "User" },
|
||||
companyId: { type: Schema.Types.ObjectId, required: true, ref: "Companie" },
|
||||
serviceId: { type: Schema.Types.ObjectId, required: true, ref: "Service" },
|
||||
employeeId: { type: Schema.Types.ObjectId, required: true, ref: "Employee" },
|
||||
targetType: { type: String, required: true, enum: Object.values(RatingTargetType) },
|
||||
targetId: { type: Schema.Types.ObjectId, required: true },
|
||||
score: { type: Number, required: true, min: 1, max: 5 },
|
||||
comment: { type: String, required: false, default: "", maxlength: RATING_COMMENT_MAX_LENGTH },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
this.schema.index({ userId: 1, targetType: 1, targetId: 1 }, { unique: true });
|
||||
this.ratingsList = (models.Rating as Model<IRatingDocument>) || model<IRatingDocument>("Rating", this.schema);
|
||||
}
|
||||
|
||||
public async create(data: Omit<IRating, "id" | "createdAt" | "updatedAt">): Promise<IRating> {
|
||||
const rating = await this.ratingsList.create(data);
|
||||
return this.mapRating(rating);
|
||||
}
|
||||
|
||||
public async find(filters: FindRatingsParams): Promise<IRating[]> {
|
||||
const ratings = await this.ratingsList.find(filters).exec();
|
||||
return ratings.map((rating) => this.mapRating(rating));
|
||||
}
|
||||
|
||||
public async findOne(filters: FindRatingsParams): Promise<IRating | null> {
|
||||
const rating = await this.ratingsList.findOne(filters).exec();
|
||||
return rating ? this.mapRating(rating) : null;
|
||||
}
|
||||
|
||||
public async count(filters: FindRatingsParams): Promise<number> {
|
||||
return this.ratingsList.countDocuments(filters).exec();
|
||||
}
|
||||
|
||||
public async summaryByTarget(filters: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult> {
|
||||
const [summary] = await this.ratingsList
|
||||
.aggregate<{ averageScore: number; totalCount: number }>([
|
||||
{
|
||||
$match: {
|
||||
targetType: filters.targetType,
|
||||
targetId: new Types.ObjectId(filters.targetId),
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
averageScore: { $avg: "$score" },
|
||||
totalCount: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
])
|
||||
.exec();
|
||||
|
||||
return {
|
||||
averageScore: summary?.averageScore || 0,
|
||||
totalCount: summary?.totalCount || 0,
|
||||
};
|
||||
}
|
||||
|
||||
public async summaryByTargets(filters: { targetType: RatingTargetType; targetIds: string[] }): Promise<RatingTargetSummaryResult> {
|
||||
const targetIds = filters.targetIds.filter((targetId) => Types.ObjectId.isValid(targetId));
|
||||
|
||||
if (targetIds.length === 0) {
|
||||
return { averageScore: 0, totalCount: 0 };
|
||||
}
|
||||
|
||||
const [summary] = await this.ratingsList
|
||||
.aggregate<{ averageScore: number; totalCount: number }>([
|
||||
{
|
||||
$match: {
|
||||
targetType: filters.targetType,
|
||||
targetId: { $in: targetIds.map((targetId) => new Types.ObjectId(targetId)) },
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
averageScore: { $avg: "$score" },
|
||||
totalCount: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
])
|
||||
.exec();
|
||||
|
||||
return {
|
||||
averageScore: summary?.averageScore || 0,
|
||||
totalCount: summary?.totalCount || 0,
|
||||
};
|
||||
}
|
||||
|
||||
public async reviewsByTarget(filters: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult> {
|
||||
const page = filters.page || 1;
|
||||
const pageSize = filters.pageSize || filters.limit || 20;
|
||||
const targetReviewsFilter = {
|
||||
targetType: filters.targetType,
|
||||
targetId: new Types.ObjectId(filters.targetId),
|
||||
comment: { $regex: /\S/ },
|
||||
};
|
||||
|
||||
const total = await this.ratingsList.countDocuments(targetReviewsFilter).exec();
|
||||
const ratings = await this.ratingsList
|
||||
.find(targetReviewsFilter)
|
||||
.sort({ score: -1, createdAt: -1 })
|
||||
.skip((page - 1) * pageSize)
|
||||
.limit(pageSize)
|
||||
.select("score comment createdAt userId")
|
||||
.populate("userId", "firstName lastName avatar")
|
||||
.exec();
|
||||
|
||||
const reviews = (ratings as unknown as RatingReviewDocument[]).map((rating) => {
|
||||
const user = rating.userId;
|
||||
const displayName = user ? joinStrings([user.firstName, user.lastName], " ") : "";
|
||||
const authorName = displayName || GENERIC_REVIEW_AUTHOR;
|
||||
|
||||
return {
|
||||
id: rating._id.toString(),
|
||||
score: rating.score,
|
||||
comment: rating.comment || "",
|
||||
createdAt: rating.createdAt,
|
||||
author: {
|
||||
displayName: authorName,
|
||||
avatarUrl: user ? getAvatar(user._id.toString(), user.avatar, "") : "",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
reviews,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
};
|
||||
}
|
||||
|
||||
private mapRating(rating: IRatingDocument): IRating {
|
||||
return {
|
||||
id: rating._id.toString(),
|
||||
appointmentId: rating.appointmentId.toString(),
|
||||
userId: rating.userId.toString(),
|
||||
companyId: rating.companyId.toString(),
|
||||
serviceId: rating.serviceId.toString(),
|
||||
employeeId: rating.employeeId.toString(),
|
||||
targetType: rating.targetType,
|
||||
targetId: rating.targetId.toString(),
|
||||
score: rating.score,
|
||||
comment: rating.comment,
|
||||
createdAt: rating.createdAt,
|
||||
updatedAt: rating.updatedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
export enum RatingTargetType {
|
||||
COMPANY = "company",
|
||||
SERVICE = "service",
|
||||
EMPLOYEE = "employee",
|
||||
}
|
||||
|
||||
export const RATING_COMMENT_MAX_LENGTH = 1000;
|
||||
|
||||
export type FindRatingsParams = {
|
||||
_id?: string;
|
||||
appointmentId?: string;
|
||||
userId?: string;
|
||||
companyId?: string;
|
||||
serviceId?: string;
|
||||
employeeId?: string;
|
||||
targetType?: RatingTargetType;
|
||||
targetId?: string | { $in: string[] };
|
||||
};
|
||||
|
||||
export type CreateRatingParams = {
|
||||
appointmentId: string;
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
score: number;
|
||||
comment?: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type PendingRatingsByUserParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type CountRatingsByUserParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type CountRatingsByUserResult = {
|
||||
count: number;
|
||||
};
|
||||
|
||||
export type ProfessionalRatingSummaryByUserParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type RatingTargetSummaryParams = {
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
};
|
||||
|
||||
export type RatingTargetSummaryResult = {
|
||||
averageScore: number;
|
||||
totalCount: number;
|
||||
};
|
||||
|
||||
export type RatingTargetReviewsParams = RatingTargetSummaryParams & {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export type RatingTargetReviewItem = {
|
||||
id: string;
|
||||
score: number;
|
||||
comment: string;
|
||||
createdAt: Date;
|
||||
author: {
|
||||
displayName: string;
|
||||
avatarUrl: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type RatingTargetReviewsResult = {
|
||||
reviews: RatingTargetReviewItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
};
|
||||
|
||||
export interface IRating {
|
||||
id?: string;
|
||||
appointmentId: string;
|
||||
userId: string;
|
||||
companyId: string;
|
||||
serviceId: string;
|
||||
employeeId: string;
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
score: number;
|
||||
comment?: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface PendingRatingItem {
|
||||
appointmentId: string;
|
||||
appointmentDate: string;
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
targetName: string;
|
||||
companyId: string;
|
||||
serviceId: string;
|
||||
employeeId: string;
|
||||
serviceName: string;
|
||||
}
|
||||
|
||||
export interface IRatingsAdapter {
|
||||
create(data: Omit<IRating, "id" | "createdAt" | "updatedAt">): Promise<IRating>;
|
||||
find(filters: FindRatingsParams): Promise<IRating[]>;
|
||||
findOne(filters: FindRatingsParams): Promise<IRating | null>;
|
||||
count(filters: FindRatingsParams): Promise<number>;
|
||||
summaryByTarget(filters: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult>;
|
||||
summaryByTargets(filters: { targetType: RatingTargetType; targetIds: string[] }): Promise<RatingTargetSummaryResult>;
|
||||
reviewsByTarget(filters: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult>;
|
||||
}
|
||||
|
||||
export interface IRatingsManager {
|
||||
ratings: IRatingsAdapter;
|
||||
createRating(data: CreateRatingParams): Promise<IRating>;
|
||||
pendingByUser(data: PendingRatingsByUserParams): Promise<PendingRatingItem[]>;
|
||||
countByUser(data: CountRatingsByUserParams): Promise<CountRatingsByUserResult>;
|
||||
professionalSummaryByUser(data: ProfessionalRatingSummaryByUserParams): Promise<RatingTargetSummaryResult>;
|
||||
summaryByTarget(data: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult>;
|
||||
reviewsByTarget(data: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult>;
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
import dayjs from "dayjs";
|
||||
import { Types } from "mongoose";
|
||||
import { isNull } from "../../helpers/IsNull";
|
||||
import { joinStrings } from "../../helpers/String";
|
||||
import AppointmentList from "../Appointments/Appointments";
|
||||
import CompaniesManager from "../Companies/Companies";
|
||||
import EmployeesList from "../Employees/Employee";
|
||||
import ServicesManager from "../Services/Service";
|
||||
import UsersManager from "../Users/Users";
|
||||
import { RatingsAdapterMongoose } from "./Ratings.Adapter.Mongoose";
|
||||
import {
|
||||
CountRatingsByUserParams,
|
||||
CountRatingsByUserResult,
|
||||
CreateRatingParams,
|
||||
IRating,
|
||||
IRatingsManager,
|
||||
PendingRatingItem,
|
||||
PendingRatingsByUserParams,
|
||||
ProfessionalRatingSummaryByUserParams,
|
||||
RATING_COMMENT_MAX_LENGTH,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
RatingTargetType,
|
||||
} from "./Ratings.Interface";
|
||||
|
||||
const PENDING_RATINGS_APPOINTMENT_LIMIT = 50;
|
||||
const TARGET_REVIEWS_LIMIT = 20;
|
||||
|
||||
class RatingsManager implements IRatingsManager {
|
||||
ratings: RatingsAdapterMongoose;
|
||||
|
||||
constructor() {
|
||||
this.ratings = new RatingsAdapterMongoose();
|
||||
}
|
||||
|
||||
public async createRating(data: CreateRatingParams): Promise<IRating> {
|
||||
await this.validateSessionUser(data.sessionUser);
|
||||
this.validateScore(data.score);
|
||||
this.validateTargetType(data.targetType);
|
||||
const comment = isNull<string>(data.comment, "").trim();
|
||||
this.validateComment(comment);
|
||||
|
||||
const appointment = await AppointmentList.Appointments.AppointmentList.findOne({
|
||||
_id: data.appointmentId,
|
||||
userId: data.sessionUser,
|
||||
});
|
||||
|
||||
if (!appointment) {
|
||||
throw new Error("No se encontró un turno válido para calificar.");
|
||||
}
|
||||
|
||||
if (!appointment.present || !dayjs(appointment.dateDay).isBefore(dayjs().startOf("day"))) {
|
||||
throw new Error("Solo puedes calificar turnos pasados a los que asististe.");
|
||||
}
|
||||
|
||||
const expectedTargetId = this.getTargetId({
|
||||
targetType: data.targetType,
|
||||
companyId: String(appointment.companyId),
|
||||
serviceId: String(appointment.serviceId),
|
||||
employeeId: String(appointment.employeeId),
|
||||
});
|
||||
|
||||
if (String(data.targetId) !== expectedTargetId) {
|
||||
throw new Error("La calificación no corresponde al turno seleccionado.");
|
||||
}
|
||||
|
||||
const existingRating = await this.ratings.findOne({
|
||||
userId: data.sessionUser,
|
||||
targetType: data.targetType,
|
||||
targetId: data.targetId,
|
||||
});
|
||||
|
||||
if (existingRating) {
|
||||
throw new Error("Ya calificaste este item.");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.ratings.create({
|
||||
appointmentId: data.appointmentId,
|
||||
userId: data.sessionUser,
|
||||
companyId: String(appointment.companyId),
|
||||
serviceId: String(appointment.serviceId),
|
||||
employeeId: String(appointment.employeeId),
|
||||
targetType: data.targetType,
|
||||
targetId: data.targetId,
|
||||
score: data.score,
|
||||
comment,
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.isDuplicateRatingError(error)) {
|
||||
throw new Error("Ya calificaste este item.");
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async pendingByUser(data: PendingRatingsByUserParams): Promise<PendingRatingItem[]> {
|
||||
await this.validateSessionUser(data.sessionUser);
|
||||
|
||||
const appointments = await AppointmentList.Appointments.AppointmentList.find({
|
||||
userId: data.sessionUser,
|
||||
present: true,
|
||||
dateDay: { $lt: dayjs().startOf("day").toDate() },
|
||||
})
|
||||
.sort({ start: -1 })
|
||||
.limit(PENDING_RATINGS_APPOINTMENT_LIMIT);
|
||||
|
||||
const pendingItems: PendingRatingItem[] = [];
|
||||
const seenTargets = new Set<string>();
|
||||
const candidateTargetIds = Array.from(
|
||||
new Set(
|
||||
appointments.flatMap((appointment) => [
|
||||
String(appointment.companyId),
|
||||
String(appointment.serviceId),
|
||||
String(appointment.employeeId),
|
||||
])
|
||||
)
|
||||
);
|
||||
const candidateTargetObjectIds = this.toObjectIds(candidateTargetIds);
|
||||
const existingRatings = await this.ratings.find({
|
||||
userId: data.sessionUser,
|
||||
targetId: { $in: candidateTargetIds },
|
||||
});
|
||||
const ratedTargets = new Set(
|
||||
existingRatings.map((rating) => `${rating.targetType}:${String(rating.targetId)}`)
|
||||
);
|
||||
const companies = await CompaniesManager.companies.find({ _id: { $in: candidateTargetObjectIds } } as any);
|
||||
const services = await ServicesManager.services.find({ _id: { $in: candidateTargetObjectIds } } as any);
|
||||
const employees = await EmployeesList.employees.find({ _id: { $in: candidateTargetObjectIds } } as any);
|
||||
const employeeUserIds = Array.from(new Set(employees.map((employee) => String(employee.userId))));
|
||||
const employeeUsers = await UsersManager.users.find({ _id: { $in: this.toObjectIds(employeeUserIds) } } as any);
|
||||
|
||||
const companiesById = new Map(companies.map((company) => [String(company.id), company]));
|
||||
const servicesById = new Map(services.map((service) => [String(service.id), service]));
|
||||
const employeesById = new Map(employees.map((employee) => [String(employee.id), employee]));
|
||||
const employeeUsersById = new Map(employeeUsers.map((user) => [String(user.id), user]));
|
||||
|
||||
for (const appointment of appointments) {
|
||||
const company = companiesById.get(String(appointment.companyId));
|
||||
const service = servicesById.get(String(appointment.serviceId));
|
||||
const employee = employeesById.get(String(appointment.employeeId));
|
||||
|
||||
if (!company || !service || !employee) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const userEmployee = employeeUsersById.get(String(employee.userId));
|
||||
const employeeName = userEmployee
|
||||
? joinStrings([isNull<string>(userEmployee.firstName, ""), isNull<string>(userEmployee.lastName, "")], " ")
|
||||
: "Profesional";
|
||||
|
||||
const candidates = [
|
||||
{ targetType: RatingTargetType.COMPANY, targetId: String(appointment.companyId), targetName: company.name },
|
||||
{ targetType: RatingTargetType.SERVICE, targetId: String(appointment.serviceId), targetName: service.name },
|
||||
{ targetType: RatingTargetType.EMPLOYEE, targetId: String(appointment.employeeId), targetName: employeeName },
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const seenKey = `${candidate.targetType}:${candidate.targetId}`;
|
||||
if (seenTargets.has(seenKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ratedTargets.has(seenKey)) {
|
||||
seenTargets.add(seenKey);
|
||||
continue;
|
||||
}
|
||||
|
||||
pendingItems.push({
|
||||
appointmentId: String(appointment.id),
|
||||
appointmentDate: dayjs(appointment.start).toISOString(),
|
||||
targetType: candidate.targetType,
|
||||
targetId: candidate.targetId,
|
||||
targetName: candidate.targetName,
|
||||
companyId: String(appointment.companyId),
|
||||
serviceId: String(appointment.serviceId),
|
||||
employeeId: String(appointment.employeeId),
|
||||
serviceName: service.name,
|
||||
});
|
||||
|
||||
seenTargets.add(seenKey);
|
||||
}
|
||||
}
|
||||
|
||||
return pendingItems;
|
||||
}
|
||||
|
||||
public async countByUser(data: CountRatingsByUserParams): Promise<CountRatingsByUserResult> {
|
||||
await this.validateSessionUser(data.sessionUser);
|
||||
|
||||
return {
|
||||
count: await this.ratings.count({ userId: data.sessionUser }),
|
||||
};
|
||||
}
|
||||
|
||||
public async professionalSummaryByUser(data: ProfessionalRatingSummaryByUserParams): Promise<RatingTargetSummaryResult> {
|
||||
await this.validateSessionUser(data.sessionUser);
|
||||
|
||||
const employees = await EmployeesList.employees.find({
|
||||
userId: data.sessionUser,
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
const employeeIds = employees.map((employee) => String(employee.id));
|
||||
|
||||
return this.ratings.summaryByTargets({
|
||||
targetType: RatingTargetType.EMPLOYEE,
|
||||
targetIds: employeeIds,
|
||||
});
|
||||
}
|
||||
|
||||
public async summaryByTarget(data: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult> {
|
||||
this.validateTargetType(data.targetType);
|
||||
|
||||
if (!Types.ObjectId.isValid(data.targetId)) {
|
||||
throw new Error("No se ha proporcionado un objetivo válido.");
|
||||
}
|
||||
|
||||
return this.ratings.summaryByTarget(data);
|
||||
}
|
||||
|
||||
public async reviewsByTarget(data: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult> {
|
||||
this.validateTargetType(data.targetType);
|
||||
|
||||
if (!Types.ObjectId.isValid(data.targetId)) {
|
||||
throw new Error("No se ha proporcionado un objetivo válido.");
|
||||
}
|
||||
|
||||
const pageSize = Math.min(Math.max(data.pageSize || data.limit || TARGET_REVIEWS_LIMIT, 1), TARGET_REVIEWS_LIMIT);
|
||||
const page = Math.max(data.page || 1, 1);
|
||||
|
||||
return this.ratings.reviewsByTarget({
|
||||
...data,
|
||||
page,
|
||||
pageSize,
|
||||
limit: pageSize,
|
||||
});
|
||||
}
|
||||
|
||||
private async validateSessionUser(sessionUser: string): Promise<void> {
|
||||
const user = await UsersManager.users.findOne({ _id: sessionUser });
|
||||
|
||||
if (!user) {
|
||||
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
|
||||
}
|
||||
}
|
||||
|
||||
private toObjectIds(ids: string[]): Types.ObjectId[] {
|
||||
return ids.filter((id) => Types.ObjectId.isValid(id)).map((id) => new Types.ObjectId(id));
|
||||
}
|
||||
|
||||
private validateScore(score: number): void {
|
||||
if (!Number.isInteger(score) || score < 1 || score > 5) {
|
||||
throw new Error("La calificación debe estar entre 1 y 5.");
|
||||
}
|
||||
}
|
||||
|
||||
private validateTargetType(targetType: RatingTargetType): void {
|
||||
if (!Object.values(RatingTargetType).includes(targetType)) {
|
||||
throw new Error("El tipo de calificación no es válido.");
|
||||
}
|
||||
}
|
||||
|
||||
private validateComment(comment: string): void {
|
||||
if (comment.length > RATING_COMMENT_MAX_LENGTH) {
|
||||
throw new Error(`El comentario no puede superar los ${RATING_COMMENT_MAX_LENGTH} caracteres.`);
|
||||
}
|
||||
}
|
||||
|
||||
private isDuplicateRatingError(error: unknown): boolean {
|
||||
return Boolean(error && typeof error === "object" && "code" in error && error.code === 11000);
|
||||
}
|
||||
|
||||
private getTargetId(data: {
|
||||
targetType: RatingTargetType;
|
||||
companyId: string;
|
||||
serviceId: string;
|
||||
employeeId: string;
|
||||
}): string {
|
||||
if (data.targetType === RatingTargetType.COMPANY) {
|
||||
return data.companyId;
|
||||
}
|
||||
|
||||
if (data.targetType === RatingTargetType.SERVICE) {
|
||||
return data.serviceId;
|
||||
}
|
||||
|
||||
return data.employeeId;
|
||||
}
|
||||
}
|
||||
|
||||
const RatingsList = new RatingsManager();
|
||||
|
||||
export default RatingsList;
|
||||
@@ -49,6 +49,49 @@ export type EnableScheduleParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ReservationPeriodScope = "employee" | "all";
|
||||
|
||||
export type ReservationPeriodDurationUnit = "week" | "month";
|
||||
|
||||
export type ReservationPeriodDuration = {
|
||||
unit: ReservationPeriodDurationUnit;
|
||||
value: number;
|
||||
};
|
||||
|
||||
export type ReservationPeriodsSummaryParams = {
|
||||
companyId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ExtendReservationPeriodsParams = {
|
||||
companyId: string;
|
||||
scope: ReservationPeriodScope;
|
||||
employeeId?: string;
|
||||
duration?: ReservationPeriodDuration;
|
||||
weeks?: number;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ReservationPeriodEmployeeSummary = {
|
||||
employeeId: string;
|
||||
employeeFullName: string;
|
||||
employeeEmail: string;
|
||||
employeeAvatar: string;
|
||||
employeeUserId: string;
|
||||
isOpen: boolean;
|
||||
currentOpenUntil: Date | null;
|
||||
daysRemaining: number | null;
|
||||
};
|
||||
|
||||
export type ReservationPeriodsSummary = {
|
||||
companyId: string;
|
||||
status: "missing" | "expired" | "near-ending" | "open";
|
||||
worstDaysRemaining: number | null;
|
||||
currentOpenUntil: Date | null;
|
||||
nearEndingThresholdDays: number;
|
||||
employees: ReservationPeriodEmployeeSummary[];
|
||||
};
|
||||
|
||||
export type DeleteSchedulesEnabledByCompanyParams = {
|
||||
companyId: string;
|
||||
};
|
||||
@@ -94,4 +137,6 @@ export interface ISchedulesEnabledManager {
|
||||
exists(data: CheckSchedulesEnabledParams): Promise<boolean>;
|
||||
deleteSchedulesEnabledByCompany(data: DeleteSchedulesEnabledByCompanyParams): Promise<void>;
|
||||
deleteSchedulesEnabledByEmployee(data: DeleteSchedulesEnabledByEmployeeParams): Promise<void>;
|
||||
summarizeReservationPeriods(data: ReservationPeriodsSummaryParams): Promise<ReservationPeriodsSummary>;
|
||||
extendReservationPeriods(data: ExtendReservationPeriodsParams): Promise<ReservationPeriodsSummary>;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,10 @@ import {
|
||||
FindSchedulesEnabledParams,
|
||||
ISchedulesEnabled,
|
||||
ISchedulesEnabledManager,
|
||||
ReservationPeriodEmployeeSummary,
|
||||
ReservationPeriodsSummary,
|
||||
ReservationPeriodsSummaryParams,
|
||||
ExtendReservationPeriodsParams,
|
||||
SchedulesEnabledView,
|
||||
} from "./SchedulesEnabled.Interface";
|
||||
import { EmployeeRoles } from "../Employees/Employees.Interface";
|
||||
@@ -21,10 +25,26 @@ import { joinStrings } from "../../helpers/String";
|
||||
import getAvatar from "../../helpers/getAvatar";
|
||||
import { NotificationsManager } from "../Notifications/Notifications";
|
||||
import dayjs from "dayjs";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import "dayjs/locale/es";
|
||||
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
dayjs.locale("es");
|
||||
|
||||
const SCHEDULE_BOUNDARY_TIMEZONE = "America/Argentina/Buenos_Aires";
|
||||
const NEAR_ENDING_THRESHOLD_DAYS = 14;
|
||||
const ALLOWED_RESERVATION_PERIOD_DURATIONS = [
|
||||
{ unit: "week", value: 1 },
|
||||
{ unit: "week", value: 2 },
|
||||
{ unit: "week", value: 3 },
|
||||
{ unit: "month", value: 1 },
|
||||
{ unit: "month", value: 2 },
|
||||
] as const;
|
||||
|
||||
class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
schedulesEnabled: SchedulesEnabledAdapterMongoose;
|
||||
|
||||
@@ -73,8 +93,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const schedulesEnabledCheck = await this.schedulesEnabled.findOne({
|
||||
employeeId: data.employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
});
|
||||
|
||||
if (schedulesEnabledCheck) {
|
||||
@@ -84,8 +104,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const newEmplyeesEnabled = await this.schedulesEnabled.create({
|
||||
employeeId: data.employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
|
||||
@@ -125,7 +145,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const employeeCheck = await EmployeesList.employees.findOne({
|
||||
companyId: data.companyId,
|
||||
_id: employeeId,
|
||||
});
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
if (!employeeCheck) {
|
||||
continue;
|
||||
@@ -134,8 +155,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const schedulesEnabledCheck = await this.schedulesEnabled.findOne({
|
||||
employeeId: employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
});
|
||||
|
||||
if (schedulesEnabledCheck) {
|
||||
@@ -145,8 +166,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
await this.schedulesEnabled.create({
|
||||
employeeId: employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
|
||||
@@ -185,7 +206,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const employeeCheck = await EmployeesList.employees.findOne({
|
||||
companyId: data.companyId,
|
||||
_id: employeeId,
|
||||
});
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
if (!employeeCheck) {
|
||||
continue;
|
||||
@@ -194,8 +216,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const schedulesEnabledCheck = await this.schedulesEnabled.findOne({
|
||||
employeeId: employeeId,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: this.normalizeScheduleStartDate(data.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(data.endDate),
|
||||
});
|
||||
|
||||
if (schedulesEnabledCheck) {
|
||||
@@ -229,11 +251,16 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
}
|
||||
|
||||
public async find(data: FindSchedulesEnabledParams): Promise<SchedulesEnabledView[]> {
|
||||
let employeeFilter: any = { companyId: data.companyId };
|
||||
const rangeStart = this.normalizeScheduleStartDate(data.startDate);
|
||||
const rangeEnd = this.normalizeScheduleEndDate(data.endDate);
|
||||
let employeeFilter: any = {
|
||||
companyId: data.companyId,
|
||||
removed: { $ne: true },
|
||||
};
|
||||
if (data.employeeId) {
|
||||
employeeFilter = {
|
||||
...employeeFilter,
|
||||
employeeId: data.employeeId,
|
||||
_id: data.employeeId,
|
||||
};
|
||||
}
|
||||
const employees = await EmployeesList.employees.find(employeeFilter);
|
||||
@@ -244,8 +271,8 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
const schedulesEnabled = await this.schedulesEnabled.schedulesEnabledList.findOne({
|
||||
employeeId: employee.id,
|
||||
companyId: data.companyId,
|
||||
startDate: dayjs(data.startDate).startOf("day").toDate(),
|
||||
endDate: dayjs(data.endDate).endOf("day").toDate(),
|
||||
startDate: { $lte: rangeStart },
|
||||
endDate: { $gte: rangeEnd },
|
||||
});
|
||||
|
||||
const employUser = await UsersManager.users.findOne({
|
||||
@@ -297,6 +324,189 @@ class SchedulesEnabledManager implements ISchedulesEnabledManager {
|
||||
|
||||
await this.schedulesEnabled.delete(String(data.id));
|
||||
}
|
||||
|
||||
public async summarizeReservationPeriods(
|
||||
data: ReservationPeriodsSummaryParams
|
||||
): Promise<ReservationPeriodsSummary> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
|
||||
|
||||
return this.buildReservationPeriodsSummary(data.companyId);
|
||||
}
|
||||
|
||||
public async extendReservationPeriods(
|
||||
data: ExtendReservationPeriodsParams
|
||||
): Promise<ReservationPeriodsSummary> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
|
||||
|
||||
const duration = data.duration || (data.weeks ? { unit: "week" as const, value: Number(data.weeks) } : null);
|
||||
|
||||
if (!duration || !ALLOWED_RESERVATION_PERIOD_DURATIONS.some(option => option.unit === duration.unit && option.value === Number(duration.value))) {
|
||||
throw new Error("El período seleccionado no es válido");
|
||||
}
|
||||
|
||||
const employees = await EmployeesList.employees.find({
|
||||
companyId: data.companyId,
|
||||
removed: { $ne: true },
|
||||
} as any);
|
||||
|
||||
let targetEmployees = employees;
|
||||
|
||||
if (data.scope === "employee") {
|
||||
if (!data.employeeId) {
|
||||
throw new Error("Debe seleccionar un colaborador");
|
||||
}
|
||||
|
||||
targetEmployees = employees.filter(employee => String(employee.id) === String(data.employeeId));
|
||||
|
||||
if (targetEmployees.length === 0) {
|
||||
throw new Error("El colaborador no existe o no pertenece a la organización");
|
||||
}
|
||||
} else if (data.scope !== "all") {
|
||||
throw new Error("El alcance seleccionado no es válido");
|
||||
}
|
||||
|
||||
if (targetEmployees.length === 0) {
|
||||
throw new Error("No hay colaboradores disponibles para extender el período de reservas");
|
||||
}
|
||||
|
||||
const today = dayjs().startOf("day");
|
||||
const summary = await this.buildReservationPeriodsSummary(data.companyId);
|
||||
const operations = targetEmployees.flatMap(employee => {
|
||||
const employeeSummary = summary.employees.find(item => String(item.employeeId) === String(employee.id));
|
||||
const startDate = employeeSummary?.currentOpenUntil && !dayjs(employeeSummary.currentOpenUntil).endOf("day").isBefore(today)
|
||||
? this.getNextWeekStartAfter(dayjs(employeeSummary.currentOpenUntil))
|
||||
: this.getWeekStart(today);
|
||||
const weekRanges = this.buildReservationPeriodWeekRanges(startDate, duration);
|
||||
|
||||
return weekRanges.map(range => ({
|
||||
updateOne: {
|
||||
filter: {
|
||||
employeeId: employee.id,
|
||||
companyId: data.companyId,
|
||||
startDate: this.normalizeScheduleStartDate(range.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(range.endDate),
|
||||
},
|
||||
update: {
|
||||
$setOnInsert: {
|
||||
employeeId: employee.id,
|
||||
companyId: data.companyId,
|
||||
startDate: this.normalizeScheduleStartDate(range.startDate),
|
||||
endDate: this.normalizeScheduleEndDate(range.endDate),
|
||||
},
|
||||
},
|
||||
upsert: true,
|
||||
},
|
||||
}));
|
||||
});
|
||||
|
||||
await this.schedulesEnabled.schedulesEnabledList.bulkWrite(operations, { ordered: true });
|
||||
|
||||
return this.buildReservationPeriodsSummary(data.companyId);
|
||||
}
|
||||
|
||||
private getWeekStart(date: dayjs.Dayjs): dayjs.Dayjs {
|
||||
return date.startOf("day").subtract((date.day() + 6) % 7, "day");
|
||||
}
|
||||
|
||||
private getNextWeekStartAfter(date: dayjs.Dayjs): dayjs.Dayjs {
|
||||
const nextDay = date.add(1, "day").startOf("day");
|
||||
const weekStart = this.getWeekStart(nextDay);
|
||||
|
||||
return weekStart.isBefore(nextDay) ? weekStart.add(1, "week") : weekStart;
|
||||
}
|
||||
|
||||
private buildReservationPeriodWeekRanges(
|
||||
startWeek: dayjs.Dayjs,
|
||||
duration: { unit: "week" | "month"; value: number }
|
||||
): { startDate: dayjs.Dayjs; endDate: dayjs.Dayjs }[] {
|
||||
const ranges: { startDate: dayjs.Dayjs; endDate: dayjs.Dayjs }[] = [];
|
||||
const targetEnd = duration.unit === "week"
|
||||
? startWeek.add(Number(duration.value), "week").subtract(1, "day").endOf("day")
|
||||
: startWeek.add(Number(duration.value), "month").subtract(1, "day").endOf("day");
|
||||
let currentWeekStart = startWeek.startOf("day");
|
||||
|
||||
while (!currentWeekStart.isAfter(targetEnd)) {
|
||||
ranges.push({
|
||||
startDate: currentWeekStart,
|
||||
endDate: currentWeekStart.add(6, "day").endOf("day"),
|
||||
});
|
||||
currentWeekStart = currentWeekStart.add(1, "week");
|
||||
}
|
||||
|
||||
return ranges;
|
||||
}
|
||||
|
||||
private normalizeScheduleStartDate(date: string | Date | dayjs.Dayjs): Date {
|
||||
return dayjs.tz(this.getScheduleDateOnly(date), SCHEDULE_BOUNDARY_TIMEZONE).startOf("day").toDate();
|
||||
}
|
||||
|
||||
private normalizeScheduleEndDate(date: string | Date | dayjs.Dayjs): Date {
|
||||
return dayjs.tz(this.getScheduleDateOnly(date), SCHEDULE_BOUNDARY_TIMEZONE).endOf("day").toDate();
|
||||
}
|
||||
|
||||
private getScheduleDateOnly(date: string | Date | dayjs.Dayjs): string {
|
||||
if (typeof date === "string") {
|
||||
return date.slice(0, 10);
|
||||
}
|
||||
|
||||
if (dayjs.isDayjs(date)) {
|
||||
return date.format("YYYY-MM-DD");
|
||||
}
|
||||
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
private async buildReservationPeriodsSummary(companyId: string): Promise<ReservationPeriodsSummary> {
|
||||
const today = dayjs().startOf("day");
|
||||
const employees = await EmployeesList.findByCompanyId({ companyId });
|
||||
const employeeSummaries: ReservationPeriodEmployeeSummary[] = [];
|
||||
|
||||
for (const employee of employees) {
|
||||
const latestPeriod = await this.schedulesEnabled.schedulesEnabledList
|
||||
.findOne({ companyId, employeeId: employee.id })
|
||||
.sort({ endDate: -1 })
|
||||
.exec();
|
||||
|
||||
const currentOpenUntil = latestPeriod ? latestPeriod.endDate : null;
|
||||
const daysRemaining = currentOpenUntil
|
||||
? dayjs(currentOpenUntil).endOf("day").diff(today, "day")
|
||||
: null;
|
||||
|
||||
employeeSummaries.push({
|
||||
employeeId: employee.id,
|
||||
employeeFullName: employee.fullName,
|
||||
employeeEmail: employee.email,
|
||||
employeeAvatar: employee.avatar,
|
||||
employeeUserId: employee.userId,
|
||||
isOpen: daysRemaining !== null && daysRemaining >= 0,
|
||||
currentOpenUntil,
|
||||
daysRemaining,
|
||||
});
|
||||
}
|
||||
|
||||
const currentOpenUntilDates = employeeSummaries
|
||||
.map(employee => employee.currentOpenUntil)
|
||||
.filter((date): date is Date => Boolean(date));
|
||||
const remainingValues = employeeSummaries
|
||||
.map(employee => employee.daysRemaining)
|
||||
.filter((days): days is number => days !== null);
|
||||
const hasMissing = employeeSummaries.some(employee => employee.currentOpenUntil === null);
|
||||
const hasExpired = employeeSummaries.some(employee => employee.daysRemaining !== null && employee.daysRemaining < 0);
|
||||
const hasNearEnding = employeeSummaries.some(employee => employee.daysRemaining !== null && employee.daysRemaining <= NEAR_ENDING_THRESHOLD_DAYS);
|
||||
|
||||
return {
|
||||
companyId,
|
||||
status: hasMissing ? "missing" : hasExpired ? "expired" : hasNearEnding ? "near-ending" : "open",
|
||||
worstDaysRemaining: remainingValues.length > 0 ? Math.min(...remainingValues) : null,
|
||||
currentOpenUntil: currentOpenUntilDates.length > 0
|
||||
? currentOpenUntilDates.reduce((max, date) => dayjs(date).isAfter(max) ? date : max, currentOpenUntilDates[0])
|
||||
: null,
|
||||
nearEndingThresholdDays: NEAR_ENDING_THRESHOLD_DAYS,
|
||||
employees: employeeSummaries,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const SchedulesEnabledList = new SchedulesEnabledManager();
|
||||
|
||||
@@ -42,6 +42,8 @@ export class ServicesAdapterMongoose implements IServicesAdapter {
|
||||
longitude: { type: Number, required: false, default: 0 },
|
||||
published: { type: String, required: false },
|
||||
banned: { type: Boolean, required: false, default: false },
|
||||
showPublicScores: { type: Boolean, required: false, default: true },
|
||||
showPublicOpinions: { type: Boolean, required: false, default: true },
|
||||
});
|
||||
|
||||
this.serviceList = model<IServiceDocument>("Service", this.schema);
|
||||
@@ -93,6 +95,8 @@ export class ServicesAdapterMongoose implements IServicesAdapter {
|
||||
if (data.latitude) updateService.latitude = data.latitude;
|
||||
if (data.longitude) updateService.longitude = data.longitude;
|
||||
if (data.banned !== undefined) updateService.banned = data.banned;
|
||||
if (data.showPublicScores !== undefined) updateService.showPublicScores = data.showPublicScores;
|
||||
if (data.showPublicOpinions !== undefined) updateService.showPublicOpinions = data.showPublicOpinions;
|
||||
|
||||
await updateService.save();
|
||||
}
|
||||
|
||||
@@ -57,6 +57,8 @@ export type CreateServiceParams = {
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
sessionUser: string;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
};
|
||||
|
||||
export type UpdateServiceParams = {
|
||||
@@ -81,6 +83,8 @@ export type UpdateServiceParams = {
|
||||
longitude?: number;
|
||||
sessionUser: string;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
};
|
||||
|
||||
export type PaginatePublicServicesParams = FindServicesParams & {
|
||||
@@ -155,6 +159,8 @@ export interface IService {
|
||||
published?: SERVICE_PUBLISHED_STATUS;
|
||||
discountId?: string;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
}
|
||||
|
||||
export interface CompanyServiceView {
|
||||
@@ -176,6 +182,8 @@ export interface CompanyServiceView {
|
||||
fontShadowColor: string;
|
||||
published: SERVICE_PUBLISHED_STATUS;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
}
|
||||
|
||||
export interface PublicServiceView {
|
||||
@@ -199,6 +207,8 @@ export interface PublicServiceView {
|
||||
fontColor: string;
|
||||
fontShadowColor: string;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
}
|
||||
|
||||
export interface FindServicesByCompanyParams {
|
||||
|
||||
@@ -46,6 +46,17 @@ class ServiceManager implements IServicesManager {
|
||||
this.services = new ServicesAdapterMongoose();
|
||||
}
|
||||
|
||||
private async validatePublicRatingFlagsPlan(ownerId: string): Promise<void> {
|
||||
const { default: PlanSubscriptionsList } = await import("../PlanSubscriptions/PlanSubscriptons");
|
||||
const subscription = await PlanSubscriptionsList.getSubscriptionByUser({
|
||||
sessionUser: ownerId,
|
||||
});
|
||||
|
||||
if (!subscription || subscription.plan.price === 0) {
|
||||
throw new Error("Esta configuración está disponible solo para planes pagos.");
|
||||
}
|
||||
}
|
||||
|
||||
public async setPublishedStatus(data: SetPublishedStatusParams): Promise<void> {
|
||||
const sessionUser = await UsersManager.users.findOne({
|
||||
_id: data.sessionUser,
|
||||
@@ -145,6 +156,10 @@ class ServiceManager implements IServicesManager {
|
||||
throw new Error("Ha alcanzado el limite de servicios permitidos de acuerdo a su plan.");
|
||||
}
|
||||
|
||||
if (data.showPublicScores !== undefined || data.showPublicOpinions !== undefined) {
|
||||
await this.validatePublicRatingFlagsPlan(String(companyCheck.ownerId));
|
||||
}
|
||||
|
||||
const newService = await this.services.create({
|
||||
...data,
|
||||
...{
|
||||
@@ -190,6 +205,10 @@ class ServiceManager implements IServicesManager {
|
||||
throw new Error(NoPermissionMessage());
|
||||
}
|
||||
|
||||
if (data.showPublicScores !== undefined || data.showPublicOpinions !== undefined) {
|
||||
await this.validatePublicRatingFlagsPlan(String(companyCheck.ownerId));
|
||||
}
|
||||
|
||||
await this.services.update(data);
|
||||
}
|
||||
|
||||
@@ -307,6 +326,8 @@ class ServiceManager implements IServicesManager {
|
||||
service.published,
|
||||
SERVICE_PUBLISHED_STATUS.PRIVATE
|
||||
),
|
||||
showPublicScores: service.showPublicScores ?? true,
|
||||
showPublicOpinions: service.showPublicOpinions ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -363,6 +384,8 @@ class ServiceManager implements IServicesManager {
|
||||
fontColor: isNull<string>(service.fontColor, defFontColor),
|
||||
fontShadowColor: isNull<string>(service.fontShadowColor, defFontShadowColor),
|
||||
published: isNull<SERVICE_PUBLISHED_STATUS>(service.published, SERVICE_PUBLISHED_STATUS.PRIVATE),
|
||||
showPublicScores: service.showPublicScores ?? true,
|
||||
showPublicOpinions: service.showPublicOpinions ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -486,6 +509,8 @@ class ServiceManager implements IServicesManager {
|
||||
color: isNull<string>(service.color, defColor),
|
||||
fontColor: isNull<string>(service.fontColor, defFontColor),
|
||||
fontShadowColor: isNull<string>(service.fontShadowColor, defFontShadowColor),
|
||||
showPublicScores: service.showPublicScores ?? true,
|
||||
showPublicOpinions: service.showPublicOpinions ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,11 @@ export type CreateSystemNotificationParams = {
|
||||
code?: string;
|
||||
};
|
||||
|
||||
export type CreateSystemNotificationBySystemParams = CreateSystemNotificationParams & {
|
||||
userId: string;
|
||||
systemToken: string;
|
||||
};
|
||||
|
||||
export type UpdateSystemNotificationParams = {
|
||||
id: string;
|
||||
readed: boolean;
|
||||
@@ -119,6 +124,7 @@ export interface ISystemNotificationsAdapter {
|
||||
export interface ISystemNotificationsManager {
|
||||
notifications: ISystemNotificationsAdapter;
|
||||
createNotification(data: CreateSystemNotificationParams): Promise<ISystemNotification>;
|
||||
createNotificationBySystem(data: CreateSystemNotificationBySystemParams): Promise<ISystemNotification>;
|
||||
updateNotification(data: UpdateSystemNotificationParams): Promise<void>;
|
||||
deleteNotification(data: DeleteSystemNotificationParams): Promise<void>;
|
||||
deleteConversationNotifications(data: DeleteSystemNotificationsByConversation): Promise<void>;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import CompaniesManager from "../Companies/Companies";
|
||||
import {
|
||||
CreateSystemNotificationParams,
|
||||
CreateSystemNotificationBySystemParams,
|
||||
DeleteNotificationsByDateParams,
|
||||
DeleteNotificationsByUserParams,
|
||||
DeleteSystemNotificationParams,
|
||||
@@ -108,6 +109,28 @@ class SystemNotificationsManager implements ISystemNotificationsManager {
|
||||
return newNotification;
|
||||
}
|
||||
|
||||
public async createNotificationBySystem(
|
||||
data: CreateSystemNotificationBySystemParams
|
||||
): Promise<ISystemNotification> {
|
||||
const expectedToken = process.env.SYSTEM_KEY || process.env.API_KEY;
|
||||
|
||||
if (!expectedToken || data.systemToken !== expectedToken) {
|
||||
throw new Error("Token de sistema inválido");
|
||||
}
|
||||
|
||||
const { systemToken, ...notificationData } = data;
|
||||
const notification = await this.createNotification(notificationData);
|
||||
|
||||
const countUnreadNotifications = await this.finUnreadNotifications({
|
||||
userId: data.userId,
|
||||
sessionUser: data.userId,
|
||||
});
|
||||
|
||||
io.to(`user:${data.userId}`).emit("new_system_notification", countUnreadNotifications);
|
||||
|
||||
return notification;
|
||||
}
|
||||
|
||||
public async updateNotification(data: UpdateSystemNotificationParams): Promise<void> {
|
||||
await validateSessionUser({
|
||||
sessionUser: data.sessionUser,
|
||||
|
||||
@@ -4,8 +4,10 @@ import { TextObjectFilterResult } from "../TextObjectFilter.model";
|
||||
export enum TemplateTypes {
|
||||
WAP_NEW_APPOINTMENT = "wap-new-appointment",
|
||||
WAP_REMINDER = "wap-reminder",
|
||||
WAP_CANCELLATION = "wap-cancellation",
|
||||
EMAIL_NEW_APPOINTMENT = "email-new-appointment",
|
||||
EMAIL_REMINDER = "email-reminder",
|
||||
EMAIL_CANCELLATION = "email-cancellation",
|
||||
}
|
||||
export interface ITemplate {
|
||||
id?: string;
|
||||
|
||||
@@ -215,12 +215,18 @@ export class TemplatesManager implements ITemplatesManager {
|
||||
case TemplateTypes.WAP_NEW_APPOINTMENT:
|
||||
defaultTemplate = `${process.env.WAP_ALTA}`;
|
||||
break;
|
||||
case TemplateTypes.WAP_CANCELLATION:
|
||||
defaultTemplate = `${process.env.WAP_CANCELLATION || process.env.WAP_CANCELACION || ""}`;
|
||||
break;
|
||||
case TemplateTypes.EMAIL_REMINDER:
|
||||
defaultTemplate = `${process.env.WAP_REMINDER}`;
|
||||
break;
|
||||
case TemplateTypes.EMAIL_NEW_APPOINTMENT:
|
||||
defaultTemplate = `${process.env.WAP_ALTA}`;
|
||||
break;
|
||||
case TemplateTypes.EMAIL_CANCELLATION:
|
||||
defaultTemplate = `${process.env.EMAIL_CANCELLATION || process.env.EMAIL_CANCELACION || process.env.WAP_CANCELLATION || process.env.WAP_CANCELACION || ""}`;
|
||||
break;
|
||||
}
|
||||
return defaultTemplate;
|
||||
}
|
||||
|
||||
@@ -55,6 +55,9 @@ export type PublicOrganizationView = {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
appointmentAlert: string;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
showPublicProfessionals: boolean;
|
||||
};
|
||||
|
||||
export type PublicOrganizationServiceViewParams = {
|
||||
@@ -163,6 +166,9 @@ class Views {
|
||||
services,
|
||||
employees: services,
|
||||
appointmentAlert: isNull<string>(company.appointmentAlert, ""),
|
||||
showPublicScores: company.showPublicScores ?? true,
|
||||
showPublicOpinions: company.showPublicOpinions ?? true,
|
||||
showPublicProfessionals: company.showPublicProfessionals ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
AppointmentAdminByClientView,
|
||||
AppointmentAdminByDateView,
|
||||
CreateAppointmentParams,
|
||||
CreateImmediateAppointmentNotificationJobsParams,
|
||||
DeleteAppointmentParams,
|
||||
FindAppointmentsParams,
|
||||
FindAppointmentSchedulesParams,
|
||||
@@ -28,6 +29,7 @@ import { AppointmentService } from "./Appointments.Service";
|
||||
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
||||
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
||||
import { rateLimiter } from "../../middleware/ratelimiter";
|
||||
import { systemTokenMiddleware } from "../../middleware/systemToken";
|
||||
|
||||
@Route("appointments/create")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
@@ -294,7 +296,7 @@ export class SendWapNotificationContrnoller extends Controller {
|
||||
}
|
||||
|
||||
@Route("appointments/send-wap-sys-notification")
|
||||
@Middlewares(rateLimiter)
|
||||
@Middlewares(systemTokenMiddleware)
|
||||
export class SendWapSystemNotificationContrnoller extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@@ -319,7 +321,7 @@ export class SendWapSystemNotificationContrnoller extends Controller {
|
||||
}
|
||||
|
||||
@Route("appointments/send-email-notification")
|
||||
@Middlewares(rateLimiter)
|
||||
@Middlewares([rateLimiter, systemTokenMiddleware])
|
||||
export class SendEmailNotificationContrnoller extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@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")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ApplyAppointmentDiscountContrnoller extends Controller {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
||||
import AppointmentList from "../../Models/Appointments/Appointments";
|
||||
import {
|
||||
CreateImmediateAppointmentNotificationJobsParams,
|
||||
AppointmentAdminByClientView,
|
||||
AppointmentAdminByDateView,
|
||||
CreateAppointmentParams,
|
||||
@@ -161,6 +162,11 @@ export class AppointmentService {
|
||||
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> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
await AppointmentList.applyDiscount(data);
|
||||
|
||||
@@ -9,6 +9,9 @@ import {
|
||||
PaginateEmployeesResults,
|
||||
ValidateEmployeeParams,
|
||||
CompanyEmployeesView,
|
||||
PublicCompanyEmployeeView,
|
||||
FindPublicEmployeeParams,
|
||||
PublicEmployeeView,
|
||||
FindEmployeesByIdParams,
|
||||
UpdateEmployeeRolesParams,
|
||||
UpdateEmployeeParams,
|
||||
@@ -117,6 +120,46 @@ export class GetEmployeesByCompanyController extends Controller {
|
||||
}
|
||||
}
|
||||
|
||||
@Route("employees/public-by-company")
|
||||
export class GetPublicEmployeesByCompanyController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async findPublicByCompanyId(
|
||||
@Body() requestBody: FindEmployeesParams
|
||||
): Promise<PublicCompanyEmployeeView[] | ApiValidationError> {
|
||||
try {
|
||||
const employees = await new EmployeesService().findPublicByCompanyId(requestBody);
|
||||
this.setStatus(200);
|
||||
return employees;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("employees/public-by-id")
|
||||
export class GetPublicEmployeeByIdController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async findPublicByEmployeeId(
|
||||
@Body() requestBody: FindPublicEmployeeParams
|
||||
): Promise<PublicEmployeeView | ApiValidationError> {
|
||||
try {
|
||||
const employee = await new EmployeesService().findPublicByEmployeeId(requestBody);
|
||||
this.setStatus(200);
|
||||
return employee;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("employees/get-by-id")
|
||||
export class GetEmployeesByIdController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
PaginateEmployeesParams,
|
||||
PaginateEmployeesResults,
|
||||
CompanyEmployeesView,
|
||||
PublicCompanyEmployeeView,
|
||||
FindPublicEmployeeParams,
|
||||
PublicEmployeeView,
|
||||
FindEmployeesByIdParams,
|
||||
UpdateEmployeeRolesParams,
|
||||
UpdateEmployeeParams,
|
||||
@@ -60,6 +63,24 @@ export class EmployeesService {
|
||||
return employees;
|
||||
}
|
||||
|
||||
public async findPublicByCompanyId(
|
||||
data: FindEmployeesParams
|
||||
): Promise<PublicCompanyEmployeeView[]> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
|
||||
const employees = await EmployeesList.findPublicByCompanyId(data);
|
||||
|
||||
return employees;
|
||||
}
|
||||
|
||||
public async findPublicByEmployeeId(data: FindPublicEmployeeParams): Promise<PublicEmployeeView> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
|
||||
const employee = await EmployeesList.findPublicByEmployeeId(data);
|
||||
|
||||
return employee;
|
||||
}
|
||||
|
||||
public async findById(data: FindEmployeesByIdParams): Promise<CompanyEmployeesView> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
|
||||
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
||||
import {
|
||||
CountRatingsByUserParams,
|
||||
CountRatingsByUserResult,
|
||||
CreateRatingParams,
|
||||
PendingRatingItem,
|
||||
PendingRatingsByUserParams,
|
||||
ProfessionalRatingSummaryByUserParams,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
} from "../../Models/Ratings/Ratings.Interface";
|
||||
import { ApiValidationError } from "../../Models/Server.Error.model";
|
||||
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
import { ratingRateLimiter } from "../../middleware/ratelimiter";
|
||||
import { RatingsService } from "./Ratings.Service";
|
||||
|
||||
@Route("ratings/create")
|
||||
@Middlewares([ratingRateLimiter, authenticateMiddleware])
|
||||
export class CreateRatingController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Calificación creada con éxito")
|
||||
@Post()
|
||||
public async createRating(@Body() requestBody: CreateRatingParams): Promise<ApiVoidResult | ApiValidationError> {
|
||||
try {
|
||||
await new RatingsService().createRating(requestBody);
|
||||
this.setStatus(200);
|
||||
return { message: "Done", success: true };
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/pending-by-user")
|
||||
@Middlewares([authenticateMiddleware])
|
||||
export class PendingRatingsByUserController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async pendingByUser(
|
||||
@Body() requestBody: PendingRatingsByUserParams
|
||||
): Promise<PendingRatingItem[] | ApiValidationError> {
|
||||
try {
|
||||
const pendingRatings = await new RatingsService().pendingByUser(requestBody);
|
||||
this.setStatus(200);
|
||||
return pendingRatings;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/count-by-user")
|
||||
@Middlewares([authenticateMiddleware])
|
||||
export class CountRatingsByUserController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async countByUser(
|
||||
@Body() requestBody: CountRatingsByUserParams
|
||||
): Promise<CountRatingsByUserResult | ApiValidationError> {
|
||||
try {
|
||||
const ratingsCount = await new RatingsService().countByUser(requestBody);
|
||||
this.setStatus(200);
|
||||
return ratingsCount;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/professional-summary-by-user")
|
||||
@Middlewares([authenticateMiddleware])
|
||||
export class ProfessionalRatingSummaryByUserController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async professionalSummaryByUser(
|
||||
@Body() requestBody: ProfessionalRatingSummaryByUserParams
|
||||
): Promise<RatingTargetSummaryResult | ApiValidationError> {
|
||||
try {
|
||||
const ratingSummary = await new RatingsService().professionalSummaryByUser(requestBody);
|
||||
this.setStatus(200);
|
||||
return ratingSummary;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/target-summary")
|
||||
export class RatingTargetSummaryController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async summaryByTarget(
|
||||
@Body() requestBody: RatingTargetSummaryParams
|
||||
): Promise<RatingTargetSummaryResult | ApiValidationError> {
|
||||
try {
|
||||
const ratingSummary = await new RatingsService().summaryByTarget(requestBody);
|
||||
this.setStatus(200);
|
||||
return ratingSummary;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("ratings/target-reviews")
|
||||
export class RatingTargetReviewsController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Busqueda completada con exito")
|
||||
@Post()
|
||||
public async reviewsByTarget(
|
||||
@Body() requestBody: RatingTargetReviewsParams
|
||||
): Promise<RatingTargetReviewsResult | ApiValidationError> {
|
||||
try {
|
||||
const ratingReviews = await new RatingsService().reviewsByTarget(requestBody);
|
||||
this.setStatus(200);
|
||||
return ratingReviews;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { connect } from "mongoose";
|
||||
import RatingsList from "../../Models/Ratings/Ratings";
|
||||
import {
|
||||
CountRatingsByUserParams,
|
||||
CountRatingsByUserResult,
|
||||
CreateRatingParams,
|
||||
IRating,
|
||||
PendingRatingItem,
|
||||
PendingRatingsByUserParams,
|
||||
ProfessionalRatingSummaryByUserParams,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
} from "../../Models/Ratings/Ratings.Interface";
|
||||
|
||||
export class RatingsService {
|
||||
public async createRating(data: CreateRatingParams): Promise<IRating> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.createRating(data);
|
||||
}
|
||||
|
||||
public async pendingByUser(data: PendingRatingsByUserParams): Promise<PendingRatingItem[]> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.pendingByUser(data);
|
||||
}
|
||||
|
||||
public async countByUser(data: CountRatingsByUserParams): Promise<CountRatingsByUserResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.countByUser(data);
|
||||
}
|
||||
|
||||
public async professionalSummaryByUser(data: ProfessionalRatingSummaryByUserParams): Promise<RatingTargetSummaryResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.professionalSummaryByUser(data);
|
||||
}
|
||||
|
||||
public async summaryByTarget(data: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.summaryByTarget(data);
|
||||
}
|
||||
|
||||
public async reviewsByTarget(data: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await RatingsList.reviewsByTarget(data);
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,11 @@ import {
|
||||
CreateSchedulesEnabledParams,
|
||||
DeleteSchedulesEnabledParams,
|
||||
EnableScheduleParams,
|
||||
ExtendReservationPeriodsParams,
|
||||
FindSchedulesEnabledParams,
|
||||
ISchedulesEnabled,
|
||||
ReservationPeriodsSummary,
|
||||
ReservationPeriodsSummaryParams,
|
||||
SchedulesEnabledView,
|
||||
} from "../../Models/SchedulesEnabled/SchedulesEnabled.Interface";
|
||||
import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
@@ -150,3 +153,45 @@ export class DisableSchedulesEnabledController extends Controller {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("schedules-enabled/reservation-periods/summary")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ReservationPeriodsSummaryController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async summarizeReservationPeriods(
|
||||
@Body() requestBody: ReservationPeriodsSummaryParams
|
||||
): Promise<ReservationPeriodsSummary | ApiValidationError> {
|
||||
try {
|
||||
const summary = await new SchedulesEnabledService().summarizeReservationPeriods(requestBody);
|
||||
this.setStatus(200);
|
||||
return summary;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("schedules-enabled/reservation-periods/extend")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class ExtendReservationPeriodsController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async extendReservationPeriods(
|
||||
@Body() requestBody: ExtendReservationPeriodsParams
|
||||
): Promise<ReservationPeriodsSummary | ApiValidationError> {
|
||||
try {
|
||||
const summary = await new SchedulesEnabledService().extendReservationPeriods(requestBody);
|
||||
this.setStatus(200);
|
||||
return summary;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
FindSchedulesEnabledParams,
|
||||
SchedulesEnabledView,
|
||||
EnableScheduleParams,
|
||||
ReservationPeriodsSummaryParams,
|
||||
ReservationPeriodsSummary,
|
||||
ExtendReservationPeriodsParams,
|
||||
} from "../../Models/SchedulesEnabled/SchedulesEnabled.Interface";
|
||||
|
||||
export class SchedulesEnabledService {
|
||||
@@ -52,4 +55,18 @@ export class SchedulesEnabledService {
|
||||
|
||||
return schedulesEnabled;
|
||||
}
|
||||
|
||||
public async summarizeReservationPeriods(
|
||||
data: ReservationPeriodsSummaryParams
|
||||
): Promise<ReservationPeriodsSummary> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return SchedulesEnabledList.summarizeReservationPeriods(data);
|
||||
}
|
||||
|
||||
public async extendReservationPeriods(
|
||||
data: ExtendReservationPeriodsParams
|
||||
): Promise<ReservationPeriodsSummary> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return SchedulesEnabledList.extendReservationPeriods(data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import { authenticateMiddleware } from "../../middleware/authentication";
|
||||
import {
|
||||
DeleteNotificationsByDateParams,
|
||||
DeleteSystemNotificationParams,
|
||||
CreateSystemNotificationBySystemParams,
|
||||
ISystemNotification,
|
||||
FindSystemNotificationsParams,
|
||||
PaginateSystemNotificationsParams,
|
||||
PaginateSystemNotificationsResults,
|
||||
@@ -13,6 +15,7 @@ import {
|
||||
UpdateSystemNotificationParams,
|
||||
} from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||
import { ApiVoidResult } from "../../Models/Api.VoidResult.type";
|
||||
import { systemTokenMiddleware } from "../../middleware/systemToken";
|
||||
|
||||
@Route("systemnotifications/set-state")
|
||||
@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 {
|
||||
DeleteNotificationsByDateParams,
|
||||
DeleteSystemNotificationParams,
|
||||
CreateSystemNotificationBySystemParams,
|
||||
ISystemNotification,
|
||||
FindSystemNotificationsParams,
|
||||
PaginateSystemNotificationsParams,
|
||||
PaginateSystemNotificationsResults,
|
||||
@@ -48,4 +50,12 @@ export class SystemNotificationsService {
|
||||
const notifications = await SystemNoficationsList.finUnreadNotifications(data);
|
||||
return notifications;
|
||||
}
|
||||
|
||||
public async createSystemNotification(
|
||||
data: CreateSystemNotificationBySystemParams
|
||||
): Promise<ISystemNotification> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
const notification = await SystemNoficationsList.createNotificationBySystem(data);
|
||||
return notification;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,13 +46,6 @@ app.use(
|
||||
|
||||
app.use(json());
|
||||
|
||||
app.use((req, _res, next) => {
|
||||
if (req.path === '/companies/create') {
|
||||
require('fs').writeFileSync('request_log.json', JSON.stringify({ body: req.body, headers: req.headers }, null, 2));
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
RegisterRoutes(app);
|
||||
|
||||
app.use(function errorHandler(
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,10 @@ import { Request, Response, NextFunction } from "express";
|
||||
import { ApiValidationError } from "../Models/Server.Error.model";
|
||||
|
||||
const ipLastRequest = new Map<string, number>();
|
||||
const ratingIpRequests = new Map<string, number[]>();
|
||||
|
||||
const RATING_RATE_LIMIT_WINDOW_MS = 60000;
|
||||
const RATING_RATE_LIMIT_MAX_REQUESTS = 20;
|
||||
|
||||
// Limpia las IPs cada hora
|
||||
setInterval(() => {
|
||||
@@ -10,6 +14,14 @@ setInterval(() => {
|
||||
ipLastRequest.forEach((time, ip) => {
|
||||
if (now - time > timeLimit) ipLastRequest.delete(ip);
|
||||
});
|
||||
ratingIpRequests.forEach((times, ip) => {
|
||||
const recentTimes = times.filter((time) => now - time <= RATING_RATE_LIMIT_WINDOW_MS);
|
||||
if (recentTimes.length === 0) {
|
||||
ratingIpRequests.delete(ip);
|
||||
return;
|
||||
}
|
||||
ratingIpRequests.set(ip, recentTimes);
|
||||
});
|
||||
}, 3600000);
|
||||
|
||||
export async function rateLimiter(
|
||||
@@ -31,3 +43,25 @@ export async function rateLimiter(
|
||||
ipLastRequest.set(ip, currentTime);
|
||||
next();
|
||||
}
|
||||
|
||||
export async function ratingRateLimiter(
|
||||
request: Request,
|
||||
response: Response,
|
||||
next: NextFunction
|
||||
): Promise<void | Response | ApiValidationError> {
|
||||
const ip = request.ip;
|
||||
const currentTime = Date.now();
|
||||
const windowStart = currentTime - RATING_RATE_LIMIT_WINDOW_MS;
|
||||
const recentRequests = (ratingIpRequests.get(ip) || []).filter((time) => time > windowStart);
|
||||
|
||||
if (recentRequests.length >= RATING_RATE_LIMIT_MAX_REQUESTS) {
|
||||
response
|
||||
.status(429)
|
||||
.json(new ApiValidationError(429, "Demasiadas solicitudes. Por favor espere!"));
|
||||
return;
|
||||
}
|
||||
|
||||
recentRequests.push(currentTime);
|
||||
ratingIpRequests.set(ip, recentRequests);
|
||||
next();
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
Generated
+306
-28
@@ -9,7 +9,7 @@
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@whiskeysockets/baileys": "^6.7.18",
|
||||
"@whiskeysockets/baileys": "6.17.16",
|
||||
"express": "^5.1.0",
|
||||
"qrcode": "^1.5.4"
|
||||
},
|
||||
@@ -20,6 +20,12 @@
|
||||
"typescript": "^5.8.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@adiwajshing/keyed-db": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "https://registry.npmjs.org/@adiwajshing/keyed-db/-/keyed-db-0.2.4.tgz",
|
||||
"integrity": "sha512-yprSnAtj80/VKuDqRcFFLDYltoNV8tChNwFfIgcf6PGD4sjzWIBgs08pRuTqGH5mk5wgL6PBRSsMCZqtZwzFEw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@cacheable/node-cache": {
|
||||
"version": "1.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@cacheable/node-cache/-/node-cache-1.5.5.tgz",
|
||||
@@ -44,6 +50,12 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@eshaz/web-worker": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@eshaz/web-worker/-/web-worker-1.2.2.tgz",
|
||||
"integrity": "sha512-WxXiHFmD9u/owrzempiDlBB1ZYqiLnm9s6aPc8AlFQalq2tKmqdmMr9GXOupDgzXtqnBipj8Un0gkIm7Sjf8mw==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@eslint-community/eslint-utils": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz",
|
||||
@@ -445,6 +457,55 @@
|
||||
"integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/@thi.ng/bitstream": {
|
||||
"version": "2.4.54",
|
||||
"resolved": "https://registry.npmjs.org/@thi.ng/bitstream/-/bitstream-2.4.54.tgz",
|
||||
"integrity": "sha512-uInkAJge5O0bWWEaYKrQpMccPbFg0z6eIA5NDCJXPm7l3rjlDje6RBHBXll3LiQz9Y051EdzlAEQRaB5hEifdg==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/postspectacular"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://patreon.com/thing_umbrella"
|
||||
},
|
||||
{
|
||||
"type": "liberapay",
|
||||
"url": "https://liberapay.com/thi.ng"
|
||||
}
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@thi.ng/errors": "^2.6.16"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@thi.ng/errors": {
|
||||
"version": "2.6.16",
|
||||
"resolved": "https://registry.npmjs.org/@thi.ng/errors/-/errors-2.6.16.tgz",
|
||||
"integrity": "sha512-a7Lv/G0La5eTNUEIyLldpeYziyFSj3rOlWNeXFu8v+ZSb8w8EnQ/L0r0sKHux7Ru6RhUkAXrcaHU7xd1ZkWovA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/postspectacular"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://patreon.com/thing_umbrella"
|
||||
},
|
||||
{
|
||||
"type": "liberapay",
|
||||
"url": "https://liberapay.com/thi.ng"
|
||||
}
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@tokenizer/token": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz",
|
||||
@@ -835,44 +896,97 @@
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@whiskeysockets/baileys": {
|
||||
"version": "6.7.18",
|
||||
"resolved": "https://registry.npmjs.org/@whiskeysockets/baileys/-/baileys-6.7.18.tgz",
|
||||
"integrity": "sha512-lstyxtAdOC7vuI9dWyxDg9DQlYSz8MhVsBkQUTX9EWt0GY0IJIa2Rnu4psGXa1OxgNvYwLaGSHiQBRil8mGb8g==",
|
||||
"hasInstallScript": true,
|
||||
"node_modules/@wasm-audio-decoders/common": {
|
||||
"version": "9.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@wasm-audio-decoders/common/-/common-9.0.7.tgz",
|
||||
"integrity": "sha512-WRaUuWSKV7pkttBygml/a6dIEpatq2nnZGFIoPTc5yPLkxL6Wk4YaslPM98OPQvWacvNZ+Py9xROGDtrFBDzag==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eshaz/web-worker": "1.2.2",
|
||||
"simple-yenc": "^1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@wasm-audio-decoders/flac": {
|
||||
"version": "0.2.10",
|
||||
"resolved": "https://registry.npmjs.org/@wasm-audio-decoders/flac/-/flac-0.2.10.tgz",
|
||||
"integrity": "sha512-YfcyoD2rYRBa6ffawZKNi5qvV5HArJmNmuMVUPoutuZ2hhGi6WNSWIzgvbROGmPbFivLL764Am7xxJENWJDhjw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@wasm-audio-decoders/common": "9.0.7",
|
||||
"codec-parser": "2.5.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/eshaz"
|
||||
}
|
||||
},
|
||||
"node_modules/@wasm-audio-decoders/ogg-vorbis": {
|
||||
"version": "0.1.20",
|
||||
"resolved": "https://registry.npmjs.org/@wasm-audio-decoders/ogg-vorbis/-/ogg-vorbis-0.1.20.tgz",
|
||||
"integrity": "sha512-zaQPasU5usRjUDXtXOHYED5tfkR4QMXd+EH3Nrz1+4+M5pCsdD+s9YxJqb0oqnTyRu/KUujOmu5Z/m/NT47vwg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@wasm-audio-decoders/common": "9.0.7",
|
||||
"codec-parser": "2.5.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/eshaz"
|
||||
}
|
||||
},
|
||||
"node_modules/@wasm-audio-decoders/opus-ml": {
|
||||
"version": "0.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@wasm-audio-decoders/opus-ml/-/opus-ml-0.0.2.tgz",
|
||||
"integrity": "sha512-58rWEqDGg+CKCyEeKm2KoxxSwTWtHh/NLTW9ObR4K8CGF6VwuuGudEI1CtniS/oSRmL1nJq/eh8MKARiluw4DQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@wasm-audio-decoders/common": "9.0.7"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/eshaz"
|
||||
}
|
||||
},
|
||||
"node_modules/@whiskeysockets/baileys": {
|
||||
"version": "6.17.16",
|
||||
"resolved": "https://registry.npmjs.org/@whiskeysockets/baileys/-/baileys-6.17.16.tgz",
|
||||
"integrity": "sha512-cZoUaKpO4fsDUNiCtyZfbjkW0Bjl/IudzHLCvpqfqtq5TACQzNynYsYdKPJz1I8Cu/SSEvmewk0RorIs0zDWyw==",
|
||||
"deprecated": "This version is affected by a zero-day vulnerability that allows spoofing of messages, please update to\n the latest versions (6.7.22^ or 7.0.0-rc12^)! For more information, check out the public advisory at\n https://github.com/WhiskeySockets/Baileys/security/advisories/GHSA-qvv5-jq5g-4cgg",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@adiwajshing/keyed-db": "^0.2.4",
|
||||
"@cacheable/node-cache": "^1.4.0",
|
||||
"@hapi/boom": "^9.1.3",
|
||||
"@whiskeysockets/eslint-config": "github:whiskeysockets/eslint-config",
|
||||
"async-mutex": "^0.5.0",
|
||||
"async-lock": "^1.4.1",
|
||||
"audio-decode": "^2.1.3",
|
||||
"axios": "^1.6.0",
|
||||
"cache-manager": "^5.7.6",
|
||||
"libphonenumber-js": "^1.10.20",
|
||||
"libsignal": "github:WhiskeySockets/libsignal-node",
|
||||
"lodash": "^4.17.21",
|
||||
"music-metadata": "^7.12.3",
|
||||
"pino": "^9.6",
|
||||
"protobufjs": "^7.2.4",
|
||||
"uuid": "^10.0.0",
|
||||
"ws": "^8.13.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"audio-decode": "^2.1.3",
|
||||
"jimp": "^0.16.1",
|
||||
"link-preview-js": "^3.0.0",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"sharp": "^0.32.6"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"audio-decode": {
|
||||
"optional": true
|
||||
},
|
||||
"jimp": {
|
||||
"optional": true
|
||||
},
|
||||
"link-preview-js": {
|
||||
"optional": true
|
||||
},
|
||||
"qrcode-terminal": {
|
||||
"optional": true
|
||||
},
|
||||
"sharp": {
|
||||
"optional": true
|
||||
}
|
||||
@@ -1006,14 +1120,11 @@
|
||||
"license": "Python-2.0",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/async-mutex": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz",
|
||||
"integrity": "sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
"node_modules/async-lock": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/async-lock/-/async-lock-1.4.1.tgz",
|
||||
"integrity": "sha512-Az2ZTpuytrtqENulXwO3GGv1Bztugx6TT37NIo7imr/Qo0gsYiGtSdBa2B6fsXhTpVZDNfu1Qn3pk531e3q+nQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/asynckit": {
|
||||
"version": "0.4.0",
|
||||
@@ -1030,6 +1141,41 @@
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/audio-buffer": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/audio-buffer/-/audio-buffer-5.0.0.tgz",
|
||||
"integrity": "sha512-gsDyj1wwUp8u7NBB+eW6yhLb9ICf+0eBmDX8NGaAS00w8/fLqFdxUlL5Ge/U8kB64DlQhdonxYC59dXy1J7H/w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/audio-decode": {
|
||||
"version": "2.2.3",
|
||||
"resolved": "https://registry.npmjs.org/audio-decode/-/audio-decode-2.2.3.tgz",
|
||||
"integrity": "sha512-Z0lHvMayR/Pad9+O9ddzaBJE0DrhZkQlStrC1RwcAHF3AhQAsdwKHeLGK8fYKyp2DDU6xHxzGb4CLMui12yVrg==",
|
||||
"deprecated": "Renamed to @audio/decode — same API; this name remains a thin alias. npm i @audio/decode",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@wasm-audio-decoders/flac": "^0.2.4",
|
||||
"@wasm-audio-decoders/ogg-vorbis": "^0.1.15",
|
||||
"audio-buffer": "^5.0.0",
|
||||
"audio-type": "^2.2.1",
|
||||
"mpg123-decoder": "^1.0.0",
|
||||
"node-wav": "^0.0.2",
|
||||
"ogg-opus-decoder": "^1.6.12",
|
||||
"qoa-format": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/audio-type": {
|
||||
"version": "2.4.2",
|
||||
"resolved": "https://registry.npmjs.org/audio-type/-/audio-type-2.4.2.tgz",
|
||||
"integrity": "sha512-E9Bl1FGGDS81H/mKvaoPq0iQ8uT3qTBe6XWjipOo5kYrhLMAbjD7hREAVle0YJFahZOVbztxTdkwi0VBDJutSA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/audiojs"
|
||||
}
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
|
||||
@@ -1141,6 +1287,21 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/cache-manager": {
|
||||
"version": "5.7.6",
|
||||
"resolved": "https://registry.npmjs.org/cache-manager/-/cache-manager-5.7.6.tgz",
|
||||
"integrity": "sha512-wBxnBHjDxF1RXpHCBD6HGvKER003Ts7IIm0CHpggliHzN1RZditb7rXoduE1rplc2DEFYKxhLKgFuchXMJje9w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"eventemitter3": "^5.0.1",
|
||||
"lodash.clonedeep": "^4.5.0",
|
||||
"lru-cache": "^10.2.2",
|
||||
"promise-coalesce": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 18"
|
||||
}
|
||||
},
|
||||
"node_modules/cacheable": {
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/cacheable/-/cacheable-1.9.0.tgz",
|
||||
@@ -1227,6 +1388,12 @@
|
||||
"wrap-ansi": "^6.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/codec-parser": {
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/codec-parser/-/codec-parser-2.5.0.tgz",
|
||||
"integrity": "sha512-Ru9t80fV8B0ZiixQl8xhMTLru+dzuis/KQld32/x5T/+3LwZb0/YvQdSKytX9JqCnRdiupvAvyYJINKrXieziQ==",
|
||||
"license": "LGPL-3.0-or-later"
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
@@ -1803,6 +1970,12 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/eventemitter3": {
|
||||
"version": "5.0.4",
|
||||
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
|
||||
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/events": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
|
||||
@@ -2460,6 +2633,12 @@
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/libphonenumber-js": {
|
||||
"version": "1.13.9",
|
||||
"resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.13.9.tgz",
|
||||
"integrity": "sha512-VNS5vWMM7r0P66BYv+TQJATxExEgLxN+34hfHDVhDkUsGAE4cRg0shCNSLTXNKm7nIUscC7AfB51TjxEeF7msQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/libsignal": {
|
||||
"name": "@whiskeysockets/libsignal-node",
|
||||
"version": "2.0.1",
|
||||
@@ -2526,6 +2705,12 @@
|
||||
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.clonedeep": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz",
|
||||
"integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.merge": {
|
||||
"version": "4.6.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
|
||||
@@ -2539,6 +2724,12 @@
|
||||
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "10.4.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
|
||||
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/make-error": {
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
|
||||
@@ -2634,6 +2825,19 @@
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/mpg123-decoder": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/mpg123-decoder/-/mpg123-decoder-1.0.3.tgz",
|
||||
"integrity": "sha512-+fjxnWigodWJm3+4pndi+KUg9TBojgn31DPk85zEsim7C6s0X5Ztc/hQYdytXkwuGXH+aB0/aEkG40Emukv6oQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@wasm-audio-decoders/common": "9.0.7"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/eshaz"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
@@ -2677,6 +2881,15 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/node-wav": {
|
||||
"version": "0.0.2",
|
||||
"resolved": "https://registry.npmjs.org/node-wav/-/node-wav-0.0.2.tgz",
|
||||
"integrity": "sha512-M6Rm/bbG6De/gKGxOpeOobx/dnGuP0dz40adqx38boqHhlWssBJZgLCPBNtb9NkrmnKYiV04xELq+R6PFOnoLA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
@@ -2689,6 +2902,22 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/ogg-opus-decoder": {
|
||||
"version": "1.7.3",
|
||||
"resolved": "https://registry.npmjs.org/ogg-opus-decoder/-/ogg-opus-decoder-1.7.3.tgz",
|
||||
"integrity": "sha512-w47tiZpkLgdkpa+34VzYD8mHUj8I9kfWVZa82mBbNwDvB1byfLXSSzW/HxA4fI3e9kVlICSpXGFwMLV1LPdjwg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@wasm-audio-decoders/common": "9.0.7",
|
||||
"@wasm-audio-decoders/opus-ml": "0.0.2",
|
||||
"codec-parser": "2.5.0",
|
||||
"opus-decoder": "0.7.11"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/eshaz"
|
||||
}
|
||||
},
|
||||
"node_modules/on-exit-leak-free": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
|
||||
@@ -2737,6 +2966,19 @@
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/opus-decoder": {
|
||||
"version": "0.7.11",
|
||||
"resolved": "https://registry.npmjs.org/opus-decoder/-/opus-decoder-0.7.11.tgz",
|
||||
"integrity": "sha512-+e+Jz3vGQLxRTBHs8YJQPRPc1Tr+/aC6coV/DlZylriA29BdHQAYXhvNRKtjftof17OFng0+P4wsFIqQu3a48A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@wasm-audio-decoders/common": "9.0.7"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/eshaz"
|
||||
}
|
||||
},
|
||||
"node_modules/p-limit": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
||||
@@ -2929,6 +3171,15 @@
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/promise-coalesce": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/promise-coalesce/-/promise-coalesce-1.5.0.tgz",
|
||||
"integrity": "sha512-cTJ30U+ur1LD7pMPyQxiKIwxjtAjLsyU7ivRhVWZrX9BNIXtf78pc37vSMc8Vikx7DVzEKNk2SEJ5KWUpSG2ig==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/protobufjs": {
|
||||
"version": "7.4.0",
|
||||
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.4.0.tgz",
|
||||
@@ -2982,6 +3233,15 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/qoa-format": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/qoa-format/-/qoa-format-1.0.1.tgz",
|
||||
"integrity": "sha512-dMB0Z6XQjdpz/Cw4Rf6RiBpQvUSPCfYlQMWvmuWlWkAT7nDQD29cVZ1SwDUB6DYJSitHENwbt90lqfI+7bvMcw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@thi.ng/bitstream": "^2.2.12"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode": {
|
||||
"version": "1.5.4",
|
||||
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
|
||||
@@ -3370,6 +3630,16 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/simple-yenc": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/simple-yenc/-/simple-yenc-1.0.4.tgz",
|
||||
"integrity": "sha512-5gvxpSd79e9a3V4QDYUqnqxeD4HGlhCakVpb6gMnDD7lexJggSBJRBO5h52y/iJrdXRilX9UCuDaIJhSWm5OWw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/eshaz"
|
||||
}
|
||||
},
|
||||
"node_modules/sonic-boom": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz",
|
||||
@@ -3578,12 +3848,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/type-check": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||
@@ -3649,6 +3913,20 @@
|
||||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
|
||||
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
|
||||
"deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/v8-compile-cache-lib": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
"license": "ISC",
|
||||
"description": "",
|
||||
"dependencies": {
|
||||
"@whiskeysockets/baileys": "^6.7.18",
|
||||
"@whiskeysockets/baileys": "6.17.16",
|
||||
"express": "^5.1.0",
|
||||
"qrcode": "^1.5.4"
|
||||
},
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ async function startServer() {
|
||||
}
|
||||
try {
|
||||
const jid = number.endsWith("@s.whatsapp.net") ? number : `${number}@s.whatsapp.net`;
|
||||
await sock.sendMessage(jid, { text: message, ephemeralExpiration: 0 });
|
||||
await sock.sendMessage(jid, { text: message });
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error("Send error:", err);
|
||||
|
||||
@@ -30,6 +30,7 @@ export type UpdateAppointmentParams = {
|
||||
export enum APPOINTMENT_NOTIFICATION_TYPE {
|
||||
"CREATION" = "creation",
|
||||
"REMINDER" = "reminder",
|
||||
"CANCELLATION" = "cancellation",
|
||||
}
|
||||
|
||||
export type SendAppointmentNotificationParams = {
|
||||
@@ -41,6 +42,7 @@ export type SendAppointmentNotificationParams = {
|
||||
export type DeleteAppointmentParams = {
|
||||
id: string;
|
||||
validation?: boolean;
|
||||
notification?: boolean;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
|
||||
@@ -39,10 +39,15 @@ export interface MyOranizationsView {
|
||||
appointmentAlert: string;
|
||||
templateWapNotifId: string;
|
||||
templateWapAltaId: string;
|
||||
templateWapCancellationId: string;
|
||||
templateEmailNotifId: string;
|
||||
templateEmailAltaId: string;
|
||||
templateEmailCancellationId: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
showPublicProfessionals: boolean;
|
||||
}
|
||||
|
||||
export type CreateCompanyParams = {
|
||||
@@ -85,10 +90,15 @@ export type UpdateCompanyParams = {
|
||||
sessionUser: string;
|
||||
templateWapNotifId?: string;
|
||||
templateWapAltaId?: string;
|
||||
templateWapCancellationId?: string;
|
||||
templateEmailNotifId?: string;
|
||||
templateEmailAltaId?: string;
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
};
|
||||
|
||||
export type DeleteCompanyParams = {
|
||||
@@ -146,12 +156,17 @@ export interface ICompany {
|
||||
appointmentAlert?: string;
|
||||
templateWapNotifId?: string;
|
||||
templateWapAltaId?: string;
|
||||
templateWapCancellationId?: string;
|
||||
templateEmailNotifId?: string;
|
||||
templateEmailAltaId?: string;
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
fixedPostIds?: Array<string>;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
}
|
||||
|
||||
export type PublicOrganizationViewParams = {
|
||||
@@ -178,6 +193,9 @@ export type PublicOrganizationView = {
|
||||
longitude: number;
|
||||
appointmentAlert: string;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
showPublicProfessionals: boolean;
|
||||
};
|
||||
|
||||
export type SetNotificationAutoParams = {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
export type PublicCompanyEmployeeView = {
|
||||
employeeId: string;
|
||||
userId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatarUrl: string;
|
||||
};
|
||||
|
||||
export type FindPublicCompanyEmployeesParams = {
|
||||
companyId: string;
|
||||
};
|
||||
|
||||
export type FindPublicEmployeeParams = {
|
||||
employeeId: string;
|
||||
};
|
||||
|
||||
export type PublicEmployeeView = {
|
||||
employeeId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatarUrl: 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()
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
export enum RatingTargetType {
|
||||
COMPANY = "company",
|
||||
SERVICE = "service",
|
||||
EMPLOYEE = "employee",
|
||||
}
|
||||
|
||||
export const RATING_COMMENT_MAX_LENGTH = 1000;
|
||||
|
||||
export type CreateRatingParams = {
|
||||
appointmentId: string;
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
score: number;
|
||||
comment?: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type PendingRatingsByUserParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type CountRatingsByUserParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type CountRatingsByUserResult = {
|
||||
count: number;
|
||||
};
|
||||
|
||||
export type ProfessionalRatingSummaryByUserParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type RatingTargetSummaryParams = {
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
};
|
||||
|
||||
export type RatingTargetSummaryResult = {
|
||||
averageScore: number;
|
||||
totalCount: number;
|
||||
};
|
||||
|
||||
export type RatingTargetReviewsParams = RatingTargetSummaryParams & {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export type RatingTargetReviewItem = {
|
||||
id: string;
|
||||
score: number;
|
||||
comment: string;
|
||||
createdAt: string;
|
||||
author: {
|
||||
displayName: string;
|
||||
avatarUrl: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type RatingTargetReviewsResult = {
|
||||
reviews: RatingTargetReviewItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
};
|
||||
|
||||
export interface PendingRatingItem {
|
||||
appointmentId: string;
|
||||
appointmentDate: string;
|
||||
targetType: RatingTargetType;
|
||||
targetId: string;
|
||||
targetName: string;
|
||||
companyId: string;
|
||||
serviceId: string;
|
||||
employeeId: string;
|
||||
serviceName: string;
|
||||
}
|
||||
@@ -18,6 +18,49 @@ export type EnableScheduleParams = {
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ReservationPeriodScope = "employee" | "all";
|
||||
|
||||
export type ReservationPeriodDurationUnit = "week" | "month";
|
||||
|
||||
export type ReservationPeriodDuration = {
|
||||
unit: ReservationPeriodDurationUnit;
|
||||
value: number;
|
||||
};
|
||||
|
||||
export type ReservationPeriodsSummaryParams = {
|
||||
companyId: string;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ExtendReservationPeriodsParams = {
|
||||
companyId: string;
|
||||
scope: ReservationPeriodScope;
|
||||
employeeId?: string;
|
||||
duration?: ReservationPeriodDuration;
|
||||
weeks?: number;
|
||||
sessionUser: string;
|
||||
};
|
||||
|
||||
export type ReservationPeriodEmployeeSummary = {
|
||||
employeeId: string;
|
||||
employeeFullName: string;
|
||||
employeeEmail: string;
|
||||
employeeAvatar: string;
|
||||
employeeUserId: string;
|
||||
isOpen: boolean;
|
||||
currentOpenUntil: string | null;
|
||||
daysRemaining: number | null;
|
||||
};
|
||||
|
||||
export type ReservationPeriodsSummary = {
|
||||
companyId: string;
|
||||
status: "missing" | "expired" | "near-ending" | "open";
|
||||
worstDaysRemaining: number | null;
|
||||
currentOpenUntil: string | null;
|
||||
nearEndingThresholdDays: number;
|
||||
employees: ReservationPeriodEmployeeSummary[];
|
||||
};
|
||||
|
||||
export interface SchedulesEnabledView {
|
||||
id: string;
|
||||
employeeId: string;
|
||||
|
||||
@@ -13,12 +13,26 @@ export class ApiValidationError implements IServerError {
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiError extends ApiValidationError {
|
||||
export class ApiError extends Error implements IServerError {
|
||||
readonly code: number;
|
||||
readonly desc: string;
|
||||
|
||||
constructor(code: number, desc: string) {
|
||||
super(code, desc);
|
||||
const message = desc || "No pudimos completar la operación.";
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.code = code;
|
||||
this.desc = message;
|
||||
}
|
||||
|
||||
format = (): string => {
|
||||
return `Atención: ${this.desc}`;
|
||||
};
|
||||
|
||||
toJSON = () => ({
|
||||
name: this.name,
|
||||
code: this.code,
|
||||
desc: this.desc,
|
||||
message: this.message,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ export type CreateServiceParams = {
|
||||
originalPrice: number;
|
||||
limit: number;
|
||||
sessionUser: string;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
};
|
||||
|
||||
export type UpdateServiceParams = {
|
||||
@@ -36,6 +38,8 @@ export type UpdateServiceParams = {
|
||||
fontColor?: string;
|
||||
fontShadowColor?: string;
|
||||
sessionUser: string;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
};
|
||||
|
||||
export type PaginateServicesParams = {
|
||||
@@ -110,6 +114,8 @@ export interface PublicServiceView {
|
||||
fontColor: string;
|
||||
fontShadowColor: string;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
}
|
||||
|
||||
export interface PublicOrganizationServiceView {
|
||||
@@ -132,6 +138,8 @@ export interface IService {
|
||||
fontColor: string;
|
||||
fontShadowColor: string;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
}
|
||||
|
||||
export interface CompanyServiceView {
|
||||
@@ -153,4 +161,6 @@ export interface CompanyServiceView {
|
||||
fontShadowColor: string;
|
||||
published: SERVICE_PUBLISHED_STATUS;
|
||||
banned?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
export enum TemplateTypes {
|
||||
WAP_NEW_APPOINTMENT = "wap-new-appointment",
|
||||
WAP_REMINDER = "wap-reminder",
|
||||
WAP_CANCELLATION = "wap-cancellation",
|
||||
EMAIL_NEW_APPOINTMENT = "email-new-appointment",
|
||||
EMAIL_REMINDER = "email-reminder",
|
||||
EMAIL_CANCELLATION = "email-cancellation",
|
||||
}
|
||||
|
||||
export const refactorFields = (text: string) => {
|
||||
|
||||
@@ -3,6 +3,26 @@ import { ApiError } from "@models/Server.Error.model";
|
||||
import axios from "@config/axios.config";
|
||||
|
||||
class ApiService {
|
||||
private normalizeError(error: unknown): ApiError {
|
||||
if (error && typeof error === "object" && "response" in error) {
|
||||
const response = (error as { response?: { data?: any; status?: number } }).response;
|
||||
const data = response?.data;
|
||||
|
||||
if (data) {
|
||||
const msg = data.desc || data.message || JSON.stringify(data.details || data) || "No pudimos completar la operación.";
|
||||
return new ApiError(data.code || response?.status || 500, msg);
|
||||
}
|
||||
|
||||
return new ApiError(response?.status || 500, "No pudimos comunicarnos con el servidor.");
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return new ApiError(500, error.message);
|
||||
}
|
||||
|
||||
return new ApiError(500, "No pudimos comunicarnos con el servidor.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a HTTP POST request to the specified endpoint with the provided data
|
||||
* and returns a promise that resolves to the response data.
|
||||
@@ -19,14 +39,7 @@ class ApiService {
|
||||
resolve(response.data);
|
||||
})
|
||||
.catch((error) => {
|
||||
try {
|
||||
const data = error.response.data;
|
||||
const msg = data.desc || data.message || JSON.stringify(data.details || data);
|
||||
reject(new ApiError(data.code || error.response.status || 500, msg));
|
||||
} catch {
|
||||
const errorMessage = process.env.VITE_API_UNAVAILABLE as string;
|
||||
reject(new ApiError(500, errorMessage));
|
||||
}
|
||||
reject(this.normalizeError(error));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -44,16 +57,7 @@ class ApiService {
|
||||
resolve(response.data);
|
||||
})
|
||||
.catch((error) => {
|
||||
try {
|
||||
console.error("Full API Error:", error.response?.data);
|
||||
const data = error.response.data;
|
||||
const msg = data.desc || data.message || JSON.stringify(data.details || data);
|
||||
reject(new ApiError(data.code || error.response.status || 500, msg));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
const errorMessage = process.env.VITE_API_UNAVAILABLE as string;
|
||||
reject(new ApiError(500, errorMessage));
|
||||
}
|
||||
reject(this.normalizeError(error));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { ApiError } from "@core/Models/Server.Error.model";
|
||||
import {
|
||||
FindPublicCompanyEmployeesParams,
|
||||
FindPublicEmployeeParams,
|
||||
PublicCompanyEmployeeView,
|
||||
PublicEmployeeView,
|
||||
} from "@core/Models/Employees.model";
|
||||
import ApiRequest from "@services/Api.Service";
|
||||
import * as Yup from "yup";
|
||||
|
||||
const schemaFindPublicCompanyEmployees = Yup.object().shape({
|
||||
companyId: Yup.string().required("No se ha proporcionado la organización."),
|
||||
});
|
||||
|
||||
const schemaFindPublicEmployee = Yup.object().shape({
|
||||
employeeId: Yup.string().required("No se ha proporcionado el profesional."),
|
||||
});
|
||||
|
||||
export const findPublicCompanyEmployees = async (
|
||||
data: FindPublicCompanyEmployeesParams
|
||||
): Promise<PublicCompanyEmployeeView[]> => {
|
||||
return new Promise<PublicCompanyEmployeeView[]>((resolve, reject) => {
|
||||
schemaFindPublicCompanyEmployees
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<PublicCompanyEmployeeView[]>("employees/public-by-company", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const findPublicEmployee = async (
|
||||
data: FindPublicEmployeeParams
|
||||
): Promise<PublicEmployeeView> => {
|
||||
return new Promise<PublicEmployeeView>((resolve, reject) => {
|
||||
schemaFindPublicEmployee
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<PublicEmployeeView>("employees/public-by-id", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -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 });
|
||||
@@ -0,0 +1,134 @@
|
||||
import ApiRequest from "@services/Api.Service";
|
||||
import { ApiVoidResult } from "@core/Models/Api.VoidResult.type";
|
||||
import { ApiError } from "@core/Models/Server.Error.model";
|
||||
import {
|
||||
CountRatingsByUserParams,
|
||||
CountRatingsByUserResult,
|
||||
CreateRatingParams,
|
||||
PendingRatingItem,
|
||||
PendingRatingsByUserParams,
|
||||
ProfessionalRatingSummaryByUserParams,
|
||||
RATING_COMMENT_MAX_LENGTH,
|
||||
RatingTargetSummaryParams,
|
||||
RatingTargetSummaryResult,
|
||||
RatingTargetReviewsParams,
|
||||
RatingTargetReviewsResult,
|
||||
RatingTargetType,
|
||||
} from "@core/Models/Ratings.model";
|
||||
import * as Yup from "yup";
|
||||
|
||||
const schemaPendingRatingsByUser = Yup.object().shape({
|
||||
sessionUser: Yup.string().required("Para ver tus calificaciones pendientes debes iniciar sesión."),
|
||||
});
|
||||
|
||||
const schemaCountRatingsByUser = Yup.object().shape({
|
||||
sessionUser: Yup.string().required("Para ver tus opiniones realizadas debes iniciar sesión."),
|
||||
});
|
||||
|
||||
const schemaProfessionalRatingSummaryByUser = Yup.object().shape({
|
||||
sessionUser: Yup.string().required("Para ver tu puntaje profesional debes iniciar sesión."),
|
||||
});
|
||||
|
||||
const schemaCreateRating = Yup.object().shape({
|
||||
appointmentId: Yup.string().required("No se ha proporcionado el turno."),
|
||||
targetType: Yup.string()
|
||||
.oneOf(Object.values(RatingTargetType), "El tipo de calificación no es válido.")
|
||||
.required("No se ha proporcionado el tipo de calificación."),
|
||||
targetId: Yup.string().required("No se ha proporcionado el item a calificar."),
|
||||
score: Yup.number().integer().min(1).max(5).required("Selecciona una calificación."),
|
||||
comment: Yup.string().max(RATING_COMMENT_MAX_LENGTH, `El comentario no puede superar los ${RATING_COMMENT_MAX_LENGTH} caracteres.`),
|
||||
sessionUser: Yup.string().required("Para calificar debes iniciar sesión."),
|
||||
});
|
||||
|
||||
const schemaRatingTargetSummary = Yup.object().shape({
|
||||
targetType: Yup.string()
|
||||
.oneOf(Object.values(RatingTargetType), "El tipo de calificación no es válido.")
|
||||
.required("No se ha proporcionado el tipo de calificación."),
|
||||
targetId: Yup.string().required("No se ha proporcionado el item calificado."),
|
||||
});
|
||||
|
||||
const schemaRatingTargetReviews = schemaRatingTargetSummary.shape({
|
||||
page: Yup.number().integer().min(1),
|
||||
pageSize: Yup.number().integer().min(1).max(20),
|
||||
limit: Yup.number().integer().min(1).max(20),
|
||||
});
|
||||
|
||||
export const pendingRatingsByUser = async (data: PendingRatingsByUserParams): Promise<PendingRatingItem[]> => {
|
||||
return new Promise<PendingRatingItem[]>((resolve, reject) => {
|
||||
schemaPendingRatingsByUser
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<PendingRatingItem[]>("ratings/pending-by-user", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const countRatingsByUser = async (data: CountRatingsByUserParams): Promise<CountRatingsByUserResult> => {
|
||||
return new Promise<CountRatingsByUserResult>((resolve, reject) => {
|
||||
schemaCountRatingsByUser
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<CountRatingsByUserResult>("ratings/count-by-user", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const professionalRatingSummaryByUser = async (
|
||||
data: ProfessionalRatingSummaryByUserParams
|
||||
): Promise<RatingTargetSummaryResult> => {
|
||||
return new Promise<RatingTargetSummaryResult>((resolve, reject) => {
|
||||
schemaProfessionalRatingSummaryByUser
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<RatingTargetSummaryResult>("ratings/professional-summary-by-user", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const createRating = async (data: CreateRatingParams): Promise<ApiVoidResult> => {
|
||||
return new Promise<ApiVoidResult>((resolve, reject) => {
|
||||
schemaCreateRating
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<ApiVoidResult>("ratings/create", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const ratingTargetSummary = async (data: RatingTargetSummaryParams): Promise<RatingTargetSummaryResult> => {
|
||||
return new Promise<RatingTargetSummaryResult>((resolve, reject) => {
|
||||
schemaRatingTargetSummary
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<RatingTargetSummaryResult>("ratings/target-summary", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const ratingTargetReviews = async (data: RatingTargetReviewsParams): Promise<RatingTargetReviewsResult> => {
|
||||
return new Promise<RatingTargetReviewsResult>((resolve, reject) => {
|
||||
schemaRatingTargetReviews
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(ApiRequest.post<RatingTargetReviewsResult>("ratings/target-reviews", data));
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -1,12 +1,15 @@
|
||||
import { create } from "zustand";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
interface IConfirmStore {
|
||||
visible: boolean;
|
||||
message: string;
|
||||
content?: ReactNode;
|
||||
title: string;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
show: (message: string, onConfirm: () => void, onCancel: () => void) => void;
|
||||
showContent: (message: string, content: ReactNode, onConfirm: () => void, onCancel: () => void) => void;
|
||||
close: () => void;
|
||||
clear: () => void;
|
||||
}
|
||||
@@ -16,6 +19,7 @@ export type ConfirmState = IConfirmStore;
|
||||
const useConfirmStore = create<ConfirmState>()((set) => ({
|
||||
visible: false,
|
||||
message: "",
|
||||
content: undefined,
|
||||
title: "",
|
||||
onConfirm: () => {},
|
||||
onCancel: () => {},
|
||||
@@ -23,6 +27,16 @@ const useConfirmStore = create<ConfirmState>()((set) => ({
|
||||
set(() => ({
|
||||
visible: true,
|
||||
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,
|
||||
onCancel: onCancel,
|
||||
title: "Atención",
|
||||
@@ -31,6 +45,7 @@ const useConfirmStore = create<ConfirmState>()((set) => ({
|
||||
set(() => ({
|
||||
visible: false,
|
||||
message: "",
|
||||
content: undefined,
|
||||
onConfirm: () => {},
|
||||
onCancel: () => {},
|
||||
title: "",
|
||||
@@ -39,6 +54,7 @@ const useConfirmStore = create<ConfirmState>()((set) => ({
|
||||
set(() => ({
|
||||
visible: false,
|
||||
message: "",
|
||||
content: undefined,
|
||||
onConfirm: () => {},
|
||||
onCancel: () => {},
|
||||
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
|
||||
})
|
||||
}));
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user