Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3b56d00fcb | |||
| f34b99b87b | |||
| 3145beca65 | |||
| 69a443dcfb | |||
| 446c65ff37 | |||
| cb830fcf01 | |||
| 146770a55d | |||
| 781310e36c | |||
| 446968c03f | |||
| 2a33f636a0 | |||
| 3d8911c093 | |||
| 0eb2e91e15 | |||
| c77d479344 | |||
| 0a285776c7 | |||
| f39ba44f59 | |||
| ece3879c8d | |||
| 68d98e8b40 | |||
| dc020d94d2 | |||
| 20b0363767 | |||
| 6c75929e21 | |||
| e6662aac18 | |||
| 4029566063 | |||
| 3988e328eb | |||
| dd3e07311d | |||
| 279e1b54cc | |||
| da3c3abb52 | |||
| 383a5bc6b4 |
@@ -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.
|
||||
+57
-7
@@ -3,6 +3,8 @@ package com.hdrdevs.turnosxpress;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.os.Message;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.util.Log;
|
||||
@@ -70,11 +72,10 @@ public class MainActivity extends AppCompatActivity {
|
||||
webView.setWebViewClient(new WebViewClient() {
|
||||
@Override
|
||||
public boolean shouldOverrideUrlLoading(WebView vw, WebResourceRequest request) {
|
||||
if (request.getUrl().toString().contains(home.getHost())) {
|
||||
if (shouldLoadInsideApp(request.getUrl(), home)) {
|
||||
vw.loadUrl(request.getUrl().toString());
|
||||
} else {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
|
||||
vw.getContext().startActivity(intent);
|
||||
openExternalUri(request.getUrl());
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -95,7 +96,7 @@ public class MainActivity extends AppCompatActivity {
|
||||
|
||||
@Override
|
||||
public boolean onShowFileChooser(WebView vw, ValueCallback<Uri[]> filePathCallback,
|
||||
FileChooserParams fileChooserParams) {
|
||||
FileChooserParams fileChooserParams) {
|
||||
if (fileChooserCallback != null) {
|
||||
fileChooserCallback.onReceiveValue(null);
|
||||
}
|
||||
@@ -112,6 +113,25 @@ public class MainActivity extends AppCompatActivity {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
|
||||
WebView popupWebView = new WebView(MainActivity.this);
|
||||
popupWebView.setWebViewClient(new WebViewClient() {
|
||||
@Override
|
||||
public boolean shouldOverrideUrlLoading(WebView popupView, WebResourceRequest request) {
|
||||
openExternalUri(request.getUrl());
|
||||
popupWebView.destroy();
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
|
||||
transport.setWebView(popupWebView);
|
||||
resultMsg.sendToTarget();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
webView.setOnKeyListener((v, keyCode, event) ->
|
||||
@@ -163,10 +183,40 @@ public class MainActivity extends AppCompatActivity {
|
||||
|
||||
private void handleURI(String uri) {
|
||||
if (uri != null) {
|
||||
Intent i = new Intent(Intent.ACTION_VIEW);
|
||||
i.setData(Uri.parse(uri.replaceFirst("^blob:", "")));
|
||||
openExternalUri(Uri.parse(uri.replaceFirst("^blob:", "")));
|
||||
}
|
||||
}
|
||||
|
||||
startActivity(i);
|
||||
private boolean shouldLoadInsideApp(Uri uri, Uri home) {
|
||||
return uri != null
|
||||
&& uri.getHost() != null
|
||||
&& uri.getHost().equals(home.getHost())
|
||||
&& ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()));
|
||||
}
|
||||
|
||||
private void openExternalUri(Uri uri) {
|
||||
if (uri == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Intent intent;
|
||||
|
||||
if ("intent".equals(uri.getScheme())) {
|
||||
intent = Intent.parseUri(uri.toString(), Intent.URI_INTENT_SCHEME);
|
||||
intent.addCategory(Intent.CATEGORY_BROWSABLE);
|
||||
intent.setComponent(null);
|
||||
} else {
|
||||
intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
}
|
||||
|
||||
startActivity(intent);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
Log.w("WEBVIEW", "No app can handle URI: " + uri, e);
|
||||
Toast.makeText(this, "No hay una aplicación disponible para abrir este enlace", Toast.LENGTH_LONG).show();
|
||||
} catch (Exception e) {
|
||||
Log.e("WEBVIEW", "Error opening URI: " + uri, e);
|
||||
Toast.makeText(this, "No se pudo abrir el enlace", Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,14 +29,8 @@ COPY --from=builder /app/dist ./dist
|
||||
# Copiar archivos de entorno a la raíz /app
|
||||
COPY --from=builder /app/.env* ./
|
||||
|
||||
# Instalar bash y cron
|
||||
RUN apk add --no-cache bash curl
|
||||
|
||||
# Crear carpeta de logs
|
||||
RUN mkdir -p /app/logs
|
||||
|
||||
# Agregar tarea de cron: todos los días a las (9-3)UTF = 6AM GMT-3
|
||||
RUN echo "0 9 * * * cd /app && NODE_ENV=production NODE_NO_WARNINGS=1 DOTENV_DISABLE_TELEMETRY=1 node dist/index.js >> /app/logs/cron.log 2>&1" > /etc/crontabs/root
|
||||
|
||||
# Mantener cron en primer plano
|
||||
CMD ["crond", "-f", "-L", "/app/logs/cron.log"]
|
||||
# Ejecutar el worker continuo de jobs de notificaciones
|
||||
CMD ["node", "dist/index.js"]
|
||||
|
||||
@@ -9,6 +9,7 @@ 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 CLEANUP_RETENTION_DAYS = 7;
|
||||
const SUPPORTED_APPOINTMENT_NOTIFICATION_TYPES = new Set(["creation", "reminder", "cancellation"]);
|
||||
|
||||
function resolveCleanupIntervalMs(): number {
|
||||
@@ -41,6 +42,12 @@ export function buildStartOfDay(date: Date): Date {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
}
|
||||
|
||||
export function buildCleanupCutoff(now: Date): Date {
|
||||
const cutoff = buildStartOfDay(now);
|
||||
cutoff.setDate(cutoff.getDate() - CLEANUP_RETENTION_DAYS);
|
||||
return cutoff;
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -91,7 +98,7 @@ export class JobProcessor {
|
||||
}
|
||||
|
||||
private async cleanupOldJobs(now = new Date()): Promise<void> {
|
||||
const cutoff = buildStartOfDay(now);
|
||||
const cutoff = buildCleanupCutoff(now);
|
||||
|
||||
try {
|
||||
const deletedCount = await this.jobModel.deleteBeforeScheduledAt(cutoff);
|
||||
|
||||
@@ -147,7 +147,7 @@ export function buildNotificationText(params: {
|
||||
}
|
||||
|
||||
export async function resolveNotificationContent(job: INotificationJobDocument): Promise<ResolvedNotificationContent> {
|
||||
if ((job.type === "creation" || job.type === "reminder" || job.type === "cancellation") && job.payload) {
|
||||
if ((job.type === "creation" || job.type === "reminder" || job.type === "update" || job.type === "cancellation") && job.payload) {
|
||||
const { email, phoneNumber, userId, companyOwnerId } = job.payload;
|
||||
const subject = job.channel === "email"
|
||||
? job.payload.emailSubject
|
||||
|
||||
@@ -4,6 +4,8 @@ export type NotificationChannel = "whatsapp" | "email" | "system";
|
||||
export type NotificationJobStatus = "pending" | "processing" | "sent" | "failed" | "cancelled";
|
||||
export type NotificationJobType = "creation" | "reminder" | "update" | "cancellation";
|
||||
|
||||
export const DELETABLE_NOTIFICATION_JOB_STATUSES: NotificationJobStatus[] = ["sent", "failed", "cancelled"];
|
||||
|
||||
export interface NotificationJobPayload {
|
||||
email?: string;
|
||||
phoneNumber?: string;
|
||||
@@ -106,6 +108,7 @@ export class NotificationJobModel {
|
||||
async deleteBeforeScheduledAt(cutoff: Date): Promise<number> {
|
||||
const result = await this.notificationJobList.deleteMany({
|
||||
scheduledAt: { $lt: cutoff },
|
||||
status: { $in: DELETABLE_NOTIFICATION_JOB_STATUSES },
|
||||
}).exec();
|
||||
|
||||
return result.deletedCount || 0;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { dispatchEmail, dispatchWhatsApp } from "../ChannelDispatchers.js";
|
||||
import { buildPendingJobQuery, buildStartOfDay, calculateNextRetryAt, JobProcessor } from "../JobProcessor.js";
|
||||
import { buildCleanupCutoff, buildPendingJobQuery, buildStartOfDay, calculateNextRetryAt, JobProcessor } from "../JobProcessor.js";
|
||||
import { DELETABLE_NOTIFICATION_JOB_STATUSES, NotificationJobModel } from "../NotificationJob.Adapter.Mongoose.js";
|
||||
import { resolveNotificationContent } from "../NotificationContentResolver.js";
|
||||
|
||||
jest.mock("../ChannelDispatchers.js", () => ({
|
||||
@@ -103,7 +104,7 @@ describe("JobProcessor", () => {
|
||||
});
|
||||
|
||||
describe("old job cleanup", () => {
|
||||
it("deletes jobs scheduled before the start of the current day", async () => {
|
||||
it("deletes jobs scheduled before the 7-day retention cutoff", async () => {
|
||||
const deleteBeforeScheduledAt = jest.fn().mockResolvedValue(3);
|
||||
const now = new Date(2026, 6, 21, 15, 30, 0, 0);
|
||||
|
||||
@@ -112,7 +113,30 @@ describe("JobProcessor", () => {
|
||||
now
|
||||
);
|
||||
|
||||
expect(deleteBeforeScheduledAt).toHaveBeenCalledWith(new Date(2026, 6, 21, 0, 0, 0, 0));
|
||||
expect(deleteBeforeScheduledAt).toHaveBeenCalledWith(new Date(2026, 6, 14, 0, 0, 0, 0));
|
||||
});
|
||||
|
||||
it("builds the 7-day retention cutoff from the start of the local day", () => {
|
||||
expect(buildCleanupCutoff(new Date(2026, 6, 21, 15, 30, 0, 0))).toEqual(
|
||||
new Date(2026, 6, 14, 0, 0, 0, 0)
|
||||
);
|
||||
});
|
||||
|
||||
it("deletes only terminal statuses and never pending or processing jobs", async () => {
|
||||
const exec = jest.fn().mockResolvedValue({ deletedCount: 3 });
|
||||
const deleteMany = jest.fn(() => ({ exec }));
|
||||
const model = Object.create(NotificationJobModel.prototype) as NotificationJobModel;
|
||||
(model as any).notificationJobList = { deleteMany };
|
||||
const cutoff = new Date("2026-07-14T00:00:00.000Z");
|
||||
|
||||
await model.deleteBeforeScheduledAt(cutoff);
|
||||
|
||||
expect(deleteMany).toHaveBeenCalledWith({
|
||||
scheduledAt: { $lt: cutoff },
|
||||
status: { $in: ["sent", "failed", "cancelled"] },
|
||||
});
|
||||
expect(DELETABLE_NOTIFICATION_JOB_STATUSES).not.toContain("pending");
|
||||
expect(DELETABLE_NOTIFICATION_JOB_STATUSES).not.toContain("processing");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -158,6 +158,111 @@ describe("NotificationContentResolver", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("uses update payload content for email jobs 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: "email",
|
||||
type: "update",
|
||||
payload: {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Generic update subject",
|
||||
message: "Generic update body.",
|
||||
emailSubject: "Email update subject",
|
||||
emailMessage: "Email update body.",
|
||||
wapMessage: "WAP update body.",
|
||||
systemSubject: "System update subject",
|
||||
systemMessage: "System update body.",
|
||||
},
|
||||
} as any);
|
||||
|
||||
expect(appointmentLookup).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Email update subject",
|
||||
message: "Email update body.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses update payload content for WhatsApp jobs 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: "update",
|
||||
payload: {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Generic update subject",
|
||||
message: "Generic update body.",
|
||||
emailSubject: "Email update subject",
|
||||
emailMessage: "Email update body.",
|
||||
wapMessage: "WAP update body.",
|
||||
systemSubject: "System update subject",
|
||||
systemMessage: "System update body.",
|
||||
},
|
||||
} as any);
|
||||
|
||||
expect(appointmentLookup).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Generic update subject",
|
||||
message: "WAP update body.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses update payload content for system jobs 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: "system",
|
||||
type: "update",
|
||||
payload: {
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "Generic update subject",
|
||||
message: "Generic update body.",
|
||||
emailSubject: "Email update subject",
|
||||
emailMessage: "Email update body.",
|
||||
wapMessage: "WAP update body.",
|
||||
systemSubject: "System update subject",
|
||||
systemMessage: "System update body.",
|
||||
},
|
||||
} as any);
|
||||
|
||||
expect(appointmentLookup).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({
|
||||
email: "client@example.com",
|
||||
phoneNumber: "5491112345678",
|
||||
userId: "user-1",
|
||||
companyOwnerId: "owner-1",
|
||||
subject: "System update subject",
|
||||
message: "System update body.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses WhatsApp cancellation payload content for WhatsApp jobs", async () => {
|
||||
const result = await resolveNotificationContent({
|
||||
appointmentId: "deleted-appointment-1",
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
server {
|
||||
server_name turnosxpress.com.ar www.turnosxpress.com.ar;
|
||||
|
||||
root /var/www/turnosxpress.com.ar;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
#Sirvo el favicon desde la pagina de working
|
||||
location = /favicon.ico {
|
||||
root /var/www/working-web;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
}
|
||||
|
||||
# Sitio web de Produccion
|
||||
location / {
|
||||
proxy_pass http://localhost:3021;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
client_max_body_size 5M;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
|
||||
# Sitio web de Mantenimiento
|
||||
#location / {
|
||||
# root /var/www/working-web;
|
||||
# index index.html;
|
||||
# try_files $uri $uri/ /index.html;
|
||||
# #Desactivar caché en los navegadores
|
||||
# add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
|
||||
# add_header Pragma "no-cache" always;
|
||||
# add_header Expires 0 always;
|
||||
#}
|
||||
|
||||
|
||||
listen 443 ssl; # managed by Certbot
|
||||
ssl_certificate /etc/letsencrypt/live/turnosxpress.com.ar/fullchain.pem; # managed by Certbot
|
||||
ssl_certificate_key /etc/letsencrypt/live/turnosxpress.com.ar/privkey.pem; # managed by Certbot
|
||||
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
|
||||
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
|
||||
|
||||
|
||||
}
|
||||
|
||||
server {
|
||||
if ($host = www.turnosxpress.com.ar) {
|
||||
return 301 https://$host$request_uri;
|
||||
} # managed by Certbot
|
||||
|
||||
|
||||
if ($host = turnosxpress.com.ar) {
|
||||
return 301 https://$host$request_uri;
|
||||
} # managed by Certbot
|
||||
|
||||
|
||||
listen 80;
|
||||
server_name turnosxpress.com.ar www.turnosxpress.com.ar;
|
||||
return 404; # managed by Certbot
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -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.
Binary file not shown.
Binary file not shown.
@@ -54,6 +54,15 @@ export type CreateImmediateAppointmentNotificationJobsParams = {
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
};
|
||||
|
||||
export type AppointmentNotificationPreviewParams = CreateImmediateAppointmentNotificationJobsParams;
|
||||
|
||||
export type AppointmentNotificationPreviewResult = {
|
||||
subject: string;
|
||||
message: string;
|
||||
emailMessage: string;
|
||||
wapMessage: string;
|
||||
};
|
||||
|
||||
export type MoveAppointmentParams = {
|
||||
id: string;
|
||||
companyId: string;
|
||||
@@ -328,6 +337,7 @@ export interface IAppointmentsManager {
|
||||
sendWapNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||
sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void>;
|
||||
createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void>;
|
||||
getAppointmentNotificationPreview(data: AppointmentNotificationPreviewParams): Promise<AppointmentNotificationPreviewResult>;
|
||||
sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void>;
|
||||
deleteAppointmentsByCompany(data: DeleteAppointmentsByCompanyParams): Promise<void>;
|
||||
changeEmployeeToOwner(data: ChangeEmployeeToOwnerParams): Promise<void>;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
AppointmentEvent,
|
||||
AppointmentEventByClient,
|
||||
AppointmentNotificationIntent,
|
||||
AppointmentNotificationPreviewResult,
|
||||
ChangeEmployeeToOwnerParams,
|
||||
CountAppointmentsByMonthParams,
|
||||
CreateAppointmentParams,
|
||||
@@ -529,51 +530,22 @@ class AppointmentManager implements IAppointmentsManager {
|
||||
type: NotificationType.APPOINTMENT,
|
||||
code: String((newAppointment as any)._id)
|
||||
});
|
||||
}
|
||||
|
||||
//Create jobs for email and whatsapp notifications
|
||||
if (newAppointment.id) {
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: String(newAppointment.id),
|
||||
sessionUser: String(companyCheck.ownerId),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
const clientPhoneNumber = await this.getOptionalClientWapNumber(checkClient);
|
||||
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",
|
||||
});
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
//Create jobs for email and whatsapp notifications
|
||||
if (this.shouldCreateCustomerNotificationJobs(notification, data.repeatId) && newAppointment.id) {
|
||||
await this.createAppointmentNotificationJobs({
|
||||
appointmentId: String(newAppointment.id),
|
||||
companyId: String(companyCheck._id),
|
||||
clientId: String(checkClient._id),
|
||||
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
|
||||
clientEmail: checkClient.email,
|
||||
client: checkClient,
|
||||
companyOwnerId: String(companyCheck.ownerId),
|
||||
companyName: companyCheck.name,
|
||||
appointmentStart: new Date(data.start),
|
||||
notification,
|
||||
});
|
||||
}
|
||||
|
||||
//Envio la notificacion al profesional.
|
||||
@@ -2238,27 +2210,122 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
reminderWapMessage: string;
|
||||
}): Promise<void> {
|
||||
const systemSubject = `Turno reservado en ${data.companyName}`;
|
||||
const reminderSystemSubject = `Recordatorio de turno en ${data.companyName}`;
|
||||
|
||||
await this.jobService.createJob({
|
||||
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.createReminderNotificationJobs(data);
|
||||
}
|
||||
|
||||
private shouldCreateCustomerNotificationJobs(notification: boolean, repeatId?: string): boolean {
|
||||
return notification || Boolean(repeatId);
|
||||
}
|
||||
|
||||
private async createAppointmentNotificationJobs(data: {
|
||||
appointmentId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
clientUserId?: string;
|
||||
clientEmail?: string;
|
||||
client: IClientDocument;
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
appointmentStart: Date;
|
||||
notification: boolean;
|
||||
}): Promise<void> {
|
||||
const clientPhoneNumber = await this.getOptionalClientWapNumber(data.client);
|
||||
const reminderEmailContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.companyOwnerId,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "email",
|
||||
});
|
||||
const reminderWapContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.companyOwnerId,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
const notificationJobData = {
|
||||
appointmentId: data.appointmentId,
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
clientUserId: data.clientUserId,
|
||||
clientEmail: data.clientEmail,
|
||||
clientPhoneNumber,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
companyName: data.companyName,
|
||||
appointmentStart: data.appointmentStart,
|
||||
reminderEmailMessage: reminderEmailContent.message,
|
||||
reminderWapMessage: reminderWapContent.message,
|
||||
};
|
||||
|
||||
if (!data.notification) {
|
||||
await this.createReminderNotificationJobs(notificationJobData);
|
||||
return;
|
||||
}
|
||||
|
||||
const emailContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.companyOwnerId,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "email",
|
||||
});
|
||||
const wapContent = await this.tryToSendNotification({
|
||||
appointmentId: data.appointmentId,
|
||||
sessionUser: data.companyOwnerId,
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.CREATION,
|
||||
channel: "whatsapp",
|
||||
});
|
||||
|
||||
await this.createCreationNotificationJobs({
|
||||
...notificationJobData,
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.message,
|
||||
});
|
||||
}
|
||||
|
||||
private async createReminderNotificationJobs(data: {
|
||||
appointmentId: string;
|
||||
companyId: string;
|
||||
clientId: string;
|
||||
clientUserId?: string;
|
||||
clientEmail?: string;
|
||||
clientPhoneNumber?: string;
|
||||
companyOwnerId: string;
|
||||
companyName: string;
|
||||
appointmentStart: Date;
|
||||
reminderEmailMessage: string;
|
||||
reminderWapMessage: string;
|
||||
}): Promise<void> {
|
||||
const reminderSystemSubject = `Recordatorio de turno en ${data.companyName}`;
|
||||
|
||||
await this.jobService.createReminderJobs({
|
||||
companyId: data.companyId,
|
||||
clientId: data.clientId,
|
||||
appointmentId: data.appointmentId,
|
||||
type: "reminder",
|
||||
appointmentStart: data.appointmentStart,
|
||||
payload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
userId: data.clientUserId,
|
||||
companyOwnerId: data.companyOwnerId,
|
||||
subject: systemSubject,
|
||||
message: data.emailMessage,
|
||||
emailSubject: "TurnosXpress :: Alta de turno",
|
||||
emailMessage: data.emailMessage,
|
||||
wapMessage: data.wapMessage,
|
||||
systemSubject,
|
||||
systemMessage: data.emailMessage,
|
||||
},
|
||||
reminderPayload: {
|
||||
email: data.clientEmail,
|
||||
phoneNumber: data.clientPhoneNumber,
|
||||
@@ -2894,6 +2961,52 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
public async getAppointmentNotificationPreview(data: CreateImmediateAppointmentNotificationJobsParams): Promise<AppointmentNotificationPreviewResult> {
|
||||
await validateSessionUser({ sessionUser: data.sessionUser });
|
||||
|
||||
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 checkAppointment = await this.Appointments.findOne({
|
||||
_id: data.appointmentId,
|
||||
});
|
||||
|
||||
if (!checkAppointment) {
|
||||
throw new Error("El turno no existe");
|
||||
}
|
||||
|
||||
await validatePermissionsByCompany({
|
||||
companyId: String(checkAppointment.companyId),
|
||||
sessionUser: data.sessionUser,
|
||||
});
|
||||
|
||||
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 isCreation = data.type === APPOINTMENT_NOTIFICATION_TYPE.CREATION;
|
||||
const subject = isCreation
|
||||
? `Turno reservado en ${emailContent.companyCheck.name}`
|
||||
: `Recordatorio de turno en ${emailContent.companyCheck.name}`;
|
||||
|
||||
return {
|
||||
subject,
|
||||
message: emailContent.message,
|
||||
emailMessage: emailContent.message,
|
||||
wapMessage: wapContent.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");
|
||||
|
||||
@@ -421,6 +421,8 @@ describe("cancellation notification jobs", () => {
|
||||
};
|
||||
(AppointmentsList as any).jobService = {
|
||||
createJob: jest.fn().mockResolvedValue([]),
|
||||
createMandatoryCreationJob: jest.fn().mockResolvedValue([]),
|
||||
createReminderJobs: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
|
||||
@@ -563,6 +565,8 @@ describe("creation notification jobs", () => {
|
||||
};
|
||||
(AppointmentsList as any).jobService = {
|
||||
createJob: jest.fn().mockResolvedValue([]),
|
||||
createMandatoryCreationJob: jest.fn().mockResolvedValue([]),
|
||||
createReminderJobs: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
|
||||
@@ -649,7 +653,7 @@ describe("creation notification jobs", () => {
|
||||
reminderWapMessage: "WAP REMINDER Ada Lovelace",
|
||||
});
|
||||
|
||||
expect((AppointmentsList as any).jobService.createJob).toHaveBeenCalledWith(
|
||||
expect((AppointmentsList as any).jobService.createMandatoryCreationJob).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: "creation",
|
||||
payload: expect.objectContaining({
|
||||
@@ -659,6 +663,11 @@ describe("creation notification jobs", () => {
|
||||
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",
|
||||
@@ -672,6 +681,73 @@ describe("creation notification jobs", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("routes customer notification jobs for creation, repeat reminder-only, and disabled notifications", () => {
|
||||
expect((AppointmentsList as any).shouldCreateCustomerNotificationJobs(true, undefined)).toBe(true);
|
||||
expect((AppointmentsList as any).shouldCreateCustomerNotificationJobs(false, "repeat-001")).toBe(true);
|
||||
expect((AppointmentsList as any).shouldCreateCustomerNotificationJobs(false, undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("creates reminder-only jobs without rendering Alta content for repeat-created appointments", async () => {
|
||||
const tryToSendNotificationSpy = jest
|
||||
.spyOn(AppointmentsList as any, "tryToSendNotification")
|
||||
.mockImplementation(({ type, channel }: any) => {
|
||||
if (type === APPOINTMENT_NOTIFICATION_TYPE.CREATION) {
|
||||
throw new Error("Creation content should not be rendered");
|
||||
}
|
||||
|
||||
return Promise.resolve({
|
||||
message: channel === "email" ? "EMAIL REMINDER Ada Lovelace" : "WAP REMINDER Ada Lovelace",
|
||||
});
|
||||
});
|
||||
const getOptionalClientWapNumberSpy = jest
|
||||
.spyOn(AppointmentsList as any, "getOptionalClientWapNumber")
|
||||
.mockResolvedValue("5491112345678");
|
||||
|
||||
try {
|
||||
await (AppointmentsList as any).createAppointmentNotificationJobs({
|
||||
appointmentId: "appt-001",
|
||||
companyId: "company-001",
|
||||
clientId: "client-001",
|
||||
clientUserId: "client-user-001",
|
||||
clientEmail: "ada@example.com",
|
||||
client: { _id: "client-001" },
|
||||
companyOwnerId: "owner-001",
|
||||
companyName: "clases llavallol",
|
||||
appointmentStart: new Date("2026-07-22T11:00:00.000Z"),
|
||||
notification: false,
|
||||
});
|
||||
|
||||
expect(tryToSendNotificationSpy).toHaveBeenCalledTimes(2);
|
||||
expect(tryToSendNotificationSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER, channel: "email" })
|
||||
);
|
||||
expect(tryToSendNotificationSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER, channel: "whatsapp" })
|
||||
);
|
||||
expect((AppointmentsList as any).jobService.createMandatoryCreationJob).not.toHaveBeenCalled();
|
||||
expect((AppointmentsList as any).jobService.createReminderJobs).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: "reminder",
|
||||
appointmentStart: new Date("2026-07-22T11:00:00.000Z"),
|
||||
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",
|
||||
systemSubject: "Recordatorio de turno en clases llavallol",
|
||||
systemMessage: "EMAIL REMINDER Ada Lovelace",
|
||||
}),
|
||||
})
|
||||
);
|
||||
} finally {
|
||||
tryToSendNotificationSpy.mockRestore();
|
||||
getOptionalClientWapNumberSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
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",
|
||||
|
||||
@@ -67,6 +67,9 @@ export class CompaniesAdapterMongoose implements ICompaniesAdapter {
|
||||
|
||||
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);
|
||||
@@ -235,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.
|
||||
|
||||
@@ -54,6 +54,9 @@ export type UpdateCompanyParams = {
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
};
|
||||
|
||||
export type SetCompanyFileParams = {
|
||||
@@ -154,6 +157,9 @@ export interface ICompany {
|
||||
onboardingCompleted?: boolean;
|
||||
fixedPostIds?: Array<string>;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
}
|
||||
|
||||
export interface MyOranizationsView {
|
||||
@@ -203,6 +209,9 @@ export interface MyOranizationsView {
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
}
|
||||
|
||||
export interface ClientOrganizationView {
|
||||
@@ -255,6 +264,75 @@ export type SysAdminSetCompanyBannedParams = {
|
||||
banned: boolean;
|
||||
};
|
||||
|
||||
export type SysAdminCompanyInsightsParams = {
|
||||
companyId: string;
|
||||
};
|
||||
|
||||
export type SysAdminCompanyInsightsResult = {
|
||||
organization: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
categoryId: number;
|
||||
banned: boolean;
|
||||
published?: COMPANY_PUBLISHED_STATUS;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
};
|
||||
owner: {
|
||||
id: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
verificated?: boolean;
|
||||
phoneCountryCode?: string;
|
||||
phoneAreaCode?: string;
|
||||
phoneNumber?: string;
|
||||
} | null;
|
||||
collaborators: {
|
||||
id: string;
|
||||
userId?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
fullName?: string;
|
||||
email?: string;
|
||||
roles?: string[];
|
||||
removed?: boolean;
|
||||
active: boolean;
|
||||
avatar?: string;
|
||||
}[];
|
||||
subscription: {
|
||||
id: string;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
isActive: boolean;
|
||||
autoRenew: boolean;
|
||||
mpStatus?: string;
|
||||
pendingPaymentType?: "extension" | "upgrade";
|
||||
plan: {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
price: number;
|
||||
limitOrganizations: number;
|
||||
limitEmployees: number;
|
||||
limitServices: number;
|
||||
limitAppointments: number;
|
||||
limitClients: number;
|
||||
} | null;
|
||||
} | null;
|
||||
stats: {
|
||||
employeesCount: number;
|
||||
activeEmployeesCount: number;
|
||||
servicesCount: number;
|
||||
activeServicesCount: number;
|
||||
clientsCount: number;
|
||||
activeClientsCount: number;
|
||||
reservationsLast30Days: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type FixCompanyPostParams = {
|
||||
companyId: string;
|
||||
postId: string;
|
||||
@@ -301,4 +379,5 @@ export interface ICompaniesManager {
|
||||
sysAdminPaginate(data: SysAdminPaginateCompaniesParams): Promise<PaginateCompaniesResults>;
|
||||
sysAdminUpdate(data: SysAdminUpdateCompanyParams): Promise<void>;
|
||||
sysAdminSetBanned(data: SysAdminSetCompanyBannedParams): Promise<void>;
|
||||
sysAdminGetInsights(data: SysAdminCompanyInsightsParams): Promise<SysAdminCompanyInsightsResult>;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ import {
|
||||
SysAdminPaginateCompaniesParams,
|
||||
SysAdminUpdateCompanyParams,
|
||||
SysAdminSetCompanyBannedParams,
|
||||
SysAdminCompanyInsightsParams,
|
||||
SysAdminCompanyInsightsResult,
|
||||
} from "./Companies.Interface";
|
||||
import UsersManager from "../Users/Users";
|
||||
import EmployeesList from "../Employees/Employee";
|
||||
@@ -54,11 +56,14 @@ import ClientAccount from "../ClientAccounts/ClientAccount";
|
||||
import Payments from "../Payments/Payments";
|
||||
import Discounts from "../Discounts/Discounts";
|
||||
import Templates from "../Templates/Templates";
|
||||
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
|
||||
import PlansList from "../Plans/Plans";
|
||||
|
||||
import Posts from "../Posts/Posts";
|
||||
import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled";
|
||||
import DiscountsEmail from "../DiscountsEmail/DiscountsEmail";
|
||||
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
|
||||
import getAvatar from "../../helpers/getAvatar";
|
||||
|
||||
class CompaniesManager implements ICompaniesManager {
|
||||
companies: ICompaniesAdapter;
|
||||
@@ -67,6 +72,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 +505,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 +621,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 +687,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 +747,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 +820,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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1053,6 +1090,137 @@ class CompaniesManager implements ICompaniesManager {
|
||||
sessionUser: "" // sysadmin override
|
||||
});
|
||||
}
|
||||
|
||||
public async sysAdminGetInsights(data: SysAdminCompanyInsightsParams): Promise<SysAdminCompanyInsightsResult> {
|
||||
const company = await this.companies.findOne({ _id: data.companyId });
|
||||
if (!company) {
|
||||
throw new Error("La compañia no existe");
|
||||
}
|
||||
|
||||
const [ownerResult, subscriptionResult] = await Promise.allSettled([
|
||||
UsersManager.users.findOne({ _id: String(company.ownerId) }),
|
||||
PlanSubscriptionsList.planSuscriptions.planSuscriptionList
|
||||
.findOne({ userId: String(company.ownerId) })
|
||||
.sort({ endDate: -1 })
|
||||
.exec(),
|
||||
]);
|
||||
const owner = ownerResult.status === "fulfilled" ? ownerResult.value : null;
|
||||
const subscription = subscriptionResult.status === "fulfilled" ? subscriptionResult.value : null;
|
||||
const collaboratorsResult = await Promise.allSettled([
|
||||
EmployeesList.employees.employeeList.find({ companyId: data.companyId }).exec(),
|
||||
]);
|
||||
const employeeDocs = collaboratorsResult[0]?.status === "fulfilled" ? collaboratorsResult[0].value : [];
|
||||
const collaboratorUserResults = await Promise.allSettled(
|
||||
employeeDocs.map((employee) => employee.userId
|
||||
? UsersManager.users.findOne({ _id: String(employee.userId) })
|
||||
: Promise.resolve(null))
|
||||
);
|
||||
const collaborators = employeeDocs.map((employee, index) => {
|
||||
const userResult = collaboratorUserResults[index];
|
||||
const user = userResult?.status === "fulfilled" ? userResult.value : null;
|
||||
const firstName = user?.firstName || employee.profileSnapshot?.firstName;
|
||||
const lastName = user?.lastName || employee.profileSnapshot?.lastName;
|
||||
const fullName = [firstName, lastName].filter(Boolean).join(" ");
|
||||
const avatar = user?.avatar
|
||||
? getAvatar(String(user.id || user._id), user.avatar, fullName)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: String(employee.id || employee._id),
|
||||
userId: employee.userId ? String(employee.userId) : undefined,
|
||||
firstName,
|
||||
lastName,
|
||||
fullName: fullName || undefined,
|
||||
email: user?.email || employee.profileSnapshot?.email,
|
||||
roles: employee.roles || [],
|
||||
removed: employee.removed ?? false,
|
||||
active: !(employee.removed ?? false),
|
||||
avatar: avatar !== fullName ? avatar : undefined,
|
||||
};
|
||||
});
|
||||
const planResult = subscription
|
||||
? await Promise.allSettled([PlansList.plans.planList.findOne({ _id: String(subscription.planId) }).exec()])
|
||||
: [];
|
||||
const plan = planResult[0]?.status === "fulfilled" ? planResult[0].value : null;
|
||||
const thirtyDaysAgo = new Date();
|
||||
thirtyDaysAgo.setUTCDate(thirtyDaysAgo.getUTCDate() - 30);
|
||||
thirtyDaysAgo.setUTCHours(0, 0, 0, 0);
|
||||
|
||||
const [
|
||||
employeesCount,
|
||||
activeEmployeesCount,
|
||||
servicesCount,
|
||||
activeServicesCount,
|
||||
clientsCount,
|
||||
activeClientsCount,
|
||||
reservationsLast30Days,
|
||||
] = (await Promise.allSettled([
|
||||
EmployeesList.employees.employeeList.countDocuments({ companyId: data.companyId }).exec(),
|
||||
EmployeesList.employees.employeeList.countDocuments({ companyId: data.companyId, removed: { $ne: true } }).exec(),
|
||||
ServiceList.services.serviceList.countDocuments({ companyId: data.companyId }).exec(),
|
||||
ServiceList.services.serviceList.countDocuments({ companyId: data.companyId, banned: { $ne: true } }).exec(),
|
||||
ClientsList.clients.clientList.countDocuments({ companyId: data.companyId }).exec(),
|
||||
ClientsList.clients.clientList.countDocuments({ companyId: data.companyId, status: true, banned: { $ne: true } }).exec(),
|
||||
AppointmentList.Appointments.AppointmentList.countDocuments({
|
||||
companyId: data.companyId,
|
||||
start: { $gte: thirtyDaysAgo },
|
||||
}).exec(),
|
||||
])).map((result) => result.status === "fulfilled" ? result.value : 0);
|
||||
|
||||
return {
|
||||
organization: {
|
||||
id: String(company.id || company._id),
|
||||
name: company.name,
|
||||
slug: company.slug,
|
||||
description: company.description,
|
||||
categoryId: company.categoryId,
|
||||
banned: company.banned ?? false,
|
||||
published: company.published,
|
||||
onboardingStep: company.onboardingStep,
|
||||
onboardingCompleted: company.onboardingCompleted,
|
||||
},
|
||||
owner: owner ? {
|
||||
id: String(owner.id || owner._id),
|
||||
firstName: owner.firstName,
|
||||
lastName: owner.lastName,
|
||||
email: owner.email,
|
||||
verificated: owner.verificated,
|
||||
phoneCountryCode: owner.phoneCountryCode,
|
||||
phoneAreaCode: owner.phoneAreaCode,
|
||||
phoneNumber: owner.phoneNumber,
|
||||
} : null,
|
||||
collaborators,
|
||||
subscription: subscription ? {
|
||||
id: String(subscription.id || subscription._id),
|
||||
startDate: subscription.startDate,
|
||||
endDate: subscription.endDate,
|
||||
isActive: subscription.isActive,
|
||||
autoRenew: subscription.autoRenew,
|
||||
mpStatus: subscription.mpStatus,
|
||||
pendingPaymentType: subscription.pendingPaymentType,
|
||||
plan: plan ? {
|
||||
id: String(plan.id || plan._id),
|
||||
name: plan.name,
|
||||
code: plan.code,
|
||||
price: plan.price,
|
||||
limitOrganizations: plan.limitOrganizations,
|
||||
limitEmployees: plan.limitEmployees,
|
||||
limitServices: plan.limitServices,
|
||||
limitAppointments: plan.limitAppointments,
|
||||
limitClients: plan.limitClients,
|
||||
} : null,
|
||||
} : null,
|
||||
stats: {
|
||||
employeesCount,
|
||||
activeEmployeesCount,
|
||||
servicesCount,
|
||||
activeServicesCount,
|
||||
clientsCount,
|
||||
activeClientsCount,
|
||||
reservationsLast30Days,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const CompaniesList = new CompaniesManager();
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
import { Document, Model, Schema, model } from "mongoose";
|
||||
import {
|
||||
CreateJobParams,
|
||||
DeleteOldJobsParams,
|
||||
DeleteOldJobsResult,
|
||||
INotificationJob,
|
||||
INotificationJobAdapter,
|
||||
NotificationJobStatus,
|
||||
} from "./NotificationJobs.Interface";
|
||||
|
||||
export const NOTIFICATION_JOB_CLEANUP_RETENTION_DAYS = 7;
|
||||
export const NOTIFICATION_JOB_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
|
||||
export const NOTIFICATION_JOB_CLEANUP_STATUSES = [
|
||||
NotificationJobStatus.SENT,
|
||||
NotificationJobStatus.FAILED,
|
||||
NotificationJobStatus.CANCELLED,
|
||||
];
|
||||
|
||||
export interface INotificationJobDocument
|
||||
extends Omit<INotificationJob, "id">,
|
||||
Document {}
|
||||
@@ -13,6 +23,7 @@ export interface INotificationJobDocument
|
||||
export class NotificationJobsAdapterMongoose implements INotificationJobAdapter {
|
||||
schema: Schema;
|
||||
notificationJobList: Model<INotificationJobDocument>;
|
||||
private lastCleanupAt?: number;
|
||||
|
||||
constructor() {
|
||||
this.schema = new Schema(
|
||||
@@ -73,6 +84,7 @@ export class NotificationJobsAdapterMongoose implements INotificationJobAdapter
|
||||
}
|
||||
|
||||
public async create(data: CreateJobParams): Promise<INotificationJob> {
|
||||
await this.cleanupOldJobsIfDueSafely();
|
||||
const doc = await this.notificationJobList.create({
|
||||
...data,
|
||||
status: NotificationJobStatus.PENDING,
|
||||
@@ -111,6 +123,7 @@ export class NotificationJobsAdapterMongoose implements INotificationJobAdapter
|
||||
}
|
||||
|
||||
public async cancelByAppointment(appointmentId: string): Promise<void> {
|
||||
await this.cleanupOldJobsIfDueSafely();
|
||||
await this.notificationJobList
|
||||
.updateMany(
|
||||
{
|
||||
@@ -123,9 +136,52 @@ export class NotificationJobsAdapterMongoose implements INotificationJobAdapter
|
||||
}
|
||||
|
||||
public async findByAppointment(appointmentId: string): Promise<INotificationJob[]> {
|
||||
await this.cleanupOldJobsIfDueSafely();
|
||||
const docs = await this.notificationJobList
|
||||
.find({ appointmentId })
|
||||
.exec();
|
||||
return docs.map((d) => d.toObject() as INotificationJob);
|
||||
}
|
||||
|
||||
public async deleteOldJobs(
|
||||
data: DeleteOldJobsParams
|
||||
): Promise<DeleteOldJobsResult> {
|
||||
const result = await this.notificationJobList
|
||||
.deleteMany({
|
||||
scheduledAt: { $lt: data.scheduledBefore },
|
||||
status: { $in: data.statuses },
|
||||
})
|
||||
.exec();
|
||||
|
||||
return { deletedCount: result.deletedCount || 0 };
|
||||
}
|
||||
|
||||
public async cleanupOldJobsIfDue(now = new Date()): Promise<void> {
|
||||
if (
|
||||
this.lastCleanupAt !== undefined &&
|
||||
now.getTime() - this.lastCleanupAt < NOTIFICATION_JOB_CLEANUP_INTERVAL_MS
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scheduledBefore = new Date(now.getTime());
|
||||
scheduledBefore.setDate(
|
||||
scheduledBefore.getDate() - NOTIFICATION_JOB_CLEANUP_RETENTION_DAYS
|
||||
);
|
||||
|
||||
await this.deleteOldJobs({
|
||||
scheduledBefore,
|
||||
statuses: NOTIFICATION_JOB_CLEANUP_STATUSES,
|
||||
});
|
||||
this.lastCleanupAt = now.getTime();
|
||||
}
|
||||
|
||||
private async cleanupOldJobsIfDueSafely(): Promise<void> {
|
||||
try {
|
||||
await this.cleanupOldJobsIfDue();
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`Notification jobs cleanup failed: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,15 @@ export interface CreateJobParams {
|
||||
payload?: NotificationJobPayload;
|
||||
}
|
||||
|
||||
export interface DeleteOldJobsParams {
|
||||
scheduledBefore: Date;
|
||||
statuses: NotificationJobStatus[];
|
||||
}
|
||||
|
||||
export interface DeleteOldJobsResult {
|
||||
deletedCount: number;
|
||||
}
|
||||
|
||||
export interface INotificationJobAdapter {
|
||||
create(data: CreateJobParams): Promise<INotificationJob>;
|
||||
findPendingDue(now: Date): Promise<INotificationJob[]>;
|
||||
@@ -68,4 +77,5 @@ export interface INotificationJobAdapter {
|
||||
): Promise<void>;
|
||||
cancelByAppointment(appointmentId: string): Promise<void>;
|
||||
findByAppointment(appointmentId: string): Promise<INotificationJob[]>;
|
||||
deleteOldJobs(data: DeleteOldJobsParams): Promise<DeleteOldJobsResult>;
|
||||
}
|
||||
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import {
|
||||
NOTIFICATION_JOB_CLEANUP_STATUSES,
|
||||
NotificationJobsAdapterMongoose,
|
||||
} from "../NotificationJobs.Adapter.Mongoose";
|
||||
import { NotificationJobStatus } from "../NotificationJobs.Interface";
|
||||
|
||||
describe("NotificationJobsAdapterMongoose cleanup", () => {
|
||||
const now = new Date("2026-07-21T15:30:00.000Z");
|
||||
|
||||
function buildAdapter() {
|
||||
return Object.create(NotificationJobsAdapterMongoose.prototype) as NotificationJobsAdapterMongoose;
|
||||
}
|
||||
|
||||
it("runs throttled retention cleanup before create on the production adapter path", async () => {
|
||||
const adapter = buildAdapter();
|
||||
const deleteOldJobs = jest.fn().mockResolvedValue({ deletedCount: 2 });
|
||||
const create = jest.fn().mockResolvedValue({ toObject: () => ({ id: "job-1" }) });
|
||||
(adapter as any).deleteOldJobs = deleteOldJobs;
|
||||
(adapter as any).notificationJobList = { create };
|
||||
|
||||
jest.useFakeTimers().setSystemTime(now);
|
||||
|
||||
await adapter.create({
|
||||
companyId: "company-1",
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: now,
|
||||
});
|
||||
|
||||
expect(deleteOldJobs).toHaveBeenCalledWith({
|
||||
scheduledBefore: new Date("2026-07-14T15:30:00.000Z"),
|
||||
statuses: NOTIFICATION_JOB_CLEANUP_STATUSES,
|
||||
});
|
||||
expect(NOTIFICATION_JOB_CLEANUP_STATUSES).toEqual([
|
||||
NotificationJobStatus.SENT,
|
||||
NotificationJobStatus.FAILED,
|
||||
NotificationJobStatus.CANCELLED,
|
||||
]);
|
||||
expect(create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
status: NotificationJobStatus.PENDING,
|
||||
attempts: 0,
|
||||
maxAttempts: 3,
|
||||
}));
|
||||
});
|
||||
|
||||
it("continues creating jobs when production cleanup fails", async () => {
|
||||
const adapter = buildAdapter();
|
||||
const deleteOldJobs = jest.fn().mockRejectedValue(new Error("database down"));
|
||||
const create = jest.fn().mockResolvedValue({ toObject: () => ({ id: "job-1" }) });
|
||||
const warn = jest.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
(adapter as any).deleteOldJobs = deleteOldJobs;
|
||||
(adapter as any).notificationJobList = { create };
|
||||
|
||||
await expect(adapter.create({
|
||||
companyId: "company-1",
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: now,
|
||||
})).resolves.toEqual({ id: "job-1" });
|
||||
|
||||
expect(warn).toHaveBeenCalledWith("Notification jobs cleanup failed: database down");
|
||||
expect(create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
status: NotificationJobStatus.PENDING,
|
||||
}));
|
||||
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it("throttles only after cleanup succeeds", async () => {
|
||||
const adapter = buildAdapter();
|
||||
const deleteOldJobs = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error("database down"))
|
||||
.mockResolvedValueOnce({ deletedCount: 0 })
|
||||
.mockResolvedValueOnce({ deletedCount: 0 });
|
||||
(adapter as any).deleteOldJobs = deleteOldJobs;
|
||||
|
||||
await expect(adapter.cleanupOldJobsIfDue(now)).rejects.toThrow("database down");
|
||||
await adapter.cleanupOldJobsIfDue(new Date(now.getTime() + 1000));
|
||||
await adapter.cleanupOldJobsIfDue(new Date(now.getTime() + 2000));
|
||||
await adapter.cleanupOldJobsIfDue(new Date(now.getTime() + 60 * 60 * 1000 + 1000));
|
||||
|
||||
expect(deleteOldJobs).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { NotificationJobStatus } from "../NotificationJobs.Interface";
|
||||
|
||||
const mockCreate = jest.fn();
|
||||
const mockCancelByAppointment = jest.fn();
|
||||
const mockFindByAppointment = jest.fn();
|
||||
const mockDeleteOldJobs = jest.fn();
|
||||
|
||||
jest.mock("../NotificationJobs.Adapter.Mongoose", () => ({
|
||||
NotificationJobsAdapterMongoose: jest.fn().mockImplementation(() => ({
|
||||
create: mockCreate,
|
||||
cancelByAppointment: mockCancelByAppointment,
|
||||
findByAppointment: mockFindByAppointment,
|
||||
deleteOldJobs: mockDeleteOldJobs,
|
||||
})),
|
||||
}));
|
||||
|
||||
describe("NotificationJobManager cleanup", () => {
|
||||
const loadNotificationJobsList = () => {
|
||||
jest.isolateModules(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
require("../NotificationJobs");
|
||||
});
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
return require("../NotificationJobs").default;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
jest.clearAllMocks();
|
||||
jest.useFakeTimers().setSystemTime(new Date("2026-07-29T12:00:00.000Z"));
|
||||
mockCreate.mockResolvedValue({ id: "job-1" });
|
||||
mockCancelByAppointment.mockResolvedValue(undefined);
|
||||
mockFindByAppointment.mockResolvedValue([]);
|
||||
mockDeleteOldJobs.mockResolvedValue({ deletedCount: 0 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it("deletes only completed old jobs before creating a job", async () => {
|
||||
const NotificationJobsList = loadNotificationJobsList();
|
||||
|
||||
await NotificationJobsList.createJob({
|
||||
companyId: "company-1",
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: new Date("2026-07-29T12:30:00.000Z"),
|
||||
});
|
||||
|
||||
expect(mockDeleteOldJobs).toHaveBeenCalledWith({
|
||||
scheduledBefore: new Date("2026-07-22T12:00:00.000Z"),
|
||||
statuses: [
|
||||
NotificationJobStatus.SENT,
|
||||
NotificationJobStatus.FAILED,
|
||||
NotificationJobStatus.CANCELLED,
|
||||
],
|
||||
});
|
||||
expect(mockCreate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("throttles cleanup across manager operations", async () => {
|
||||
const NotificationJobsList = loadNotificationJobsList();
|
||||
|
||||
await NotificationJobsList.createJob({
|
||||
companyId: "company-1",
|
||||
appointmentId: "appointment-1",
|
||||
clientId: "client-1",
|
||||
channel: "email",
|
||||
type: "creation",
|
||||
scheduledAt: new Date("2026-07-29T12:30:00.000Z"),
|
||||
});
|
||||
await NotificationJobsList.cancelByAppointment("appointment-1");
|
||||
await NotificationJobsList.findByAppointment("appointment-1");
|
||||
|
||||
expect(mockDeleteOldJobs).toHaveBeenCalledTimes(1);
|
||||
|
||||
jest.setSystemTime(new Date("2026-07-29T13:00:00.000Z"));
|
||||
|
||||
await NotificationJobsList.findByAppointment("appointment-1");
|
||||
|
||||
expect(mockDeleteOldJobs).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
CreateJobParams,
|
||||
NotificationChannel,
|
||||
} from "../NotificationJobs/NotificationJobs.Interface";
|
||||
import { NotificationJobsAdapterMongoose } from "../NotificationJobs/NotificationJobs.Adapter.Mongoose";
|
||||
import { PolicyResolver, ResolvedPolicy } from "./PolicyResolver";
|
||||
@@ -121,6 +122,79 @@ export class NotificationJobService {
|
||||
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.
|
||||
@@ -165,6 +239,24 @@ export class NotificationJobService {
|
||||
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,
|
||||
|
||||
@@ -93,6 +93,21 @@ export class PolicyResolver {
|
||||
};
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
@@ -10,6 +10,7 @@ jest.mock("../../NotificationJobs/NotificationJobs.Adapter.Mongoose", () => ({
|
||||
jest.mock("../PolicyResolver", () => ({
|
||||
PolicyResolver: jest.fn().mockImplementation(() => ({
|
||||
resolve: jest.fn(),
|
||||
resolveAvailableChannels: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
@@ -27,6 +28,7 @@ describe("NotificationJobService.createJob", () => {
|
||||
let service: NotificationJobService;
|
||||
let mockJobCreate: jest.Mock;
|
||||
let mockResolverResolve: jest.Mock;
|
||||
let mockResolveAvailableChannels: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -36,6 +38,7 @@ describe("NotificationJobService.createJob", () => {
|
||||
|
||||
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 () => {
|
||||
@@ -219,6 +222,114 @@ describe("NotificationJobService.createJob", () => {
|
||||
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"],
|
||||
|
||||
@@ -309,4 +309,43 @@ describe("PolicyResolver", () => {
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
CreateWapServerParams,
|
||||
FindWapServerParams,
|
||||
IWapServer,
|
||||
IWapServerAdapter,
|
||||
@@ -28,6 +29,10 @@ export class WapServerAdapterMongoose implements IWapServerAdapter {
|
||||
this.serverList = model<IWapServerDocument>("WapServer", this.schema);
|
||||
}
|
||||
|
||||
public async create(data: CreateWapServerParams): Promise<IWapServer> {
|
||||
return await this.serverList.create(data);
|
||||
}
|
||||
|
||||
public async find(data: FindWapServerParams): Promise<IWapServer[]> {
|
||||
return this.serverList.find(data).exec();
|
||||
}
|
||||
@@ -36,6 +41,10 @@ export class WapServerAdapterMongoose implements IWapServerAdapter {
|
||||
return this.serverList.findOne(data).exec();
|
||||
}
|
||||
|
||||
public async delete(id: string): Promise<void> {
|
||||
await this.serverList.deleteOne({ _id: id });
|
||||
}
|
||||
|
||||
private buildSearchCriteria(filters: FindWapServerParams): FilterQuery<IWapServerDocument> {
|
||||
const searchCriteria: FilterQuery<IWapServerDocument> = {};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ export type FindWapServerParams = {
|
||||
description?: string;
|
||||
countBots?: number;
|
||||
maxBots?: number;
|
||||
port?: number;
|
||||
active?: boolean;
|
||||
countBotsFrom?: number;
|
||||
countBotsTo?: number;
|
||||
@@ -100,9 +101,29 @@ export interface IWapServer {
|
||||
ipv6: string;
|
||||
countBots: number;
|
||||
maxBots: number;
|
||||
port: number;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export type UpdateWapServerParams = {
|
||||
serverId: string;
|
||||
name?: string;
|
||||
ipv4?: string;
|
||||
port?: number;
|
||||
maxBots?: number;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type CreateWapServerParams = {
|
||||
name: string;
|
||||
ipv4: string;
|
||||
port: number;
|
||||
maxBots: number;
|
||||
ipv6?: string;
|
||||
description?: string;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type PaginateWapServerParams = FindWapServerParams & {
|
||||
page: number;
|
||||
limit: number;
|
||||
@@ -114,13 +135,124 @@ export type PaginateWapServerResults = {
|
||||
pages: number;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerByIdParams = {
|
||||
serverId: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerAuditParams = SysAdminWapServerByIdParams;
|
||||
|
||||
export type SysAdminWapServerRecalculateCountParams = SysAdminWapServerByIdParams;
|
||||
|
||||
export type SysAdminDeleteWapServerParams = SysAdminWapServerByIdParams & {
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export type SysAdminDeleteWapServerResult = {
|
||||
serverId: string;
|
||||
deleted: true;
|
||||
force?: boolean;
|
||||
detachedOrganizations?: number;
|
||||
deletedRuntimeBots?: number;
|
||||
skippedRuntimeBots?: number;
|
||||
auditFailed?: boolean;
|
||||
auditMessage?: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerOrganizationActionParams = SysAdminWapServerByIdParams & {
|
||||
organizationId: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerQrResult = {
|
||||
serverId: string;
|
||||
organizationId: string;
|
||||
qr: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerDetachResult = {
|
||||
serverId: string;
|
||||
organizationId: string;
|
||||
botDeleted: boolean;
|
||||
botAlreadyMissing: boolean;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerDeleteBotResult = {
|
||||
serverId: string;
|
||||
organizationId: string;
|
||||
assignmentRemains: true;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
export type SysAdminWapAssignedOrganization = {
|
||||
id: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export type SysAdminWapContainerDto = {
|
||||
id?: string;
|
||||
name?: string;
|
||||
organizationId?: string;
|
||||
image?: string;
|
||||
state?: string;
|
||||
status?: string;
|
||||
ports?: unknown[];
|
||||
created?: number;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerAuditResult = {
|
||||
serverId: string;
|
||||
assignedOrganizations: SysAdminWapAssignedOrganization[];
|
||||
detectedBots: SysAdminWapContainerDto[];
|
||||
validBots: SysAdminWapContainerDto[];
|
||||
ghostBots: SysAdminWapContainerDto[];
|
||||
missingBots: SysAdminWapAssignedOrganization[];
|
||||
expectedCountBots: number;
|
||||
storedCountBots: number;
|
||||
runtimeCountBots: number;
|
||||
countMismatch: boolean;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerRecalculateCountResult = {
|
||||
serverId: string;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
export type SysAdminGetWapServerParams = PaginateWapServerParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminCreateWapServerParams = CreateWapServerParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminUpdateWapServerParams = UpdateWapServerParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminAuditWapServerParams = SysAdminWapServerAuditParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminRecalculateWapServerCountParams = SysAdminWapServerRecalculateCountParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminDeleteWapServerRequest = SysAdminDeleteWapServerParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type SysAdminWapServerOrganizationActionRequest = SysAdminWapServerOrganizationActionParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export interface IWapServerAdapter {
|
||||
create(data: CreateWapServerParams): Promise<IWapServer>;
|
||||
find(data: FindWapServerParams): Promise<IWapServer[]>;
|
||||
findOne(data: FindWapServerParams): Promise<IWapServerDocument | null>;
|
||||
delete(id: string): Promise<void>;
|
||||
paginate(filters: PaginateWapServerParams): Promise<PaginateWapServerResults>;
|
||||
}
|
||||
|
||||
@@ -140,4 +272,15 @@ export interface IWapServerManager {
|
||||
getQr(data: BotEventParams): Promise<string>;
|
||||
sendMessage(data: SendBotMessageParams): Promise<void>;
|
||||
sysAdminGetWapServers(data: PaginateWapServerParams): Promise<PaginateWapServerResults>;
|
||||
sysAdminCreateWapServer(data: CreateWapServerParams): Promise<IWapServer>;
|
||||
sysAdminUpdateWapServer(data: UpdateWapServerParams): Promise<IWapServer>;
|
||||
sysAdminAuditWapServer(data: SysAdminWapServerAuditParams): Promise<SysAdminWapServerAuditResult>;
|
||||
sysAdminRecalculateWapServerCount(data: SysAdminWapServerRecalculateCountParams): Promise<SysAdminWapServerRecalculateCountResult>;
|
||||
sysAdminDeleteWapServer(data: SysAdminDeleteWapServerParams): Promise<SysAdminDeleteWapServerResult>;
|
||||
sysAdminStartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void>;
|
||||
sysAdminStopBot(data: SysAdminWapServerOrganizationActionParams): Promise<void>;
|
||||
sysAdminRestartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void>;
|
||||
sysAdminGetQr(data: SysAdminWapServerOrganizationActionParams): Promise<SysAdminWapServerQrResult>;
|
||||
sysAdminDeleteBot(data: SysAdminWapServerOrganizationActionParams): Promise<SysAdminWapServerDeleteBotResult>;
|
||||
sysAdminDetachOrganizationServer(data: SysAdminWapServerOrganizationActionParams): Promise<SysAdminWapServerDetachResult>;
|
||||
}
|
||||
|
||||
@@ -13,20 +13,39 @@ import {
|
||||
BotView,
|
||||
IWapServer,
|
||||
IWapServerManager,
|
||||
SysAdminDeleteWapServerParams,
|
||||
SysAdminDeleteWapServerResult,
|
||||
SysAdminWapContainerDto,
|
||||
SysAdminWapServerAuditParams,
|
||||
SysAdminWapServerAuditResult,
|
||||
SysAdminWapServerRecalculateCountParams,
|
||||
SysAdminWapServerRecalculateCountResult,
|
||||
SysAdminWapServerDetachResult,
|
||||
SysAdminWapServerDeleteBotResult,
|
||||
SysAdminWapServerOrganizationActionParams,
|
||||
SysAdminWapServerQrResult,
|
||||
SendBotMessageParams,
|
||||
ValidateBotEventStatus,
|
||||
BOT_STATE,
|
||||
SERVER_STATE,
|
||||
BOT_SESSION_STATUS,
|
||||
CreateWapServerParams,
|
||||
VALIDATE_BOT_ENVENT_ERRORS,
|
||||
PaginateWapServerResults,
|
||||
PaginateWapServerParams,
|
||||
UpdateWapServerParams,
|
||||
} from "./WapServer.Interface";
|
||||
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
|
||||
import { PlanFeatures } from "../Plans/Plans.interface";
|
||||
import axios, { AxiosError } from "axios";
|
||||
import { isNull } from "../../helpers/IsNull";
|
||||
|
||||
const BOT_ADMIN_ACTION_TIMEOUT_MS = 10000;
|
||||
const BOT_ADMIN_RESTART_STATUS_RETRIES = 5;
|
||||
const BOT_ADMIN_RESTART_STATUS_DELAY_MS = 1000;
|
||||
const MONGO_OBJECT_ID_REGEX = /^[a-fA-F0-9]{24}$/;
|
||||
const WAP_SERVER_METADATA_HOSTS = new Set(["169.254.169.254", "metadata.google.internal"]);
|
||||
|
||||
export interface CreateBotResult {
|
||||
organizationId: string;
|
||||
port: number;
|
||||
@@ -142,10 +161,259 @@ class WapServerManager implements IWapServerManager {
|
||||
return servidores;
|
||||
}
|
||||
|
||||
private normalizeBotAdminApiUrl(url: string): string {
|
||||
const rawUrl = String(url).trim();
|
||||
|
||||
if (!rawUrl) {
|
||||
throw new Error("URL is required");
|
||||
}
|
||||
|
||||
if (/\s|[\x00-\x1F\x7F]/.test(rawUrl)) {
|
||||
throw new Error("URL must not contain whitespace or control characters");
|
||||
}
|
||||
|
||||
const hasProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(rawUrl);
|
||||
const normalizedInput = hasProtocol ? rawUrl : `http://${rawUrl}`;
|
||||
let parsedUrl: URL;
|
||||
|
||||
try {
|
||||
parsedUrl = new URL(normalizedInput);
|
||||
} catch (error) {
|
||||
throw new Error("URL must be a valid HTTP(S) origin");
|
||||
}
|
||||
|
||||
if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
|
||||
throw new Error("URL protocol must be http or https");
|
||||
}
|
||||
|
||||
if (!parsedUrl.hostname) {
|
||||
throw new Error("URL host is required");
|
||||
}
|
||||
|
||||
if (parsedUrl.username || parsedUrl.password) {
|
||||
throw new Error("URL must not include credentials");
|
||||
}
|
||||
|
||||
const path = decodeURIComponent(parsedUrl.pathname);
|
||||
if ((parsedUrl.pathname && parsedUrl.pathname !== "/") || path.includes("..")) {
|
||||
throw new Error("URL path is not allowed; use only the origin");
|
||||
}
|
||||
|
||||
if (parsedUrl.search || parsedUrl.hash) {
|
||||
throw new Error("URL must not include query string or hash");
|
||||
}
|
||||
|
||||
if (WAP_SERVER_METADATA_HOSTS.has(parsedUrl.hostname.toLowerCase())) {
|
||||
throw new Error("URL host is not allowed");
|
||||
}
|
||||
|
||||
return `${parsedUrl.origin}/`;
|
||||
}
|
||||
|
||||
private getBotAdminApiUrl(url: string): string {
|
||||
//return `https://${url}:${process.env.DEFAULT_BOT_ADMIN_PORT}/`;
|
||||
//return `https://${url}/`;
|
||||
return url;
|
||||
return this.normalizeBotAdminApiUrl(url);
|
||||
}
|
||||
|
||||
private formatResponseBody(data: unknown): string {
|
||||
if (data === undefined || data === null) {
|
||||
return "empty body";
|
||||
}
|
||||
|
||||
const body = typeof data === "string" ? data : JSON.stringify(data);
|
||||
|
||||
return body.length > 1000 ? `${body.slice(0, 1000)}...` : body;
|
||||
}
|
||||
|
||||
private createBotAdminContainersError(error: unknown, targetUrl: string): Error {
|
||||
if (axios.isAxiosError(error)) {
|
||||
const status = error.response?.status;
|
||||
const body = this.formatResponseBody(error.response?.data);
|
||||
const statusText = status ? `status ${status}` : error.code || "no response";
|
||||
|
||||
return new Error(`Bot-admin containers request failed for ${targetUrl}: ${statusText}; body: ${body}`);
|
||||
}
|
||||
|
||||
if (error instanceof Error && error.message) {
|
||||
return new Error(`Bot-admin containers request failed for ${targetUrl}: ${error.message}`);
|
||||
}
|
||||
|
||||
return new Error(`Bot-admin containers request failed for ${targetUrl}: unknown error`);
|
||||
}
|
||||
|
||||
private createBotAdminActionError(error: unknown, targetUrl: string): Error {
|
||||
if (axios.isAxiosError(error)) {
|
||||
const status = error.response?.status;
|
||||
const body = this.formatResponseBody(error.response?.data);
|
||||
const statusText = status ? `status ${status}` : error.code || "no response";
|
||||
|
||||
return new Error(`Bot-admin request failed for ${targetUrl}: ${statusText}; body: ${body}`);
|
||||
}
|
||||
|
||||
if (error instanceof Error && error.message) {
|
||||
return new Error(`Bot-admin request failed for ${targetUrl}: ${error.message}`);
|
||||
}
|
||||
|
||||
return new Error(`Bot-admin request failed for ${targetUrl}: unknown error`);
|
||||
}
|
||||
|
||||
private isBotAdminMissingContainerError(error: unknown): boolean {
|
||||
if (!axios.isAxiosError(error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const status = error.response?.status;
|
||||
const body = this.formatResponseBody(error.response?.data).toLowerCase();
|
||||
|
||||
// Be conservative: only allow detach to continue for explicit missing-container signals.
|
||||
return status === 404 || body.includes("not found") || body.includes("no such container");
|
||||
}
|
||||
|
||||
private async getSysAdminServerActionTarget(data: SysAdminWapServerOrganizationActionParams): Promise<{
|
||||
server: any;
|
||||
baseUrl: string;
|
||||
encodedOrganizationId: string;
|
||||
}> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!data.organizationId) {
|
||||
throw new Error("Organization id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.organizationId)) {
|
||||
throw new Error("Organization id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
return { server, baseUrl: this.getBotAdminApiUrl(server.ipv4), encodedOrganizationId: encodeURIComponent(data.organizationId) };
|
||||
}
|
||||
|
||||
private async postSysAdminBotAction(
|
||||
data: SysAdminWapServerOrganizationActionParams,
|
||||
action: "start" | "stop",
|
||||
): Promise<void> {
|
||||
const { baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const targetUrl = `${baseUrl}containers/${encodedOrganizationId}/${action}`;
|
||||
|
||||
try {
|
||||
const response = await axios.post(targetUrl, {}, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: BOT_ADMIN_ACTION_TIMEOUT_MS,
|
||||
});
|
||||
const result: CreateBotResult = response.data;
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
} catch (error) {
|
||||
throw this.createBotAdminActionError(error, targetUrl);
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteSysAdminRuntimeBot(
|
||||
baseUrl: string,
|
||||
encodedOrganizationId: string,
|
||||
allowMissingContainer = false,
|
||||
): Promise<{ botDeleted: boolean; botAlreadyMissing: boolean }> {
|
||||
const targetUrl = `${baseUrl}containers/${encodedOrganizationId}`;
|
||||
|
||||
try {
|
||||
const response = await axios.delete(targetUrl, { timeout: BOT_ADMIN_ACTION_TIMEOUT_MS });
|
||||
const result: CreateBotResult = response.data;
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
return { botDeleted: true, botAlreadyMissing: false };
|
||||
} catch (error) {
|
||||
if (allowMissingContainer && this.isBotAdminMissingContainerError(error)) {
|
||||
return { botDeleted: false, botAlreadyMissing: true };
|
||||
}
|
||||
|
||||
throw this.createBotAdminActionError(error, targetUrl);
|
||||
}
|
||||
}
|
||||
|
||||
private async waitForSysAdminBotStopped(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
const { baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const targetUrl = `${baseUrl}containers/${encodedOrganizationId}/status`;
|
||||
|
||||
for (let attempt = 0; attempt < BOT_ADMIN_RESTART_STATUS_RETRIES; attempt += 1) {
|
||||
try {
|
||||
const response = await axios.post(targetUrl, {}, { timeout: BOT_ADMIN_ACTION_TIMEOUT_MS });
|
||||
const status = String(response.data?.status || "").toLowerCase();
|
||||
|
||||
if (!status.includes("up")) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response?.status === 500) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw this.createBotAdminActionError(error, targetUrl);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, BOT_ADMIN_RESTART_STATUS_DELAY_MS));
|
||||
}
|
||||
|
||||
throw new Error("Bot did not stop before restart timeout; start was not attempted.");
|
||||
}
|
||||
|
||||
private extractOrganizationIdFromContainer(container: any): string | undefined {
|
||||
const names = Array.isArray(container?.Names) ? container.Names : [];
|
||||
|
||||
for (const rawName of names) {
|
||||
const name = String(rawName || "").replace(/^\//, "");
|
||||
const match = name.match(/^(.+)_bot_\d+$/);
|
||||
if (match && match[1]) {
|
||||
return match[1];
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private sanitizeContainer(container: any): SysAdminWapContainerDto {
|
||||
const names = Array.isArray(container?.Names) ? container.Names : [];
|
||||
const firstName = names.length > 0 ? String(names[0]).replace(/^\//, "") : undefined;
|
||||
|
||||
return {
|
||||
id: container?.Id,
|
||||
name: firstName,
|
||||
organizationId: this.extractOrganizationIdFromContainer(container),
|
||||
image: container?.Image,
|
||||
state: container?.State,
|
||||
status: container?.Status,
|
||||
ports: Array.isArray(container?.Ports) ? container.Ports : [],
|
||||
created: container?.Created,
|
||||
};
|
||||
}
|
||||
|
||||
private async getSysAdminRuntimeContainers(server: any): Promise<SysAdminWapContainerDto[]> {
|
||||
const containersUrl = this.getBotAdminApiUrl(server.ipv4) + "containers";
|
||||
|
||||
try {
|
||||
const response = await axios.get(containersUrl, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: BOT_ADMIN_ACTION_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
return Array.isArray(response.data)
|
||||
? response.data.map((container: any) => this.sanitizeContainer(container))
|
||||
: [];
|
||||
} catch (error) {
|
||||
throw this.createBotAdminContainersError(error, containersUrl);
|
||||
}
|
||||
}
|
||||
|
||||
public async getAvailableServer(): Promise<IWapServer> {
|
||||
@@ -713,6 +981,345 @@ class WapServerManager implements IWapServerManager {
|
||||
|
||||
return servers;
|
||||
}
|
||||
|
||||
public async sysAdminCreateWapServer(data: CreateWapServerParams): Promise<IWapServer> {
|
||||
if (!data.name || !String(data.name).trim()) {
|
||||
throw new Error("Name is required");
|
||||
}
|
||||
|
||||
if (!data.ipv4 || !String(data.ipv4).trim()) {
|
||||
throw new Error("IPv4 is required");
|
||||
}
|
||||
|
||||
if (!Number.isFinite(data.port) || data.port < 0) {
|
||||
throw new Error("Port must be a finite non-negative number");
|
||||
}
|
||||
|
||||
if (!Number.isFinite(data.maxBots) || data.maxBots < 0) {
|
||||
throw new Error("Max bots must be a finite non-negative number");
|
||||
}
|
||||
|
||||
return await this.servers.create({
|
||||
name: String(data.name).trim(),
|
||||
description: data.description ? String(data.description).trim() : "",
|
||||
ipv4: this.normalizeBotAdminApiUrl(data.ipv4),
|
||||
ipv6: data.ipv6 ? String(data.ipv6).trim() : "",
|
||||
countBots: 0,
|
||||
port: data.port,
|
||||
maxBots: data.maxBots,
|
||||
active: data.active === undefined ? true : Boolean(data.active),
|
||||
} as CreateWapServerParams & { countBots: number });
|
||||
}
|
||||
|
||||
public async sysAdminUpdateWapServer(data: UpdateWapServerParams): Promise<IWapServer> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.serverId)) {
|
||||
throw new Error("Server id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
if (data.name !== undefined) {
|
||||
server.name = String(data.name).trim();
|
||||
}
|
||||
|
||||
if (data.ipv4 !== undefined) {
|
||||
server.ipv4 = this.normalizeBotAdminApiUrl(data.ipv4);
|
||||
}
|
||||
|
||||
if (data.port !== undefined) {
|
||||
if (!Number.isFinite(data.port) || data.port < 0) {
|
||||
throw new Error("Port must be a finite non-negative number");
|
||||
}
|
||||
|
||||
server.port = data.port;
|
||||
}
|
||||
|
||||
if (data.maxBots !== undefined) {
|
||||
if (!Number.isFinite(data.maxBots) || data.maxBots < 0) {
|
||||
throw new Error("Max bots must be a finite non-negative number");
|
||||
}
|
||||
|
||||
server.maxBots = data.maxBots;
|
||||
}
|
||||
|
||||
if (data.active !== undefined) {
|
||||
server.active = Boolean(data.active);
|
||||
}
|
||||
|
||||
await server.save();
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
public async sysAdminAuditWapServer(data: SysAdminWapServerAuditParams): Promise<SysAdminWapServerAuditResult> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.serverId)) {
|
||||
throw new Error("Server id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
const assignedOrganizations = assignedCompanies.map((company: any) => ({
|
||||
id: String(company.id || company._id),
|
||||
name: company.name,
|
||||
}));
|
||||
const assignedIds = new Set(assignedOrganizations.map((organization) => organization.id));
|
||||
|
||||
const detectedBots = await this.getSysAdminRuntimeContainers(server);
|
||||
const runtimeOrganizationIds = new Set(
|
||||
detectedBots
|
||||
.map((container) => container.organizationId)
|
||||
.filter((organizationId): organizationId is string => Boolean(organizationId)),
|
||||
);
|
||||
|
||||
const validBots = detectedBots.filter(
|
||||
(container) => container.organizationId && assignedIds.has(container.organizationId),
|
||||
);
|
||||
const ghostBots = detectedBots.filter(
|
||||
(container) => !container.organizationId || !assignedIds.has(container.organizationId),
|
||||
);
|
||||
const missingBots = assignedOrganizations.filter(
|
||||
(organization) => !runtimeOrganizationIds.has(organization.id),
|
||||
);
|
||||
const expectedCountBots = assignedOrganizations.length;
|
||||
const storedCountBots = server.countBots ?? 0;
|
||||
const runtimeCountBots = detectedBots.length;
|
||||
|
||||
return {
|
||||
serverId: String(server.id || server._id),
|
||||
assignedOrganizations,
|
||||
detectedBots,
|
||||
validBots,
|
||||
ghostBots,
|
||||
missingBots,
|
||||
expectedCountBots,
|
||||
storedCountBots,
|
||||
runtimeCountBots,
|
||||
countMismatch: storedCountBots !== expectedCountBots || runtimeCountBots !== expectedCountBots,
|
||||
};
|
||||
}
|
||||
|
||||
public async sysAdminRecalculateWapServerCount(
|
||||
data: SysAdminWapServerRecalculateCountParams,
|
||||
): Promise<SysAdminWapServerRecalculateCountResult> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.serverId)) {
|
||||
throw new Error("Server id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
const before = server.countBots;
|
||||
const after = assignedCompanies.length;
|
||||
|
||||
server.countBots = after;
|
||||
await server.save();
|
||||
|
||||
return { serverId: String(server.id || server._id), before, after };
|
||||
}
|
||||
|
||||
public async sysAdminDeleteWapServer(data: SysAdminDeleteWapServerParams): Promise<SysAdminDeleteWapServerResult> {
|
||||
if (!data.serverId) {
|
||||
throw new Error("Server id is required");
|
||||
}
|
||||
|
||||
if (!MONGO_OBJECT_ID_REGEX.test(data.serverId)) {
|
||||
throw new Error("Server id must be a valid Mongo ObjectId");
|
||||
}
|
||||
|
||||
const server = await this.servers.serverList.findOne({ _id: data.serverId });
|
||||
|
||||
if (!server) {
|
||||
throw new Error("WAP server not found");
|
||||
}
|
||||
|
||||
const force = data.force === true;
|
||||
|
||||
if (!force && server.active) {
|
||||
throw new Error("WAP server must be inactive before deletion");
|
||||
}
|
||||
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
|
||||
if (!force && assignedCompanies.length > 0) {
|
||||
throw new Error(`WAP server cannot be deleted because it has ${assignedCompanies.length} associated bot(s) in DB`);
|
||||
}
|
||||
|
||||
let detectedBots: SysAdminWapContainerDto[] = [];
|
||||
let auditFailed = false;
|
||||
let auditMessage: string | undefined;
|
||||
|
||||
try {
|
||||
detectedBots = await this.getSysAdminRuntimeContainers(server);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error && error.message ? error.message : "unknown error";
|
||||
|
||||
if (!force) {
|
||||
throw new Error(`WAP server cannot be deleted because bot-admin could not be audited. Verify runtime bots manually before deleting. ${message}`);
|
||||
}
|
||||
|
||||
auditFailed = true;
|
||||
auditMessage = message;
|
||||
}
|
||||
|
||||
if (!force && detectedBots.length > 0) {
|
||||
throw new Error(`WAP server cannot be deleted because bot-admin detected ${detectedBots.length} runtime bot(s)`);
|
||||
}
|
||||
|
||||
let deletedRuntimeBots = 0;
|
||||
let skippedRuntimeBots = 0;
|
||||
|
||||
if (force) {
|
||||
const baseUrl = this.getBotAdminApiUrl(server.ipv4);
|
||||
|
||||
for (const bot of detectedBots) {
|
||||
if (!bot.organizationId) {
|
||||
skippedRuntimeBots += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.deleteSysAdminRuntimeBot(baseUrl, encodeURIComponent(bot.organizationId), true);
|
||||
|
||||
if (result.botDeleted) {
|
||||
deletedRuntimeBots += 1;
|
||||
}
|
||||
} catch (_error) {
|
||||
skippedRuntimeBots += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (const company of assignedCompanies) {
|
||||
const companyDocument = company as typeof company & { save: () => Promise<unknown> };
|
||||
|
||||
companyDocument.wapServerId = undefined;
|
||||
await companyDocument.save();
|
||||
}
|
||||
}
|
||||
|
||||
await this.servers.delete(data.serverId);
|
||||
|
||||
return {
|
||||
serverId: data.serverId,
|
||||
deleted: true,
|
||||
...(force
|
||||
? {
|
||||
force: true,
|
||||
detachedOrganizations: assignedCompanies.length,
|
||||
deletedRuntimeBots,
|
||||
skippedRuntimeBots,
|
||||
...(auditFailed ? { auditFailed: true, auditMessage } : {}),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
public async sysAdminStartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postSysAdminBotAction(data, "start");
|
||||
}
|
||||
|
||||
public async sysAdminStopBot(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postSysAdminBotAction(data, "stop");
|
||||
}
|
||||
|
||||
public async sysAdminRestartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postSysAdminBotAction(data, "stop");
|
||||
await this.waitForSysAdminBotStopped(data);
|
||||
|
||||
try {
|
||||
await this.postSysAdminBotAction(data, "start");
|
||||
} catch (error) {
|
||||
const message = error instanceof Error && error.message ? error.message : "unknown error";
|
||||
|
||||
throw new Error(`Bot restart stopped the bot, but start failed. The bot may be stopped. ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
public async sysAdminGetQr(data: SysAdminWapServerOrganizationActionParams): Promise<SysAdminWapServerQrResult> {
|
||||
const { baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const targetUrl = `${baseUrl}containers/${encodedOrganizationId}/qr`;
|
||||
|
||||
try {
|
||||
const response = await axios.get(targetUrl, {
|
||||
responseType: "arraybuffer",
|
||||
timeout: BOT_ADMIN_ACTION_TIMEOUT_MS,
|
||||
});
|
||||
const qr = Buffer.from(response.data, "binary").toString("base64");
|
||||
|
||||
return { serverId: data.serverId, organizationId: data.organizationId, qr };
|
||||
} catch (error) {
|
||||
throw this.createBotAdminActionError(error, targetUrl);
|
||||
}
|
||||
}
|
||||
|
||||
public async sysAdminDeleteBot(
|
||||
data: SysAdminWapServerOrganizationActionParams,
|
||||
): Promise<SysAdminWapServerDeleteBotResult> {
|
||||
const { server, baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const before = server.countBots ?? 0;
|
||||
|
||||
await this.deleteSysAdminRuntimeBot(baseUrl, encodedOrganizationId);
|
||||
|
||||
// Deleting the runtime bot intentionally keeps the DB assignment; detach is a separate sysadmin action.
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
const after = assignedCompanies.length;
|
||||
server.countBots = after;
|
||||
await server.save();
|
||||
|
||||
return { serverId: data.serverId, organizationId: data.organizationId, assignmentRemains: true, before, after };
|
||||
}
|
||||
|
||||
public async sysAdminDetachOrganizationServer(
|
||||
data: SysAdminWapServerOrganizationActionParams,
|
||||
): Promise<SysAdminWapServerDetachResult> {
|
||||
const { server, baseUrl, encodedOrganizationId } = await this.getSysAdminServerActionTarget(data);
|
||||
const company = await CompaniesManager.companies.findOne({ _id: data.organizationId });
|
||||
|
||||
if (!company) {
|
||||
throw new Error("Organization not found");
|
||||
}
|
||||
|
||||
if (String(company.wapServerId || "") !== data.serverId) {
|
||||
throw new Error("Organization is not assigned to this WAP server");
|
||||
}
|
||||
|
||||
const before = server.countBots ?? 0;
|
||||
const deleteResult = await this.deleteSysAdminRuntimeBot(baseUrl, encodedOrganizationId, true);
|
||||
|
||||
company.wapServerId = undefined;
|
||||
await company.save();
|
||||
|
||||
const assignedCompanies = await CompaniesManager.companies.find({ wapServerId: data.serverId });
|
||||
const after = assignedCompanies.length;
|
||||
server.countBots = after;
|
||||
await server.save();
|
||||
|
||||
return { serverId: data.serverId, organizationId: data.organizationId, ...deleteResult, before, after };
|
||||
}
|
||||
}
|
||||
|
||||
const WapServerList = new WapServerManager();
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
AppointmentAdminByDateView,
|
||||
CreateAppointmentParams,
|
||||
CreateImmediateAppointmentNotificationJobsParams,
|
||||
AppointmentNotificationPreviewParams,
|
||||
AppointmentNotificationPreviewResult,
|
||||
DeleteAppointmentParams,
|
||||
FindAppointmentsParams,
|
||||
FindAppointmentSchedulesParams,
|
||||
@@ -368,6 +370,27 @@ export class CreateImmediateAppointmentNotificationJobsController extends Contro
|
||||
}
|
||||
}
|
||||
|
||||
@Route("appointments/notification-preview")
|
||||
@Middlewares(authenticateMiddleware)
|
||||
export class AppointmentNotificationPreviewController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
public async getAppointmentNotificationPreview(
|
||||
@Body() requestBody: AppointmentNotificationPreviewParams
|
||||
): Promise<AppointmentNotificationPreviewResult | ApiValidationError> {
|
||||
try {
|
||||
const preview = await new AppointmentService().getAppointmentNotificationPreview(requestBody);
|
||||
this.setStatus(200);
|
||||
return preview;
|
||||
} 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 {
|
||||
|
||||
@@ -2,6 +2,8 @@ import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
|
||||
import AppointmentList from "../../Models/Appointments/Appointments";
|
||||
import {
|
||||
CreateImmediateAppointmentNotificationJobsParams,
|
||||
AppointmentNotificationPreviewParams,
|
||||
AppointmentNotificationPreviewResult,
|
||||
AppointmentAdminByClientView,
|
||||
AppointmentAdminByDateView,
|
||||
CreateAppointmentParams,
|
||||
@@ -167,6 +169,11 @@ export class AppointmentService {
|
||||
await AppointmentList.createImmediateNotificationJobs(data);
|
||||
}
|
||||
|
||||
public async getAppointmentNotificationPreview(data: AppointmentNotificationPreviewParams): Promise<AppointmentNotificationPreviewResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return AppointmentList.getAppointmentNotificationPreview(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,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
SysAdminPaginateCompaniesParams,
|
||||
SysAdminUpdateCompanyParams,
|
||||
SysAdminSetCompanyBannedParams,
|
||||
SysAdminCompanyInsightsParams,
|
||||
SysAdminCompanyInsightsResult,
|
||||
} from "../../../Models/Companies/Companies.Interface";
|
||||
import { ApiValidationError } from "../../../Models/Server.Error.model";
|
||||
import { ApiVoidResult } from "../../../Models/Api.VoidResult.type";
|
||||
@@ -66,4 +68,23 @@ export class SysAdminCompaniesController extends Controller {
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post("insights")
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminGetInsights(
|
||||
@Body() requestBody: SysAdminCompanyInsightsParams,
|
||||
): Promise<SysAdminCompanyInsightsResult | ApiValidationError> {
|
||||
try {
|
||||
const { payload, ...cleanRequestBody } = requestBody as any;
|
||||
const result = await new SA_CompaniesService().sysAdminGetInsights(cleanRequestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, errorOccurred.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
SysAdminPaginateCompaniesParams,
|
||||
SysAdminUpdateCompanyParams,
|
||||
SysAdminSetCompanyBannedParams,
|
||||
SysAdminCompanyInsightsParams,
|
||||
SysAdminCompanyInsightsResult,
|
||||
} from "../../../Models/Companies/Companies.Interface";
|
||||
import CompaniesList from "../../../Models/Companies/Companies";
|
||||
|
||||
@@ -22,4 +24,9 @@ export class SA_CompaniesService {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await CompaniesList.sysAdminSetBanned(data);
|
||||
}
|
||||
|
||||
public async sysAdminGetInsights(data: SysAdminCompanyInsightsParams): Promise<SysAdminCompanyInsightsResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await CompaniesList.sysAdminGetInsights(data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,82 @@
|
||||
import {
|
||||
PaginateWapServerResults,
|
||||
SysAdminCreateWapServerParams,
|
||||
SysAdminDeleteWapServerRequest,
|
||||
SysAdminDeleteWapServerResult,
|
||||
SysAdminAuditWapServerParams,
|
||||
SysAdminGetWapServerParams,
|
||||
SysAdminRecalculateWapServerCountParams,
|
||||
SysAdminWapServerDeleteBotResult,
|
||||
SysAdminWapServerDetachResult,
|
||||
SysAdminWapServerAuditResult,
|
||||
SysAdminWapServerOrganizationActionRequest,
|
||||
SysAdminWapServerQrResult,
|
||||
SysAdminWapServerRecalculateCountResult,
|
||||
SysAdminUpdateWapServerParams,
|
||||
IWapServer,
|
||||
} from "../../../Models/WapServer/WapServer.Interface";
|
||||
import { ApiValidationError } from "../../../Models/Server.Error.model";
|
||||
import { ApiVoidResult } from "../../../Models/Api.VoidResult.type";
|
||||
import axios from "axios";
|
||||
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
|
||||
import { SA_WapServerService } from "./SysAdminWapServer.Service";
|
||||
import { sysAdminAuthMiddleware } from "../../../middleware/sysadminAuth";
|
||||
|
||||
const stringifyErrorBody = (data: unknown): string => {
|
||||
if (data === undefined || data === null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof data === "string") {
|
||||
return data;
|
||||
}
|
||||
|
||||
const body = JSON.stringify(data);
|
||||
|
||||
return body.length > 1000 ? `${body.slice(0, 1000)}...` : body;
|
||||
};
|
||||
|
||||
const getErrorDesc = (error: unknown): string => {
|
||||
if (axios.isAxiosError(error)) {
|
||||
const responseData = error.response?.data as any;
|
||||
const responseMessage =
|
||||
responseData?.desc || responseData?.message || responseData?.error || stringifyErrorBody(responseData);
|
||||
const requestUrl = error.config?.url ? ` url ${error.config.url}` : "";
|
||||
const status = error.response?.status ? `status ${error.response.status}` : error.code || "no response";
|
||||
|
||||
return responseMessage || `Upstream request failed:${requestUrl} ${status}`.trim();
|
||||
}
|
||||
|
||||
if (error instanceof Error && error.message) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
const fallback = stringifyErrorBody(error);
|
||||
|
||||
return fallback || "Unknown error while auditing WAP server";
|
||||
};
|
||||
|
||||
@Route("sysadmin/wapserver/create")
|
||||
export class SysAdminWapServerCreateController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminCreateWapServer(
|
||||
@Body() requestBody: SysAdminCreateWapServerParams,
|
||||
): Promise<IWapServer | ApiValidationError> {
|
||||
try {
|
||||
const { payload, ...cleanRequestBody } = requestBody as any;
|
||||
const result = await new SA_WapServerService().sysAdminCreateWapServer(cleanRequestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("sysadmin/wapserver/get")
|
||||
export class SysAdminWapServerGetController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@@ -20,6 +90,69 @@ export class SysAdminWapServerGetController extends Controller {
|
||||
const result = await new SA_WapServerService().sysAdminGetWapServers(requestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("sysadmin/wapserver/update")
|
||||
export class SysAdminWapServerUpdateController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminUpdateWapServer(
|
||||
@Body() requestBody: SysAdminUpdateWapServerParams,
|
||||
): Promise<IWapServer | ApiValidationError> {
|
||||
try {
|
||||
const { payload, ...cleanRequestBody } = requestBody as any;
|
||||
const result = await new SA_WapServerService().sysAdminUpdateWapServer(cleanRequestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("sysadmin/wapserver/audit")
|
||||
export class SysAdminWapServerAuditController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminAuditWapServer(
|
||||
@Body() requestBody: SysAdminAuditWapServerParams,
|
||||
): Promise<SysAdminWapServerAuditResult | ApiValidationError> {
|
||||
try {
|
||||
const { payload, ...cleanRequestBody } = requestBody as any;
|
||||
const result = await new SA_WapServerService().sysAdminAuditWapServer(cleanRequestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("sysadmin/wapserver/recalculate-count")
|
||||
export class SysAdminWapServerRecalculateCountController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminRecalculateWapServerCount(
|
||||
@Body() requestBody: SysAdminRecalculateWapServerCountParams,
|
||||
): Promise<SysAdminWapServerRecalculateCountResult | ApiValidationError> {
|
||||
try {
|
||||
const { payload, ...cleanRequestBody } = requestBody as any;
|
||||
const result = await new SA_WapServerService().sysAdminRecalculateWapServerCount(cleanRequestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
const errorOccurred: Error = e as Error;
|
||||
this.setStatus(500);
|
||||
@@ -27,3 +160,137 @@ export class SysAdminWapServerGetController extends Controller {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("sysadmin/wapserver/delete")
|
||||
export class SysAdminWapServerDeleteController extends Controller {
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post()
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminDeleteWapServer(
|
||||
@Body() requestBody: SysAdminDeleteWapServerRequest,
|
||||
): Promise<SysAdminDeleteWapServerResult | ApiValidationError> {
|
||||
try {
|
||||
const { payload, ...cleanRequestBody } = requestBody as any;
|
||||
const result = await new SA_WapServerService().sysAdminDeleteWapServer(cleanRequestBody);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Route("sysadmin/wapserver/bot")
|
||||
export class SysAdminWapServerBotController extends Controller {
|
||||
private cleanRequestBody(requestBody: SysAdminWapServerOrganizationActionRequest) {
|
||||
const { payload, ...cleanRequestBody } = requestBody as any;
|
||||
|
||||
return cleanRequestBody;
|
||||
}
|
||||
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post("start")
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminStartBot(
|
||||
@Body() requestBody: SysAdminWapServerOrganizationActionRequest,
|
||||
): Promise<ApiVoidResult | ApiValidationError> {
|
||||
try {
|
||||
await new SA_WapServerService().sysAdminStartBot(this.cleanRequestBody(requestBody));
|
||||
this.setStatus(200);
|
||||
return { success: true, message: "ok" };
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post("stop")
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminStopBot(
|
||||
@Body() requestBody: SysAdminWapServerOrganizationActionRequest,
|
||||
): Promise<ApiVoidResult | ApiValidationError> {
|
||||
try {
|
||||
await new SA_WapServerService().sysAdminStopBot(this.cleanRequestBody(requestBody));
|
||||
this.setStatus(200);
|
||||
return { success: true, message: "ok" };
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post("restart")
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminRestartBot(
|
||||
@Body() requestBody: SysAdminWapServerOrganizationActionRequest,
|
||||
): Promise<ApiVoidResult | ApiValidationError> {
|
||||
try {
|
||||
await new SA_WapServerService().sysAdminRestartBot(this.cleanRequestBody(requestBody));
|
||||
this.setStatus(200);
|
||||
return { success: true, message: "ok" };
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post("qr")
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminGetQr(
|
||||
@Body() requestBody: SysAdminWapServerOrganizationActionRequest,
|
||||
): Promise<SysAdminWapServerQrResult | ApiValidationError> {
|
||||
try {
|
||||
const result = await new SA_WapServerService().sysAdminGetQr(this.cleanRequestBody(requestBody));
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post("delete")
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminDeleteBot(
|
||||
@Body() requestBody: SysAdminWapServerOrganizationActionRequest,
|
||||
): Promise<SysAdminWapServerDeleteBotResult | ApiValidationError> {
|
||||
try {
|
||||
const result = await new SA_WapServerService().sysAdminDeleteBot(this.cleanRequestBody(requestBody));
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Response<ApiValidationError>(500, "Ha ocurrido un error")
|
||||
@SuccessResponse(200, "Done")
|
||||
@Post("detach")
|
||||
@Middlewares(sysAdminAuthMiddleware)
|
||||
public async sysAdminDetachOrganizationServer(
|
||||
@Body() requestBody: SysAdminWapServerOrganizationActionRequest,
|
||||
): Promise<SysAdminWapServerDetachResult | ApiValidationError> {
|
||||
try {
|
||||
const result = await new SA_WapServerService().sysAdminDetachOrganizationServer(
|
||||
this.cleanRequestBody(requestBody),
|
||||
);
|
||||
this.setStatus(200);
|
||||
return result;
|
||||
} catch (e) {
|
||||
this.setStatus(500);
|
||||
return new ApiValidationError(500, getErrorDesc(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import { connect } from "mongoose";
|
||||
|
||||
import {
|
||||
CreateWapServerParams,
|
||||
PaginateWapServerParams,
|
||||
PaginateWapServerResults,
|
||||
SysAdminDeleteWapServerParams,
|
||||
SysAdminDeleteWapServerResult,
|
||||
SysAdminWapServerAuditParams,
|
||||
SysAdminWapServerAuditResult,
|
||||
SysAdminWapServerDeleteBotResult,
|
||||
SysAdminWapServerDetachResult,
|
||||
SysAdminWapServerOrganizationActionParams,
|
||||
SysAdminWapServerQrResult,
|
||||
SysAdminWapServerRecalculateCountParams,
|
||||
SysAdminWapServerRecalculateCountResult,
|
||||
UpdateWapServerParams,
|
||||
} from "../../../Models/WapServer/WapServer.Interface";
|
||||
import WapServerList from "../../../Models/WapServer/WapServer";
|
||||
|
||||
@@ -11,4 +23,65 @@ export class SA_WapServerService {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await WapServerList.sysAdminGetWapServers(data);
|
||||
}
|
||||
|
||||
public async sysAdminCreateWapServer(data: CreateWapServerParams) {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await WapServerList.sysAdminCreateWapServer(data);
|
||||
}
|
||||
|
||||
public async sysAdminUpdateWapServer(data: UpdateWapServerParams) {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await WapServerList.sysAdminUpdateWapServer(data);
|
||||
}
|
||||
|
||||
public async sysAdminAuditWapServer(data: SysAdminWapServerAuditParams): Promise<SysAdminWapServerAuditResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await WapServerList.sysAdminAuditWapServer(data);
|
||||
}
|
||||
|
||||
public async sysAdminRecalculateWapServerCount(
|
||||
data: SysAdminWapServerRecalculateCountParams,
|
||||
): Promise<SysAdminWapServerRecalculateCountResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await WapServerList.sysAdminRecalculateWapServerCount(data);
|
||||
}
|
||||
|
||||
public async sysAdminDeleteWapServer(data: SysAdminDeleteWapServerParams): Promise<SysAdminDeleteWapServerResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await WapServerList.sysAdminDeleteWapServer(data);
|
||||
}
|
||||
|
||||
public async sysAdminStartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
await WapServerList.sysAdminStartBot(data);
|
||||
}
|
||||
|
||||
public async sysAdminStopBot(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
await WapServerList.sysAdminStopBot(data);
|
||||
}
|
||||
|
||||
public async sysAdminRestartBot(data: SysAdminWapServerOrganizationActionParams): Promise<void> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
await WapServerList.sysAdminRestartBot(data);
|
||||
}
|
||||
|
||||
public async sysAdminGetQr(data: SysAdminWapServerOrganizationActionParams): Promise<SysAdminWapServerQrResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await WapServerList.sysAdminGetQr(data);
|
||||
}
|
||||
|
||||
public async sysAdminDeleteBot(
|
||||
data: SysAdminWapServerOrganizationActionParams,
|
||||
): Promise<SysAdminWapServerDeleteBotResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await WapServerList.sysAdminDeleteBot(data);
|
||||
}
|
||||
|
||||
public async sysAdminDetachOrganizationServer(
|
||||
data: SysAdminWapServerOrganizationActionParams,
|
||||
): Promise<SysAdminWapServerDetachResult> {
|
||||
await connect(`${process.env.DATABASE_CONNECTION}`);
|
||||
return await WapServerList.sysAdminDetachOrganizationServer(data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -174,6 +174,156 @@ export const fetchWapServers = async (filters: any) => {
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export type WapServer = {
|
||||
id?: string;
|
||||
_id?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
ipv4: string;
|
||||
ipv6?: string;
|
||||
countBots: number;
|
||||
maxBots: number;
|
||||
port: number;
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
export type UpdateWapServerPayload = {
|
||||
serverId: string;
|
||||
name?: string;
|
||||
ipv4?: string;
|
||||
port?: number;
|
||||
maxBots?: number;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type CreateWapServerPayload = {
|
||||
name: string;
|
||||
ipv4: string;
|
||||
port: number;
|
||||
maxBots: number;
|
||||
ipv6?: string;
|
||||
description?: string;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export const createWapServer = async (data: CreateWapServerPayload): Promise<WapServer> => {
|
||||
const res = await sysadminApi.post('/wap/create', data);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateWapServer = async (data: UpdateWapServerPayload): Promise<WapServer> => {
|
||||
const res = await sysadminApi.post('/wap/update', data);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export type WapAssignedOrganization = {
|
||||
id: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export type WapContainerDto = {
|
||||
id?: string;
|
||||
name?: string;
|
||||
organizationId?: string;
|
||||
image?: string;
|
||||
state?: string;
|
||||
status?: string;
|
||||
ports?: unknown[];
|
||||
created?: number;
|
||||
};
|
||||
|
||||
export type WapServerAuditResult = {
|
||||
serverId: string;
|
||||
assignedOrganizations: WapAssignedOrganization[];
|
||||
detectedBots: WapContainerDto[];
|
||||
validBots: WapContainerDto[];
|
||||
ghostBots: WapContainerDto[];
|
||||
missingBots: WapAssignedOrganization[];
|
||||
expectedCountBots: number;
|
||||
storedCountBots: number;
|
||||
runtimeCountBots: number;
|
||||
countMismatch: boolean;
|
||||
};
|
||||
|
||||
export type WapServerRecalculateCountResult = {
|
||||
serverId: string;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
export type WapServerDeleteResult = {
|
||||
serverId: string;
|
||||
deleted: true;
|
||||
force?: boolean;
|
||||
detachedOrganizations?: number;
|
||||
deletedRuntimeBots?: number;
|
||||
skippedRuntimeBots?: number;
|
||||
auditFailed?: boolean;
|
||||
auditMessage?: string;
|
||||
};
|
||||
|
||||
export type WapServerDeletePayload = {
|
||||
serverId: string;
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export type WapServerOrganizationActionPayload = {
|
||||
serverId: string;
|
||||
organizationId: string;
|
||||
};
|
||||
|
||||
export type WapServerQrResult = WapServerOrganizationActionPayload & {
|
||||
qr: string;
|
||||
};
|
||||
|
||||
export type WapServerDetachResult = WapServerOrganizationActionPayload & {
|
||||
botDeleted: boolean;
|
||||
botAlreadyMissing: boolean;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
export const auditWapServer = async (serverId: string): Promise<WapServerAuditResult> => {
|
||||
const res = await sysadminApi.post('/wap/audit', { serverId });
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const recalculateWapServerCount = async (serverId: string): Promise<WapServerRecalculateCountResult> => {
|
||||
const res = await sysadminApi.post('/wap/recalculate-count', { serverId });
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const deleteWapServer = async (data: WapServerDeletePayload): Promise<WapServerDeleteResult> => {
|
||||
const res = await sysadminApi.post('/wap/delete', data);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const startWapBot = async (data: WapServerOrganizationActionPayload): Promise<void> => {
|
||||
await sysadminApi.post('/wap/bot/start', data);
|
||||
};
|
||||
|
||||
export const stopWapBot = async (data: WapServerOrganizationActionPayload): Promise<void> => {
|
||||
await sysadminApi.post('/wap/bot/stop', data);
|
||||
};
|
||||
|
||||
export const restartWapBot = async (data: WapServerOrganizationActionPayload): Promise<void> => {
|
||||
await sysadminApi.post('/wap/bot/restart', data);
|
||||
};
|
||||
|
||||
export const getWapBotQr = async (data: WapServerOrganizationActionPayload): Promise<WapServerQrResult> => {
|
||||
const res = await sysadminApi.post('/wap/bot/qr', data);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const deleteWapBot = async (data: WapServerOrganizationActionPayload): Promise<void> => {
|
||||
await sysadminApi.post('/wap/bot/delete', data);
|
||||
};
|
||||
|
||||
export const detachWapOrganizationServer = async (data: WapServerOrganizationActionPayload): Promise<WapServerDetachResult> => {
|
||||
const res = await sysadminApi.post('/wap/bot/detach', data);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
// Companies API Calls
|
||||
export const fetchCompanies = async (filters: any) => {
|
||||
const res = await sysadminApi.post('/companies/paginate', filters);
|
||||
@@ -190,6 +340,76 @@ export const setCompanyBanned = async (id: string, banned: boolean) => {
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export type OrganizationInsights = {
|
||||
organization: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
categoryId: number;
|
||||
banned: boolean;
|
||||
published?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
};
|
||||
owner: {
|
||||
id: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
verificated?: boolean;
|
||||
phoneCountryCode?: string;
|
||||
phoneAreaCode?: string;
|
||||
phoneNumber?: string;
|
||||
} | null;
|
||||
collaborators: {
|
||||
id: string;
|
||||
userId?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
fullName?: string;
|
||||
email?: string;
|
||||
roles?: string[];
|
||||
removed?: boolean;
|
||||
active: boolean;
|
||||
avatar?: string;
|
||||
}[];
|
||||
subscription: {
|
||||
id: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
isActive: boolean;
|
||||
autoRenew: boolean;
|
||||
mpStatus?: string;
|
||||
pendingPaymentType?: 'extension' | 'upgrade';
|
||||
plan: {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
price: number;
|
||||
limitOrganizations: number;
|
||||
limitEmployees: number;
|
||||
limitServices: number;
|
||||
limitAppointments: number;
|
||||
limitClients: number;
|
||||
} | null;
|
||||
} | null;
|
||||
stats: {
|
||||
employeesCount: number;
|
||||
activeEmployeesCount: number;
|
||||
servicesCount: number;
|
||||
activeServicesCount: number;
|
||||
clientsCount: number;
|
||||
activeClientsCount: number;
|
||||
reservationsLast30Days: number;
|
||||
};
|
||||
};
|
||||
|
||||
export const fetchOrganizationInsights = async (companyId: string): Promise<OrganizationInsights> => {
|
||||
const res = await sysadminApi.post('/companies/insights', { companyId });
|
||||
return res.data;
|
||||
};
|
||||
|
||||
// Services API Calls
|
||||
export const fetchServices = async (filters: any) => {
|
||||
const res = await sysadminApi.post('/services/paginate', filters);
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { AlertCircle, CalendarDays, CheckCircle2, Users, X } from 'lucide-react';
|
||||
import { fetchOrganizationInsights } from '../../api/sysadmin';
|
||||
import type { OrganizationInsights } from '../../api/sysadmin';
|
||||
|
||||
interface OrganizationInsightsModalProps {
|
||||
company: any;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const formatDate = (value?: string) => {
|
||||
if (!value) return '-';
|
||||
return new Intl.DateTimeFormat('es-AR', { dateStyle: 'medium' }).format(new Date(value));
|
||||
};
|
||||
|
||||
const fullName = (owner: OrganizationInsights['owner']) => {
|
||||
if (!owner) return '-';
|
||||
return [owner.firstName, owner.lastName].filter(Boolean).join(' ') || owner.email || '-';
|
||||
};
|
||||
|
||||
const phone = (owner: OrganizationInsights['owner']) => {
|
||||
if (!owner) return '-';
|
||||
return [owner.phoneCountryCode, owner.phoneAreaCode, owner.phoneNumber].filter(Boolean).join(' ') || '-';
|
||||
};
|
||||
|
||||
const collaboratorName = (collaborator: OrganizationInsights['collaborators'][number]) => {
|
||||
return collaborator.fullName || [collaborator.firstName, collaborator.lastName].filter(Boolean).join(' ') || collaborator.email || collaborator.userId || '-';
|
||||
};
|
||||
|
||||
const StatCard = ({ label, value }: { label: string; value: number }) => (
|
||||
<div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid var(--glass-border)', borderRadius: '12px', padding: '1rem' }}>
|
||||
<div style={{ color: 'var(--text-muted)', fontSize: '0.82rem', marginBottom: '0.35rem' }}>{label}</div>
|
||||
<div style={{ color: 'var(--text-main)', fontSize: '1.6rem', fontWeight: 700 }}>{value}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const OrganizationInsightsModal: React.FC<OrganizationInsightsModalProps> = ({ company, onClose }) => {
|
||||
const [insights, setInsights] = useState<OrganizationInsights | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const loadInsights = async () => {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const result = await fetchOrganizationInsights(company.id || company._id);
|
||||
setInsights(result);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setError('No se pudo cargar el detalle de la organización.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadInsights();
|
||||
}, [company]);
|
||||
|
||||
return (
|
||||
<div className="modal-overlay" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100 }}>
|
||||
<motion.div
|
||||
initial={{ scale: 0.95, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
className="glass-panel"
|
||||
style={{ width: '92%', maxWidth: '900px', padding: '2rem', position: 'relative', display: 'flex', flexDirection: 'column', maxHeight: '85vh', overflow: 'auto' }}
|
||||
>
|
||||
<button onClick={onClose} style={{ position: 'absolute', top: '1rem', right: '1rem', background: 'transparent', color: 'var(--text-muted)' }}>
|
||||
<X size={24} />
|
||||
</button>
|
||||
|
||||
<h2 style={{ fontSize: '1.5rem', marginBottom: '0.35rem', fontWeight: 'bold' }}>Detalle de {company.name}</h2>
|
||||
<p style={{ color: 'var(--text-muted)', marginBottom: '1.5rem' }}>Vista de solo lectura para SysAdmin.</p>
|
||||
|
||||
{loading ? (
|
||||
<div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>Cargando detalle...</div>
|
||||
) : error ? (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', color: 'var(--danger)', padding: '1rem', border: '1px solid rgba(255,0,0,0.25)', borderRadius: '12px' }}>
|
||||
<AlertCircle size={18} /> {error}
|
||||
</div>
|
||||
) : !insights ? (
|
||||
<div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No hay información disponible.</div>
|
||||
) : (
|
||||
<div style={{ display: 'grid', gap: '1rem' }}>
|
||||
<section style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '1rem' }}>
|
||||
<StatCard label="Colaboradores" value={insights.stats.employeesCount} />
|
||||
<StatCard label="Colaboradores activos" value={insights.stats.activeEmployeesCount} />
|
||||
<StatCard label="Servicios" value={insights.stats.servicesCount} />
|
||||
<StatCard label="Servicios activos" value={insights.stats.activeServicesCount} />
|
||||
<StatCard label="Clientes" value={insights.stats.clientsCount} />
|
||||
<StatCard label="Clientes activos" value={insights.stats.activeClientsCount} />
|
||||
<StatCard label="Reservas últimos 30 días" value={insights.stats.reservationsLast30Days} />
|
||||
</section>
|
||||
|
||||
<section style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '1rem' }}>
|
||||
<div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid var(--glass-border)', borderRadius: '12px', padding: '1rem' }}>
|
||||
<h3 style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '1rem', marginBottom: '1rem' }}><CheckCircle2 size={18} /> Organización</h3>
|
||||
<p><strong>Nombre:</strong> {insights.organization.name}</p>
|
||||
<p><strong>Slug:</strong> {insights.organization.slug || '-'}</p>
|
||||
<p><strong>Estado:</strong> {insights.organization.banned ? 'Baneada' : 'Activa'}</p>
|
||||
<p><strong>Publicación:</strong> {insights.organization.published || '-'}</p>
|
||||
<p><strong>Onboarding:</strong> {insights.organization.onboardingCompleted ? 'Completo' : `Paso ${insights.organization.onboardingStep || 0}`}</p>
|
||||
</div>
|
||||
|
||||
<div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid var(--glass-border)', borderRadius: '12px', padding: '1rem' }}>
|
||||
<h3 style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '1rem', marginBottom: '1rem' }}><Users size={18} /> Dueño</h3>
|
||||
<p><strong>Nombre:</strong> {fullName(insights.owner)}</p>
|
||||
<p><strong>Email:</strong> {insights.owner?.email || '-'}</p>
|
||||
<p><strong>Teléfono:</strong> {phone(insights.owner)}</p>
|
||||
<p><strong>Verificado:</strong> {insights.owner?.verificated ? 'Sí' : 'No'}</p>
|
||||
</div>
|
||||
|
||||
<div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid var(--glass-border)', borderRadius: '12px', padding: '1rem' }}>
|
||||
<h3 style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '1rem', marginBottom: '1rem' }}><CalendarDays size={18} /> Plan</h3>
|
||||
{insights.subscription ? (
|
||||
<>
|
||||
<p><strong>Plan:</strong> {insights.subscription.plan?.name || 'Sin plan asociado'}</p>
|
||||
<p><strong>Código:</strong> {insights.subscription.plan?.code || '-'}</p>
|
||||
<p><strong>Estado:</strong> {insights.subscription.mpStatus || (insights.subscription.isActive ? 'active' : 'inactive')}</p>
|
||||
<p><strong>Inicio:</strong> {formatDate(insights.subscription.startDate)}</p>
|
||||
<p><strong>Fin:</strong> {formatDate(insights.subscription.endDate)}</p>
|
||||
</>
|
||||
) : (
|
||||
<p style={{ color: 'var(--text-muted)' }}>No se encontró suscripción.</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid var(--glass-border)', borderRadius: '12px', padding: '1rem' }}>
|
||||
<h3 style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '1rem', marginBottom: '1rem' }}><Users size={18} /> Colaboradores</h3>
|
||||
{insights.collaborators.length === 0 ? (
|
||||
<p style={{ color: 'var(--text-muted)' }}>No hay colaboradores asociados.</p>
|
||||
) : (
|
||||
<div style={{ display: 'grid', gap: '0.75rem' }}>
|
||||
{insights.collaborators.map((collaborator) => (
|
||||
<div key={collaborator.id} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: '0.75rem', alignItems: 'center', padding: '0.75rem', border: '1px solid var(--glass-border)', borderRadius: '10px' }}>
|
||||
<div style={{ width: '36px', height: '36px', borderRadius: '999px', overflow: 'hidden', background: 'rgba(255,255,255,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-muted)', fontWeight: 700 }}>
|
||||
{collaborator.avatar ? <img src={collaborator.avatar} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : collaboratorName(collaborator).charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ color: 'var(--text-main)', fontWeight: 600 }}>{collaboratorName(collaborator)}</div>
|
||||
<div style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>{collaborator.email || 'Sin email disponible'}</div>
|
||||
<div style={{ color: 'var(--text-muted)', fontSize: '0.78rem' }}>Roles: {collaborator.roles?.join(', ') || '-'}</div>
|
||||
</div>
|
||||
<span style={{ color: collaborator.active ? 'var(--success)' : 'var(--text-muted)', fontSize: '0.82rem', fontWeight: 700 }}>
|
||||
{collaborator.active ? 'Activo' : 'Removido'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -160,3 +160,36 @@ button {
|
||||
.animate-fade-in {
|
||||
animation: fadeIn 0.4s ease-out forwards;
|
||||
}
|
||||
|
||||
.sticky-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
background: rgba(10, 10, 15, 0.95);
|
||||
backdrop-filter: blur(10px);
|
||||
border-bottom: 1px solid var(--glass-border);
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.sortable-header:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.table-row-hover:hover {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.companies-page-container {
|
||||
height: auto !important;
|
||||
overflow: visible !important;
|
||||
}
|
||||
|
||||
.filters-bar form > div {
|
||||
flex: 1 1 100% !important;
|
||||
}
|
||||
|
||||
.table-scroll-container {
|
||||
overflow-x: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Search, Edit2, ShieldAlert, ShieldCheck, ChevronUp, ChevronDown, RotateCcw, Box } from 'lucide-react';
|
||||
import { Search, Edit2, ShieldAlert, ShieldCheck, ChevronUp, ChevronDown, RotateCcw, Box, Eye } from 'lucide-react';
|
||||
import { fetchCompanies, setCompanyBanned } from '../api/sysadmin';
|
||||
import { EditCompanyModal } from '../components/ui/EditCompanyModal';
|
||||
import { CompanyServicesModal } from '../components/ui/CompanyServicesModal';
|
||||
import { OrganizationInsightsModal } from '../components/ui/OrganizationInsightsModal';
|
||||
|
||||
export const CompaniesPage = () => {
|
||||
const [companies, setCompanies] = useState<any[]>([]);
|
||||
@@ -22,6 +23,7 @@ export const CompaniesPage = () => {
|
||||
// Modals state
|
||||
const [editingCompany, setEditingCompany] = useState<any>(null);
|
||||
const [servicesCompany, setServicesCompany] = useState<any>(null);
|
||||
const [insightsCompany, setInsightsCompany] = useState<any>(null);
|
||||
|
||||
const loadCompanies = async () => {
|
||||
setLoading(true);
|
||||
@@ -176,6 +178,7 @@ export const CompaniesPage = () => {
|
||||
</td>
|
||||
<td style={{ padding: '1rem', textAlign: 'right' }}>
|
||||
<div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
|
||||
<button className="icon-btn" title="Ver detalle" onClick={() => setInsightsCompany(c)}><Eye size={18} /></button>
|
||||
<button className="icon-btn" title="Ver Servicios" onClick={() => setServicesCompany(c)}><Box size={18} /></button>
|
||||
<button className="icon-btn" title="Editar Detalles" onClick={() => setEditingCompany(c)}><Edit2 size={18} /></button>
|
||||
</div>
|
||||
@@ -197,68 +200,10 @@ export const CompaniesPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style dangerouslySetInnerHTML={{__html: `
|
||||
.sticky-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
background: rgba(10, 10, 15, 0.95);
|
||||
backdrop-filter: blur(10px);
|
||||
border-bottom: 1px solid var(--glass-border);
|
||||
transition: background 0.2s;
|
||||
}
|
||||
.sortable-header:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
.table-row-hover:hover {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
.icon-btn {
|
||||
background: rgba(255,255,255,0.05);
|
||||
color: var(--text-muted);
|
||||
padding: 8px;
|
||||
border-radius: 8px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.icon-btn:hover {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
.icon-btn.danger:hover {
|
||||
background: var(--danger);
|
||||
}
|
||||
.btn-secondary {
|
||||
background: rgba(255,255,255,0.05);
|
||||
color: var(--text-main);
|
||||
border: 1px solid var(--glass-border);
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 8px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
background: rgba(255,255,255,0.1);
|
||||
}
|
||||
.btn-secondary:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.companies-page-container {
|
||||
height: auto !important;
|
||||
overflow: visible !important;
|
||||
}
|
||||
.filters-bar form > div {
|
||||
flex: 1 1 100% !important;
|
||||
}
|
||||
.table-scroll-container {
|
||||
overflow-x: auto;
|
||||
}
|
||||
}
|
||||
`}} />
|
||||
|
||||
{/* Modals */}
|
||||
{editingCompany && <EditCompanyModal company={editingCompany} onClose={() => setEditingCompany(null)} onSaved={loadCompanies} />}
|
||||
{servicesCompany && <CompanyServicesModal company={servicesCompany} onClose={() => setServicesCompany(null)} />}
|
||||
{insightsCompany && <OrganizationInsightsModal company={insightsCompany} onClose={() => setInsightsCompany(null)} />}
|
||||
</motion.div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,13 +1,39 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Search, RotateCcw, CheckCircle, XCircle, Server, ServerOff } from 'lucide-react';
|
||||
import { fetchWapServers } from '../api/sysadmin';
|
||||
import { Search, RotateCcw, CheckCircle, XCircle, Server, ServerOff, ClipboardList, Calculator, X, MoreVertical, Play, Pause, Power, Trash2, Unlink, QrCode, RotateCw, Edit3, Plus } from 'lucide-react';
|
||||
import { auditWapServer, createWapServer, deleteWapBot, deleteWapServer, detachWapOrganizationServer, fetchWapServers, getWapBotQr, recalculateWapServerCount, restartWapBot, startWapBot, stopWapBot, updateWapServer, type WapContainerDto, type WapServerAuditResult, type WapServerDeleteResult, type WapServerQrResult, type WapServerRecalculateCountResult } from '../api/sysadmin';
|
||||
|
||||
const getErrorMessage = (error: unknown, fallback: string): string => {
|
||||
const responseData = (error as any)?.response?.data;
|
||||
|
||||
if (typeof responseData === 'string') {
|
||||
return responseData;
|
||||
}
|
||||
|
||||
const responseError = responseData?.error;
|
||||
|
||||
return responseData?.desc || responseData?.message || responseError?.desc || responseError?.message || responseError || (error as Error)?.message || fallback;
|
||||
};
|
||||
|
||||
export const WapServersPage = () => {
|
||||
const [servers, setServers] = useState<any[]>([]);
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [auditByServer, setAuditByServer] = useState<Record<string, WapServerAuditResult>>({});
|
||||
const [selectedAuditServerId, setSelectedAuditServerId] = useState<string | null>(null);
|
||||
const [auditTab, setAuditTab] = useState<'assigned' | 'ghosts' | 'missing'>('assigned');
|
||||
const [recalculateResult, setRecalculateResult] = useState<WapServerRecalculateCountResult | null>(null);
|
||||
const [qrResult, setQrResult] = useState<WapServerQrResult | null>(null);
|
||||
const [actionMessage, setActionMessage] = useState<string | null>(null);
|
||||
const [actionServerId, setActionServerId] = useState<string | null>(null);
|
||||
const [openActionsServerId, setOpenActionsServerId] = useState<string | null>(null);
|
||||
const [openAuditActionKey, setOpenAuditActionKey] = useState<string | null>(null);
|
||||
const [editingServer, setEditingServer] = useState<any | null>(null);
|
||||
const [deleteServerTarget, setDeleteServerTarget] = useState<any | null>(null);
|
||||
const [forceDeleteServer, setForceDeleteServer] = useState(false);
|
||||
const [serverFormMode, setServerFormMode] = useState<'create' | 'edit'>('edit');
|
||||
const [editForm, setEditForm] = useState({ name: '', ipv4: '', port: '', maxBots: '', active: true });
|
||||
|
||||
// Filters
|
||||
const [filters, setFilters] = useState({
|
||||
@@ -42,6 +68,18 @@ export const WapServersPage = () => {
|
||||
loadServers();
|
||||
}, [page, filters.active]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!openActionsServerId && !openAuditActionKey) return;
|
||||
|
||||
const closeActionsMenu = () => {
|
||||
setOpenActionsServerId(null);
|
||||
setOpenAuditActionKey(null);
|
||||
};
|
||||
document.addEventListener('click', closeActionsMenu);
|
||||
|
||||
return () => document.removeEventListener('click', closeActionsMenu);
|
||||
}, [openActionsServerId, openAuditActionKey]);
|
||||
|
||||
const handleSearch = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setPage(1);
|
||||
@@ -59,16 +97,225 @@ export const WapServersPage = () => {
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const getServerId = (server: any) => server.id || server._id;
|
||||
|
||||
const runRowAction = (action: () => void) => {
|
||||
setOpenActionsServerId(null);
|
||||
setOpenAuditActionKey(null);
|
||||
action();
|
||||
};
|
||||
|
||||
const openEditServer = (server: any) => {
|
||||
setServerFormMode('edit');
|
||||
setEditingServer(server);
|
||||
setEditForm({
|
||||
name: server.name || '',
|
||||
ipv4: server.ipv4 || '',
|
||||
port: server.port === undefined || server.port === null ? '' : String(server.port),
|
||||
maxBots: server.maxBots === undefined || server.maxBots === null ? '' : String(server.maxBots),
|
||||
active: Boolean(server.active),
|
||||
});
|
||||
};
|
||||
|
||||
const openCreateServer = () => {
|
||||
setServerFormMode('create');
|
||||
setEditingServer({});
|
||||
setEditForm({ name: '', ipv4: '', port: '', maxBots: '', active: true });
|
||||
};
|
||||
|
||||
const handleSaveServer = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!editingServer) return;
|
||||
|
||||
const serverId = serverFormMode === 'edit' ? getServerId(editingServer) : 'create';
|
||||
const port = Number(editForm.port);
|
||||
const maxBots = Number(editForm.maxBots);
|
||||
|
||||
if (!Number.isFinite(port) || port < 0 || !Number.isFinite(maxBots) || maxBots < 0) {
|
||||
alert('Puerto y cantidad máxima de bots deben ser números no negativos.');
|
||||
return;
|
||||
}
|
||||
|
||||
setActionServerId(serverId);
|
||||
try {
|
||||
if (serverFormMode === 'create') {
|
||||
await createWapServer({
|
||||
name: editForm.name,
|
||||
ipv4: editForm.ipv4,
|
||||
port,
|
||||
maxBots,
|
||||
active: editForm.active,
|
||||
});
|
||||
setActionMessage('Servidor WAP creado.');
|
||||
} else {
|
||||
await updateWapServer({
|
||||
serverId,
|
||||
name: editForm.name,
|
||||
ipv4: editForm.ipv4,
|
||||
port,
|
||||
maxBots,
|
||||
active: editForm.active,
|
||||
});
|
||||
setActionMessage('Servidor WAP actualizado.');
|
||||
}
|
||||
setEditingServer(null);
|
||||
await loadServers();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(getErrorMessage(e, 'Error actualizando servidor WAP'));
|
||||
}
|
||||
setActionServerId(null);
|
||||
};
|
||||
|
||||
const refreshSelectedAudit = async (serverId: string) => {
|
||||
const audit = await auditWapServer(serverId);
|
||||
setAuditByServer(prev => ({ ...prev, [serverId]: audit }));
|
||||
};
|
||||
|
||||
const handleAudit = async (serverId: string) => {
|
||||
setActionServerId(serverId);
|
||||
try {
|
||||
const audit = await auditWapServer(serverId);
|
||||
setAuditByServer(prev => ({ ...prev, [serverId]: audit }));
|
||||
setAuditTab('assigned');
|
||||
setSelectedAuditServerId(serverId);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(getErrorMessage(e, 'Error auditando servidor WAP'));
|
||||
}
|
||||
setActionServerId(null);
|
||||
};
|
||||
|
||||
const handleRecalculateCount = async (serverId: string) => {
|
||||
setActionServerId(serverId);
|
||||
try {
|
||||
const result = await recalculateWapServerCount(serverId);
|
||||
setRecalculateResult(result);
|
||||
setSelectedAuditServerId(null);
|
||||
await loadServers();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(getErrorMessage(e, 'Error recalculando contador WAP'));
|
||||
}
|
||||
setActionServerId(null);
|
||||
};
|
||||
|
||||
const handleDeleteServer = async (server: any) => {
|
||||
setForceDeleteServer(false);
|
||||
setDeleteServerTarget(server);
|
||||
};
|
||||
|
||||
const confirmDeleteServer = async () => {
|
||||
if (!deleteServerTarget) return;
|
||||
|
||||
const server = deleteServerTarget;
|
||||
const serverId = getServerId(server);
|
||||
const serverLabel = server.name || serverId;
|
||||
|
||||
setActionServerId(serverId);
|
||||
try {
|
||||
const result: WapServerDeleteResult = await deleteWapServer({ serverId, force: forceDeleteServer || undefined });
|
||||
const forceSummary = result.force
|
||||
? ` Modo forzado: organizaciones desasociadas ${result.detachedOrganizations ?? 0}, bots runtime eliminados ${result.deletedRuntimeBots ?? 0}, bots omitidos ${result.skippedRuntimeBots ?? 0}${result.auditFailed ? `. Auditoría no disponible: ${result.auditMessage || 'sin detalle'}` : ''}.`
|
||||
: '';
|
||||
|
||||
setActionMessage(`Servidor WAP eliminado: ${serverLabel}.${forceSummary}`);
|
||||
setSelectedAuditServerId(null);
|
||||
setDeleteServerTarget(null);
|
||||
setForceDeleteServer(false);
|
||||
await loadServers();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(getErrorMessage(e, 'Error eliminando servidor WAP'));
|
||||
}
|
||||
setActionServerId(null);
|
||||
};
|
||||
|
||||
const handleBotAction = async (
|
||||
serverId: string,
|
||||
organizationId: string,
|
||||
action: 'start' | 'pause' | 'restart' | 'qr' | 'poweroff' | 'delete' | 'detach'
|
||||
) => {
|
||||
const labels = {
|
||||
start: 'iniciar el bot',
|
||||
pause: 'pausar el bot',
|
||||
restart: 'reiniciar el bot',
|
||||
qr: 'obtener QR',
|
||||
poweroff: 'apagar el bot',
|
||||
delete: 'eliminar el bot',
|
||||
detach: 'desasociar el servidor'
|
||||
};
|
||||
const destructive = action === 'poweroff' || action === 'delete' || action === 'detach';
|
||||
|
||||
if (destructive && !window.confirm(`Confirmá ${labels[action]} para la organización ${organizationId}.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setActionServerId(serverId);
|
||||
try {
|
||||
const payload = { serverId, organizationId };
|
||||
|
||||
if (action === 'start') await startWapBot(payload);
|
||||
if (action === 'pause' || action === 'poweroff') await stopWapBot(payload);
|
||||
if (action === 'restart') await restartWapBot(payload);
|
||||
if (action === 'qr') setQrResult(await getWapBotQr(payload));
|
||||
if (action === 'delete') await deleteWapBot(payload);
|
||||
if (action === 'detach') {
|
||||
const result = await detachWapOrganizationServer(payload);
|
||||
const botMessage = result.botAlreadyMissing ? 'El bot ya no existía en el servidor.' : 'Bot eliminado del servidor.';
|
||||
setActionMessage(`Servidor desasociado. ${botMessage} Contador: ${result.before} -> ${result.after}.`);
|
||||
await loadServers();
|
||||
}
|
||||
|
||||
if (action !== 'qr' && action !== 'detach') {
|
||||
setActionMessage(`Acción completada: ${labels[action]}.`);
|
||||
}
|
||||
|
||||
await refreshSelectedAudit(serverId);
|
||||
if (action === 'delete') await loadServers();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(getErrorMessage(e, `Error al ${labels[action]}`));
|
||||
}
|
||||
setActionServerId(null);
|
||||
};
|
||||
|
||||
const renderAuditActionsMenu = (key: string, serverId: string, organizationId: string, includeBotActions: boolean, includeDetach: boolean) => (
|
||||
<div className="actions-menu-wrapper audit-actions-wrapper" onClick={(e) => e.stopPropagation()}>
|
||||
<button className="icon-btn" title="Acciones" aria-label={`Acciones para organización ${organizationId}`} aria-haspopup="menu" aria-expanded={openAuditActionKey === key} disabled={actionServerId === serverId} onClick={() => setOpenAuditActionKey(openAuditActionKey === key ? null : key)}>
|
||||
<MoreVertical size={16} />
|
||||
</button>
|
||||
{openAuditActionKey === key && (
|
||||
<div className="actions-menu audit-row-menu" role="menu">
|
||||
{includeBotActions && <button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => handleBotAction(serverId, organizationId, 'start'))}><Play size={16} /> Reanudar bot</button>}
|
||||
{includeBotActions && <button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => handleBotAction(serverId, organizationId, 'pause'))}><Pause size={16} /> Pausar</button>}
|
||||
{includeBotActions && <button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => handleBotAction(serverId, organizationId, 'restart'))}><RotateCw size={16} /> Reiniciar</button>}
|
||||
{includeBotActions && <button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => handleBotAction(serverId, organizationId, 'qr'))}><QrCode size={16} /> Obtener QR</button>}
|
||||
{includeBotActions && <button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => handleBotAction(serverId, organizationId, 'poweroff'))}><Power size={16} /> Apagar</button>}
|
||||
{includeBotActions && <button type="button" className="actions-menu-item danger" role="menuitem" onClick={() => runRowAction(() => handleBotAction(serverId, organizationId, 'delete'))}><Trash2 size={16} /> Eliminar bot</button>}
|
||||
{includeDetach && <button type="button" className="actions-menu-item danger" role="menuitem" onClick={() => runRowAction(() => handleBotAction(serverId, organizationId, 'detach'))}><Unlink size={16} /> Desasociar servidor</button>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (filters.name === '' && filters.description === '' && filters.active === 'all' && filters.countBotsFrom === '' && filters.countBotsTo === '') {
|
||||
loadServers();
|
||||
}
|
||||
}, [filters]);
|
||||
|
||||
const selectedAudit = selectedAuditServerId ? auditByServer[selectedAuditServerId] : null;
|
||||
const selectedAuditServer = selectedAuditServerId ? servers.find(s => getServerId(s) === selectedAuditServerId) : null;
|
||||
const recalculateServer = recalculateResult ? servers.find(s => getServerId(s) === recalculateResult.serverId) : null;
|
||||
|
||||
return (
|
||||
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="animate-fade-in users-page-container" style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem', flexShrink: 0 }}>
|
||||
<h1 style={{ fontSize: '2rem', fontWeight: '700' }}>Servidores WAP</h1>
|
||||
<button type="button" className="btn-primary" onClick={openCreateServer} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<Plus size={18} /> Nuevo servidor
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters Bar */}
|
||||
@@ -147,16 +394,22 @@ export const WapServersPage = () => {
|
||||
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Dirección IP</th>
|
||||
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'center' }}>Capacidad</th>
|
||||
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'center' }}>Estado</th>
|
||||
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'center' }}>Diagnóstico</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr><td colSpan={4} style={{ padding: '2rem', textAlign: 'center' }}>Cargando servidores...</td></tr>
|
||||
<tr><td colSpan={5} style={{ padding: '2rem', textAlign: 'center' }}>Cargando servidores...</td></tr>
|
||||
) : servers.length === 0 ? (
|
||||
<tr><td colSpan={4} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No se encontraron servidores WAP</td></tr>
|
||||
<tr><td colSpan={5} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No se encontraron servidores WAP</td></tr>
|
||||
) : (
|
||||
servers.map(s => (
|
||||
<tr key={s._id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)', transition: 'background 0.2s' }} className="table-row-hover">
|
||||
servers.map(s => {
|
||||
const serverId = getServerId(s);
|
||||
const isRunningAction = actionServerId === serverId;
|
||||
|
||||
return (
|
||||
<React.Fragment key={serverId}>
|
||||
<tr style={{ borderBottom: '1px solid rgba(255,255,255,0.05)', transition: 'background 0.2s' }} className="table-row-hover">
|
||||
<td style={{ padding: '1rem' }}>
|
||||
<div style={{ fontWeight: '600', color: 'var(--text-main)', display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
{s.active ? <Server size={16} color="var(--primary)" /> : <ServerOff size={16} color="var(--text-muted)" />}
|
||||
@@ -179,8 +432,40 @@ export const WapServersPage = () => {
|
||||
{s.active ? 'Activo' : 'Inactivo'}
|
||||
</div>
|
||||
</td>
|
||||
<td style={{ padding: '1rem' }}>
|
||||
<div className="actions-menu-wrapper" onClick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
className="icon-btn"
|
||||
title="Acciones"
|
||||
aria-label={`Acciones para ${s.name || serverId}`}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={openActionsServerId === serverId}
|
||||
disabled={isRunningAction}
|
||||
onClick={() => setOpenActionsServerId(openActionsServerId === serverId ? null : serverId)}
|
||||
>
|
||||
<MoreVertical size={18} />
|
||||
</button>
|
||||
{openActionsServerId === serverId && (
|
||||
<div className="actions-menu" role="menu">
|
||||
<button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => openEditServer(s))}>
|
||||
<Edit3 size={16} /> Editar
|
||||
</button>
|
||||
<button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => handleAudit(serverId))}>
|
||||
<ClipboardList size={16} /> Auditar
|
||||
</button>
|
||||
<button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => handleRecalculateCount(serverId))}>
|
||||
<Calculator size={16} /> Recalcular contador
|
||||
</button>
|
||||
<button type="button" className="actions-menu-item danger" role="menuitem" onClick={() => runRowAction(() => handleDeleteServer(s))}>
|
||||
<Trash2 size={16} /> Eliminar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
</React.Fragment>
|
||||
);})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -196,6 +481,255 @@ export const WapServersPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedAudit && (
|
||||
<div className="modal-overlay" onClick={() => setSelectedAuditServerId(null)}>
|
||||
<div className="audit-modal glass-panel" onClick={(event) => event.stopPropagation()}>
|
||||
<div className="audit-modal-header">
|
||||
<div>
|
||||
<h2>Diagnóstico WAP</h2>
|
||||
<p>{selectedAuditServer?.name || selectedAudit.serverId}</p>
|
||||
</div>
|
||||
<button className="btn-secondary" onClick={() => setSelectedAuditServerId(null)} aria-label="Cerrar diagnóstico">
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="audit-panel">
|
||||
<div className="audit-summary">
|
||||
<span>Stored: <strong>{selectedAudit.storedCountBots}</strong></span>
|
||||
<span>Expected: <strong>{selectedAudit.expectedCountBots}</strong></span>
|
||||
<span>Runtime: <strong>{selectedAudit.runtimeCountBots}</strong></span>
|
||||
<span style={{ color: selectedAudit.countMismatch ? 'var(--warning)' : 'var(--success)' }}>
|
||||
{selectedAudit.countMismatch ? 'Mismatch' : 'OK'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="audit-tabs" role="tablist" aria-label="Resultados del diagnóstico WAP">
|
||||
<button type="button" role="tab" className={auditTab === 'assigned' ? 'audit-tab active' : 'audit-tab'} onClick={() => setAuditTab('assigned')}>
|
||||
Organizaciones asignadas ({selectedAudit.assignedOrganizations.length})
|
||||
</button>
|
||||
<button type="button" role="tab" className={auditTab === 'ghosts' ? 'audit-tab active' : 'audit-tab'} onClick={() => setAuditTab('ghosts')}>
|
||||
Bots Fantasmas ({selectedAudit.ghostBots.length})
|
||||
</button>
|
||||
<button type="button" role="tab" className={auditTab === 'missing' ? 'audit-tab active' : 'audit-tab'} onClick={() => setAuditTab('missing')}>
|
||||
Organizaciones sin bots ({selectedAudit.missingBots.length})
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="audit-tab-panel">
|
||||
{auditTab === 'assigned' && (
|
||||
selectedAudit.assignedOrganizations.length === 0
|
||||
? <p>Sin organizaciones asignadas.</p>
|
||||
: <table className="audit-result-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Organización</th>
|
||||
<th>ID</th>
|
||||
<th>Estado del bot</th>
|
||||
<th style={{ textAlign: 'right' }}>Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{selectedAudit.assignedOrganizations.map(org => {
|
||||
const bot = selectedAudit.validBots.find((item: WapContainerDto) => item.organizationId === org.id);
|
||||
return (
|
||||
<tr key={org.id}>
|
||||
<td>{org.name || 'Sin nombre'}</td>
|
||||
<td><small>{org.id}</small></td>
|
||||
<td>{bot?.status || bot?.state || 'Sin bot detectado'}</td>
|
||||
<td>{renderAuditActionsMenu(`assigned-${org.id}`, selectedAudit.serverId, org.id, true, true)}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{auditTab === 'ghosts' && (
|
||||
selectedAudit.ghostBots.length === 0
|
||||
? <p>Sin bots fantasma.</p>
|
||||
: <table className="audit-result-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Bot</th>
|
||||
<th>Organización</th>
|
||||
<th>Estado</th>
|
||||
<th style={{ textAlign: 'right' }}>Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{selectedAudit.ghostBots.map((bot: WapContainerDto) => (
|
||||
<tr key={bot.id || bot.name}>
|
||||
<td>{bot.name || bot.id || 'Sin nombre'}</td>
|
||||
<td><small>{bot.organizationId || 'organizationId no detectado'}</small></td>
|
||||
<td>{bot.status || bot.state || '-'}</td>
|
||||
<td>{bot.organizationId ? renderAuditActionsMenu(`ghost-${bot.organizationId}-${bot.id || bot.name}`, selectedAudit.serverId, bot.organizationId, true, false) : '-'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{auditTab === 'missing' && (
|
||||
selectedAudit.missingBots.length === 0
|
||||
? <p>Sin organizaciones sin bot.</p>
|
||||
: <table className="audit-result-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Organización</th>
|
||||
<th>ID</th>
|
||||
<th style={{ textAlign: 'right' }}>Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{selectedAudit.missingBots.map(org => (
|
||||
<tr key={org.id}>
|
||||
<td>{org.name || 'Sin nombre'}</td>
|
||||
<td><small>{org.id}</small></td>
|
||||
<td>{renderAuditActionsMenu(`missing-${org.id}`, selectedAudit.serverId, org.id, false, true)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editingServer && (
|
||||
<div className="modal-overlay" onClick={() => setEditingServer(null)}>
|
||||
<form className="edit-server-modal glass-panel" onSubmit={handleSaveServer} onClick={(event) => event.stopPropagation()}>
|
||||
<div className="audit-modal-header">
|
||||
<div>
|
||||
<h2>{serverFormMode === 'create' ? 'Nuevo servidor' : 'Editar servidor'}</h2>
|
||||
<p>{serverFormMode === 'create' ? 'Crear servidor WAP' : editingServer.name || getServerId(editingServer)}</p>
|
||||
</div>
|
||||
<button type="button" className="btn-secondary" onClick={() => setEditingServer(null)} aria-label="Cerrar edición">
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="edit-server-grid">
|
||||
<label>
|
||||
<span>Nombre</span>
|
||||
<input className="input-glass" value={editForm.name} onChange={(e) => setEditForm({ ...editForm, name: e.target.value })} />
|
||||
</label>
|
||||
<label>
|
||||
<span>URL</span>
|
||||
<input className="input-glass" value={editForm.ipv4} onChange={(e) => setEditForm({ ...editForm, ipv4: e.target.value })} placeholder="http://localhost:3005/" required />
|
||||
<small style={{ color: 'var(--text-muted)' }}>Usá solo el origen HTTP(S), sin path, query ni credenciales.</small>
|
||||
</label>
|
||||
<label>
|
||||
<span>Puerto</span>
|
||||
<input className="input-glass" type="number" min="0" value={editForm.port} onChange={(e) => setEditForm({ ...editForm, port: e.target.value })} required />
|
||||
</label>
|
||||
<label>
|
||||
<span>Cantidad máxima de bots</span>
|
||||
<input className="input-glass" type="number" min="0" value={editForm.maxBots} onChange={(e) => setEditForm({ ...editForm, maxBots: e.target.value })} required />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button type="button" className={editForm.active ? 'status-toggle active' : 'status-toggle'} onClick={() => setEditForm({ ...editForm, active: !editForm.active })}>
|
||||
{editForm.active ? <CheckCircle size={16} /> : <XCircle size={16} />}
|
||||
{editForm.active ? 'Activo' : 'Inactivo'}
|
||||
</button>
|
||||
|
||||
<div className="edit-server-actions">
|
||||
<button type="button" className="btn-secondary" onClick={() => setEditingServer(null)}>Cancelar</button>
|
||||
<button type="submit" className="btn-primary" disabled={actionServerId === (serverFormMode === 'create' ? 'create' : getServerId(editingServer))}>{serverFormMode === 'create' ? 'Crear servidor' : 'Guardar cambios'}</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{deleteServerTarget && (
|
||||
<div className="modal-overlay" onClick={() => setDeleteServerTarget(null)}>
|
||||
<div className="delete-server-modal glass-panel" onClick={(event) => event.stopPropagation()}>
|
||||
<div className="audit-modal-header">
|
||||
<div>
|
||||
<h2>Eliminar servidor WAP</h2>
|
||||
<p>{deleteServerTarget.name || getServerId(deleteServerTarget)}</p>
|
||||
</div>
|
||||
<button type="button" className="btn-secondary" onClick={() => setDeleteServerTarget(null)} aria-label="Cerrar confirmación">
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="delete-warning">
|
||||
<strong>Esta acción elimina el servidor WAP.</strong>
|
||||
<p>Sin forzar, el servidor debe estar inactivo y no tener bots asociados.</p>
|
||||
<p>Si activás borrado forzado, se omiten esas validaciones: las organizaciones asignadas se desasocian y los bots/contenedores runtime detectados pueden eliminarse u omitirse si no se pueden identificar con seguridad.</p>
|
||||
</div>
|
||||
|
||||
<label className="force-delete-option">
|
||||
<input type="checkbox" checked={forceDeleteServer} onChange={(event) => setForceDeleteServer(event.target.checked)} />
|
||||
<span>Forzar eliminación y desasociar organizaciones/bots aunque el servidor esté activo.</span>
|
||||
</label>
|
||||
|
||||
<div className="edit-server-actions">
|
||||
<button type="button" className="btn-secondary" onClick={() => setDeleteServerTarget(null)}>Cancelar</button>
|
||||
<button type="button" className="btn-danger" disabled={actionServerId === getServerId(deleteServerTarget)} onClick={confirmDeleteServer}>Eliminar servidor</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{recalculateResult && (
|
||||
<div className="modal-overlay" onClick={() => setRecalculateResult(null)}>
|
||||
<div className="recalculate-modal glass-panel" onClick={(event) => event.stopPropagation()}>
|
||||
<div className="audit-modal-header">
|
||||
<div>
|
||||
<h2>Contador recalculado</h2>
|
||||
<p>{recalculateServer?.name || recalculateResult.serverId}</p>
|
||||
</div>
|
||||
<button className="btn-secondary" onClick={() => setRecalculateResult(null)} aria-label="Cerrar resultado">
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="recalculate-summary">
|
||||
<span>Antes: <strong>{recalculateResult.before}</strong></span>
|
||||
<span>Después: <strong>{recalculateResult.after}</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{qrResult && (
|
||||
<div className="modal-overlay" onClick={() => setQrResult(null)}>
|
||||
<div className="recalculate-modal glass-panel" onClick={(event) => event.stopPropagation()}>
|
||||
<div className="audit-modal-header">
|
||||
<div>
|
||||
<h2>QR del bot</h2>
|
||||
<p>{qrResult.organizationId}</p>
|
||||
</div>
|
||||
<button className="btn-secondary" onClick={() => setQrResult(null)} aria-label="Cerrar QR">
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="qr-result">
|
||||
<img src={`data:image/png;base64,${qrResult.qr}`} alt={`QR para ${qrResult.organizationId}`} />
|
||||
<textarea readOnly value={qrResult.qr} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{actionMessage && (
|
||||
<div className="modal-overlay" onClick={() => setActionMessage(null)}>
|
||||
<div className="recalculate-modal glass-panel" onClick={(event) => event.stopPropagation()}>
|
||||
<div className="audit-modal-header">
|
||||
<div>
|
||||
<h2>Acción completada</h2>
|
||||
<p>{actionMessage}</p>
|
||||
</div>
|
||||
<button className="btn-secondary" onClick={() => setActionMessage(null)} aria-label="Cerrar resultado">
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<style dangerouslySetInnerHTML={{__html: `
|
||||
.sticky-header {
|
||||
position: sticky;
|
||||
@@ -209,6 +743,326 @@ export const WapServersPage = () => {
|
||||
.table-row-hover:hover {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
.icon-btn {
|
||||
background: rgba(255,255,255,0.05);
|
||||
color: var(--text-muted);
|
||||
padding: 8px;
|
||||
border-radius: 8px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.icon-btn:hover:not(:disabled) {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
.icon-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.actions-menu-wrapper {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
justify-content: flex-end;
|
||||
width: 100%;
|
||||
}
|
||||
.actions-menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 8px);
|
||||
right: 0;
|
||||
z-index: 30;
|
||||
min-width: 220px;
|
||||
padding: 0.4rem;
|
||||
border: 1px solid rgba(255, 255, 255, 0.14);
|
||||
border-radius: 12px;
|
||||
background: #111827;
|
||||
box-shadow: 0 18px 45px rgba(0, 0, 0, 0.45);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
.actions-menu-item {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
padding: 0.65rem 0.75rem;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: #f8fafc;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.actions-menu-item:hover {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: #ffffff;
|
||||
}
|
||||
.actions-menu-item.danger {
|
||||
color: #fecaca;
|
||||
}
|
||||
.actions-menu-item.danger:hover {
|
||||
background: rgba(239, 68, 68, 0.18);
|
||||
color: #ffffff;
|
||||
}
|
||||
.audit-actions-wrapper {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.audit-row-menu {
|
||||
z-index: 50;
|
||||
}
|
||||
.audit-panel {
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: 14px;
|
||||
padding: 1rem;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
}
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1.5rem;
|
||||
background: rgba(0, 0, 0, 0.65);
|
||||
backdrop-filter: blur(8px);
|
||||
overflow: auto;
|
||||
}
|
||||
.audit-modal {
|
||||
width: min(1100px, 96vw);
|
||||
max-height: 86vh;
|
||||
overflow: visible;
|
||||
padding: 1.25rem;
|
||||
}
|
||||
.recalculate-modal {
|
||||
width: min(520px, 96vw);
|
||||
padding: 1.25rem;
|
||||
}
|
||||
.edit-server-modal {
|
||||
width: min(560px, 96vw);
|
||||
padding: 1.25rem;
|
||||
}
|
||||
.delete-server-modal {
|
||||
width: min(560px, 96vw);
|
||||
padding: 1.25rem;
|
||||
}
|
||||
.delete-warning {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgba(239, 68, 68, 0.32);
|
||||
border-radius: 14px;
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
color: var(--text-main);
|
||||
}
|
||||
.delete-warning p {
|
||||
margin: 0;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.force-delete-option {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1rem;
|
||||
padding: 0.9rem;
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: 12px;
|
||||
color: #fecaca;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
cursor: pointer;
|
||||
}
|
||||
.force-delete-option input {
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
.btn-danger {
|
||||
background: rgba(239, 68, 68, 0.9);
|
||||
color: #ffffff;
|
||||
border: 0;
|
||||
border-radius: 10px;
|
||||
padding: 0.75rem 1rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn-danger:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.edit-server-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
.edit-server-grid label {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.status-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-top: 1rem;
|
||||
padding: 0.7rem 0.9rem;
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: 12px;
|
||||
background: rgba(245, 158, 11, 0.12);
|
||||
color: var(--warning);
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
.status-toggle.active {
|
||||
background: rgba(34, 197, 94, 0.12);
|
||||
color: var(--success);
|
||||
}
|
||||
.edit-server-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1.25rem;
|
||||
}
|
||||
.audit-modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.audit-modal-header h2 {
|
||||
margin: 0;
|
||||
color: var(--text-main);
|
||||
}
|
||||
.audit-modal-header p {
|
||||
margin: 0.25rem 0 0;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.recalculate-summary {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: 14px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.qr-result {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
.qr-result img {
|
||||
max-width: 260px;
|
||||
width: 100%;
|
||||
justify-self: center;
|
||||
border-radius: 12px;
|
||||
background: #ffffff;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
.qr-result textarea {
|
||||
min-height: 120px;
|
||||
width: 100%;
|
||||
resize: vertical;
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: 12px;
|
||||
background: rgba(0, 0, 0, 0.22);
|
||||
color: var(--text-muted);
|
||||
padding: 0.75rem;
|
||||
font-family: monospace;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.audit-summary {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 1rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.audit-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
.audit-grid h3 {
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 0.5rem;
|
||||
color: var(--text-main);
|
||||
}
|
||||
.audit-grid p {
|
||||
margin: 0 0 0.4rem;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.audit-grid small {
|
||||
display: block;
|
||||
opacity: 0.75;
|
||||
word-break: break-all;
|
||||
}
|
||||
.audit-tabs {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 1rem;
|
||||
border-bottom: 1px solid var(--glass-border);
|
||||
}
|
||||
.audit-tab {
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
padding: 0.75rem 0.85rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.audit-tab:hover,
|
||||
.audit-tab.active {
|
||||
color: var(--text-main);
|
||||
border-bottom-color: var(--primary);
|
||||
}
|
||||
.audit-tab-panel p {
|
||||
margin: 0 0 0.6rem;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.audit-tab-panel small {
|
||||
display: block;
|
||||
opacity: 0.75;
|
||||
word-break: break-all;
|
||||
}
|
||||
.audit-result-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
text-align: left;
|
||||
}
|
||||
.audit-result-table th {
|
||||
padding: 0.85rem 1rem;
|
||||
color: var(--text-muted);
|
||||
font-weight: 600;
|
||||
border-bottom: 1px solid var(--glass-border);
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
}
|
||||
.audit-result-table td {
|
||||
padding: 0.85rem 1rem;
|
||||
color: var(--text-main);
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
.audit-result-table tr:hover td {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
.audit-result-table small {
|
||||
color: var(--text-muted);
|
||||
word-break: break-all;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.audit-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.edit-server-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
`}} />
|
||||
</motion.div>
|
||||
);
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
API_HOST = http://localhost:3000
|
||||
API_HOST_DEV = http://localhost:3000
|
||||
API_HOST_PROD = https://api.turnosxpress.com.ar
|
||||
API_PRIVATE_KEY=keys/tx-sysadmin-private.key
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Request, Response } from "express";
|
||||
import { paginateCompanies, setCompanyBanned, updateCompany } from "../services/companies.service";
|
||||
import { getOrganizationInsights, paginateCompanies, setCompanyBanned, updateCompany } from "../services/companies.service";
|
||||
|
||||
export const paginate = async (req: Request, res: Response) => {
|
||||
try {
|
||||
@@ -33,3 +33,14 @@ export const setBanned = async (req: Request, res: Response) => {
|
||||
res.status(500).json({ error: err });
|
||||
}
|
||||
};
|
||||
|
||||
export const insights = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const result = await getOrganizationInsights(req.body);
|
||||
res.json(result);
|
||||
} catch (e: any) {
|
||||
console.log(e);
|
||||
const err = e.response ? e.response.data : e.message;
|
||||
res.status(500).json({ error: err });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
import axios from "axios";
|
||||
import { Request, Response } from "express";
|
||||
import { WapService } from "../services/wap.service";
|
||||
import { PaginateWapServerParams } from "src/models/WapServers.Model";
|
||||
import { CreateWapServerParams, PaginateWapServerParams, UpdateWapServerParams, WapServerByIdParams, WapServerDeleteParams, WapServerOrganizationActionParams } from "src/models/WapServers.Model";
|
||||
|
||||
const wapService = new WapService();
|
||||
|
||||
const getErrorStatus = (error: unknown): number => {
|
||||
if (axios.isAxiosError(error) && error.response?.status) {
|
||||
return error.response.status;
|
||||
}
|
||||
|
||||
return 500;
|
||||
};
|
||||
|
||||
const getErrorMessage = (error: unknown): string => {
|
||||
const responseData = axios.isAxiosError(error) ? error.response?.data : undefined;
|
||||
|
||||
if (typeof responseData === "string") {
|
||||
return responseData;
|
||||
}
|
||||
|
||||
return responseData?.desc || responseData?.message || responseData?.error || (error as Error)?.message || "Internal Server Error";
|
||||
};
|
||||
|
||||
export class WapController {
|
||||
public getServers = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
@@ -15,4 +34,128 @@ export class WapController {
|
||||
res.status(500).json({ success: false, message: "Internal Server Error" });
|
||||
}
|
||||
};
|
||||
|
||||
public auditServer = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const data: WapServerByIdParams = req.body as WapServerByIdParams;
|
||||
const audit = await wapService.auditWapServer(data);
|
||||
res.json(audit);
|
||||
} catch (error) {
|
||||
console.error("Error auditing wap server:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public updateServer = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const result = await wapService.updateWapServer(req.body as UpdateWapServerParams);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
console.error("Error updating wap server:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public createServer = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const result = await wapService.createWapServer(req.body as CreateWapServerParams);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
console.error("Error creating wap server:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public recalculateCount = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const data: WapServerByIdParams = req.body as WapServerByIdParams;
|
||||
const result = await wapService.recalculateWapServerCount(data);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
console.error("Error recalculating wap server count:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public deleteServer = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const data: WapServerDeleteParams = req.body as WapServerDeleteParams;
|
||||
const result = await wapService.deleteWapServer(data);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
console.error("Error deleting wap server:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public startBot = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
await wapService.startBot(req.body as WapServerOrganizationActionParams);
|
||||
res.json({ success: true, message: "ok" });
|
||||
} catch (error) {
|
||||
console.error("Error starting wap bot:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public stopBot = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
await wapService.stopBot(req.body as WapServerOrganizationActionParams);
|
||||
res.json({ success: true, message: "ok" });
|
||||
} catch (error) {
|
||||
console.error("Error stopping wap bot:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public restartBot = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
await wapService.restartBot(req.body as WapServerOrganizationActionParams);
|
||||
res.json({ success: true, message: "ok" });
|
||||
} catch (error) {
|
||||
console.error("Error restarting wap bot:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public getBotQr = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const result = await wapService.getBotQr(req.body as WapServerOrganizationActionParams);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
console.error("Error getting wap bot qr:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public deleteBot = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
await wapService.deleteBot(req.body as WapServerOrganizationActionParams);
|
||||
res.json({ success: true, message: "ok" });
|
||||
} catch (error) {
|
||||
console.error("Error deleting wap bot:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
|
||||
public detachOrganizationServer = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const result = await wapService.detachOrganizationServer(req.body as WapServerOrganizationActionParams);
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
console.error("Error detaching wap organization server:", error);
|
||||
const message = getErrorMessage(error);
|
||||
res.status(getErrorStatus(error)).json({ success: false, message, desc: message });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -35,3 +35,72 @@ export type SetCompanyBannedParams = {
|
||||
id: string;
|
||||
banned: boolean;
|
||||
};
|
||||
|
||||
export type OrganizationInsightsParams = {
|
||||
companyId: string;
|
||||
};
|
||||
|
||||
export type OrganizationInsightsResult = {
|
||||
organization: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
categoryId: number;
|
||||
banned: boolean;
|
||||
published?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
};
|
||||
owner: {
|
||||
id: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
verificated?: boolean;
|
||||
phoneCountryCode?: string;
|
||||
phoneAreaCode?: string;
|
||||
phoneNumber?: string;
|
||||
} | null;
|
||||
collaborators: {
|
||||
id: string;
|
||||
userId?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
fullName?: string;
|
||||
email?: string;
|
||||
roles?: string[];
|
||||
removed?: boolean;
|
||||
active: boolean;
|
||||
avatar?: string;
|
||||
}[];
|
||||
subscription: {
|
||||
id: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
isActive: boolean;
|
||||
autoRenew: boolean;
|
||||
mpStatus?: string;
|
||||
pendingPaymentType?: "extension" | "upgrade";
|
||||
plan: {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
price: number;
|
||||
limitOrganizations: number;
|
||||
limitEmployees: number;
|
||||
limitServices: number;
|
||||
limitAppointments: number;
|
||||
limitClients: number;
|
||||
} | null;
|
||||
} | null;
|
||||
stats: {
|
||||
employeesCount: number;
|
||||
activeEmployeesCount: number;
|
||||
servicesCount: number;
|
||||
activeServicesCount: number;
|
||||
clientsCount: number;
|
||||
activeClientsCount: number;
|
||||
reservationsLast30Days: number;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -6,6 +6,7 @@ export type FindWapServerParams = {
|
||||
description?: string;
|
||||
countBots?: number;
|
||||
maxBots?: number;
|
||||
port?: number;
|
||||
active?: boolean;
|
||||
countBotsFrom?: number;
|
||||
countBotsTo?: number;
|
||||
@@ -19,9 +20,29 @@ export interface IWapServer {
|
||||
ipv6: string;
|
||||
countBots: number;
|
||||
maxBots: number;
|
||||
port: number;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export type UpdateWapServerParams = {
|
||||
serverId: string;
|
||||
name?: string;
|
||||
ipv4?: string;
|
||||
port?: number;
|
||||
maxBots?: number;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type CreateWapServerParams = {
|
||||
name: string;
|
||||
ipv4: string;
|
||||
port: number;
|
||||
maxBots: number;
|
||||
ipv6?: string;
|
||||
description?: string;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type PaginateWapServerParams = FindWapServerParams & {
|
||||
page: number;
|
||||
limit: number;
|
||||
@@ -36,3 +57,72 @@ export type PaginateWapServerResults = {
|
||||
export type SysAdminGetWapServerParams = PaginateWapServerParams & {
|
||||
payload: IPayload;
|
||||
};
|
||||
|
||||
export type WapServerByIdParams = {
|
||||
serverId: string;
|
||||
};
|
||||
|
||||
export type WapServerDeleteParams = WapServerByIdParams & {
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export type WapServerDeleteResult = {
|
||||
serverId: string;
|
||||
deleted: true;
|
||||
force?: boolean;
|
||||
detachedOrganizations?: number;
|
||||
deletedRuntimeBots?: number;
|
||||
skippedRuntimeBots?: number;
|
||||
auditFailed?: boolean;
|
||||
auditMessage?: string;
|
||||
};
|
||||
|
||||
export type WapServerOrganizationActionParams = WapServerByIdParams & {
|
||||
organizationId: string;
|
||||
};
|
||||
|
||||
export type WapServerQrResult = WapServerOrganizationActionParams & {
|
||||
qr: string;
|
||||
};
|
||||
|
||||
export type WapServerDetachResult = WapServerOrganizationActionParams & {
|
||||
botDeleted: boolean;
|
||||
botAlreadyMissing: boolean;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
export type WapAssignedOrganization = {
|
||||
id: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export type WapContainerDto = {
|
||||
id?: string;
|
||||
name?: string;
|
||||
organizationId?: string;
|
||||
image?: string;
|
||||
state?: string;
|
||||
status?: string;
|
||||
ports?: unknown[];
|
||||
created?: number;
|
||||
};
|
||||
|
||||
export type WapServerAuditResult = {
|
||||
serverId: string;
|
||||
assignedOrganizations: WapAssignedOrganization[];
|
||||
detectedBots: WapContainerDto[];
|
||||
validBots: WapContainerDto[];
|
||||
ghostBots: WapContainerDto[];
|
||||
missingBots: WapAssignedOrganization[];
|
||||
expectedCountBots: number;
|
||||
storedCountBots: number;
|
||||
runtimeCountBots: number;
|
||||
countMismatch: boolean;
|
||||
};
|
||||
|
||||
export type WapServerRecalculateCountResult = {
|
||||
serverId: string;
|
||||
before: number;
|
||||
after: number;
|
||||
};
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Router } from "express";
|
||||
import { paginate, setBanned, update } from "../controllers/companies.controller";
|
||||
import { insights, paginate, setBanned, update } from "../controllers/companies.controller";
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.post("/paginate", paginate);
|
||||
router.post("/update", update);
|
||||
router.post("/set-banned", setBanned);
|
||||
router.post("/insights", insights);
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -5,5 +5,16 @@ const router = Router();
|
||||
const wapController = new WapController();
|
||||
|
||||
router.post("/paginate", wapController.getServers);
|
||||
router.post("/create", wapController.createServer);
|
||||
router.post("/update", wapController.updateServer);
|
||||
router.post("/audit", wapController.auditServer);
|
||||
router.post("/recalculate-count", wapController.recalculateCount);
|
||||
router.post("/delete", wapController.deleteServer);
|
||||
router.post("/bot/start", wapController.startBot);
|
||||
router.post("/bot/stop", wapController.stopBot);
|
||||
router.post("/bot/restart", wapController.restartBot);
|
||||
router.post("/bot/qr", wapController.getBotQr);
|
||||
router.post("/bot/delete", wapController.deleteBot);
|
||||
router.post("/bot/detach", wapController.detachOrganizationServer);
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -5,6 +5,8 @@ import { getApiHost } from "../helpers/GetApiHost";
|
||||
import {
|
||||
PaginateCompaniesParams,
|
||||
PaginateCompaniesResults,
|
||||
OrganizationInsightsParams,
|
||||
OrganizationInsightsResult,
|
||||
SetCompanyBannedParams,
|
||||
UpdateCompanyParams,
|
||||
} from "../models/Companies.Model";
|
||||
@@ -35,3 +37,12 @@ export const setCompanyBanned = async (params: SetCompanyBannedParams): Promise<
|
||||
});
|
||||
return result.data;
|
||||
};
|
||||
|
||||
export const getOrganizationInsights = async (params: OrganizationInsightsParams): Promise<OrganizationInsightsResult> => {
|
||||
const nonce = await getSysAdminNonce();
|
||||
const result = await axios.post(`${getApiHost()}/sysadmin/companies/insights`, {
|
||||
...params,
|
||||
payload: getPayload(nonce),
|
||||
});
|
||||
return result.data;
|
||||
};
|
||||
|
||||
@@ -2,7 +2,21 @@ import { getSysAdminNonce } from "../helpers/GetSysAdminNonce";
|
||||
import { getApiHost } from "../helpers/GetApiHost";
|
||||
import axios from "axios";
|
||||
import { getPayload } from "../helpers/GetPayload";
|
||||
import { PaginateWapServerParams, PaginateWapServerResults } from "../models/WapServers.Model";
|
||||
import {
|
||||
CreateWapServerParams,
|
||||
PaginateWapServerParams,
|
||||
PaginateWapServerResults,
|
||||
WapServerAuditResult,
|
||||
WapServerByIdParams,
|
||||
WapServerDeleteParams,
|
||||
WapServerDeleteResult,
|
||||
WapServerDetachResult,
|
||||
WapServerOrganizationActionParams,
|
||||
WapServerQrResult,
|
||||
WapServerRecalculateCountResult,
|
||||
UpdateWapServerParams,
|
||||
IWapServer,
|
||||
} from "../models/WapServers.Model";
|
||||
|
||||
export class WapService {
|
||||
public async getWapServers(filters: PaginateWapServerParams): Promise<PaginateWapServerResults> {
|
||||
@@ -20,4 +34,100 @@ export class WapService {
|
||||
|
||||
return resultado;
|
||||
}
|
||||
|
||||
public async auditWapServer(data: WapServerByIdParams): Promise<WapServerAuditResult> {
|
||||
const nonce = await getSysAdminNonce();
|
||||
const postData = { ...data, ...{ payload: getPayload(nonce) } };
|
||||
|
||||
const response = await axios.post(`${getApiHost()}/sysadmin/wapserver/audit`, postData, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
return response.data as WapServerAuditResult;
|
||||
}
|
||||
|
||||
public async createWapServer(data: CreateWapServerParams): Promise<IWapServer> {
|
||||
const nonce = await getSysAdminNonce();
|
||||
const postData = { ...data, ...{ payload: getPayload(nonce) } };
|
||||
|
||||
const response = await axios.post(`${getApiHost()}/sysadmin/wapserver/create`, postData, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
return response.data as IWapServer;
|
||||
}
|
||||
|
||||
public async updateWapServer(data: UpdateWapServerParams): Promise<IWapServer> {
|
||||
const nonce = await getSysAdminNonce();
|
||||
const postData = { ...data, ...{ payload: getPayload(nonce) } };
|
||||
|
||||
const response = await axios.post(`${getApiHost()}/sysadmin/wapserver/update`, postData, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
return response.data as IWapServer;
|
||||
}
|
||||
|
||||
public async recalculateWapServerCount(data: WapServerByIdParams): Promise<WapServerRecalculateCountResult> {
|
||||
const nonce = await getSysAdminNonce();
|
||||
const postData = { ...data, ...{ payload: getPayload(nonce) } };
|
||||
|
||||
const response = await axios.post(`${getApiHost()}/sysadmin/wapserver/recalculate-count`, postData, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
return response.data as WapServerRecalculateCountResult;
|
||||
}
|
||||
|
||||
public async deleteWapServer(data: WapServerDeleteParams): Promise<WapServerDeleteResult> {
|
||||
const nonce = await getSysAdminNonce();
|
||||
const postData = { ...data, ...{ payload: getPayload(nonce) } };
|
||||
|
||||
const response = await axios.post(`${getApiHost()}/sysadmin/wapserver/delete`, postData, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
return response.data as WapServerDeleteResult;
|
||||
}
|
||||
|
||||
private async postBotAction<T>(path: string, data: WapServerOrganizationActionParams, timeout = 10000): Promise<T> {
|
||||
const nonce = await getSysAdminNonce();
|
||||
const postData = { ...data, ...{ payload: getPayload(nonce) } };
|
||||
|
||||
const response = await axios.post(`${getApiHost()}/sysadmin/wapserver/bot/${path}`, postData, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
timeout,
|
||||
});
|
||||
|
||||
return response.data as T;
|
||||
}
|
||||
|
||||
public async startBot(data: WapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postBotAction("start", data);
|
||||
}
|
||||
|
||||
public async stopBot(data: WapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postBotAction("stop", data);
|
||||
}
|
||||
|
||||
public async restartBot(data: WapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postBotAction("restart", data, 15000);
|
||||
}
|
||||
|
||||
public async getBotQr(data: WapServerOrganizationActionParams): Promise<WapServerQrResult> {
|
||||
return await this.postBotAction<WapServerQrResult>("qr", data);
|
||||
}
|
||||
|
||||
public async deleteBot(data: WapServerOrganizationActionParams): Promise<void> {
|
||||
await this.postBotAction("delete", data);
|
||||
}
|
||||
|
||||
public async detachOrganizationServer(data: WapServerOrganizationActionParams): Promise<WapServerDetachResult> {
|
||||
return await this.postBotAction<WapServerDetachResult>("detach", data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M12 3V15" stroke="#3f3a4d" stroke-width="2" stroke-linecap="round"/>
|
||||
<path d="M7 10L12 15L17 10" stroke="#3f3a4d" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M5 19H19" stroke="#3f3a4d" stroke-width="2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 376 B |
Binary file not shown.
@@ -39,6 +39,13 @@ export type SendAppointmentNotificationParams = {
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE;
|
||||
};
|
||||
|
||||
export type AppointmentNotificationPreviewResult = {
|
||||
subject: string;
|
||||
message: string;
|
||||
emailMessage: string;
|
||||
wapMessage: string;
|
||||
};
|
||||
|
||||
export type DeleteAppointmentParams = {
|
||||
id: string;
|
||||
validation?: boolean;
|
||||
|
||||
@@ -45,6 +45,9 @@ export interface MyOranizationsView {
|
||||
templateEmailCancellationId: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
showPublicScores: boolean;
|
||||
showPublicOpinions: boolean;
|
||||
showPublicProfessionals: boolean;
|
||||
}
|
||||
|
||||
export type CreateCompanyParams = {
|
||||
@@ -93,6 +96,9 @@ export type UpdateCompanyParams = {
|
||||
templateEmailCancellationId?: string;
|
||||
onboardingStep?: number;
|
||||
onboardingCompleted?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
};
|
||||
|
||||
export type DeleteCompanyParams = {
|
||||
@@ -158,6 +164,9 @@ export interface ICompany {
|
||||
onboardingCompleted?: boolean;
|
||||
fixedPostIds?: Array<string>;
|
||||
banned?: boolean;
|
||||
showPublicScores?: boolean;
|
||||
showPublicOpinions?: boolean;
|
||||
showPublicProfessionals?: boolean;
|
||||
}
|
||||
|
||||
export type PublicOrganizationViewParams = {
|
||||
@@ -184,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,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;
|
||||
}
|
||||
|
||||
@@ -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,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));
|
||||
});
|
||||
});
|
||||
};
|
||||
+18
@@ -1,6 +1,7 @@
|
||||
import ApiRequest from "@services/Api.Service";
|
||||
import {
|
||||
ApplyAppointmentDiscountParams,
|
||||
AppointmentNotificationPreviewResult,
|
||||
AppointmentAdminByClientView,
|
||||
AppointmentEventByClient,
|
||||
DeleteAppointmentDiscountParams,
|
||||
@@ -108,6 +109,23 @@ export const createImmediateNotificationJobs = async (
|
||||
});
|
||||
};
|
||||
|
||||
export const getAppointmentNotificationPreview = async (
|
||||
data: SendAppointmentNotificationParams
|
||||
): Promise<AppointmentNotificationPreviewResult> => {
|
||||
return new Promise<AppointmentNotificationPreviewResult>((resolve, reject) => {
|
||||
schemaSendWapNotification
|
||||
.validate(data, { abortEarly: true })
|
||||
.then(() => {
|
||||
resolve(
|
||||
ApiRequest.post<AppointmentNotificationPreviewResult>("appointments/notification-preview", data)
|
||||
);
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(new ApiError(500, error.message));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const schemaApplyDiscount = Yup.object().shape({
|
||||
appointmentId: Yup.string().required("Debe seleccionar un turno."),
|
||||
companyId: Yup.string().required("Organización no seleccionada."),
|
||||
|
||||
+158
@@ -13,12 +13,14 @@ import {
|
||||
deleteAppointment,
|
||||
deleteAppointmentDiscount,
|
||||
findAppointmentsAdminByClient,
|
||||
getAppointmentNotificationPreview,
|
||||
updateAppointment,
|
||||
} from "../Appointments.Service";
|
||||
import {
|
||||
ApplyAppointmentDiscountParams,
|
||||
APPOINTMENT_NOTIFICATION_TYPE,
|
||||
AppointmentEventByClient,
|
||||
AppointmentNotificationPreviewResult,
|
||||
DeleteAppointmentDiscountParams,
|
||||
UpdateAppointmentParams,
|
||||
} from "@core/Models/Appointments.model";
|
||||
@@ -27,6 +29,10 @@ import Textbox from "@core/app/components/Textbox/Textbox";
|
||||
import { useMenuStore } from "@core/Store/Menu.Store";
|
||||
import NotificationsActiveOutlinedIcon from "@mui/icons-material/NotificationsActiveOutlined";
|
||||
import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
|
||||
import EmailIcon from "@mui/icons-material/Email";
|
||||
import ShareIcon from "@mui/icons-material/Share";
|
||||
import WhatsAppIcon from "@mui/icons-material/WhatsApp";
|
||||
|
||||
import Switch from "@mui/material/Switch";
|
||||
import { ThemeProvider } from "@emotion/react";
|
||||
@@ -91,6 +97,8 @@ export default function ClientAppointment() {
|
||||
const [comments, setComments] = useState<string>("");
|
||||
|
||||
const [dialogDiscountVisible, setDialogDiscountVisible] = useState(false);
|
||||
const [dialogShareVisible, setDialogShareVisible] = useState(false);
|
||||
const [sharePreview, setSharePreview] = useState<AppointmentNotificationPreviewResult | undefined>(undefined);
|
||||
|
||||
const [discountsFilterContent] = useState<TextObjectModalContent>({
|
||||
header: (
|
||||
@@ -361,6 +369,14 @@ export default function ClientAppointment() {
|
||||
icon: <NotificationsActiveOutlinedIcon />,
|
||||
});
|
||||
|
||||
menu.add({
|
||||
text: "Compartir",
|
||||
onClick: () => {
|
||||
openShareDialog();
|
||||
},
|
||||
icon: <ShareIcon />,
|
||||
});
|
||||
|
||||
if (showQuitDiscount) {
|
||||
menu.divider();
|
||||
|
||||
@@ -408,6 +424,66 @@ export default function ClientAppointment() {
|
||||
});
|
||||
};
|
||||
|
||||
const openShareDialog = () => {
|
||||
if (!appointmentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDialogShareVisible(true);
|
||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||
getAppointmentNotificationPreview({
|
||||
appointmentId: appointmentId.toString(),
|
||||
type: APPOINTMENT_NOTIFICATION_TYPE.REMINDER,
|
||||
sessionUser: SessionUser.userId,
|
||||
})
|
||||
.then((preview) => {
|
||||
setSharePreview(preview);
|
||||
})
|
||||
.catch((error) => {
|
||||
alert.showError(error.format());
|
||||
setDialogShareVisible(false);
|
||||
})
|
||||
.finally(() => {
|
||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||
});
|
||||
};
|
||||
|
||||
const copyShareText = async () => {
|
||||
if (!sharePreview) {
|
||||
return;
|
||||
}
|
||||
|
||||
await navigator.clipboard.writeText(sharePreview.wapMessage);
|
||||
alert.showSuccess("Texto copiado al portapapeles");
|
||||
};
|
||||
|
||||
const shareByWhatsApp = () => {
|
||||
if (!sharePreview) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.open(`https://wa.me/?text=${encodeURIComponent(sharePreview.wapMessage)}`, "_blank");
|
||||
};
|
||||
|
||||
const shareByEmail = () => {
|
||||
if (!sharePreview) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.location.href = `mailto:?subject=${encodeURIComponent(sharePreview.subject)}&body=${encodeURIComponent(sharePreview.emailMessage)}`;
|
||||
};
|
||||
|
||||
const nativeShare = async () => {
|
||||
if (!sharePreview || !navigator.share) {
|
||||
return;
|
||||
}
|
||||
|
||||
await navigator.share({
|
||||
title: sharePreview.subject,
|
||||
text: sharePreview.wapMessage,
|
||||
});
|
||||
};
|
||||
|
||||
const applyDiscountHandler = () => {
|
||||
if (!SessionUser.userId) {
|
||||
return;
|
||||
@@ -728,6 +804,88 @@ export default function ClientAppointment() {
|
||||
</>
|
||||
</DialogWindow>
|
||||
|
||||
<DialogWindow
|
||||
visible={dialogShareVisible}
|
||||
setVisible={setDialogShareVisible}
|
||||
>
|
||||
<>
|
||||
<DialogContent
|
||||
style={{
|
||||
maxWidth: "520px",
|
||||
minWidth: "300px",
|
||||
margin: "auto",
|
||||
}}
|
||||
>
|
||||
<h3 style={{ marginBottom: "10px" }}>Compartir recordatorio</h3>
|
||||
<p style={{ fontSize: "14px", fontWeight: 500, marginBottom: "10px" }}>
|
||||
Este texto usa el mismo contenido del recordatorio de notificaciones.
|
||||
</p>
|
||||
<textarea
|
||||
readOnly
|
||||
value={sharePreview?.wapMessage || ""}
|
||||
style={{
|
||||
width: "100%",
|
||||
minHeight: "180px",
|
||||
border: "1px solid var(--gray)",
|
||||
borderRadius: "8px",
|
||||
color: "var(--black)",
|
||||
fontSize: "14px",
|
||||
padding: "10px",
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions style={{ flexWrap: "wrap", gap: "8px" }}>
|
||||
<ButtonMaterial
|
||||
variant="contained"
|
||||
color="primary"
|
||||
startIcon={<WhatsAppIcon />}
|
||||
disabled={!sharePreview}
|
||||
onClick={shareByWhatsApp}
|
||||
>
|
||||
WhatsApp
|
||||
</ButtonMaterial>
|
||||
<ButtonMaterial
|
||||
variant="contained"
|
||||
color="primary"
|
||||
startIcon={<EmailIcon />}
|
||||
disabled={!sharePreview}
|
||||
onClick={shareByEmail}
|
||||
>
|
||||
Email
|
||||
</ButtonMaterial>
|
||||
<ButtonMaterial
|
||||
variant="contained"
|
||||
color="primary"
|
||||
startIcon={<ContentCopyIcon />}
|
||||
disabled={!sharePreview}
|
||||
onClick={copyShareText}
|
||||
>
|
||||
Copiar
|
||||
</ButtonMaterial>
|
||||
{typeof navigator !== "undefined" && !!navigator.share && (
|
||||
<ButtonMaterial
|
||||
variant="contained"
|
||||
color="primary"
|
||||
startIcon={<ShareIcon />}
|
||||
disabled={!sharePreview}
|
||||
onClick={nativeShare}
|
||||
>
|
||||
Compartir
|
||||
</ButtonMaterial>
|
||||
)}
|
||||
<ButtonMaterial
|
||||
variant="contained"
|
||||
color="secondary"
|
||||
onClick={() => {
|
||||
setDialogShareVisible(false);
|
||||
}}
|
||||
>
|
||||
Cerrar
|
||||
</ButtonMaterial>
|
||||
</DialogActions>
|
||||
</>
|
||||
</DialogWindow>
|
||||
|
||||
<DialogWindow
|
||||
visible={dialogChangeServiceVisible}
|
||||
setVisible={setDialogChangeServiceVisible}
|
||||
|
||||
@@ -8,7 +8,10 @@ import { ApiVoidResult } from "@models/Api.VoidResult.type";
|
||||
import ApiRequest from "@services/Api.Service";
|
||||
import {
|
||||
EnableScheduleParams,
|
||||
ExtendReservationPeriodsParams,
|
||||
FindSchedulesEnabledParams,
|
||||
ReservationPeriodsSummary,
|
||||
ReservationPeriodsSummaryParams,
|
||||
SchedulesEnabledView,
|
||||
} from "@models/SchedulesEnabled.type";
|
||||
import {
|
||||
@@ -56,6 +59,18 @@ export const disableSchedule = async (data: EnableScheduleParams): Promise<ApiVo
|
||||
return ApiRequest.post<ApiVoidResult>("schedules-enabled/disable", data);
|
||||
};
|
||||
|
||||
export const summarizeReservationPeriods = async (
|
||||
data: ReservationPeriodsSummaryParams
|
||||
): Promise<ReservationPeriodsSummary> => {
|
||||
return ApiRequest.post<ReservationPeriodsSummary>("schedules-enabled/reservation-periods/summary", data);
|
||||
};
|
||||
|
||||
export const extendReservationPeriods = async (
|
||||
data: ExtendReservationPeriodsParams
|
||||
): Promise<ReservationPeriodsSummary> => {
|
||||
return ApiRequest.post<ReservationPeriodsSummary>("schedules-enabled/reservation-periods/extend", data);
|
||||
};
|
||||
|
||||
export const uploadHeaderImage = async (data: FormData): Promise<ApiVoidResult> => {
|
||||
return ApiRequest.postFile<ApiVoidResult>("companies/upload-header", data);
|
||||
};
|
||||
|
||||
@@ -11,12 +11,14 @@ import OrgConfigIcon from "@mui/icons-material/SettingsOutlined";
|
||||
import Textbox from "@components/Textbox/Textbox";
|
||||
import TextPhone from "@components/TextPhone/TextPhone";
|
||||
import MaterialAlert from "@mui/material/Alert";
|
||||
import Checkbox from "@mui/material/Checkbox";
|
||||
import * as Yup from "yup";
|
||||
import {
|
||||
loadOrganizationsById,
|
||||
savePublishedStatus,
|
||||
updateOrganizationsById,
|
||||
} from "../Org.Service";
|
||||
import { loadServicesByCompany, updateService } from "../services/Services.Service";
|
||||
import {
|
||||
COMPANY_PUBLISHED_STATUS,
|
||||
MyOranizationsView,
|
||||
@@ -35,6 +37,7 @@ import { useConfirmStore } from "@core/Store/Confirm.Store";
|
||||
import Switch from "@core/app/components/Switch/Switch";
|
||||
import { FindTemplatesParams } from "@core/Models/Templates.model";
|
||||
import filterObjects from "@core/app/components/TextObjectFilter/Filter.Service";
|
||||
import { CompanyServiceView } from "@models/Service.model";
|
||||
|
||||
type UrlData = {
|
||||
id: string;
|
||||
@@ -57,6 +60,14 @@ export default function OrganizationEdit() {
|
||||
const [cancellationTime, setCancellationTime] = useState("");
|
||||
const [appointmentAlert, setAppointmentAlert] = useState("");
|
||||
const [orgSlug, setOrgSlug] = useState("");
|
||||
const [showPublicScores, setShowPublicScores] = useState(true);
|
||||
const [showPublicOpinions, setShowPublicOpinions] = useState(true);
|
||||
const [showPublicProfessionals, setShowPublicProfessionals] = useState(true);
|
||||
const [servicesShowPublicScores, setServicesShowPublicScores] = useState(true);
|
||||
const [servicesShowPublicOpinions, setServicesShowPublicOpinions] = useState(true);
|
||||
const [originalServicesShowPublicScores, setOriginalServicesShowPublicScores] = useState(true);
|
||||
const [originalServicesShowPublicOpinions, setOriginalServicesShowPublicOpinions] = useState(true);
|
||||
const [services, setServices] = useState<CompanyServiceView[]>([]);
|
||||
|
||||
const [orgPublished, setOrgPublished] = useState<COMPANY_PUBLISHED_STATUS | undefined>(
|
||||
undefined
|
||||
@@ -65,6 +76,8 @@ export default function OrganizationEdit() {
|
||||
const [savePublishedStatusAvailable, setSavePublishedStatusAvailable] = useState(false);
|
||||
|
||||
const [combosLoaded, setCombosLoaded] = useState<boolean>(false);
|
||||
const ownerSubscription = SessionInfo.organizationSubscriptions[id];
|
||||
const canEditPublicVisibilityFlags = (ownerSubscription?.plan.price || 0) > 0;
|
||||
|
||||
const [categoryFilterContent] = useState<TextObjectModalContent>({
|
||||
header: (
|
||||
@@ -210,28 +223,53 @@ export default function OrganizationEdit() {
|
||||
useEffect(() => {
|
||||
if (combosLoaded) {
|
||||
eventHandler.setEventType(EVENT_TYPES.LOADING);
|
||||
loadOrganizationsById({ id: id, sessionUser: SessionInfo.userId })
|
||||
.then((response: MyOranizationsView) => {
|
||||
setOrgName(response.name);
|
||||
setOrgDescription(response.description);
|
||||
setHeatMapFraction(response.heatMapFraction.toString());
|
||||
setAppointmentTime(response.appointmentTime.toString());
|
||||
setCancellationTime(response.cancellationTime.toString());
|
||||
setAppointmentAlert(response.appointmentAlert);
|
||||
setAreaCode(response.phoneAreaCode);
|
||||
setPhone(response.phoneNumber);
|
||||
setCategoryId(response.categoryId.toString());
|
||||
setOrgSlug(getSlug(response.name));
|
||||
setOrgPublished(response.published);
|
||||
Promise.all([
|
||||
loadOrganizationsById({ id: id, sessionUser: SessionInfo.userId }),
|
||||
loadServicesByCompany(id),
|
||||
])
|
||||
.then((response) => {
|
||||
const [organization, loadedServices] = response;
|
||||
|
||||
setOrgName(organization.name);
|
||||
setOrgDescription(organization.description);
|
||||
setHeatMapFraction(organization.heatMapFraction.toString());
|
||||
setAppointmentTime(organization.appointmentTime.toString());
|
||||
setCancellationTime(organization.cancellationTime.toString());
|
||||
setAppointmentAlert(organization.appointmentAlert);
|
||||
setAreaCode(organization.phoneAreaCode);
|
||||
setPhone(organization.phoneNumber);
|
||||
setCategoryId(organization.categoryId.toString());
|
||||
setOrgSlug(getSlug(organization.name));
|
||||
setOrgPublished(organization.published);
|
||||
setShowPublicScores(organization.showPublicScores !== undefined ? organization.showPublicScores : true);
|
||||
setShowPublicOpinions(organization.showPublicOpinions !== undefined ? organization.showPublicOpinions : true);
|
||||
setShowPublicProfessionals(
|
||||
organization.showPublicProfessionals !== undefined
|
||||
? organization.showPublicProfessionals
|
||||
: true
|
||||
);
|
||||
setServices(loadedServices);
|
||||
setServicesShowPublicScores(
|
||||
loadedServices.every((service) => service.showPublicScores !== false)
|
||||
);
|
||||
setServicesShowPublicOpinions(
|
||||
loadedServices.every((service) => service.showPublicOpinions !== false)
|
||||
);
|
||||
setOriginalServicesShowPublicScores(
|
||||
loadedServices.every((service) => service.showPublicScores !== false)
|
||||
);
|
||||
setOriginalServicesShowPublicOpinions(
|
||||
loadedServices.every((service) => service.showPublicOpinions !== false)
|
||||
);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
setTemplateWapNotifId(response.templateWapNotifId);
|
||||
setTemplateWapAltaId(response.templateWapAltaId);
|
||||
setTemplateWapCancellationId(response.templateWapCancellationId);
|
||||
setTemplateWapNotifId(organization.templateWapNotifId);
|
||||
setTemplateWapAltaId(organization.templateWapAltaId);
|
||||
setTemplateWapCancellationId(organization.templateWapCancellationId);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
alert.showError(error.format());
|
||||
.catch((error: ApiError | Error) => {
|
||||
alert.showError(error instanceof ApiError ? error.format() : error.message);
|
||||
})
|
||||
.finally(() => {
|
||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||
@@ -270,6 +308,13 @@ export default function OrganizationEdit() {
|
||||
templateWapNotifId: templateWapNotifId === "" ? undefined : templateWapNotifId,
|
||||
templateWapAltaId: templateWapAltaId === "" ? undefined : templateWapAltaId,
|
||||
templateWapCancellationId: templateWapCancellationId === "" ? undefined : templateWapCancellationId,
|
||||
...(canEditPublicVisibilityFlags
|
||||
? {
|
||||
showPublicScores,
|
||||
showPublicOpinions,
|
||||
showPublicProfessionals,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
const schema = Yup.object().shape({
|
||||
@@ -335,10 +380,61 @@ export default function OrganizationEdit() {
|
||||
.then(() => {
|
||||
updateOrganizationsById(data)
|
||||
.then(() => {
|
||||
alert.showSuccess("Organizacion actualizada!");
|
||||
const servicesShowPublicScoresChanged =
|
||||
originalServicesShowPublicScores !== servicesShowPublicScores;
|
||||
const servicesShowPublicOpinionsChanged =
|
||||
originalServicesShowPublicOpinions !== servicesShowPublicOpinions;
|
||||
const changedServices =
|
||||
canEditPublicVisibilityFlags &&
|
||||
(servicesShowPublicScoresChanged || servicesShowPublicOpinionsChanged)
|
||||
? services
|
||||
: [];
|
||||
|
||||
return Promise.all(
|
||||
changedServices.map((service) =>
|
||||
updateService({
|
||||
id: service.id,
|
||||
companyId: id,
|
||||
name: service.name,
|
||||
description: service.description,
|
||||
originalPrice: service.originalPrice,
|
||||
limit: service.limit,
|
||||
length: service.length,
|
||||
color: service.color,
|
||||
fontColor: service.fontColor,
|
||||
fontShadowColor: service.fontShadowColor,
|
||||
sessionUser: SessionInfo.userId,
|
||||
showPublicScores: servicesShowPublicScoresChanged
|
||||
? servicesShowPublicScores
|
||||
: service.showPublicScores !== undefined
|
||||
? service.showPublicScores
|
||||
: true,
|
||||
showPublicOpinions: servicesShowPublicOpinionsChanged
|
||||
? servicesShowPublicOpinions
|
||||
: service.showPublicOpinions !== undefined
|
||||
? service.showPublicOpinions
|
||||
: true,
|
||||
})
|
||||
)
|
||||
).then(() => {
|
||||
const updatedServices = services.map((service) => ({
|
||||
...service,
|
||||
showPublicScores: servicesShowPublicScoresChanged
|
||||
? servicesShowPublicScores
|
||||
: service.showPublicScores,
|
||||
showPublicOpinions: servicesShowPublicOpinionsChanged
|
||||
? servicesShowPublicOpinions
|
||||
: service.showPublicOpinions,
|
||||
}));
|
||||
|
||||
setServices(updatedServices);
|
||||
setOriginalServicesShowPublicScores(servicesShowPublicScores);
|
||||
setOriginalServicesShowPublicOpinions(servicesShowPublicOpinions);
|
||||
alert.showSuccess("Organizacion actualizada!");
|
||||
});
|
||||
})
|
||||
.catch((error: ApiError) => {
|
||||
alert.showError(error.format());
|
||||
.catch((error: ApiError | Error) => {
|
||||
alert.showError(error instanceof ApiError ? error.format() : error.message);
|
||||
})
|
||||
.finally(() => {
|
||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||
@@ -484,6 +580,99 @@ export default function OrganizationEdit() {
|
||||
}}
|
||||
/>
|
||||
|
||||
<MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
|
||||
<b>Visibilidad pública:</b> Elegí si querés mostrar puntuaciones, opiniones y profesionales en el perfil público y las páginas de reserva. Disponible para planes pagos.
|
||||
</MaterialAlert>
|
||||
{!canEditPublicVisibilityFlags && (
|
||||
<MaterialAlert severity="warning" sx={{ marginTop: "10px" }}>
|
||||
Para modificar las opciones de visibilidad pública de opiniones, puntuaciones y profesionales de esta organización y sus servicios, el propietario de la organización necesita un plan pago.
|
||||
</MaterialAlert>
|
||||
)}
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "10px", marginTop: "10px" }}>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={showPublicScores}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setShowPublicScores(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar puntuaciones públicas
|
||||
</label>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={showPublicOpinions}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setShowPublicOpinions(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar opiniones públicas
|
||||
</label>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={showPublicProfessionals}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setShowPublicProfessionals(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar profesionales en el perfil público
|
||||
</label>
|
||||
{!canEditPublicVisibilityFlags && (
|
||||
<span style={{ color: "var(--gray-darkest)", fontSize: "13px" }}>
|
||||
Disponible para planes pagos.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{services.length > 0 && (
|
||||
<>
|
||||
<MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
|
||||
<b>Visibilidad pública de servicios:</b> Configurá si se muestran puntuaciones y opiniones en todos los servicios. Disponible para planes pagos.
|
||||
</MaterialAlert>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "10px",
|
||||
marginTop: "10px",
|
||||
}}
|
||||
>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={servicesShowPublicScores}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setServicesShowPublicScores(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar puntuaciones públicas de los servicios
|
||||
</label>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Checkbox
|
||||
checked={servicesShowPublicOpinions}
|
||||
disabled={!canEditPublicVisibilityFlags}
|
||||
onChange={(event) => {
|
||||
setServicesShowPublicOpinions(event.target.checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar opiniones públicas de los servicios
|
||||
</label>
|
||||
{!canEditPublicVisibilityFlags && (
|
||||
<span style={{ color: "var(--gray-darkest)", fontSize: "13px" }}>
|
||||
Para cambiar la visibilidad pública de los servicios necesitás un plan pago.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<TextObjectFilter
|
||||
placeholder="Categoría"
|
||||
content={categoryFilterContent}
|
||||
|
||||
@@ -12,14 +12,12 @@ import { disableSchedule, enableSchedule, loadSchedulesEnabled } from "../Org.Se
|
||||
import WeekInput from "@core/app/components/WeekInput/WeekInput";
|
||||
import dayjs from "dayjs";
|
||||
import "dayjs/locale/es";
|
||||
import weekday from "dayjs/plugin/weekday";
|
||||
import "dayjs/locale/es";
|
||||
import { SchedulesEnabledView } from "@models/SchedulesEnabled.type";
|
||||
import Avatar from "@components/Avatar/Avatar";
|
||||
import Button from "@core/app/components/Button/Button";
|
||||
import { useConfirmStore } from "@core/Store/Confirm.Store";
|
||||
import { getMondayWeekStart } from "@core/helpers/week";
|
||||
|
||||
dayjs.extend(weekday);
|
||||
dayjs.locale("es");
|
||||
|
||||
type UrlData = {
|
||||
@@ -34,7 +32,7 @@ export default function Schedules() {
|
||||
const SessionInfo = useSessionStore();
|
||||
const alert = useAlert();
|
||||
const confirm = useConfirmStore();
|
||||
const [startDate, setStartDate] = useState<dayjs.Dayjs>(dayjs().weekday(0));
|
||||
const [startDate, setStartDate] = useState<dayjs.Dayjs>(getMondayWeekStart());
|
||||
const [collaborators, setCollaborators] = useState<SchedulesEnabledView[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
+51
@@ -72,6 +72,8 @@ export default function OrganizationService() {
|
||||
const [serviceColor, setServiceColor] = useState("");
|
||||
const [serviceFontColor, setServiceFontColor] = useState("");
|
||||
const [serviceFontShadowColor, setServiceFontShadowColor] = useState("");
|
||||
const [showPublicScores, setShowPublicScores] = useState(true);
|
||||
const [showPublicOpinions, setShowPublicOpinions] = useState(true);
|
||||
|
||||
const [serviceDiscountType, setServiceDiscountType] = useState<string | undefined>(undefined);
|
||||
const [serviceDiscountValue, setServiceDiscountValue] = useState<number | undefined>(undefined);
|
||||
@@ -116,6 +118,8 @@ export default function OrganizationService() {
|
||||
|
||||
const [discountsFilterData, setDiscountsFilterData] = useState<TextObjectFilterResult[]>([]);
|
||||
const [discountId, setDiscountId] = useState<string>("");
|
||||
const ownerSubscription = SessionInfo.organizationSubscriptions[id];
|
||||
const canEditPublicRatingFlags = (ownerSubscription?.plan.price || 0) > 0;
|
||||
|
||||
useEffect(() => {
|
||||
eventHandler.setEventType(EVENT_TYPES.SLEEP);
|
||||
@@ -200,6 +204,12 @@ export default function OrganizationService() {
|
||||
limit: parseInt(serviceLimit),
|
||||
length: parseInt(serviceLength),
|
||||
sessionUser: SessionInfo.userId,
|
||||
...(canEditPublicRatingFlags
|
||||
? {
|
||||
showPublicScores,
|
||||
showPublicOpinions,
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
.then(() => {
|
||||
alert.showSuccess("Servicio creado");
|
||||
@@ -225,6 +235,12 @@ export default function OrganizationService() {
|
||||
fontColor: serviceFontColor,
|
||||
fontShadowColor: serviceFontShadowColor,
|
||||
sessionUser: SessionInfo.userId,
|
||||
...(canEditPublicRatingFlags
|
||||
? {
|
||||
showPublicScores,
|
||||
showPublicOpinions,
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
.then(() => {
|
||||
alert.showSuccess("Servicio Actualizado");
|
||||
@@ -255,6 +271,8 @@ export default function OrganizationService() {
|
||||
setServiceDiscountType(response.discountType);
|
||||
setServiceDiscountValue(response.discountValue);
|
||||
setServiceDiscountName(response.discountName);
|
||||
setShowPublicScores(response.showPublicScores !== undefined ? response.showPublicScores : true);
|
||||
setShowPublicOpinions(response.showPublicOpinions !== undefined ? response.showPublicOpinions : true);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
@@ -486,6 +504,39 @@ export default function OrganizationService() {
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
|
||||
<MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
|
||||
<b>Visibilidad pública:</b> Elegí si querés mostrar puntuaciones y opiniones de este servicio en páginas públicas. Disponible para planes pagos.
|
||||
</MaterialAlert>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "10px", marginTop: "10px" }}>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Switch
|
||||
checked={showPublicScores}
|
||||
disabled={!canEditPublicRatingFlags}
|
||||
onChange={(checked) => {
|
||||
setShowPublicScores(checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar puntuaciones públicas
|
||||
</label>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: "10px", fontWeight: 600 }}>
|
||||
<Switch
|
||||
checked={showPublicOpinions}
|
||||
disabled={!canEditPublicRatingFlags}
|
||||
onChange={(checked) => {
|
||||
setShowPublicOpinions(checked);
|
||||
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
|
||||
}}
|
||||
/>
|
||||
Mostrar opiniones públicas
|
||||
</label>
|
||||
{!canEditPublicRatingFlags && (
|
||||
<span style={{ color: "var(--gray-darkest)", fontSize: "13px" }}>
|
||||
Disponible para planes pagos.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Textbox
|
||||
name="servicePrice"
|
||||
placeholder="Precio del servicio"
|
||||
|
||||
@@ -13,6 +13,7 @@ import { useNavigation } from "@hooks/goto";
|
||||
import { useAlert } from "@core/Store/Alert.Store";
|
||||
import currency from "currency.js";
|
||||
import { getServiceImage } from "@core/helpers/getServiceImage";
|
||||
import ServiceRatingSummary from "@components/ServiceRatingSummary/ServiceRatingSummary";
|
||||
|
||||
import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
|
||||
import Dialog from "@mui/material/Dialog";
|
||||
@@ -113,6 +114,7 @@ export default function Org() {
|
||||
<div className={style.serviceInfo}>
|
||||
<h1>{data.name}</h1>
|
||||
<p>{data.description}</p>
|
||||
<ServiceRatingSummary serviceId={data.id} variant="row" showOpinionCount={false} />
|
||||
</div>
|
||||
<div className={style.serviceActions}>
|
||||
<span className={style.servicePrice}>{formatPrice(data.price)}</span>
|
||||
|
||||
@@ -85,6 +85,10 @@ export default function OrganizationEdit() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (wapView?.botSession === "ok") {
|
||||
return;
|
||||
}
|
||||
|
||||
wapServerBotGetQR({
|
||||
companyId: id,
|
||||
sessionUser: SessionInfo.userId,
|
||||
|
||||
@@ -15,7 +15,12 @@ import EventRepeatIcon from "@mui/icons-material/EventRepeat";
|
||||
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
|
||||
import ColorLensIcon from '@mui/icons-material/ColorLens';
|
||||
import PinDropIcon from '@mui/icons-material/PinDrop';
|
||||
import ReviewsIcon from '@mui/icons-material/Reviews';
|
||||
import NotificationsIcon from '@mui/icons-material/Notifications';
|
||||
import WhatsAppIcon from '@mui/icons-material/WhatsApp';
|
||||
import QrCode2Icon from '@mui/icons-material/QrCode2';
|
||||
import API from "@services/Api.Service";
|
||||
import { ReservationPeriodsSummary } from "@models/SchedulesEnabled.type";
|
||||
|
||||
|
||||
type FlowDefinition = {
|
||||
@@ -65,6 +70,42 @@ const AVAILABLE_FLOWS: FlowDefinition[] = [
|
||||
keywords: ["telefono", "contacto", "email", "whatsapp", "redes", "celular"],
|
||||
icon: AddCircleOutlineIcon
|
||||
},
|
||||
{
|
||||
id: "public-visibility",
|
||||
flowId: "public-visibility",
|
||||
title: "Visibilidad Pública",
|
||||
description: "Configura opiniones, puntuaciones y profesionales visibles para tus clientes.",
|
||||
category: "Negocio",
|
||||
keywords: ["opiniones", "puntuaciones", "calificaciones", "profesionales", "visibilidad", "reseñas", "publico"],
|
||||
icon: ReviewsIcon
|
||||
},
|
||||
{
|
||||
id: "public-link",
|
||||
flowId: "public-link",
|
||||
title: "Link Público y QR",
|
||||
description: "Obtén el enlace público de tu organización y un código QR para compartirlo.",
|
||||
category: "Negocio",
|
||||
keywords: ["link", "enlace", "url", "slug", "qr", "codigo qr", "publico", "reservas"],
|
||||
icon: QrCode2Icon
|
||||
},
|
||||
{
|
||||
id: "notifications",
|
||||
flowId: "notifications",
|
||||
title: "Notificaciones",
|
||||
description: "Configura canales de notificación, recordatorios y horario silencioso para la organización o un cliente.",
|
||||
category: "Comunicación",
|
||||
keywords: ["notificaciones", "canales", "whatsapp", "email", "sistema", "recordatorio", "silencioso", "cliente"],
|
||||
icon: NotificationsIcon
|
||||
},
|
||||
{
|
||||
id: "whatsapp-bot",
|
||||
flowId: "whatsapp-bot",
|
||||
title: "WhatsApp",
|
||||
description: "Configura tu bot de WhatsApp para enviar notificaciones automáticas a tus clientes.",
|
||||
category: "Comunicación",
|
||||
keywords: ["whatsapp", "bot", "notificaciones", "wap", "mensajes", "automatico", "qr"],
|
||||
icon: WhatsAppIcon
|
||||
},
|
||||
{
|
||||
id: "new-service",
|
||||
flowId: "onboarding-service&action=new-service",
|
||||
@@ -83,6 +124,15 @@ const AVAILABLE_FLOWS: FlowDefinition[] = [
|
||||
keywords: ["horarios", "disponibilidad", "semana", "apertura", "cierre", "jornada"],
|
||||
icon: CalendarMonthIcon
|
||||
},
|
||||
{
|
||||
id: "open-reservation-periods",
|
||||
flowId: "open-reservation-periods",
|
||||
title: "Extender Reservas",
|
||||
description: "Abrir más semanas para que tus clientes puedan reservar turnos.",
|
||||
category: "Horarios",
|
||||
keywords: ["reservas", "periodo", "agenda", "extender", "habilitar", "semanas"],
|
||||
icon: EventBusyIcon
|
||||
},
|
||||
{
|
||||
id: "override-schedule",
|
||||
flowId: "override-schedule",
|
||||
@@ -125,6 +175,7 @@ export default function AssistantHome() {
|
||||
|
||||
const [incompleteOrgs, setIncompleteOrgs] = React.useState<IncompleteOrgData[]>([]);
|
||||
const [incompleteCollaborators, setIncompleteCollaborators] = React.useState<any[]>([]);
|
||||
const [reservationPeriodAlerts, setReservationPeriodAlerts] = React.useState<Array<{ org: any; summary: ReservationPeriodsSummary }>>([]);
|
||||
const [isLoadingFlow, setIsLoadingFlow] = React.useState(true);
|
||||
const [searchQuery, setSearchQuery] = React.useState("");
|
||||
|
||||
@@ -134,9 +185,25 @@ export default function AssistantHome() {
|
||||
const response = await API.post<any[]>("companies/get-by-user", { sessionUser: SessionInfo.userId });
|
||||
const orgs = response || [];
|
||||
const newIncompleteOrgs: IncompleteOrgData[] = [];
|
||||
const reservationAlerts: Array<{ org: any; summary: ReservationPeriodsSummary }> = [];
|
||||
|
||||
if (orgs.length > 0) {
|
||||
for (const org of orgs) {
|
||||
if (org.isAdmin) {
|
||||
try {
|
||||
const summary = await API.post<ReservationPeriodsSummary>("schedules-enabled/reservation-periods/summary", {
|
||||
companyId: org.id || org._id,
|
||||
sessionUser: SessionInfo.userId
|
||||
});
|
||||
|
||||
if (summary && summary.status !== "open") {
|
||||
reservationAlerts.push({ org, summary });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error checking reservation periods", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (org.onboardingCompleted) continue;
|
||||
|
||||
const isNameMissing = !org.name || org.name.trim() === "";
|
||||
@@ -199,6 +266,7 @@ export default function AssistantHome() {
|
||||
}
|
||||
|
||||
setIncompleteOrgs(newIncompleteOrgs);
|
||||
setReservationPeriodAlerts(reservationAlerts);
|
||||
} else {
|
||||
setIncompleteOrgs([{
|
||||
org: null,
|
||||
@@ -206,6 +274,7 @@ export default function AssistantHome() {
|
||||
currentStepName: "Detalles del Negocio",
|
||||
flowToTrigger: "onboarding-org"
|
||||
}]);
|
||||
setReservationPeriodAlerts([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching organizations:", error);
|
||||
@@ -215,6 +284,7 @@ export default function AssistantHome() {
|
||||
currentStepName: "Detalles del Negocio",
|
||||
flowToTrigger: "onboarding-org"
|
||||
}]);
|
||||
setReservationPeriodAlerts([]);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -233,7 +303,7 @@ export default function AssistantHome() {
|
||||
}, [SessionInfo.metrics, SessionInfo.userId, router]);
|
||||
|
||||
const isSetupIncomplete = () => {
|
||||
return incompleteOrgs.length > 0 || incompleteCollaborators.length > 0;
|
||||
return incompleteOrgs.length > 0 || incompleteCollaborators.length > 0 || reservationPeriodAlerts.length > 0;
|
||||
};
|
||||
|
||||
const handleStartFlow = (flowId: string, companyId?: string) => {
|
||||
@@ -357,6 +427,46 @@ export default function AssistantHome() {
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{reservationPeriodAlerts.map(({ org, summary }, index) => {
|
||||
const orgId = org.id || org._id;
|
||||
const reservationPeriodCopy = summary.status === "missing"
|
||||
? {
|
||||
title: "Falta abrir el período de reservas",
|
||||
description: "Uno o más colaboradores todavía no tienen un período abierto para recibir reservas. Abrilo para que tus clientes puedan sacar turnos.",
|
||||
}
|
||||
: summary.status === "expired"
|
||||
? {
|
||||
title: "El período de reservas está vencido",
|
||||
description: "Uno o más colaboradores tienen el período de reservas vencido. Extendelo para que tus clientes puedan volver a reservar turnos.",
|
||||
}
|
||||
: {
|
||||
title: "El período de reservas está por finalizar",
|
||||
description: "El período abierto para reservas de uno o más colaboradores está por llegar a su fin. Extendelo para que tus clientes puedan seguir reservando turnos.",
|
||||
};
|
||||
|
||||
return (
|
||||
<div key={`reservation-period-${orgId || index}`} className={style.onboardingCard}>
|
||||
<div className={style.onboardingContent}>
|
||||
<div className={style.onboardingIcon}>
|
||||
<EventBusyIcon fontSize="large" style={{ color: "#fff" }} />
|
||||
</div>
|
||||
<div className={style.onboardingTexts} style={{ flex: 1 }}>
|
||||
<h3>{reservationPeriodCopy.title}</h3>
|
||||
<p>{reservationPeriodCopy.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
<AssistantButton
|
||||
text={isLoadingFlow ? "Cargando..." : "Extender período"}
|
||||
onClick={() => {
|
||||
if (!isLoadingFlow) {
|
||||
handleStartFlow("open-reservation-periods", orgId);
|
||||
}
|
||||
}}
|
||||
style={{ width: "100%", marginTop: "20px", height: "48px" }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.65);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
animation: overlayFadeIn 0.25s ease-out;
|
||||
}
|
||||
|
||||
@keyframes overlayFadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from { transform: translateY(100%); }
|
||||
to { transform: translateY(0); }
|
||||
}
|
||||
|
||||
.sheet {
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
max-height: min(80vh, 600px);
|
||||
background: linear-gradient(160deg, var(--wine-superdark) 0%, #1a0a2e 100%);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.55);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
animation: sheetIn 0.3s ease-out;
|
||||
color: white;
|
||||
}
|
||||
|
||||
@keyframes sheetIn {
|
||||
from { opacity: 0; transform: scale(0.97) translateY(8px); }
|
||||
to { opacity: 1; transform: scale(1) translateY(0); }
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 20px 20px 16px 20px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.header h2 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
letter-spacing: -0.01em;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.closeButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
border: none;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, color 0.2s, transform 0.25s;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.closeButton:hover {
|
||||
background: rgba(255, 42, 127, 0.15);
|
||||
color: var(--wine-red);
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.searchWrap {
|
||||
position: relative;
|
||||
margin: 0 20px 14px 20px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.searchInput {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 12px 44px 12px 44px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: white;
|
||||
font-size: 15px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color 0.25s, box-shadow 0.25s, background 0.25s;
|
||||
}
|
||||
|
||||
.searchInput::placeholder {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.searchInput:focus {
|
||||
border-color: var(--wine-red);
|
||||
box-shadow: 0 0 0 3px rgba(255, 42, 127, 0.18);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.clearButton {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: none;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border-radius: 50%;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: color 0.2s, background 0.2s;
|
||||
}
|
||||
|
||||
.clearButton:hover {
|
||||
color: white;
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
.results {
|
||||
flex: 1 1 auto;
|
||||
overflow-y: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
padding: 4px 14px 18px 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
|
||||
}
|
||||
|
||||
.results::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.results::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.clientCard {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
font-family: inherit;
|
||||
transition: transform 0.2s, border-color 0.2s, box-shadow 0.2s, background 0.2s;
|
||||
}
|
||||
|
||||
.clientCard:hover,
|
||||
.clientCard:focus-visible {
|
||||
transform: translateY(-1px);
|
||||
border-color: rgba(255, 255, 255, 0.18);
|
||||
background: rgba(255, 255, 255, 0.07);
|
||||
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.clientCardSelected {
|
||||
border-color: var(--wine-red);
|
||||
background: rgba(255, 42, 127, 0.08);
|
||||
box-shadow: 0 0 24px rgba(255, 42, 127, 0.2), inset 0 0 0 1px rgba(255, 42, 127, 0.25);
|
||||
}
|
||||
|
||||
.clientCardSelected:hover,
|
||||
.clientCardSelected:focus-visible {
|
||||
background: rgba(255, 42, 127, 0.12);
|
||||
border-color: var(--wine-red);
|
||||
}
|
||||
|
||||
.avatarWrap {
|
||||
position: relative;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.avatarFallback {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
letter-spacing: 0.02em;
|
||||
background: linear-gradient(135deg, var(--wine-red) 0%, var(--wine-dark) 100%);
|
||||
}
|
||||
|
||||
.avatarImg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 50%;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
|
||||
.cardBody {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.cardTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fullName {
|
||||
color: white;
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.bannedChip {
|
||||
flex-shrink: 0;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: #ffd1cc;
|
||||
background: rgba(255, 42, 42, 0.16);
|
||||
border: 1px solid rgba(255, 42, 42, 0.32);
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.subLine {
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.checkWrap {
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: white;
|
||||
background: linear-gradient(135deg, var(--wine-red) 0%, var(--wine-dark) 100%);
|
||||
box-shadow: 0 0 14px rgba(255, 42, 127, 0.45);
|
||||
}
|
||||
|
||||
.centerState {
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.emptyTitle {
|
||||
margin: 0;
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.emptyText {
|
||||
margin: 0;
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
max-width: 300px;
|
||||
}
|
||||
|
||||
.clearCta {
|
||||
margin-top: 6px;
|
||||
padding: 8px 16px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(255, 42, 127, 0.4);
|
||||
background: rgba(255, 42, 127, 0.1);
|
||||
color: white;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, border-color 0.2s;
|
||||
}
|
||||
|
||||
.clearCta:hover {
|
||||
background: rgba(255, 42, 127, 0.2);
|
||||
border-color: var(--wine-red);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
border: 3px solid rgba(255, 255, 255, 0.18);
|
||||
border-top-color: var(--wine-red);
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Mobile: bottom sheet */
|
||||
@media (max-width: 600px) {
|
||||
.overlay {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.sheet {
|
||||
max-width: 100%;
|
||||
width: 100%;
|
||||
max-height: 82vh;
|
||||
border-radius: 24px 24px 0 0;
|
||||
border-left: none;
|
||||
border-right: none;
|
||||
border-bottom: none;
|
||||
animation: slideUp 0.3s ease-out;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding: 18px 18px 12px 18px;
|
||||
}
|
||||
|
||||
.searchWrap {
|
||||
margin: 0 14px 12px 14px;
|
||||
}
|
||||
|
||||
.results {
|
||||
padding: 4px 10px 22px 10px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
"use client";
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
import style from "./ClientPicker.module.css";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import SearchIcon from "@mui/icons-material/Search";
|
||||
import CheckIcon from "@mui/icons-material/Check";
|
||||
import PersonOffOutlined from "@mui/icons-material/PersonOffOutlined";
|
||||
import { OrganizationClientView } from "@models/Clients.model";
|
||||
|
||||
export interface ClientPickerProps {
|
||||
open: boolean;
|
||||
clients: OrganizationClientView[];
|
||||
selectedId: string | null;
|
||||
onSelect: (id: string) => void;
|
||||
onClose: () => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
function formatPhone(c: OrganizationClientView): string {
|
||||
const parts = [c.phoneCountryCode, c.phoneAreaCode, c.phoneNumber]
|
||||
.filter(p => p != null && String(p).trim() !== "");
|
||||
if (parts.length === 0) return "";
|
||||
const joined = parts.map(p => String(p).trim()).join(" ");
|
||||
return joined.startsWith("+") ? joined : `+${joined}`;
|
||||
}
|
||||
|
||||
function getInitials(c: OrganizationClientView): string {
|
||||
const f = (c.firstName?.[0] || "").toUpperCase();
|
||||
const l = (c.lastName?.[0] || "").toUpperCase();
|
||||
return `${f}${l}` || "?";
|
||||
}
|
||||
|
||||
export default function ClientPicker({
|
||||
open,
|
||||
clients,
|
||||
selectedId,
|
||||
onSelect,
|
||||
onClose,
|
||||
loading,
|
||||
}: ClientPickerProps) {
|
||||
const [query, setQuery] = useState("");
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
setQuery("");
|
||||
const t = setTimeout(() => {
|
||||
inputRef.current?.focus();
|
||||
inputRef.current?.select();
|
||||
}, 80);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey);
|
||||
clearTimeout(t);
|
||||
};
|
||||
}, [open, onClose]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return clients;
|
||||
return clients.filter(c =>
|
||||
(c.firstName || "").toLowerCase().includes(q) ||
|
||||
(c.lastName || "").toLowerCase().includes(q) ||
|
||||
(c.fullName || "").toLowerCase().includes(q)
|
||||
);
|
||||
}, [clients, query]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const hasClients = clients.length > 0;
|
||||
const noResults = hasClients && filtered.length === 0 && query.trim() !== "";
|
||||
const searching = query.trim() !== "";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={style.overlay}
|
||||
onClick={onClose}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Seleccionar cliente"
|
||||
>
|
||||
<div
|
||||
className={style.sheet}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<header className={style.header}>
|
||||
<h2>Selecciona un cliente</h2>
|
||||
<button
|
||||
type="button"
|
||||
className={style.closeButton}
|
||||
onClick={onClose}
|
||||
aria-label="Cerrar"
|
||||
>
|
||||
<CloseIcon style={{ fontSize: 20 }} />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className={style.searchWrap}>
|
||||
<SearchIcon
|
||||
style={{
|
||||
fontSize: 22,
|
||||
position: "absolute",
|
||||
left: "14px",
|
||||
top: "50%",
|
||||
transform: "translateY(-50%)",
|
||||
color: "rgba(255,255,255,0.5)",
|
||||
pointerEvents: "none",
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
className={style.searchInput}
|
||||
placeholder="Buscar por nombre o apellido..."
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
aria-label="Buscar cliente"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
/>
|
||||
{searching && (
|
||||
<button
|
||||
type="button"
|
||||
className={style.clearButton}
|
||||
onClick={() => setQuery("")}
|
||||
aria-label="Limpiar búsqueda"
|
||||
>
|
||||
<CloseIcon style={{ fontSize: 16 }} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={style.results}>
|
||||
{loading ? (
|
||||
<div className={style.centerState}>
|
||||
<div className={style.spinner} />
|
||||
<p className={style.emptyText}>Cargando clientes…</p>
|
||||
</div>
|
||||
) : !hasClients ? (
|
||||
<div className={style.centerState}>
|
||||
<PersonOffOutlined style={{ fontSize: 46, color: "rgba(255,255,255,0.35)" }} />
|
||||
<p className={style.emptyTitle}>Sin clientes todavía</p>
|
||||
<p className={style.emptyText}>
|
||||
No hay clientes para esta organización todavía. Cuando alguien reserve un turno, aparecerá acá.
|
||||
</p>
|
||||
</div>
|
||||
) : noResults ? (
|
||||
<div className={style.centerState}>
|
||||
<p className={style.emptyTitle}>No encontramos clientes con ese nombre.</p>
|
||||
<button
|
||||
type="button"
|
||||
className={style.clearCta}
|
||||
onClick={() => setQuery("")}
|
||||
>
|
||||
Limpiar búsqueda
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
filtered.map(c => {
|
||||
const isSelected = c.id === selectedId;
|
||||
const sub = (c.email && c.email.trim() !== "") ? c.email : formatPhone(c);
|
||||
const avatar = c.avatar && c.avatar.trim() !== "";
|
||||
return (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
className={`${style.clientCard} ${isSelected ? style.clientCardSelected : ""}`}
|
||||
onClick={() => onSelect(c.id)}
|
||||
>
|
||||
<div className={style.avatarWrap}>
|
||||
<div className={style.avatarFallback}>{getInitials(c)}</div>
|
||||
{avatar && (
|
||||
<img
|
||||
src={c.avatar}
|
||||
alt={c.fullName}
|
||||
className={style.avatarImg}
|
||||
onError={(e) => {
|
||||
(e.currentTarget as HTMLImageElement).style.opacity = "0";
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={style.cardBody}>
|
||||
<div className={style.cardTitle}>
|
||||
<span className={style.fullName}>{c.fullName}</span>
|
||||
{c.banned && (
|
||||
<span className={style.bannedChip}>Suspendido</span>
|
||||
)}
|
||||
</div>
|
||||
{sub && <span className={style.subLine}>{sub}</span>}
|
||||
</div>
|
||||
|
||||
{isSelected && (
|
||||
<span className={style.checkWrap} aria-label="Seleccionado">
|
||||
<CheckIcon style={{ fontSize: 18 }} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+38
@@ -0,0 +1,38 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function OrganizationPicker({ allOrganizations, loadOrganizationContext }: Props) {
|
||||
return (
|
||||
<QuestionCard
|
||||
isActive={true}
|
||||
title="Selecciona la Organización"
|
||||
description="¿A qué negocio deseas aplicar estos cambios?"
|
||||
onNext={() => {}}
|
||||
disableNext={true}
|
||||
nextLabel=""
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
|
||||
{allOrganizations.map((org: any) => (
|
||||
<div
|
||||
key={org.id || org._id}
|
||||
onClick={() => loadOrganizationContext(org)}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: 'rgba(255,255,255,0.05)',
|
||||
border: '2px solid transparent',
|
||||
color: 'white', transition: 'all 0.2s ease',
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center'
|
||||
}}
|
||||
onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--wine-red)'}
|
||||
onMouseLeave={(e) => e.currentTarget.style.borderColor = 'transparent'}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>{org.name}</h4>
|
||||
<p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>{org.street} {org.streetNumber}, {org.city}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import React from "react";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function SuccessScreen(props: Props) {
|
||||
const { action, flowId, isStandaloneAction, router } = props;
|
||||
|
||||
const getSuccessMessage = () => {
|
||||
if (action === "new-service") return "Has agregado tu nuevo servicio exitosamente.";
|
||||
if (action === "edit-schedule") return "Tus horarios se han actualizado exitosamente.";
|
||||
if (action === "edit-location") return "La ubicación de tu negocio ha sido actualizada.";
|
||||
if (action === "edit-contact") return "Tus datos de contacto han sido actualizados.";
|
||||
if (action === "edit-appearance") return "La apariencia de tu negocio ha sido actualizada.";
|
||||
if (flowId === "override-schedule" || flowId === "disable-schedule") return "El horario especial ha sido guardado exitosamente.";
|
||||
if (flowId === "new-collaborator") return "El colaborador fue invitado exitosamente.";
|
||||
if (flowId === "setup-collaborator") return "El colaborador ha sido configurado exitosamente y ya puede comenzar a recibir reservas.";
|
||||
if (flowId === "notifications") return "La configuración de notificaciones se ha guardado exitosamente.";
|
||||
if (flowId === "whatsapp-bot") return "Tu bot de WhatsApp está configurado y funcionando. Tus clientes recibirán notificaciones automáticas por WhatsApp.";
|
||||
if (flowId === "open-reservation-periods") return "El período de reservas fue extendido exitosamente.";
|
||||
if (isStandaloneAction) return "Tus cambios se han guardado exitosamente.";
|
||||
return "Has configurado exitosamente tu negocio. Todo está listo para que empieces a recibir reservas y gestionar tu agenda como un profesional.";
|
||||
};
|
||||
|
||||
const successButtonStyle: React.CSSProperties = {
|
||||
padding: '16px 40px', fontSize: '18px', fontWeight: 'bold',
|
||||
background: 'white', color: 'var(--wine-red)', border: 'none',
|
||||
borderRadius: '30px', cursor: 'pointer',
|
||||
boxShadow: '0 4px 15px rgba(0,0,0,0.3)',
|
||||
transition: 'transform 0.2s, box-shadow 0.2s'
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh',
|
||||
background: 'linear-gradient(135deg, #1a0515 0%, #300018 100%)',
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
|
||||
zIndex: 9999, overflow: 'hidden', padding: '20px', boxSizing: 'border-box'
|
||||
}}>
|
||||
<div style={{
|
||||
width: '120px', height: '120px', borderRadius: '50%', background: 'rgba(255,255,255,0.1)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '30px',
|
||||
boxShadow: '0 0 50px rgba(255, 255, 255, 0.2)',
|
||||
animation: 'pulse 2s infinite ease-in-out'
|
||||
}}>
|
||||
<span style={{ fontSize: '60px' }}>🎉</span>
|
||||
</div>
|
||||
<h1 style={{ color: 'white', fontSize: '32px', marginBottom: '15px', textAlign: 'center', textShadow: '0 2px 10px rgba(0,0,0,0.5)' }}>
|
||||
¡Felicitaciones!
|
||||
</h1>
|
||||
<p style={{ color: 'rgba(255,255,255,0.8)', fontSize: '18px', maxWidth: '500px', textAlign: 'center', marginBottom: '40px', lineHeight: '1.5' }}>
|
||||
{getSuccessMessage()}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => {
|
||||
if (isStandaloneAction) router.push("/admin/assistant");
|
||||
else window.location.href = "/landing/dashboard";
|
||||
}}
|
||||
style={successButtonStyle}
|
||||
onMouseOver={(e) => {
|
||||
e.currentTarget.style.transform = 'translateY(-2px)';
|
||||
e.currentTarget.style.boxShadow = '0 6px 20px rgba(255,255,255,0.3)';
|
||||
}}
|
||||
onMouseOut={(e) => {
|
||||
e.currentTarget.style.transform = 'translateY(0)';
|
||||
e.currentTarget.style.boxShadow = '0 4px 15px rgba(0,0,0,0.3)';
|
||||
}}
|
||||
>
|
||||
{isStandaloneAction ? "Volver al Menú Principal" : "Ir a mi Panel de Control"}
|
||||
</button>
|
||||
<style>{`
|
||||
@keyframes pulse {
|
||||
0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.4); }
|
||||
70% { transform: scale(1.05); box-shadow: 0 0 0 30px rgba(255, 255, 255, 0); }
|
||||
100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NotificationChannel } from "@models/NotificationPreferences.model";
|
||||
|
||||
export const NOTIF_CHANNELS: { key: NotificationChannel; label: string; description: string }[] = [
|
||||
{ key: "whatsapp", label: "WhatsApp", description: "Mensajes automáticos por WhatsApp." },
|
||||
{ key: "email", label: "Email", description: "Correos electrónicos al cliente." },
|
||||
{ key: "system", label: "Sistema", description: "Notificaciones dentro de la plataforma." }
|
||||
];
|
||||
|
||||
export const NOTIF_REMINDER_PRESETS: { minutes: number; label: string }[] = [
|
||||
{ minutes: 60, label: "1 hora antes" },
|
||||
{ minutes: 180, label: "3 horas antes" },
|
||||
{ minutes: 360, label: "6 horas antes" },
|
||||
{ minutes: 720, label: "12 horas antes" },
|
||||
{ minutes: 1440, label: "1 día antes" },
|
||||
{ minutes: 2880, label: "2 días antes" }
|
||||
];
|
||||
|
||||
export const ALL_NOTIF_CHANNELS: NotificationChannel[] = ["whatsapp", "email", "system"];
|
||||
@@ -0,0 +1,9 @@
|
||||
import { ReservationPeriodDuration } from "@models/SchedulesEnabled.type";
|
||||
|
||||
export const reservationPeriodOptions: Array<ReservationPeriodDuration & { label: string }> = [
|
||||
{ unit: "week", value: 1, label: "1 semana" },
|
||||
{ unit: "week", value: 2, label: "2 semanas" },
|
||||
{ unit: "week", value: 3, label: "3 semanas" },
|
||||
{ unit: "month", value: 1, label: "1 mes" },
|
||||
{ unit: "month", value: 2, label: "2 meses" },
|
||||
];
|
||||
@@ -0,0 +1,292 @@
|
||||
import React from "react";
|
||||
import QuestionCard from "../../QuestionCard/QuestionCard";
|
||||
|
||||
type Props = any;
|
||||
|
||||
export default function DisableScheduleFlow(props: Props) {
|
||||
const { currentStepIndex, scheduleScope, setScheduleScope, targetEmployeeId, setTargetEmployeeId, allEmployees, handleNext, workingDaysMode, setWorkingDaysMode, openTime, setOpenTime, closeTime, setCloseTime, hasBreak, setHasBreak, breakStart, setBreakStart, breakEnd, setBreakEnd, isCreating, handleUpdateScheduleSubmit, handleOverrideScheduleSubmit, disableDuration, setDisableDuration, disableStartDate, setDisableStartDate, disableEndDate, setDisableEndDate, isFullDayDisabled, setIsFullDayDisabled, disableStartTime, setDisableStartTime, disableEndTime, setDisableEndTime, handleDisableScheduleSubmit } = props;
|
||||
return (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 0}
|
||||
title="Cerrar Agenda"
|
||||
description="¿A quiénes quieres aplicar esta inhabilitación de agenda?"
|
||||
onNext={() => {
|
||||
if (scheduleScope === "specific" && !targetEmployeeId) {
|
||||
alert("Por favor selecciona un colaborador.");
|
||||
return;
|
||||
}
|
||||
handleNext();
|
||||
}}
|
||||
disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
|
||||
<div
|
||||
onClick={() => setScheduleScope("me")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>Solo a mí</h4>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setScheduleScope("specific")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setScheduleScope("all")}
|
||||
style={{
|
||||
padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
|
||||
</div>
|
||||
|
||||
{scheduleScope === "specific" && (
|
||||
<div style={{ marginTop: '15px', width: '100%' }}>
|
||||
<select
|
||||
value={targetEmployeeId || ""}
|
||||
onChange={(e) => setTargetEmployeeId(e.target.value)}
|
||||
style={{
|
||||
width: '100%', padding: '12px', borderRadius: '8px',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
|
||||
outline: 'none', fontSize: '16px'
|
||||
}}
|
||||
>
|
||||
<option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
|
||||
{allEmployees.map((emp: any) => (
|
||||
<option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
|
||||
{emp.firstName} {emp.lastName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 1}
|
||||
title="Duración del Cierre"
|
||||
description="¿Por cuánto tiempo se cerrará la agenda?"
|
||||
onNext={handleNext}
|
||||
disableNext={!disableDuration}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
|
||||
<div
|
||||
onClick={() => setDisableDuration("one-day")}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: disableDuration === "one-day" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${disableDuration === "one-day" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Solo por un día
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setDisableDuration("multi-day")}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: disableDuration === "multi-day" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${disableDuration === "multi-day" ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Por varios días
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
{disableDuration === "one-day" && (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="Fecha del Cierre"
|
||||
description="Selecciona la fecha en la que no se recibirán turnos."
|
||||
onNext={handleNext}
|
||||
disableNext={!disableStartDate}
|
||||
>
|
||||
<div style={{ display: 'flex', width: '100%', justifyContent: 'center' }}>
|
||||
<input
|
||||
type="date"
|
||||
value={disableStartDate}
|
||||
onChange={(e) => setDisableStartDate(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '16px', fontFamily: 'sans-serif'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="Rango Horario"
|
||||
description="¿Esta inhabilitación aplica para todo el día o solo en una franja horaria?"
|
||||
onNext={() => {
|
||||
if (isFullDayDisabled) {
|
||||
handleDisableScheduleSubmit();
|
||||
} else if (disableStartTime && disableEndTime) {
|
||||
handleDisableScheduleSubmit();
|
||||
}
|
||||
}}
|
||||
nextLabel={isCreating ? "Guardando..." : "Cerrar Agenda"}
|
||||
disableNext={(!isFullDayDisabled && (!disableStartTime || !disableEndTime)) || isCreating}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
|
||||
<div style={{ display: 'flex', gap: '15px', width: '100%' }}>
|
||||
<div
|
||||
onClick={() => setIsFullDayDisabled(true)}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: isFullDayDisabled === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${isFullDayDisabled === true ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Todo el día
|
||||
</div>
|
||||
<div
|
||||
onClick={() => setIsFullDayDisabled(false)}
|
||||
style={{
|
||||
flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
|
||||
background: isFullDayDisabled === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
|
||||
border: `2px solid ${isFullDayDisabled === false ? 'var(--wine-red)' : 'transparent'}`,
|
||||
color: 'white', textAlign: 'center'
|
||||
}}
|
||||
>
|
||||
Franja Específica
|
||||
</div>
|
||||
</div>
|
||||
{!isFullDayDisabled && (
|
||||
<div style={{ display: 'flex', gap: '20px' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Desde (Hora)</label>
|
||||
<input
|
||||
type="time"
|
||||
value={disableStartTime}
|
||||
onChange={(e) => setDisableStartTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hasta (Hora)</label>
|
||||
<input
|
||||
type="time"
|
||||
value={disableEndTime}
|
||||
onChange={(e) => setDisableEndTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
)}
|
||||
|
||||
{disableDuration === "multi-day" && (
|
||||
<>
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 2}
|
||||
title="¿Cuándo inicia?"
|
||||
description="Selecciona la fecha y hora de inicio de la inhabilitación."
|
||||
onNext={handleNext}
|
||||
disableNext={!disableStartDate || !disableStartTime}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fecha de Inicio</label>
|
||||
<input
|
||||
type="date"
|
||||
value={disableStartDate}
|
||||
onChange={(e) => setDisableStartDate(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '16px', fontFamily: 'sans-serif'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hora de Inicio</label>
|
||||
<input
|
||||
type="time"
|
||||
value={disableStartTime}
|
||||
onChange={(e) => setDisableStartTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
|
||||
<QuestionCard
|
||||
isActive={currentStepIndex === 3}
|
||||
title="¿Cuándo termina?"
|
||||
description="Selecciona la fecha y hora en la que finaliza el cierre."
|
||||
onNext={handleDisableScheduleSubmit}
|
||||
nextLabel={isCreating ? "Guardando..." : "Cerrar Agenda"}
|
||||
disableNext={!disableEndDate || !disableEndTime || isCreating}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fecha de Fin</label>
|
||||
<input
|
||||
type="date"
|
||||
value={disableEndDate}
|
||||
onChange={(e) => setDisableEndDate(e.target.value)}
|
||||
min={disableStartDate}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '16px', fontFamily: 'sans-serif'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
|
||||
<label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hora de Fin</label>
|
||||
<input
|
||||
type="time"
|
||||
value={disableEndTime}
|
||||
onChange={(e) => setDisableEndTime(e.target.value)}
|
||||
style={{
|
||||
padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
|
||||
background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
|
||||
fontSize: '18px', fontFamily: 'monospace'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuestionCard>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user