18 Commits

Author SHA1 Message Date
horacio 28295e346c feat: add TypeScript definitions and utility functions for date formatting
- Created a global TypeScript declaration for the txadmin interface on the Window object.
- Implemented date formatting utilities using date-fns with Spanish locale support.
- Added TypeScript configuration files for app, Electron, and Node environments.
- Set up Vite configuration for React application.
2026-08-14 19:13:32 -03:00
horacio 9efb1792c7 feat: mejorar generación de reportes PDF con logo y tabla de movimientos 2026-08-13 20:25:00 -03:00
horacio 4ffb6a281f feat: support ARCA production environment with dynamic endpoint configuration and environment selection 2026-08-12 09:04:06 -03:00
horacio 6e7bf6e835 feat: implement organization fiscal profile management including ARCA activity search and fiscal data configuration 2026-08-10 13:05:09 -03:00
horacio ebd8096112 feat: add AFIP Factura C issuance support to ArcaCredentials and update cash flow model 2026-08-07 14:23:47 -03:00
horacio a93681357f feat: implement ARCA integration architecture including credential, fiscal profile, and invoice models, services, and onboarding flows 2026-08-06 19:36:53 -03:00
horacio 3b56d00fcb feat: add Nginx configuration file for production deployment with SSL support 2026-08-03 19:24:33 -03:00
horacio f34b99b87b refactor: modularize notification job creation to support reminder-only flow for recurring appointments 2026-08-02 21:38:32 -03:00
horacio 3145beca65 refactor: migrate touch and mouse click handling to native onClick event to improve interaction reliability 2026-07-30 18:24:52 -03:00
horacio 69a443dcfb style: update internal brochure design assets 2026-07-30 18:01:46 -03:00
horacio 446c65ff37 feat: add forced WAP server deletion support to clean up associated organizations and runtime bots 2026-07-30 17:58:10 -03:00
horacio cb830fcf01 feat: implement create functionality for WapServers across server, sysadmin, and CLI layers 2026-07-30 17:45:45 -03:00
horacio 146770a55d feat: implement organization insights dashboard with detailed metrics and collaboration data in sysadmin-cli 2026-07-30 17:33:57 -03:00
horacio 781310e36c chore: add development and production API host environment variables 2026-07-29 23:02:58 -03:00
horacio 446968c03f refactor: replace cron-based notification scheduling with continuous worker execution in Dockerfile 2026-07-29 15:36:02 -03:00
horacio 2a33f636a0 feat: add appointment notification sharing functionality via WhatsApp, email, and system clipboard 2026-07-29 14:38:13 -03:00
horacio 3d8911c093 feat: implement full CRUD and administrative management endpoints for WAP servers in the sysadmin API 2026-07-28 22:45:26 -03:00
horacio 0eb2e91e15 feat: add popup window support and improve external URI handling with intent parsing 2026-07-28 20:33:17 -03:00
133 changed files with 20361 additions and 240 deletions
+10
View File
@@ -24,6 +24,16 @@ server/*.local
server/build server/build
# server/uploads # server/uploads
# txadmin Electron app
txadmin/node_modules
txadmin/dist
txadmin/dist-electron
txadmin/release
txadmin/release-portable
txadmin/*.local
txadmin/*.tsbuildinfo
txadmin/node_modules/.tmp
# Editor directories and files # Editor directories and files
.vscode/* .vscode/*
!.vscode/extensions.json !.vscode/extensions.json
@@ -3,6 +3,8 @@ package com.hdrdevs.turnosxpress;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import android.os.Bundle;
import android.os.Message;
import android.content.ActivityNotFoundException;
import android.content.Intent; import android.content.Intent;
import android.net.Uri; import android.net.Uri;
import android.util.Log; import android.util.Log;
@@ -70,11 +72,10 @@ public class MainActivity extends AppCompatActivity {
webView.setWebViewClient(new WebViewClient() { webView.setWebViewClient(new WebViewClient() {
@Override @Override
public boolean shouldOverrideUrlLoading(WebView vw, WebResourceRequest request) { public boolean shouldOverrideUrlLoading(WebView vw, WebResourceRequest request) {
if (request.getUrl().toString().contains(home.getHost())) { if (shouldLoadInsideApp(request.getUrl(), home)) {
vw.loadUrl(request.getUrl().toString()); vw.loadUrl(request.getUrl().toString());
} else { } else {
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl()); openExternalUri(request.getUrl());
vw.getContext().startActivity(intent);
} }
return true; return true;
@@ -95,7 +96,7 @@ public class MainActivity extends AppCompatActivity {
@Override @Override
public boolean onShowFileChooser(WebView vw, ValueCallback<Uri[]> filePathCallback, public boolean onShowFileChooser(WebView vw, ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams) { FileChooserParams fileChooserParams) {
if (fileChooserCallback != null) { if (fileChooserCallback != null) {
fileChooserCallback.onReceiveValue(null); fileChooserCallback.onReceiveValue(null);
} }
@@ -112,6 +113,25 @@ public class MainActivity extends AppCompatActivity {
return true; 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) -> webView.setOnKeyListener((v, keyCode, event) ->
@@ -163,10 +183,40 @@ public class MainActivity extends AppCompatActivity {
private void handleURI(String uri) { private void handleURI(String uri) {
if (uri != null) { if (uri != null) {
Intent i = new Intent(Intent.ACTION_VIEW); openExternalUri(Uri.parse(uri.replaceFirst("^blob:", "")));
i.setData(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();
} }
} }
+2 -8
View File
@@ -29,14 +29,8 @@ COPY --from=builder /app/dist ./dist
# Copiar archivos de entorno a la raíz /app # Copiar archivos de entorno a la raíz /app
COPY --from=builder /app/.env* ./ COPY --from=builder /app/.env* ./
# Instalar bash y cron
RUN apk add --no-cache bash curl
# Crear carpeta de logs # Crear carpeta de logs
RUN mkdir -p /app/logs RUN mkdir -p /app/logs
# Agregar tarea de cron: todos los días a las (9-3)UTF = 6AM GMT-3 # Ejecutar el worker continuo de jobs de notificaciones
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 CMD ["node", "dist/index.js"]
# Mantener cron en primer plano
CMD ["crond", "-f", "-L", "/app/logs/cron.log"]
@@ -9,6 +9,7 @@ const BASE_RETRY_DELAY_MS = 5000;
const MAX_JITTER_MS = 3000; const MAX_JITTER_MS = 3000;
const THROTTLE_RETRY_DELAY_MS = 8000; const THROTTLE_RETRY_DELAY_MS = 8000;
const DEFAULT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000; const DEFAULT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
const CLEANUP_RETENTION_DAYS = 7;
const SUPPORTED_APPOINTMENT_NOTIFICATION_TYPES = new Set(["creation", "reminder", "cancellation"]); const SUPPORTED_APPOINTMENT_NOTIFICATION_TYPES = new Set(["creation", "reminder", "cancellation"]);
function resolveCleanupIntervalMs(): number { function resolveCleanupIntervalMs(): number {
@@ -41,6 +42,12 @@ export function buildStartOfDay(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate()); 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 { 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"); const value = job.id || job._id || job.get?.("_id");
if (value) return String(value); if (value) return String(value);
@@ -91,7 +98,7 @@ export class JobProcessor {
} }
private async cleanupOldJobs(now = new Date()): Promise<void> { private async cleanupOldJobs(now = new Date()): Promise<void> {
const cutoff = buildStartOfDay(now); const cutoff = buildCleanupCutoff(now);
try { try {
const deletedCount = await this.jobModel.deleteBeforeScheduledAt(cutoff); const deletedCount = await this.jobModel.deleteBeforeScheduledAt(cutoff);
@@ -147,7 +147,7 @@ export function buildNotificationText(params: {
} }
export async function resolveNotificationContent(job: INotificationJobDocument): Promise<ResolvedNotificationContent> { 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 { email, phoneNumber, userId, companyOwnerId } = job.payload;
const subject = job.channel === "email" const subject = job.channel === "email"
? job.payload.emailSubject ? job.payload.emailSubject
@@ -4,6 +4,8 @@ export type NotificationChannel = "whatsapp" | "email" | "system";
export type NotificationJobStatus = "pending" | "processing" | "sent" | "failed" | "cancelled"; export type NotificationJobStatus = "pending" | "processing" | "sent" | "failed" | "cancelled";
export type NotificationJobType = "creation" | "reminder" | "update" | "cancellation"; export type NotificationJobType = "creation" | "reminder" | "update" | "cancellation";
export const DELETABLE_NOTIFICATION_JOB_STATUSES: NotificationJobStatus[] = ["sent", "failed", "cancelled"];
export interface NotificationJobPayload { export interface NotificationJobPayload {
email?: string; email?: string;
phoneNumber?: string; phoneNumber?: string;
@@ -106,6 +108,7 @@ export class NotificationJobModel {
async deleteBeforeScheduledAt(cutoff: Date): Promise<number> { async deleteBeforeScheduledAt(cutoff: Date): Promise<number> {
const result = await this.notificationJobList.deleteMany({ const result = await this.notificationJobList.deleteMany({
scheduledAt: { $lt: cutoff }, scheduledAt: { $lt: cutoff },
status: { $in: DELETABLE_NOTIFICATION_JOB_STATUSES },
}).exec(); }).exec();
return result.deletedCount || 0; return result.deletedCount || 0;
@@ -1,5 +1,6 @@
import { dispatchEmail, dispatchWhatsApp } from "../ChannelDispatchers.js"; 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"; import { resolveNotificationContent } from "../NotificationContentResolver.js";
jest.mock("../ChannelDispatchers.js", () => ({ jest.mock("../ChannelDispatchers.js", () => ({
@@ -103,7 +104,7 @@ describe("JobProcessor", () => {
}); });
describe("old job cleanup", () => { 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 deleteBeforeScheduledAt = jest.fn().mockResolvedValue(3);
const now = new Date(2026, 6, 21, 15, 30, 0, 0); const now = new Date(2026, 6, 21, 15, 30, 0, 0);
@@ -112,7 +113,30 @@ describe("JobProcessor", () => {
now 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 () => { it("uses WhatsApp cancellation payload content for WhatsApp jobs", async () => {
const result = await resolveNotificationContent({ const result = await resolveNotificationContent({
appointmentId: "deleted-appointment-1", appointmentId: "deleted-appointment-1",
+67
View File
@@ -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
}
+5
View File
@@ -69,3 +69,8 @@ FILE_SERVER_URL = http://localhost:4000/
FILE_SERVER_URL_prod = https://files.turnosxpress.com.ar/ FILE_SERVER_URL_prod = https://files.turnosxpress.com.ar/
SYS_ADMIN_API_PUBLIC_KEY = keys/tx-sysadmin-public.key SYS_ADMIN_API_PUBLIC_KEY = keys/tx-sysadmin-public.key
ARCA_ENVIRONMENT=homologation
ARCA_WSAA_URL=https://wsaahomo.afip.gov.ar/ws/services/LoginCms
ARCA_WSFE_URL=https://wswhomo.afip.gov.ar/wsfev1/service.asmx
ARCA_CREDENTIALS_MASTER_KEY=ZmFrZS1kZXYtYXJjYS1tYXN0ZXIta2V5LTEyMzQ1Njc=
+5
View File
@@ -67,3 +67,8 @@ SYSTEM_KEY = ad7c956a-76bf-45hdr60-8a50-2ca7b2180997
FILE_SERVER_URL = https://files.turnosxpress.com.ar/ FILE_SERVER_URL = https://files.turnosxpress.com.ar/
SYS_ADMIN_API_PUBLIC_KEY = keys/tx-sysadmin-public.key SYS_ADMIN_API_PUBLIC_KEY = keys/tx-sysadmin-public.key
ARCA_ENVIRONMENT=production
ARCA_WSAA_URL=https://wsaa.afip.gov.ar/ws/services/LoginCms
ARCA_WSFE_URL=https://servicios1.afip.gov.ar/wsfev1/service.asmx
ARCA_CREDENTIALS_MASTER_KEY=ZmFrZS1kZXYtYXJjYS1tYXN0ZXIta2V5LTEyMzQ1Njc=
+103 -36
View File
@@ -20,6 +20,7 @@
"jsonwebtoken": "^9.0.3", "jsonwebtoken": "^9.0.3",
"mongoose": "8.8.3", "mongoose": "8.8.3",
"multer": "^1.4.5-lts.2", "multer": "^1.4.5-lts.2",
"node-forge": "^1.4.0",
"nodemailer": "^6.10.1", "nodemailer": "^6.10.1",
"sanitize-html": "^2.17.6", "sanitize-html": "^2.17.6",
"sharp": "^0.33.5", "sharp": "^0.33.5",
@@ -33,6 +34,7 @@
"@types/express": "^4.17.25", "@types/express": "^4.17.25",
"@types/jest": "^30.0.0", "@types/jest": "^30.0.0",
"@types/jsonwebtoken": "^9.0.10", "@types/jsonwebtoken": "^9.0.10",
"@types/node-forge": "^1.3.14",
"@types/nodemailer": "^6.4.24", "@types/nodemailer": "^6.4.24",
"@types/sanitize-html": "^2.16.1", "@types/sanitize-html": "^2.16.1",
"@types/socket.io": "^3.0.2", "@types/socket.io": "^3.0.2",
@@ -775,9 +777,6 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -794,9 +793,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -813,9 +809,6 @@
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -832,9 +825,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -851,9 +841,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -870,9 +857,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
@@ -889,9 +873,6 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -914,9 +895,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -939,9 +917,6 @@
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -964,9 +939,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"libc": [
"glibc"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -989,9 +961,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"libc": [
"musl"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -1014,9 +983,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"libc": [
"musl"
],
"license": "Apache-2.0", "license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2119,6 +2085,16 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.2.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.2.tgz",
"integrity": "sha512-Dd0BYtWgnWJKwO1jkmTrzofjK2QXXcai0dmtzvIBhcA+RsG5h8R3xlyta0kGOZRNfL9GuRtb1knmPEhQrePCEw==" "integrity": "sha512-Dd0BYtWgnWJKwO1jkmTrzofjK2QXXcai0dmtzvIBhcA+RsG5h8R3xlyta0kGOZRNfL9GuRtb1knmPEhQrePCEw=="
}, },
"node_modules/@types/node-forge": {
"version": "1.3.14",
"resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.14.tgz",
"integrity": "sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/nodemailer": { "node_modules/@types/nodemailer": {
"version": "6.4.24", "version": "6.4.24",
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.24.tgz", "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.24.tgz",
@@ -6672,6 +6648,38 @@
"url": "https://opencollective.com/mongoose" "url": "https://opencollective.com/mongoose"
} }
}, },
"node_modules/mongoose/node_modules/gaxios": {
"version": "5.1.3",
"resolved": "https://registry.npmjs.org/gaxios/-/gaxios-5.1.3.tgz",
"integrity": "sha512-95hVgBRgEIRQQQHIbnxBXeHbW4TqFk4ZDJW7wmVtvYar72FdhRIo1UGOLS2eRAKCPEdPBWu+M7+A33D9CdX9rA==",
"license": "Apache-2.0",
"optional": true,
"peer": true,
"dependencies": {
"extend": "^3.0.2",
"https-proxy-agent": "^5.0.0",
"is-stream": "^2.0.0",
"node-fetch": "^2.6.9"
},
"engines": {
"node": ">=12"
}
},
"node_modules/mongoose/node_modules/gcp-metadata": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-5.3.0.tgz",
"integrity": "sha512-FNTkdNEnBdlqF2oatizolQqNANMrcqJt6AAYt99B3y1aLLC8Hc5IOBb+ZnnzllodEEf6xMBp6wRcBbc16fa65w==",
"license": "Apache-2.0",
"optional": true,
"peer": true,
"dependencies": {
"gaxios": "^5.0.0",
"json-bigint": "^1.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/mongoose/node_modules/mongodb": { "node_modules/mongoose/node_modules/mongodb": {
"version": "6.10.0", "version": "6.10.0",
"resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.10.0.tgz", "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.10.0.tgz",
@@ -6723,6 +6731,56 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
}, },
"node_modules/mongoose/node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/mongoose/node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/mongoose/node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"license": "BSD-2-Clause",
"optional": true,
"peer": true
},
"node_modules/mongoose/node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/mpath": { "node_modules/mpath": {
"version": "0.9.0", "version": "0.9.0",
"resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz",
@@ -6892,6 +6950,15 @@
"url": "https://opencollective.com/node-fetch" "url": "https://opencollective.com/node-fetch"
} }
}, },
"node_modules/node-forge": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.0.tgz",
"integrity": "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==",
"license": "(BSD-3-Clause OR GPL-2.0)",
"engines": {
"node": ">= 6.13.0"
}
},
"node_modules/node-int64": { "node_modules/node-int64": {
"version": "0.4.0", "version": "0.4.0",
"resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
+2
View File
@@ -19,6 +19,7 @@
"@types/express": "^4.17.25", "@types/express": "^4.17.25",
"@types/jest": "^30.0.0", "@types/jest": "^30.0.0",
"@types/jsonwebtoken": "^9.0.10", "@types/jsonwebtoken": "^9.0.10",
"@types/node-forge": "^1.3.14",
"@types/nodemailer": "^6.4.24", "@types/nodemailer": "^6.4.24",
"@types/sanitize-html": "^2.16.1", "@types/sanitize-html": "^2.16.1",
"@types/socket.io": "^3.0.2", "@types/socket.io": "^3.0.2",
@@ -42,6 +43,7 @@
"jsonwebtoken": "^9.0.3", "jsonwebtoken": "^9.0.3",
"mongoose": "8.8.3", "mongoose": "8.8.3",
"multer": "^1.4.5-lts.2", "multer": "^1.4.5-lts.2",
"node-forge": "^1.4.0",
"nodemailer": "^6.10.1", "nodemailer": "^6.10.1",
"sanitize-html": "^2.17.6", "sanitize-html": "^2.17.6",
"sharp": "^0.33.5", "sharp": "^0.33.5",
@@ -54,6 +54,15 @@ export type CreateImmediateAppointmentNotificationJobsParams = {
type: APPOINTMENT_NOTIFICATION_TYPE; type: APPOINTMENT_NOTIFICATION_TYPE;
}; };
export type AppointmentNotificationPreviewParams = CreateImmediateAppointmentNotificationJobsParams;
export type AppointmentNotificationPreviewResult = {
subject: string;
message: string;
emailMessage: string;
wapMessage: string;
};
export type MoveAppointmentParams = { export type MoveAppointmentParams = {
id: string; id: string;
companyId: string; companyId: string;
@@ -328,6 +337,7 @@ export interface IAppointmentsManager {
sendWapNotification(data: SendAppointmentNotificationParams): Promise<void>; sendWapNotification(data: SendAppointmentNotificationParams): Promise<void>;
sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void>; sendEmailNotification(data: SendAppointmentNotificationParams): Promise<void>;
createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void>; createImmediateNotificationJobs(data: CreateImmediateAppointmentNotificationJobsParams): Promise<void>;
getAppointmentNotificationPreview(data: AppointmentNotificationPreviewParams): Promise<AppointmentNotificationPreviewResult>;
sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void>; sendWapSystemNotification(data: SendWapSystemNotificationParams): Promise<void>;
deleteAppointmentsByCompany(data: DeleteAppointmentsByCompanyParams): Promise<void>; deleteAppointmentsByCompany(data: DeleteAppointmentsByCompanyParams): Promise<void>;
changeEmployeeToOwner(data: ChangeEmployeeToOwnerParams): Promise<void>; changeEmployeeToOwner(data: ChangeEmployeeToOwnerParams): Promise<void>;
+138 -34
View File
@@ -7,6 +7,7 @@ import {
AppointmentEvent, AppointmentEvent,
AppointmentEventByClient, AppointmentEventByClient,
AppointmentNotificationIntent, AppointmentNotificationIntent,
AppointmentNotificationPreviewResult,
ChangeEmployeeToOwnerParams, ChangeEmployeeToOwnerParams,
CountAppointmentsByMonthParams, CountAppointmentsByMonthParams,
CreateAppointmentParams, CreateAppointmentParams,
@@ -532,47 +533,18 @@ class AppointmentManager implements IAppointmentsManager {
} }
//Create jobs for email and whatsapp notifications //Create jobs for email and whatsapp notifications
if (notification && newAppointment.id) { if (this.shouldCreateCustomerNotificationJobs(notification, data.repeatId) && newAppointment.id) {
const emailContent = await this.tryToSendNotification({ await this.createAppointmentNotificationJobs({
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), appointmentId: String(newAppointment.id),
companyId: String(companyCheck._id), companyId: String(companyCheck._id),
clientId: String(checkClient._id), clientId: String(checkClient._id),
clientUserId: checkClient.userId ? String(checkClient.userId) : undefined, clientUserId: checkClient.userId ? String(checkClient.userId) : undefined,
clientEmail: checkClient.email, clientEmail: checkClient.email,
clientPhoneNumber, client: checkClient,
companyOwnerId: String(companyCheck.ownerId), companyOwnerId: String(companyCheck.ownerId),
companyName: companyCheck.name, companyName: companyCheck.name,
appointmentStart: new Date(data.start), appointmentStart: new Date(data.start),
emailMessage: emailContent.message, notification,
wapMessage: wapContent.message,
reminderEmailMessage: reminderEmailContent.message,
reminderWapMessage: reminderWapContent.message,
}); });
} }
@@ -2238,7 +2210,6 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
reminderWapMessage: string; reminderWapMessage: string;
}): Promise<void> { }): Promise<void> {
const systemSubject = `Turno reservado en ${data.companyName}`; const systemSubject = `Turno reservado en ${data.companyName}`;
const reminderSystemSubject = `Recordatorio de turno en ${data.companyName}`;
const payload = { const payload = {
email: data.clientEmail, email: data.clientEmail,
@@ -2262,6 +2233,93 @@ public async updateAppointment(data: UpdateAppointmentParams): Promise<void> {
payload, 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({ await this.jobService.createReminderJobs({
companyId: data.companyId, companyId: data.companyId,
clientId: data.clientId, clientId: data.clientId,
@@ -2903,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> { public async sendWapNotification(data: SendAppointmentNotificationParams): Promise<void> {
if (!data.sessionUser) { if (!data.sessionUser) {
throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción"); throw new Error("No se ha encontrado el usuario o no tiene permisos para realizar esta acción");
@@ -681,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 () => { it("falls back to organization WAP Alta template for email when email Alta is absent", async () => {
(CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({ (CompaniesManager.companies.findOne as jest.Mock).mockResolvedValue({
_id: "company-001", _id: "company-001",
@@ -0,0 +1,134 @@
import { TextObjectFilterResult } from "../TextObjectFilter.model";
export type ArcaActivity = {
code: string;
description: string;
};
export const ARCA_ACTIVITIES: ArcaActivity[] = [
{ code: "011111", description: "Cultivo de arroz" },
{ code: "011112", description: "Cultivo de trigo" },
{ code: "011119", description: "Cultivo de cereales n.c.p., excepto los de uso forrajero" },
{ code: "011121", description: "Cultivo de maíz" },
{ code: "011129", description: "Cultivo de cereales de uso forrajero n.c.p." },
{ code: "011130", description: "Cultivo de oleaginosas, excepto soja" },
{ code: "011140", description: "Cultivo de pastos de uso forrajero" },
{ code: "011211", description: "Cultivo de papa, batata y mandioca" },
{ code: "011221", description: "Cultivo de tomate" },
{ code: "011229", description: "Cultivo de bulbos, brotes, raíces y hortalizas de fruto n.c.p." },
{ code: "011240", description: "Cultivo de legumbres" },
{ code: "012110", description: "Cultivo de vid para vinificar" },
{ code: "012121", description: "Cultivo de uva de mesa" },
{ code: "012200", description: "Cultivo de frutas cítricas" },
{ code: "012311", description: "Cultivo de manzana y pera" },
{ code: "012320", description: "Cultivo de frutas de carozo" },
{ code: "012410", description: "Cultivo de frutas tropicales y subtropicales" },
{ code: "012510", description: "Cultivo de frutas secas" },
{ code: "013011", description: "Producción de semillas híbridas de cereales y oleaginosas" },
{ code: "013019", description: "Producción de semillas varietales o autofecundadas de cereales, oleaginosas, y forrajeras" },
{ code: "014113", description: "Cría de ganado bovino, excepto la realizada en cabañas y para la producción de leche" },
{ code: "014114", description: "Invernada de ganado bovino excepto el engorde en corrales (feed-lot)" },
{ code: "014115", description: "Engorde en corrales (feed-lot)" },
{ code: "014211", description: "Cría de ganado equino, excepto la realizada en haras" },
{ code: "014300", description: "Cría de ganado camélido" },
{ code: "014410", description: "Cría de ganado ovino, excepto en cabañas y para la producción de lana" },
{ code: "014420", description: "Cría de ganado ovino realizada en cabañas" },
{ code: "014430", description: "Cría de ganado ovino para la producción de lana" },
{ code: "014510", description: "Cría de ganado porcino, excepto la realizada en cabañas" },
{ code: "014520", description: "Cría de ganado porcino realizada en cabañas" },
{ code: "014610", description: "Producción de leche bovina" },
{ code: "014620", description: "Producción de leche de oveja y de cabra" },
{ code: "014710", description: "Producción de huevos" },
{ code: "014720", description: "Cría de aves para producción de carnes" },
{ code: "014740", description: "Producción de pollitos BB" },
{ code: "014810", description: "Cría de abejas" },
{ code: "014820", description: "Producción de pelos de ganado" },
{ code: "014910", description: "Cría de animales para la obtención de pieles y cueros" },
{ code: "014990", description: "Cría de animales y obtención de productos de origen animal n.c.p." },
{ code: "016111", description: "Servicios de labranza, siembra, transplante y cuidados culturales" },
{ code: "016112", description: "Servicios de pulverización, desinfección y fumigación terrestre" },
{ code: "016113", description: "Servicios de pulverización, desinfección y fumigación aérea" },
{ code: "016119", description: "Servicios de maquinaria agrícola n.c.p., excepto los de cosecha mecánica" },
{ code: "016120", description: "Servicios de cosecha mecánica" },
{ code: "016130", description: "Servicios de contratistas de mano de obra agrícola" },
{ code: "016140", description: "Servicios de post cosecha" },
{ code: "016150", description: "Servicios de procesamiento de semillas para su siembra" },
{ code: "016190", description: "Servicios de apoyo agrícolas n.c.p." },
{ code: "016210", description: "Inseminación artificial y servicios n.c.p. para mejorar la reproducción de los animales y el rendimiento de sus productos" },
{ code: "016220", description: "Servicios de contratistas de mano de obra pecuaria" },
{ code: "016230", description: "Servicios de esquila de animales" },
{ code: "016291", description: "Servicios para el control de plagas, baños parasiticidas, etc." },
{ code: "016292", description: "Albergue y cuidado de animales de terceros" },
{ code: "016299", description: "Servicios de apoyo pecuarios n.c.p." },
{ code: "551010", description: "Servicios de alojamiento por hora" },
{ code: "551021", description: "Servicios de alojamiento en pensiones" },
{ code: "551022", description: "Servicios de alojamiento en hoteles, hosterías y residenciales similares, excepto por hora, que incluyen servicio de restaurante al público" },
{ code: "551023", description: "Servicios de alojamiento en hoteles, hosterías y residenciales similares, excepto por hora, que no incluyen servicio de restaurante al público" },
{ code: "561011", description: "Servicios de restaurantes y cantinas sin espectáculo" },
{ code: "561012", description: "Servicios de restaurantes y cantinas con espectáculo" },
{ code: "561013", description: "Servicios de fast food y locales de venta de comidas y bebidas al paso" },
{ code: "561014", description: "Servicios de expendio de bebidas en bares" },
{ code: "561019", description: "Servicios de expendio de comidas y bebidas en establecimientos con servicio de mesa y/o en mostrador n.c.p." },
{ code: "620100", description: "Servicios de consultores en informática y suministros de programas de informática" },
{ code: "620200", description: "Servicios de consultores en equipo de informática" },
{ code: "620300", description: "Servicios de consultores en tecnología de la información" },
{ code: "620900", description: "Servicios de informática n.c.p." },
{ code: "681098", description: "Servicios inmobiliarios realizados por cuenta propia, con bienes urbanos propios o arrendados n.c.p." },
{ code: "681099", description: "Servicios inmobiliarios realizados por cuenta propia, con bienes rurales propios o arrendados n.c.p." },
{ code: "691001", description: "Servicios jurídicos" },
{ code: "692000", description: "Servicios de contabilidad, auditoría y asesoría fiscal" },
{ code: "702091", description: "Servicios de asesoramiento, dirección y gestión empresarial realizados por integrantes de los órganos de administración y/o fiscalización en sociedades anónimas" },
{ code: "702092", description: "Servicios de asesoramiento, dirección y gestión empresarial realizados por integrantes de cuerpos de dirección en sociedades excepto las anónimas" },
{ code: "702099", description: "Servicios de asesoramiento, dirección y gestión empresarial n.c.p." },
{ code: "749009", description: "Actividades profesionales, científicas y técnicas n.c.p." },
{ code: "851010", description: "Guarderías y jardines maternales" },
{ code: "851020", description: "Enseñanza inicial, jardín de infantes y primaria" },
{ code: "852100", description: "Enseñanza secundaria de formación general" },
{ code: "852200", description: "Enseñanza secundaria de formación técnica y profesional" },
{ code: "853100", description: "Enseñanza terciaria" },
{ code: "853201", description: "Enseñanza universitaria excepto formación de posgrado" },
{ code: "853300", description: "Formación de posgrado" },
{ code: "854910", description: "Enseñanza de idiomas" },
{ code: "854920", description: "Enseñanza de cursos relacionados con informática" },
{ code: "854930", description: "Enseñanza para adultos, excepto discapacitados" },
{ code: "854940", description: "Enseñanza especial y para discapacitados" },
{ code: "854950", description: "Enseñanza de gimnasia, deportes y actividades físicas" },
{ code: "854960", description: "Enseñanza artística" },
{ code: "854990", description: "Servicios de enseñanza n.c.p." },
{ code: "855000", description: "Servicios de apoyo a la educación" },
{ code: "861010", description: "Servicios de internación" },
{ code: "862110", description: "Servicios de consulta médica" },
{ code: "862120", description: "Servicios de atención médica en dispensarios, salitas, vacunatorios y otros locales de atención primaria de la salud" },
{ code: "862130", description: "Servicios de atención médica en otros establecimientos n.c.p." },
{ code: "862200", description: "Servicios odontológicos" },
{ code: "869010", description: "Servicios de prácticas de diagnóstico en laboratorios" },
{ code: "869090", description: "Servicios relacionados con la salud humana n.c.p." },
{ code: "900011", description: "Producción de espectáculos teatrales y musicales" },
{ code: "900021", description: "Composición y representación de obras teatrales, musicales y artísticas" },
{ code: "931010", description: "Servicios de organización, dirección y gestión de prácticas deportivas y explotación de las instalaciones" },
{ code: "931020", description: "Servicios prestados por profesionales y técnicos para la realización de prácticas deportivas" },
{ code: "960201", description: "Servicios de peluquería" },
{ code: "960202", description: "Servicios de tratamiento de belleza, excepto los de peluquería" },
{ code: "960990", description: "Servicios personales n.c.p." },
];
export const findArcaActivityByCode = (code: string): ArcaActivity | undefined => {
return ARCA_ACTIVITIES.find((activity) => activity.code === code.trim());
};
export const filterArcaActivities = (name?: string): TextObjectFilterResult[] => {
const normalizedFilter = (name || "").trim().toLowerCase();
return ARCA_ACTIVITIES.filter((activity) => {
if (!normalizedFilter) return true;
return (
activity.code.includes(normalizedFilter) ||
activity.description.toLowerCase().includes(normalizedFilter)
);
}).map((activity) => ({
id: activity.code,
name: activity.description,
description: activity.code,
}));
};
@@ -0,0 +1,83 @@
import { Document, FilterQuery, Model, Schema, model } from "mongoose";
import {
ARCA_CREDENTIAL_STATUS,
CreateArcaCredentialParams,
FindArcaCredentialsParams,
IArcaCredential,
IArcaCredentialsAdapter,
UpdateArcaCredentialParams,
} from "./ArcaCredentials.Interface";
export interface IArcaCredentialDocument extends Omit<IArcaCredential, "id">, Document {}
export class ArcaCredentialsAdapterMongoose implements IArcaCredentialsAdapter {
schema: Schema;
arcaCredentialList: Model<IArcaCredentialDocument>;
constructor() {
this.schema = new Schema({
companyId: {
type: Schema.Types.ObjectId,
required: true,
ref: "Company",
unique: true,
index: true,
},
csrPem: { type: String, required: false },
certificatePem: { type: String, required: false },
encryptedPrivateKey: { type: String, required: true },
privateKeyIv: { type: String, required: true },
privateKeyAuthTag: { type: String, required: true },
encryptionKeyVersion: { type: String, required: false, default: "v1" },
status: {
type: String,
required: true,
enum: Object.values(ARCA_CREDENTIAL_STATUS),
index: true,
},
certificateValidFrom: { type: Date, required: false },
certificateValidTo: { type: Date, required: false },
lastValidationError: { type: String, required: false },
createdAt: { type: Date, required: true, default: Date.now },
updatedAt: { type: Date, required: true, default: Date.now },
});
this.arcaCredentialList = model<IArcaCredentialDocument>("ArcaCredential", this.schema);
}
public async create(data: CreateArcaCredentialParams): Promise<IArcaCredential> {
return await this.arcaCredentialList.create(data);
}
private buildSearchCriteria(filters: FindArcaCredentialsParams): FilterQuery<IArcaCredential> {
const searchCriteria: FilterQuery<IArcaCredential> = {};
if (filters.id) searchCriteria._id = filters.id;
if (filters.companyId) searchCriteria.companyId = filters.companyId;
if (filters.status) searchCriteria.status = filters.status;
return searchCriteria;
}
public async find(filters: FindArcaCredentialsParams): Promise<IArcaCredential[]> {
const searchCriteria = this.buildSearchCriteria(filters);
return this.arcaCredentialList.find(searchCriteria).sort({ createdAt: -1 }).exec();
}
public async findOne(filters: FindArcaCredentialsParams): Promise<IArcaCredentialDocument | null> {
const searchCriteria = this.buildSearchCriteria(filters);
return this.arcaCredentialList.findOne(searchCriteria).exec();
}
public async update(data: UpdateArcaCredentialParams): Promise<IArcaCredentialDocument | null> {
const { id, companyId, sessionUser, ...updateData } = data;
if (!id && !companyId) {
throw new Error("Se requiere un identificador para actualizar las credenciales ARCA");
}
return this.arcaCredentialList
.findOneAndUpdate(this.buildSearchCriteria({ id, companyId, sessionUser }), updateData, { new: true })
.exec();
}
}
@@ -0,0 +1,198 @@
import { IArcaCredentialDocument } from "./ArcaCredentials.Adapter.Mongoose";
import { ARCA_WSAA_ENVIRONMENT, ARCA_WSAA_SERVICE } from "../ArcaWsaaTokens/ArcaWsaaTokens.Interface";
export enum ARCA_CREDENTIAL_STATUS {
CSR_GENERATED = "CSR_GENERATED",
CERTIFICATE_UPLOADED = "CERTIFICATE_UPLOADED",
READY = "READY",
INVALID = "INVALID",
DISABLED = "DISABLED",
}
export type GenerateArcaCredentialCsrParams = {
companyId: string;
sessionUser: string;
};
export type UploadArcaCredentialCertificateParams = {
companyId: string;
certificatePem: string;
sessionUser: string;
};
export type TestArcaWsaaLoginParams = {
companyId: string;
sessionUser: string;
};
export type ArcaWsaaLoginTestResult = {
status: "cached" | "created";
environment: ARCA_WSAA_ENVIRONMENT;
service: ARCA_WSAA_SERVICE;
endpoints: ArcaEndpointMetadata;
expirationTime: Date;
cached: boolean;
};
export type ArcaWsfeLastVoucherParams = {
companyId: string;
sessionUser: string;
};
export type ArcaWsfeLastVoucherResult = {
environment: ARCA_WSAA_ENVIRONMENT;
service: ARCA_WSAA_SERVICE;
endpoints: ArcaEndpointMetadata;
pointOfSale: number;
voucherType: 11;
lastVoucherNumber: number;
};
export type ArcaWsfeIssueFacturaCParams = {
companyId: string;
amount: number;
billingDate: Date;
servicePeriodFrom: Date;
servicePeriodTo: Date;
paymentDueDate: Date;
receiverDocumentType?: number | string;
receiverDocumentNumber?: number | string;
sessionUser: string;
};
export type ArcaWsfeIssueFacturaCResult = {
environment: ARCA_WSAA_ENVIRONMENT;
service: ARCA_WSAA_SERVICE;
endpoints: ArcaEndpointMetadata;
pointOfSale: number;
voucherType: 11;
voucherNumber: number;
cae: string;
caeExpiresAt: Date;
};
export type ArcaWsfeIssueFacturaCAttempt = {
pointOfSale: number;
voucherType: 11;
voucherNumber: number;
};
export type ArcaWsfeDiagnosticsParams = {
companyId: string;
sessionUser: string;
};
export type ArcaEndpointMetadata = {
wsaaHost?: string;
wsfeHost?: string;
};
export type ArcaWsfeDiagnosticsResult = {
environment: ARCA_WSAA_ENVIRONMENT;
service: ARCA_WSAA_SERVICE;
endpoints: ArcaEndpointMetadata;
dummy: {
ok: boolean;
appServer?: string;
dbServer?: string;
authServer?: string;
error?: string;
};
voucherTypes: {
ok: boolean;
count?: number;
includesFacturaC?: boolean;
error?: string;
};
pointsOfSale: {
ok: boolean;
points?: number[];
includesConfiguredPointOfSale?: boolean;
configuredPointOfSale: number;
error?: string;
};
lastVoucher: {
ok: boolean;
pointOfSale: number;
voucherType: 11;
lastVoucherNumber?: number;
error?: string;
};
};
export type FindArcaCredentialsParams = {
id?: string;
companyId?: string;
status?: ARCA_CREDENTIAL_STATUS;
sessionUser?: string;
};
export type CreateArcaCredentialParams = {
companyId: string;
csrPem?: string;
certificatePem?: string;
encryptedPrivateKey: string;
privateKeyIv: string;
privateKeyAuthTag: string;
encryptionKeyVersion?: string;
status: ARCA_CREDENTIAL_STATUS;
certificateValidFrom?: Date;
certificateValidTo?: Date;
lastValidationError?: string;
createdAt: Date;
updatedAt: Date;
};
export type UpdateArcaCredentialParams = FindArcaCredentialsParams & {
csrPem?: string;
certificatePem?: string;
encryptedPrivateKey?: string;
privateKeyIv?: string;
privateKeyAuthTag?: string;
encryptionKeyVersion?: string;
status?: ARCA_CREDENTIAL_STATUS;
certificateValidFrom?: Date;
certificateValidTo?: Date;
lastValidationError?: string;
updatedAt: Date;
};
export interface IArcaCredential {
id?: string;
companyId: string;
csrPem?: string;
certificatePem?: string;
encryptedPrivateKey: string;
privateKeyIv: string;
privateKeyAuthTag: string;
encryptionKeyVersion?: string;
status: ARCA_CREDENTIAL_STATUS;
certificateValidFrom?: Date;
certificateValidTo?: Date;
lastValidationError?: string;
createdAt: Date;
updatedAt: Date;
}
export type ArcaCredentialView = Omit<
IArcaCredential,
"encryptedPrivateKey" | "privateKeyIv" | "privateKeyAuthTag"
>;
export interface IArcaCredentialsAdapter {
create(data: CreateArcaCredentialParams): Promise<IArcaCredential>;
find(filters: FindArcaCredentialsParams): Promise<IArcaCredential[]>;
findOne(filters: FindArcaCredentialsParams): Promise<IArcaCredentialDocument | null>;
update(data: UpdateArcaCredentialParams): Promise<IArcaCredentialDocument | null>;
}
export interface IArcaCredentialsManager {
arcaCredentials: IArcaCredentialsAdapter;
generateCsr(data: GenerateArcaCredentialCsrParams): Promise<ArcaCredentialView>;
uploadCertificate(data: UploadArcaCredentialCertificateParams): Promise<ArcaCredentialView>;
testWsaaLogin(data: TestArcaWsaaLoginParams): Promise<ArcaWsaaLoginTestResult>;
getWsfeLastVoucher(data: ArcaWsfeLastVoucherParams): Promise<ArcaWsfeLastVoucherResult>;
issueFacturaC(data: ArcaWsfeIssueFacturaCParams): Promise<ArcaWsfeIssueFacturaCResult>;
getWsfeDiagnostics(data: ArcaWsfeDiagnosticsParams): Promise<ArcaWsfeDiagnosticsResult>;
find(data: FindArcaCredentialsParams): Promise<ArcaCredentialView[]>;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,97 @@
import { Document, FilterQuery, Model, Schema, model, models } from "mongoose";
import {
ARCA_WSAA_ENVIRONMENT,
ARCA_WSAA_SERVICE,
ArcaWsaaTokenLookupParams,
CreateArcaWsaaTokenParams,
IArcaWsaaToken,
IArcaWsaaTokensAdapter,
UpdateArcaWsaaTokenParams,
} from "./ArcaWsaaTokens.Interface";
export interface IArcaWsaaTokenDocument extends Omit<IArcaWsaaToken, "id">, Document {}
export class ArcaWsaaTokensAdapterMongoose implements IArcaWsaaTokensAdapter {
schema: Schema;
arcaWsaaTokenList: Model<IArcaWsaaTokenDocument>;
constructor() {
this.schema = new Schema({
companyId: {
type: Schema.Types.ObjectId,
required: true,
ref: "Company",
index: true,
},
service: {
type: String,
required: true,
enum: Object.values(ARCA_WSAA_SERVICE),
index: true,
},
environment: {
type: String,
required: true,
enum: Object.values(ARCA_WSAA_ENVIRONMENT),
index: true,
},
token: { type: String, required: true },
sign: { type: String, required: true },
generationTime: { type: Date, required: false },
expirationTime: { type: Date, required: true, index: true },
createdAt: { type: Date, required: true, default: Date.now },
updatedAt: { type: Date, required: true, default: Date.now },
});
this.schema.index({ companyId: 1, service: 1, environment: 1 }, { unique: true });
this.arcaWsaaTokenList =
models.ArcaWsaaToken || model<IArcaWsaaTokenDocument>("ArcaWsaaToken", this.schema);
}
public async create(data: CreateArcaWsaaTokenParams): Promise<IArcaWsaaToken> {
return await this.arcaWsaaTokenList.create(data);
}
private buildSearchCriteria(
filters: Partial<ArcaWsaaTokenLookupParams>
): FilterQuery<IArcaWsaaToken> {
const searchCriteria: FilterQuery<IArcaWsaaToken> = {};
if (filters.companyId) searchCriteria.companyId = filters.companyId;
if (filters.service) searchCriteria.service = filters.service;
if (filters.environment) searchCriteria.environment = filters.environment;
return searchCriteria;
}
public async find(filters: Partial<ArcaWsaaTokenLookupParams>): Promise<IArcaWsaaToken[]> {
return this.arcaWsaaTokenList.find(this.buildSearchCriteria(filters)).sort({ createdAt: -1 }).exec();
}
public async findOne(
filters: Partial<ArcaWsaaTokenLookupParams>
): Promise<IArcaWsaaTokenDocument | null> {
return this.arcaWsaaTokenList.findOne(this.buildSearchCriteria(filters)).exec();
}
public async update(data: UpdateArcaWsaaTokenParams): Promise<IArcaWsaaTokenDocument | null> {
const { companyId, service, environment, ...updateData } = data;
return this.arcaWsaaTokenList
.findOneAndUpdate(this.buildSearchCriteria({ companyId, service, environment }), updateData, {
new: true,
})
.exec();
}
public async upsert(data: CreateArcaWsaaTokenParams): Promise<IArcaWsaaTokenDocument | null> {
const { companyId, service, environment, createdAt, ...updateData } = data;
return this.arcaWsaaTokenList
.findOneAndUpdate(
this.buildSearchCriteria({ companyId, service, environment }),
{ $set: updateData, $setOnInsert: { companyId, service, environment, createdAt } },
{ new: true, upsert: true }
)
.exec();
}
}
@@ -0,0 +1,68 @@
import { IArcaWsaaTokenDocument } from "./ArcaWsaaTokens.Adapter.Mongoose";
export enum ARCA_WSAA_SERVICE {
WSFE = "wsfe",
}
export enum ARCA_WSAA_ENVIRONMENT {
HOMOLOGATION = "homologation",
PRODUCTION = "production",
}
export type ArcaWsaaTokenLookupParams = {
companyId: string;
service: ARCA_WSAA_SERVICE;
environment: ARCA_WSAA_ENVIRONMENT;
};
export type CreateArcaWsaaTokenParams = ArcaWsaaTokenLookupParams & {
token: string;
sign: string;
generationTime?: Date;
expirationTime: Date;
createdAt: Date;
updatedAt: Date;
};
export type UpdateArcaWsaaTokenParams = ArcaWsaaTokenLookupParams & {
token?: string;
sign?: string;
generationTime?: Date;
expirationTime?: Date;
updatedAt: Date;
};
export type UpsertArcaWsaaTokenParams = ArcaWsaaTokenLookupParams & {
token: string;
sign: string;
generationTime?: Date;
expirationTime: Date;
};
export interface IArcaWsaaToken {
id?: string;
companyId: string;
service: ARCA_WSAA_SERVICE;
environment: ARCA_WSAA_ENVIRONMENT;
token: string;
sign: string;
generationTime?: Date;
expirationTime: Date;
createdAt: Date;
updatedAt: Date;
}
export interface IArcaWsaaTokensAdapter {
create(data: CreateArcaWsaaTokenParams): Promise<IArcaWsaaToken>;
find(filters: Partial<ArcaWsaaTokenLookupParams>): Promise<IArcaWsaaToken[]>;
findOne(filters: Partial<ArcaWsaaTokenLookupParams>): Promise<IArcaWsaaTokenDocument | null>;
update(data: UpdateArcaWsaaTokenParams): Promise<IArcaWsaaTokenDocument | null>;
upsert(data: CreateArcaWsaaTokenParams): Promise<IArcaWsaaTokenDocument | null>;
}
export interface IArcaWsaaTokensManager {
arcaWsaaTokens: IArcaWsaaTokensAdapter;
getValidToken(data: ArcaWsaaTokenLookupParams): Promise<IArcaWsaaToken | null>;
saveToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken>;
upsertToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken>;
}
@@ -0,0 +1,58 @@
import { ArcaWsaaTokensAdapterMongoose } from "./ArcaWsaaTokens.Adapter.Mongoose";
import {
ArcaWsaaTokenLookupParams,
IArcaWsaaToken,
IArcaWsaaTokensManager,
UpsertArcaWsaaTokenParams,
} from "./ArcaWsaaTokens.Interface";
const TOKEN_REUSE_SKEW_MS = 10 * 60 * 1000;
class ArcaWsaaTokensManager implements IArcaWsaaTokensManager {
arcaWsaaTokens: ArcaWsaaTokensAdapterMongoose;
constructor() {
this.arcaWsaaTokens = new ArcaWsaaTokensAdapterMongoose();
}
public async getValidToken(data: ArcaWsaaTokenLookupParams): Promise<IArcaWsaaToken | null> {
const existingToken = await this.arcaWsaaTokens.findOne(data);
if (!existingToken) {
return null;
}
const reuseUntil = Date.now() + TOKEN_REUSE_SKEW_MS;
if (new Date(existingToken.expirationTime).getTime() <= reuseUntil) {
return null;
}
return existingToken;
}
public async saveToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken> {
const now = new Date();
return await this.arcaWsaaTokens.create({
...data,
createdAt: now,
updatedAt: now,
});
}
public async upsertToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken> {
const now = new Date();
const token = await this.arcaWsaaTokens.upsert({
...data,
createdAt: now,
updatedAt: now,
});
if (!token) {
throw new Error("No se pudo guardar el token WSAA de ARCA");
}
return token;
}
}
export default new ArcaWsaaTokensManager();
@@ -264,6 +264,75 @@ export type SysAdminSetCompanyBannedParams = {
banned: boolean; 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 = { export type FixCompanyPostParams = {
companyId: string; companyId: string;
postId: string; postId: string;
@@ -310,4 +379,5 @@ export interface ICompaniesManager {
sysAdminPaginate(data: SysAdminPaginateCompaniesParams): Promise<PaginateCompaniesResults>; sysAdminPaginate(data: SysAdminPaginateCompaniesParams): Promise<PaginateCompaniesResults>;
sysAdminUpdate(data: SysAdminUpdateCompanyParams): Promise<void>; sysAdminUpdate(data: SysAdminUpdateCompanyParams): Promise<void>;
sysAdminSetBanned(data: SysAdminSetCompanyBannedParams): Promise<void>; sysAdminSetBanned(data: SysAdminSetCompanyBannedParams): Promise<void>;
sysAdminGetInsights(data: SysAdminCompanyInsightsParams): Promise<SysAdminCompanyInsightsResult>;
} }
+136
View File
@@ -27,6 +27,8 @@ import {
SysAdminPaginateCompaniesParams, SysAdminPaginateCompaniesParams,
SysAdminUpdateCompanyParams, SysAdminUpdateCompanyParams,
SysAdminSetCompanyBannedParams, SysAdminSetCompanyBannedParams,
SysAdminCompanyInsightsParams,
SysAdminCompanyInsightsResult,
} from "./Companies.Interface"; } from "./Companies.Interface";
import UsersManager from "../Users/Users"; import UsersManager from "../Users/Users";
import EmployeesList from "../Employees/Employee"; import EmployeesList from "../Employees/Employee";
@@ -54,11 +56,14 @@ import ClientAccount from "../ClientAccounts/ClientAccount";
import Payments from "../Payments/Payments"; import Payments from "../Payments/Payments";
import Discounts from "../Discounts/Discounts"; import Discounts from "../Discounts/Discounts";
import Templates from "../Templates/Templates"; import Templates from "../Templates/Templates";
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
import PlansList from "../Plans/Plans";
import Posts from "../Posts/Posts"; import Posts from "../Posts/Posts";
import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled"; import SchedulesDisabledList from "../SchedulesDisabled/SchedulesDisabled";
import DiscountsEmail from "../DiscountsEmail/DiscountsEmail"; import DiscountsEmail from "../DiscountsEmail/DiscountsEmail";
import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface"; import { NotificationType } from "../../Models/SystemNotifications/SystemNotification.Interface";
import getAvatar from "../../helpers/getAvatar";
class CompaniesManager implements ICompaniesManager { class CompaniesManager implements ICompaniesManager {
companies: ICompaniesAdapter; companies: ICompaniesAdapter;
@@ -1085,6 +1090,137 @@ class CompaniesManager implements ICompaniesManager {
sessionUser: "" // sysadmin override 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(); const CompaniesList = new CompaniesManager();
@@ -0,0 +1,112 @@
import { Document, FilterQuery, Model, Schema, model } from "mongoose";
import {
CreateInvoiceParams,
FindInvoicesParams,
IInvoice,
IInvoicesAdapter,
INVOICE_STATUS,
INVOICE_TYPE,
UpdateInvoiceParams,
} from "./Invoices.Interface";
export interface IInvoiceDocument extends Omit<IInvoice, "id">, Document {}
export class InvoicesAdapterMongoose implements IInvoicesAdapter {
schema: Schema;
invoiceList: Model<IInvoiceDocument>;
constructor() {
this.schema = new Schema({
cashMovementId: {
type: Schema.Types.ObjectId,
required: true,
ref: "CashFlow",
unique: true,
index: true,
},
companyId: {
type: Schema.Types.ObjectId,
required: true,
ref: "Company",
index: true,
},
clientId: { type: Schema.Types.ObjectId, required: false, ref: "Client" },
paymentId: { type: Schema.Types.ObjectId, required: false, ref: "Payment" },
clientAccountMovementId: {
type: Schema.Types.ObjectId,
required: false,
ref: "ClientAccountMovement",
},
appointmentId: { type: Schema.Types.ObjectId, required: false, ref: "Appointment" },
amount: { type: Number, required: true },
type: { type: String, required: true, enum: Object.values(INVOICE_TYPE) },
status: { type: String, required: true, enum: Object.values(INVOICE_STATUS), index: true },
billingDate: { type: Date, required: true },
servicePeriodFrom: { type: Date, required: true },
servicePeriodTo: { type: Date, required: true },
paymentDueDate: { type: Date, required: true },
activityCode: { type: String, required: true },
activityDescription: { type: String, required: true },
receiverIvaCondition: { type: Number, required: true, default: 5 },
receiverDocumentType: { type: Schema.Types.Mixed, required: false },
receiverDocumentNumber: { type: Schema.Types.Mixed, required: false },
receiverName: { type: String, required: false },
receiverAddress: { type: String, required: false },
receiverEmail: { type: String, required: false },
saleCondition: { type: String, required: true },
itemDescription: { type: String, required: true },
itemQuantity: { type: Number, required: true, default: 1 },
itemUnit: { type: String, required: false },
itemUnitPrice: { type: Number, required: true },
itemDiscountPercent: { type: Number, required: true, default: 0 },
itemDiscountAmount: { type: Number, required: true, default: 0 },
itemSubtotal: { type: Number, required: true },
cae: { type: String, required: false },
caeExpiresAt: { type: Date, required: false },
pointOfSale: { type: Number, required: false },
voucherNumber: { type: Number, required: false },
voucherType: { type: String, required: false },
arcaErrorCode: { type: String, required: false },
arcaErrorMessage: { type: String, required: false },
createdAt: { type: Date, required: true, default: Date.now },
updatedAt: { type: Date, required: true, default: Date.now },
});
this.invoiceList = model<IInvoiceDocument>("Invoice", this.schema);
}
public async create(data: CreateInvoiceParams): Promise<IInvoice> {
return await this.invoiceList.create(data);
}
private buildSearchCriteria(filters: FindInvoicesParams): FilterQuery<IInvoice> {
const searchCriteria: FilterQuery<IInvoice> = {};
if (filters.id) searchCriteria._id = filters.id;
if (filters.cashMovementId) searchCriteria.cashMovementId = filters.cashMovementId;
if (filters.cashMovementIds && filters.cashMovementIds.length > 0) {
searchCriteria.cashMovementId = { $in: filters.cashMovementIds };
}
if (filters.companyId) searchCriteria.companyId = filters.companyId;
if (filters.status) searchCriteria.status = filters.status;
return searchCriteria;
}
public async find(filters: FindInvoicesParams): Promise<IInvoice[]> {
const searchCriteria = this.buildSearchCriteria(filters);
return this.invoiceList.find(searchCriteria).sort({ createdAt: -1 }).exec();
}
public async findOne(filters: FindInvoicesParams): Promise<IInvoiceDocument | null> {
const searchCriteria = this.buildSearchCriteria(filters);
return this.invoiceList.findOne(searchCriteria).exec();
}
public async update(data: UpdateInvoiceParams): Promise<IInvoiceDocument | null> {
const { sessionUser, id, cashMovementId, cashMovementIds, companyId, ...updateData } = data;
const searchCriteria = this.buildSearchCriteria({ id, cashMovementId, companyId });
return this.invoiceList.findOneAndUpdate(searchCriteria, updateData, { new: true }).exec();
}
}
@@ -0,0 +1,159 @@
import { IInvoiceDocument } from "./Invoices.Adapter.Mongoose";
export enum INVOICE_TYPE {
FACTURA_C = "FACTURA_C",
}
export enum INVOICE_STATUS {
PENDING_ARCA = "PENDING_ARCA",
APPROVED = "APPROVED",
PENDING_VERIFICATION = "PENDING_VERIFICATION",
REJECTED = "REJECTED",
FAILED = "FAILED",
}
export enum INVOICE_SALE_CONDITION {
CASH = "cash",
CONTADO = "contado",
BANK_TRANSFER = "bank_transfer",
CREDIT_CARD = "credit_card",
DEBIT_CARD = "debit_card",
CURRENT_ACCOUNT = "current_account",
CHECK = "check",
OTHER = "other",
ELECTRONIC_PAYMENT = "electronic_payment",
}
export const FINAL_CONSUMER_IVA_CONDITION_ID = 5;
export type CreateInvoiceFromCashMovementParams = {
cashMovementId: string;
billingDate: Date | string;
servicePeriodFrom: Date | string;
servicePeriodTo: Date | string;
paymentDueDate: Date | string;
activityCode: string;
activityDescription: string;
receiverIvaCondition?: 5;
receiverDocumentType?: number | string;
receiverDocumentNumber?: number | string;
receiverName?: string;
receiverAddress?: string;
receiverEmail?: string;
saleCondition: INVOICE_SALE_CONDITION | string;
itemDescription: string;
itemQuantity?: number;
itemUnit?: string;
itemUnitPrice: number;
itemDiscountPercent?: number;
itemDiscountAmount?: number;
itemSubtotal: number;
sessionUser: string;
};
export type FindInvoicesParams = {
id?: string;
cashMovementId?: string;
cashMovementIds?: string[];
companyId?: string;
status?: INVOICE_STATUS;
sessionUser?: string;
};
export type CreateInvoiceParams = {
cashMovementId: string;
companyId: string;
clientId?: string;
paymentId?: string;
clientAccountMovementId?: string;
appointmentId?: string;
amount: number;
type: INVOICE_TYPE;
status: INVOICE_STATUS;
billingDate: Date;
servicePeriodFrom: Date;
servicePeriodTo: Date;
paymentDueDate: Date;
activityCode: string;
activityDescription: string;
receiverIvaCondition: 5;
receiverDocumentType?: number | string;
receiverDocumentNumber?: number | string;
receiverName?: string;
receiverAddress?: string;
receiverEmail?: string;
saleCondition: INVOICE_SALE_CONDITION | string;
itemDescription: string;
itemQuantity: number;
itemUnit?: string;
itemUnitPrice: number;
itemDiscountPercent: number;
itemDiscountAmount: number;
itemSubtotal: number;
cae?: string;
caeExpiresAt?: Date;
pointOfSale?: number;
voucherNumber?: number;
voucherType?: string;
arcaErrorCode?: string;
arcaErrorMessage?: string;
createdAt: Date;
updatedAt: Date;
};
export type UpdateInvoiceParams = FindInvoicesParams & Partial<CreateInvoiceParams>;
export interface IInvoice {
id?: string;
cashMovementId: string;
companyId: string;
clientId?: string;
paymentId?: string;
clientAccountMovementId?: string;
appointmentId?: string;
amount: number;
type: INVOICE_TYPE;
status: INVOICE_STATUS;
billingDate: Date;
servicePeriodFrom: Date;
servicePeriodTo: Date;
paymentDueDate: Date;
activityCode: string;
activityDescription: string;
receiverIvaCondition: 5;
receiverDocumentType?: number | string;
receiverDocumentNumber?: number | string;
receiverName?: string;
receiverAddress?: string;
receiverEmail?: string;
saleCondition: INVOICE_SALE_CONDITION | string;
itemDescription: string;
itemQuantity: number;
itemUnit?: string;
itemUnitPrice: number;
itemDiscountPercent: number;
itemDiscountAmount: number;
itemSubtotal: number;
cae?: string;
caeExpiresAt?: Date;
pointOfSale?: number;
voucherNumber?: number;
voucherType?: string;
arcaErrorCode?: string;
arcaErrorMessage?: string;
createdAt: Date;
updatedAt: Date;
}
export interface IInvoicesAdapter {
create(data: CreateInvoiceParams): Promise<IInvoice>;
find(filters: FindInvoicesParams): Promise<IInvoice[]>;
findOne(filters: FindInvoicesParams): Promise<IInvoiceDocument | null>;
update(data: UpdateInvoiceParams): Promise<IInvoiceDocument | null>;
}
export interface IInvoicesManager {
invoices: IInvoicesAdapter;
createFromCashMovement(data: CreateInvoiceFromCashMovementParams): Promise<IInvoice>;
find(data: FindInvoicesParams): Promise<IInvoice[]>;
}
+518
View File
@@ -0,0 +1,518 @@
import CashFlow from "../CashFlow/CashFlow";
import { CLIENT_ACCOUNT_MOVEMENT_TYPES } from "../ClientAccountMovements/ClientAccountMovements.Interface";
import CompaniesList from "../Companies/Companies";
import OrganizationFiscalProfiles from "../OrganizationFiscalProfiles/OrganizationFiscalProfiles";
import { ORGANIZATION_FISCAL_PROFILE_STATUS } from "../OrganizationFiscalProfiles/OrganizationFiscalProfiles.Interface";
import ArcaCredentials, { ArcaWsfeIssueFacturaCError } from "../ArcaCredentials/ArcaCredentials";
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
import { PlanFeatures } from "../Plans/Plans.interface";
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
import { InvoicesAdapterMongoose } from "./Invoices.Adapter.Mongoose";
import {
CreateInvoiceFromCashMovementParams,
CreateInvoiceParams,
FindInvoicesParams,
FINAL_CONSUMER_IVA_CONDITION_ID,
IInvoice,
IInvoicesManager,
INVOICE_SALE_CONDITION,
INVOICE_STATUS,
INVOICE_TYPE,
} from "./Invoices.Interface";
const FACTURA_C_VOUCHER_TYPE = "11";
const ARGENTINA_TIME_ZONE = "America/Argentina/Buenos_Aires";
const TEXT_MAX_LENGTH = 500;
const RECEIVER_TEXT_MAX_LENGTH = 200;
const CENTS_TOLERANCE = 0.01;
const YYYY_MM_DD_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
const DNI_DOCUMENT_TYPE = 96;
const FINAL_CONSUMER_DOCUMENT_TYPE = 99;
const FINAL_CONSUMER_DOCUMENT_NUMBER = 0;
const FINAL_CONSUMER_COMPATIBLE_DOCUMENT_TYPES = new Set([DNI_DOCUMENT_TYPE, FINAL_CONSUMER_DOCUMENT_TYPE]);
class InvoicesManager implements IInvoicesManager {
invoices: InvoicesAdapterMongoose;
constructor() {
this.invoices = new InvoicesAdapterMongoose();
}
private isDuplicateKeyError(error: unknown): boolean {
return typeof error === "object" && error !== null && "code" in error && error.code === 11000;
}
private async validatePaymentsPlan(companyId: string): Promise<void> {
const company = await CompaniesList.companies.findOne({ _id: companyId });
if (!company) {
throw new Error("No se ha encontrado la organización");
}
const canAccess = await PlanSubscriptionsList.checkFeature({
userId: String(company.ownerId),
feature: PlanFeatures.PAYMENTS,
});
if (!canAccess) {
throw new Error("La organizacion no tiene un plan que soporte el módulo de pagos");
}
}
private formatArgentinaCalendarDate(date: Date): string {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: ARGENTINA_TIME_ZONE,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(date);
const year = parts.find((part) => part.type === "year")?.value || "";
const month = parts.find((part) => part.type === "month")?.value || "";
const day = parts.find((part) => part.type === "day")?.value || "";
return `${year}-${month}-${day}`;
}
private parseArgentinaCalendarDate(dateValue: Date | string, requiredMessage: string, invalidMessage: string): Date {
if (!dateValue) {
throw new Error(requiredMessage);
}
let parsedDate: Date;
if (typeof dateValue === "string") {
const localDateMatch = dateValue.match(YYYY_MM_DD_PATTERN);
if (!localDateMatch) {
throw new Error(invalidMessage);
}
const [, year, month, day] = localDateMatch;
const yearNumber = Number(year);
const monthNumber = Number(month);
const dayNumber = Number(day);
parsedDate = new Date(Date.UTC(yearNumber, monthNumber - 1, dayNumber, 12));
if (
parsedDate.getUTCFullYear() !== yearNumber ||
parsedDate.getUTCMonth() !== monthNumber - 1 ||
parsedDate.getUTCDate() !== dayNumber
) {
throw new Error(invalidMessage);
}
} else {
parsedDate = dateValue;
}
if (Number.isNaN(parsedDate.getTime())) {
throw new Error(invalidMessage);
}
return parsedDate;
}
private parseBillingDate(billingDate: Date | string): Date {
const parsedDate = this.parseArgentinaCalendarDate(
billingDate,
"Se requiere la fecha del comprobante",
"La fecha del comprobante no es válida"
);
const selectedDate = this.formatArgentinaCalendarDate(parsedDate);
const todayDate = this.formatArgentinaCalendarDate(new Date());
if (selectedDate > todayDate) {
throw new Error("La fecha del comprobante no puede ser futura");
}
return parsedDate;
}
private validateSaleCondition(saleCondition: string): INVOICE_SALE_CONDITION {
if (!Object.values(INVOICE_SALE_CONDITION).includes(saleCondition as INVOICE_SALE_CONDITION)) {
throw new Error("La condición de venta de la factura no es válida");
}
return saleCondition as INVOICE_SALE_CONDITION;
}
private trimOptional(value?: string): string | undefined {
const trimmed = value?.trim();
return trimmed || undefined;
}
private parseReceiverDocumentCode(value: number | string, fieldName: string): number {
if (typeof value === "string" && value.trim() === "") {
throw new Error(`${fieldName} del receptor no es válido`);
}
const parsedValue = typeof value === "string" ? Number(value.trim()) : value;
if (!Number.isInteger(parsedValue) || !Number.isFinite(parsedValue) || parsedValue < 0) {
throw new Error(`${fieldName} del receptor no es válido`);
}
return parsedValue;
}
private validateReceiverDocumentPair(data: CreateInvoiceFromCashMovementParams): {
receiverDocumentType: number;
receiverDocumentNumber: number;
} {
const hasDocumentType = data.receiverDocumentType !== undefined && data.receiverDocumentType !== null && data.receiverDocumentType !== "";
const hasDocumentNumber = data.receiverDocumentNumber !== undefined && data.receiverDocumentNumber !== null && data.receiverDocumentNumber !== "";
if (hasDocumentType !== hasDocumentNumber) {
throw new Error("Tipo y número de documento del receptor deben informarse juntos");
}
if (!hasDocumentType && !hasDocumentNumber) {
return {
receiverDocumentType: FINAL_CONSUMER_DOCUMENT_TYPE,
receiverDocumentNumber: FINAL_CONSUMER_DOCUMENT_NUMBER,
};
}
const receiverDocumentType = this.parseReceiverDocumentCode(data.receiverDocumentType as number | string, "El tipo de documento");
const receiverDocumentNumber = this.parseReceiverDocumentCode(data.receiverDocumentNumber as number | string, "El número de documento");
if (!FINAL_CONSUMER_COMPATIBLE_DOCUMENT_TYPES.has(receiverDocumentType)) {
throw new Error("El tipo de documento del receptor no es compatible con Consumidor Final");
}
if (receiverDocumentType === FINAL_CONSUMER_DOCUMENT_TYPE && receiverDocumentNumber !== FINAL_CONSUMER_DOCUMENT_NUMBER) {
throw new Error("El número de documento debe ser 0 cuando el tipo es Consumidor Final");
}
return {
receiverDocumentType,
receiverDocumentNumber,
};
}
public async createFromCashMovement(data: CreateInvoiceFromCashMovementParams): Promise<IInvoice> {
await validateSessionUser({ sessionUser: data.sessionUser });
if (!data.cashMovementId || !data.cashMovementId.trim()) {
throw new Error("Se requiere un movimiento de caja para emitir la factura");
}
const billingDate = this.parseBillingDate(data.billingDate);
const servicePeriodFrom = this.parseArgentinaCalendarDate(
data.servicePeriodFrom,
"Se requiere la fecha de inicio del período facturado",
"La fecha de inicio del período facturado no es válida"
);
const servicePeriodTo = this.parseArgentinaCalendarDate(
data.servicePeriodTo,
"Se requiere la fecha de fin del período facturado",
"La fecha de fin del período facturado no es válida"
);
const paymentDueDate = this.parseArgentinaCalendarDate(
data.paymentDueDate,
"Se requiere el vencimiento de pago",
"El vencimiento de pago no es válido"
);
const servicePeriodFromValue = this.formatArgentinaCalendarDate(servicePeriodFrom);
const servicePeriodToValue = this.formatArgentinaCalendarDate(servicePeriodTo);
const billingDateValue = this.formatArgentinaCalendarDate(billingDate);
const paymentDueDateValue = this.formatArgentinaCalendarDate(paymentDueDate);
if (servicePeriodFromValue > servicePeriodToValue) {
throw new Error("El inicio del período facturado no puede ser posterior al fin");
}
if (paymentDueDateValue < billingDateValue) {
throw new Error("El vencimiento de pago no puede ser anterior a la fecha del comprobante");
}
const activityCode = data.activityCode?.trim();
const activityDescription = data.activityDescription?.trim();
const itemDescription = data.itemDescription?.trim();
if (!activityCode) {
throw new Error("Se requiere el código de actividad");
}
if (!activityDescription) {
throw new Error("Se requiere la descripción de la actividad");
}
if (!itemDescription) {
throw new Error("Se requiere la descripción del ítem facturado");
}
if ([activityCode, activityDescription, itemDescription].some((value) => value.length > TEXT_MAX_LENGTH)) {
throw new Error(`Los datos de actividad e ítem no pueden superar los ${TEXT_MAX_LENGTH} caracteres`);
}
if (!data.saleCondition || !data.saleCondition.trim()) {
throw new Error("Se requiere la condición de venta");
}
const saleCondition = this.validateSaleCondition(data.saleCondition.trim());
const receiverDocument = this.validateReceiverDocumentPair(data);
const itemQuantity = data.itemQuantity ?? 1;
const itemDiscountPercent = data.itemDiscountPercent ?? 0;
const itemDiscountAmount = data.itemDiscountAmount ?? 0;
if (!Number.isFinite(data.itemUnitPrice) || !Number.isFinite(data.itemSubtotal)) {
throw new Error("El importe del ítem no es válido");
}
if (itemQuantity !== 1 || data.itemUnitPrice <= 0 || itemDiscountPercent !== 0 || itemDiscountAmount !== 0) {
throw new Error("El MVP permite un único ítem de servicio sin descuentos por el total del movimiento");
}
const movement = await CashFlow.movements.movementList.findOne({
_id: data.cashMovementId,
});
if (!movement) {
throw new Error("No se ha encontrado el movimiento de caja");
}
const companyId = String(movement.companyId);
await validatePermissionsByCompany({ companyId, sessionUser: data.sessionUser });
await this.validatePaymentsPlan(companyId);
if (movement.type !== CLIENT_ACCOUNT_MOVEMENT_TYPES.DEPOSIT || movement.amount <= 0) {
throw new Error("El movimiento de caja no es facturable");
}
const expectedSubtotal = Number((itemQuantity * data.itemUnitPrice - itemDiscountAmount).toFixed(2));
const sentSubtotal = Number(data.itemSubtotal.toFixed(2));
const movementAmount = Number(movement.amount.toFixed(2));
if (
Math.abs(expectedSubtotal - sentSubtotal) > CENTS_TOLERANCE ||
Math.abs(sentSubtotal - movementAmount) > CENTS_TOLERANCE
) {
throw new Error("El total del ítem debe coincidir con el importe del movimiento");
}
const fiscalProfiles = await OrganizationFiscalProfiles.find({
companyId,
status: ORGANIZATION_FISCAL_PROFILE_STATUS.ACTIVE,
sessionUser: data.sessionUser,
});
if (fiscalProfiles.length === 0) {
throw new Error("La organización debe tener un perfil fiscal activo para emitir facturas");
}
const existingInvoice = await this.invoices.findOne({
cashMovementId: data.cashMovementId,
});
if (existingInvoice?.status === INVOICE_STATUS.APPROVED) {
return existingInvoice;
}
if (existingInvoice?.status === INVOICE_STATUS.PENDING_VERIFICATION) {
return existingInvoice;
}
if (existingInvoice?.status === INVOICE_STATUS.PENDING_ARCA && existingInvoice.voucherNumber) {
const updatedPendingInvoice = await this.invoices.update({
cashMovementId: data.cashMovementId,
status: INVOICE_STATUS.PENDING_VERIFICATION,
arcaErrorMessage:
existingInvoice.arcaErrorMessage ||
"La emisión quedó pendiente de verificación en ARCA. Revisá el comprobante antes de reintentar.",
updatedAt: new Date(),
});
return updatedPendingInvoice || existingInvoice;
}
const baseInvoiceData: CreateInvoiceParams = {
cashMovementId: data.cashMovementId,
companyId,
clientId: movement.clientId ? String(movement.clientId) : undefined,
paymentId: movement.paymentId ? String(movement.paymentId) : undefined,
clientAccountMovementId: movement.clientAccountMovementId
? String(movement.clientAccountMovementId)
: undefined,
appointmentId: movement.appointmentId ? String(movement.appointmentId) : undefined,
amount: movement.amount,
type: INVOICE_TYPE.FACTURA_C,
status: INVOICE_STATUS.PENDING_ARCA,
billingDate,
servicePeriodFrom,
servicePeriodTo,
paymentDueDate,
activityCode,
activityDescription,
receiverIvaCondition: FINAL_CONSUMER_IVA_CONDITION_ID,
receiverDocumentType: receiverDocument.receiverDocumentType,
receiverDocumentNumber: receiverDocument.receiverDocumentNumber,
receiverName: this.trimOptional(data.receiverName)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
receiverAddress: this.trimOptional(data.receiverAddress)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
receiverEmail: this.trimOptional(data.receiverEmail)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
saleCondition,
itemDescription,
itemQuantity,
itemUnit: this.trimOptional(data.itemUnit),
itemUnitPrice: data.itemUnitPrice,
itemDiscountPercent,
itemDiscountAmount,
itemSubtotal: sentSubtotal,
createdAt: new Date(),
updatedAt: new Date(),
};
let invoice: IInvoice | null = existingInvoice;
if (!invoice) {
try {
invoice = await this.invoices.create(baseInvoiceData);
} catch (error) {
if (this.isDuplicateKeyError(error)) {
const duplicateInvoice = await this.invoices.findOne({
cashMovementId: data.cashMovementId,
});
if (duplicateInvoice) {
return duplicateInvoice;
}
}
throw error;
}
}
if (!invoice) {
throw new Error("No se pudo crear el registro local de factura");
}
if (
existingInvoice?.status === INVOICE_STATUS.PENDING_ARCA ||
existingInvoice?.status === INVOICE_STATUS.REJECTED ||
existingInvoice?.status === INVOICE_STATUS.FAILED
) {
invoice = await this.invoices.update({
cashMovementId: data.cashMovementId,
billingDate,
servicePeriodFrom,
servicePeriodTo,
paymentDueDate,
activityCode,
activityDescription,
receiverIvaCondition: FINAL_CONSUMER_IVA_CONDITION_ID,
receiverDocumentType: receiverDocument.receiverDocumentType,
receiverDocumentNumber: receiverDocument.receiverDocumentNumber,
receiverName: this.trimOptional(data.receiverName)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
receiverAddress: this.trimOptional(data.receiverAddress)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
receiverEmail: this.trimOptional(data.receiverEmail)?.slice(0, RECEIVER_TEXT_MAX_LENGTH),
saleCondition,
itemDescription,
itemQuantity,
itemUnit: this.trimOptional(data.itemUnit),
itemUnitPrice: data.itemUnitPrice,
itemDiscountPercent,
itemDiscountAmount,
itemSubtotal: sentSubtotal,
updatedAt: new Date(),
}) || invoice;
}
let invoiceData: Pick<
CreateInvoiceParams,
| "status"
| "cae"
| "caeExpiresAt"
| "pointOfSale"
| "voucherNumber"
| "voucherType"
| "arcaErrorMessage"
>;
try {
const arcaInvoice = await ArcaCredentials.issueFacturaC({
companyId,
amount: movement.amount,
billingDate,
servicePeriodFrom,
servicePeriodTo,
paymentDueDate,
receiverDocumentType: receiverDocument.receiverDocumentType,
receiverDocumentNumber: receiverDocument.receiverDocumentNumber,
sessionUser: data.sessionUser,
});
invoiceData = {
status: INVOICE_STATUS.APPROVED,
cae: arcaInvoice.cae,
caeExpiresAt: arcaInvoice.caeExpiresAt,
pointOfSale: arcaInvoice.pointOfSale,
voucherNumber: arcaInvoice.voucherNumber,
voucherType: String(arcaInvoice.voucherType),
arcaErrorMessage: "",
};
} catch (error) {
const errorOccurred = error as Error;
const arcaError = error as ArcaWsfeIssueFacturaCError;
const hasArcaAttempt = error instanceof ArcaWsfeIssueFacturaCError;
invoiceData = {
status: hasArcaAttempt
? arcaError.isAmbiguous
? INVOICE_STATUS.PENDING_VERIFICATION
: INVOICE_STATUS.REJECTED
: INVOICE_STATUS.FAILED,
pointOfSale: hasArcaAttempt ? arcaError.attempt.pointOfSale : undefined,
voucherNumber: hasArcaAttempt ? arcaError.attempt.voucherNumber : undefined,
voucherType: hasArcaAttempt ? String(arcaError.attempt.voucherType) : FACTURA_C_VOUCHER_TYPE,
arcaErrorMessage: errorOccurred.message,
};
}
const updatedInvoice = await this.invoices.update({
cashMovementId: data.cashMovementId,
...invoiceData,
updatedAt: new Date(),
});
if (!updatedInvoice) {
return invoice;
}
return updatedInvoice;
}
public async find(data: FindInvoicesParams): Promise<IInvoice[]> {
if (!data.sessionUser) {
throw new Error("Se requiere un usuario autenticado");
}
const sessionUser = data.sessionUser;
await validateSessionUser({ sessionUser });
if (data.companyId) {
await validatePermissionsByCompany({
companyId: data.companyId,
sessionUser,
});
await this.validatePaymentsPlan(data.companyId);
} else if (data.id || data.cashMovementId) {
const invoice = await this.invoices.findOne(data);
if (!invoice) {
return [];
}
await validatePermissionsByCompany({
companyId: String(invoice.companyId),
sessionUser,
});
await this.validatePaymentsPlan(String(invoice.companyId));
return [invoice];
} else {
throw new Error("Se requiere una organización para buscar facturas");
}
return await this.invoices.find(data);
}
}
export default new InvoicesManager();
@@ -1,11 +1,21 @@
import { Document, Model, Schema, model } from "mongoose"; import { Document, Model, Schema, model } from "mongoose";
import { import {
CreateJobParams, CreateJobParams,
DeleteOldJobsParams,
DeleteOldJobsResult,
INotificationJob, INotificationJob,
INotificationJobAdapter, INotificationJobAdapter,
NotificationJobStatus, NotificationJobStatus,
} from "./NotificationJobs.Interface"; } 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 export interface INotificationJobDocument
extends Omit<INotificationJob, "id">, extends Omit<INotificationJob, "id">,
Document {} Document {}
@@ -13,6 +23,7 @@ export interface INotificationJobDocument
export class NotificationJobsAdapterMongoose implements INotificationJobAdapter { export class NotificationJobsAdapterMongoose implements INotificationJobAdapter {
schema: Schema; schema: Schema;
notificationJobList: Model<INotificationJobDocument>; notificationJobList: Model<INotificationJobDocument>;
private lastCleanupAt?: number;
constructor() { constructor() {
this.schema = new Schema( this.schema = new Schema(
@@ -73,6 +84,7 @@ export class NotificationJobsAdapterMongoose implements INotificationJobAdapter
} }
public async create(data: CreateJobParams): Promise<INotificationJob> { public async create(data: CreateJobParams): Promise<INotificationJob> {
await this.cleanupOldJobsIfDueSafely();
const doc = await this.notificationJobList.create({ const doc = await this.notificationJobList.create({
...data, ...data,
status: NotificationJobStatus.PENDING, status: NotificationJobStatus.PENDING,
@@ -111,6 +123,7 @@ export class NotificationJobsAdapterMongoose implements INotificationJobAdapter
} }
public async cancelByAppointment(appointmentId: string): Promise<void> { public async cancelByAppointment(appointmentId: string): Promise<void> {
await this.cleanupOldJobsIfDueSafely();
await this.notificationJobList await this.notificationJobList
.updateMany( .updateMany(
{ {
@@ -123,9 +136,52 @@ export class NotificationJobsAdapterMongoose implements INotificationJobAdapter
} }
public async findByAppointment(appointmentId: string): Promise<INotificationJob[]> { public async findByAppointment(appointmentId: string): Promise<INotificationJob[]> {
await this.cleanupOldJobsIfDueSafely();
const docs = await this.notificationJobList const docs = await this.notificationJobList
.find({ appointmentId }) .find({ appointmentId })
.exec(); .exec();
return docs.map((d) => d.toObject() as INotificationJob); 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; payload?: NotificationJobPayload;
} }
export interface DeleteOldJobsParams {
scheduledBefore: Date;
statuses: NotificationJobStatus[];
}
export interface DeleteOldJobsResult {
deletedCount: number;
}
export interface INotificationJobAdapter { export interface INotificationJobAdapter {
create(data: CreateJobParams): Promise<INotificationJob>; create(data: CreateJobParams): Promise<INotificationJob>;
findPendingDue(now: Date): Promise<INotificationJob[]>; findPendingDue(now: Date): Promise<INotificationJob[]>;
@@ -68,4 +77,5 @@ export interface INotificationJobAdapter {
): Promise<void>; ): Promise<void>;
cancelByAppointment(appointmentId: string): Promise<void>; cancelByAppointment(appointmentId: string): Promise<void>;
findByAppointment(appointmentId: string): Promise<INotificationJob[]>; findByAppointment(appointmentId: string): Promise<INotificationJob[]>;
deleteOldJobs(data: DeleteOldJobsParams): Promise<DeleteOldJobsResult>;
} }
@@ -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);
});
});
@@ -0,0 +1,102 @@
import { Document, FilterQuery, Model, Schema, model } from "mongoose";
import {
CreateOrganizationFiscalProfileParams,
FindOrganizationFiscalProfilesParams,
IOrganizationFiscalProfile,
IOrganizationFiscalProfilesAdapter,
ORGANIZATION_FISCAL_PROFILE_STATUS,
ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION,
UpdateOrganizationFiscalProfileParams,
} from "./OrganizationFiscalProfiles.Interface";
export interface IOrganizationFiscalProfileDocument
extends Omit<IOrganizationFiscalProfile, "id">,
Document {}
export class OrganizationFiscalProfilesAdapterMongoose implements IOrganizationFiscalProfilesAdapter {
schema: Schema;
organizationFiscalProfileList: Model<IOrganizationFiscalProfileDocument>;
constructor() {
this.schema = new Schema({
companyId: {
type: Schema.Types.ObjectId,
required: true,
ref: "Company",
unique: true,
index: true,
},
cuit: { type: String, required: true },
legalName: { type: String, required: true },
taxCondition: {
type: String,
required: true,
enum: Object.values(ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION),
},
pointOfSale: { type: Number, required: true },
activityCode: { type: String, required: false },
activityDescription: { type: String, required: false },
status: {
type: String,
required: true,
enum: Object.values(ORGANIZATION_FISCAL_PROFILE_STATUS),
index: true,
},
createdAt: { type: Date, required: true, default: Date.now },
updatedAt: { type: Date, required: true, default: Date.now },
});
this.organizationFiscalProfileList = model<IOrganizationFiscalProfileDocument>(
"OrganizationFiscalProfile",
this.schema
);
}
public async create(
data: CreateOrganizationFiscalProfileParams
): Promise<IOrganizationFiscalProfile> {
return await this.organizationFiscalProfileList.create(data);
}
private buildSearchCriteria(
filters: FindOrganizationFiscalProfilesParams
): FilterQuery<IOrganizationFiscalProfile> {
const searchCriteria: FilterQuery<IOrganizationFiscalProfile> = {};
if (filters.id) searchCriteria._id = filters.id;
if (filters.companyId) searchCriteria.companyId = filters.companyId;
if (filters.status) searchCriteria.status = filters.status;
return searchCriteria;
}
public async find(
filters: FindOrganizationFiscalProfilesParams
): Promise<IOrganizationFiscalProfile[]> {
const searchCriteria = this.buildSearchCriteria(filters);
return this.organizationFiscalProfileList.find(searchCriteria).sort({ createdAt: -1 }).exec();
}
public async findOne(
filters: FindOrganizationFiscalProfilesParams
): Promise<IOrganizationFiscalProfileDocument | null> {
const searchCriteria = this.buildSearchCriteria(filters);
return this.organizationFiscalProfileList.findOne(searchCriteria).exec();
}
public async update(
data: UpdateOrganizationFiscalProfileParams
): Promise<IOrganizationFiscalProfileDocument | null> {
const { id, companyId, sessionUser, ...updateData } = data;
if (!id && !companyId) {
throw new Error("Se requiere un identificador para actualizar el perfil fiscal");
}
return this.organizationFiscalProfileList
.findOneAndUpdate(this.buildSearchCriteria({ id, companyId, sessionUser }), updateData, {
new: true,
})
.exec();
}
}
@@ -0,0 +1,83 @@
import { IOrganizationFiscalProfileDocument } from "./OrganizationFiscalProfiles.Adapter.Mongoose";
export enum ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION {
MONOTRIBUTO = "MONOTRIBUTO",
EXENTO = "EXENTO",
}
export enum ORGANIZATION_FISCAL_PROFILE_STATUS {
PENDING = "PENDING",
ACTIVE = "ACTIVE",
DISABLED = "DISABLED",
}
export type UpsertOrganizationFiscalProfileParams = {
companyId: string;
cuit: string;
legalName: string;
taxCondition: ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION;
pointOfSale: number;
activityCode?: string;
activityDescription?: string;
sessionUser: string;
};
export type FindOrganizationFiscalProfilesParams = {
id?: string;
companyId?: string;
status?: ORGANIZATION_FISCAL_PROFILE_STATUS;
sessionUser?: string;
};
export type CreateOrganizationFiscalProfileParams = {
companyId: string;
cuit: string;
legalName: string;
taxCondition: ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION;
pointOfSale: number;
activityCode?: string;
activityDescription?: string;
status: ORGANIZATION_FISCAL_PROFILE_STATUS;
createdAt: Date;
updatedAt: Date;
};
export type UpdateOrganizationFiscalProfileParams = FindOrganizationFiscalProfilesParams & {
cuit?: string;
legalName?: string;
taxCondition?: ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION;
pointOfSale?: number;
activityCode?: string;
activityDescription?: string;
status?: ORGANIZATION_FISCAL_PROFILE_STATUS;
updatedAt: Date;
};
export interface IOrganizationFiscalProfile {
id?: string;
companyId: string;
cuit: string;
legalName: string;
taxCondition: ORGANIZATION_FISCAL_PROFILE_TAX_CONDITION;
pointOfSale: number;
activityCode?: string;
activityDescription?: string;
status: ORGANIZATION_FISCAL_PROFILE_STATUS;
createdAt: Date;
updatedAt: Date;
}
export interface IOrganizationFiscalProfilesAdapter {
create(data: CreateOrganizationFiscalProfileParams): Promise<IOrganizationFiscalProfile>;
find(filters: FindOrganizationFiscalProfilesParams): Promise<IOrganizationFiscalProfile[]>;
findOne(
filters: FindOrganizationFiscalProfilesParams
): Promise<IOrganizationFiscalProfileDocument | null>;
update(data: UpdateOrganizationFiscalProfileParams): Promise<IOrganizationFiscalProfileDocument | null>;
}
export interface IOrganizationFiscalProfilesManager {
organizationFiscalProfiles: IOrganizationFiscalProfilesAdapter;
upsert(data: UpsertOrganizationFiscalProfileParams): Promise<IOrganizationFiscalProfile>;
find(data: FindOrganizationFiscalProfilesParams): Promise<IOrganizationFiscalProfile[]>;
}
@@ -0,0 +1,164 @@
import { validatePermissionsByCompany, validateSessionUser } from "../../helpers/check";
import { findArcaActivityByCode } from "../ArcaActivities/ArcaActivities.Catalog";
import { OrganizationFiscalProfilesAdapterMongoose } from "./OrganizationFiscalProfiles.Adapter.Mongoose";
import {
FindOrganizationFiscalProfilesParams,
IOrganizationFiscalProfile,
IOrganizationFiscalProfilesManager,
ORGANIZATION_FISCAL_PROFILE_STATUS,
UpsertOrganizationFiscalProfileParams,
} from "./OrganizationFiscalProfiles.Interface";
class OrganizationFiscalProfilesManager implements IOrganizationFiscalProfilesManager {
organizationFiscalProfiles: OrganizationFiscalProfilesAdapterMongoose;
constructor() {
this.organizationFiscalProfiles = new OrganizationFiscalProfilesAdapterMongoose();
}
private isDuplicateKeyError(error: unknown): boolean {
return typeof error === "object" && error !== null && "code" in error && error.code === 11000;
}
private validateProfileFields(data: UpsertOrganizationFiscalProfileParams): void {
if (!/^\d{11}$/.test(data.cuit)) {
throw new Error("El CUIT debe contener 11 dígitos");
}
if (!data.legalName || !data.legalName.trim()) {
throw new Error("La razón social es requerida");
}
if (!data.pointOfSale || data.pointOfSale <= 0) {
throw new Error("El punto de venta debe ser mayor a 0");
}
const activityCode = data.activityCode?.trim();
if (activityCode && !/^\d{6}$/.test(activityCode)) {
throw new Error("El código de actividad debe contener 6 dígitos");
}
if (activityCode && !findArcaActivityByCode(activityCode)) {
throw new Error("La actividad ARCA/CLAE seleccionada no existe en el catálogo");
}
}
private buildProfileData(data: UpsertOrganizationFiscalProfileParams) {
const activityCode = data.activityCode?.trim();
const activity = activityCode ? findArcaActivityByCode(activityCode) : undefined;
return {
cuit: data.cuit,
legalName: data.legalName.trim(),
taxCondition: data.taxCondition,
pointOfSale: data.pointOfSale,
activityCode: activity?.code || "",
activityDescription: activity?.description || "",
status: ORGANIZATION_FISCAL_PROFILE_STATUS.ACTIVE,
};
}
public async upsert(
data: UpsertOrganizationFiscalProfileParams
): Promise<IOrganizationFiscalProfile> {
await validateSessionUser({ sessionUser: data.sessionUser });
if (!data.companyId || !data.companyId.trim()) {
throw new Error("Se requiere una organización para guardar el perfil fiscal");
}
await validatePermissionsByCompany({ companyId: data.companyId, sessionUser: data.sessionUser });
this.validateProfileFields(data);
const existingProfile = await this.organizationFiscalProfiles.findOne({
companyId: data.companyId,
});
const now = new Date();
const profileData = this.buildProfileData(data);
if (existingProfile) {
const updatedProfile = await this.organizationFiscalProfiles.update({
companyId: data.companyId,
...profileData,
updatedAt: now,
});
if (!updatedProfile) {
throw new Error("No se pudo actualizar el perfil fiscal");
}
return updatedProfile;
}
try {
return await this.organizationFiscalProfiles.create({
companyId: data.companyId,
...profileData,
createdAt: now,
updatedAt: now,
});
} catch (error) {
if (this.isDuplicateKeyError(error)) {
const updatedProfile = await this.organizationFiscalProfiles.update({
companyId: data.companyId,
...profileData,
updatedAt: new Date(),
});
if (updatedProfile) {
return updatedProfile;
}
const existingProfile = await this.organizationFiscalProfiles.findOne({
companyId: data.companyId,
});
if (existingProfile) {
return existingProfile;
}
}
throw error;
}
}
public async find(
data: FindOrganizationFiscalProfilesParams
): Promise<IOrganizationFiscalProfile[]> {
if (!data.sessionUser) {
throw new Error("Se requiere un usuario autenticado");
}
const sessionUser = data.sessionUser;
await validateSessionUser({ sessionUser });
if (data.companyId) {
await validatePermissionsByCompany({
companyId: data.companyId,
sessionUser,
});
} else if (data.id) {
const profile = await this.organizationFiscalProfiles.findOne(data);
if (!profile) {
return [];
}
await validatePermissionsByCompany({
companyId: String(profile.companyId),
sessionUser,
});
return [profile];
} else {
throw new Error("Se requiere una organización para buscar perfiles fiscales");
}
return await this.organizationFiscalProfiles.find(data);
}
}
export default new OrganizationFiscalProfilesManager();
@@ -1,4 +1,5 @@
import { import {
CreateWapServerParams,
FindWapServerParams, FindWapServerParams,
IWapServer, IWapServer,
IWapServerAdapter, IWapServerAdapter,
@@ -28,6 +29,10 @@ export class WapServerAdapterMongoose implements IWapServerAdapter {
this.serverList = model<IWapServerDocument>("WapServer", this.schema); 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[]> { public async find(data: FindWapServerParams): Promise<IWapServer[]> {
return this.serverList.find(data).exec(); return this.serverList.find(data).exec();
} }
@@ -36,6 +41,10 @@ export class WapServerAdapterMongoose implements IWapServerAdapter {
return this.serverList.findOne(data).exec(); 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> { private buildSearchCriteria(filters: FindWapServerParams): FilterQuery<IWapServerDocument> {
const searchCriteria: FilterQuery<IWapServerDocument> = {}; const searchCriteria: FilterQuery<IWapServerDocument> = {};
@@ -7,6 +7,7 @@ export type FindWapServerParams = {
description?: string; description?: string;
countBots?: number; countBots?: number;
maxBots?: number; maxBots?: number;
port?: number;
active?: boolean; active?: boolean;
countBotsFrom?: number; countBotsFrom?: number;
countBotsTo?: number; countBotsTo?: number;
@@ -100,9 +101,29 @@ export interface IWapServer {
ipv6: string; ipv6: string;
countBots: number; countBots: number;
maxBots: number; maxBots: number;
port: number;
active: boolean; 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 & { export type PaginateWapServerParams = FindWapServerParams & {
page: number; page: number;
limit: number; limit: number;
@@ -114,13 +135,124 @@ export type PaginateWapServerResults = {
pages: number; 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 & { export type SysAdminGetWapServerParams = PaginateWapServerParams & {
payload: IPayload; 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 { export interface IWapServerAdapter {
create(data: CreateWapServerParams): Promise<IWapServer>;
find(data: FindWapServerParams): Promise<IWapServer[]>; find(data: FindWapServerParams): Promise<IWapServer[]>;
findOne(data: FindWapServerParams): Promise<IWapServerDocument | null>; findOne(data: FindWapServerParams): Promise<IWapServerDocument | null>;
delete(id: string): Promise<void>;
paginate(filters: PaginateWapServerParams): Promise<PaginateWapServerResults>; paginate(filters: PaginateWapServerParams): Promise<PaginateWapServerResults>;
} }
@@ -140,4 +272,15 @@ export interface IWapServerManager {
getQr(data: BotEventParams): Promise<string>; getQr(data: BotEventParams): Promise<string>;
sendMessage(data: SendBotMessageParams): Promise<void>; sendMessage(data: SendBotMessageParams): Promise<void>;
sysAdminGetWapServers(data: PaginateWapServerParams): Promise<PaginateWapServerResults>; 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>;
} }
+608 -1
View File
@@ -13,20 +13,39 @@ import {
BotView, BotView,
IWapServer, IWapServer,
IWapServerManager, IWapServerManager,
SysAdminDeleteWapServerParams,
SysAdminDeleteWapServerResult,
SysAdminWapContainerDto,
SysAdminWapServerAuditParams,
SysAdminWapServerAuditResult,
SysAdminWapServerRecalculateCountParams,
SysAdminWapServerRecalculateCountResult,
SysAdminWapServerDetachResult,
SysAdminWapServerDeleteBotResult,
SysAdminWapServerOrganizationActionParams,
SysAdminWapServerQrResult,
SendBotMessageParams, SendBotMessageParams,
ValidateBotEventStatus, ValidateBotEventStatus,
BOT_STATE, BOT_STATE,
SERVER_STATE, SERVER_STATE,
BOT_SESSION_STATUS, BOT_SESSION_STATUS,
CreateWapServerParams,
VALIDATE_BOT_ENVENT_ERRORS, VALIDATE_BOT_ENVENT_ERRORS,
PaginateWapServerResults, PaginateWapServerResults,
PaginateWapServerParams, PaginateWapServerParams,
UpdateWapServerParams,
} from "./WapServer.Interface"; } from "./WapServer.Interface";
import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons"; import PlanSubscriptionsList from "../PlanSubscriptions/PlanSubscriptons";
import { PlanFeatures } from "../Plans/Plans.interface"; import { PlanFeatures } from "../Plans/Plans.interface";
import axios, { AxiosError } from "axios"; import axios, { AxiosError } from "axios";
import { isNull } from "../../helpers/IsNull"; 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 { export interface CreateBotResult {
organizationId: string; organizationId: string;
port: number; port: number;
@@ -142,10 +161,259 @@ class WapServerManager implements IWapServerManager {
return servidores; 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 { private getBotAdminApiUrl(url: string): string {
//return `https://${url}:${process.env.DEFAULT_BOT_ADMIN_PORT}/`; //return `https://${url}:${process.env.DEFAULT_BOT_ADMIN_PORT}/`;
//return `https://${url}/`; //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> { public async getAvailableServer(): Promise<IWapServer> {
@@ -713,6 +981,345 @@ class WapServerManager implements IWapServerManager {
return servers; 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(); const WapServerList = new WapServerManager();
@@ -6,6 +6,8 @@ import {
AppointmentAdminByDateView, AppointmentAdminByDateView,
CreateAppointmentParams, CreateAppointmentParams,
CreateImmediateAppointmentNotificationJobsParams, CreateImmediateAppointmentNotificationJobsParams,
AppointmentNotificationPreviewParams,
AppointmentNotificationPreviewResult,
DeleteAppointmentParams, DeleteAppointmentParams,
FindAppointmentsParams, FindAppointmentsParams,
FindAppointmentSchedulesParams, 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") @Route("appointments/apply-discount")
@Middlewares(authenticateMiddleware) @Middlewares(authenticateMiddleware)
export class ApplyAppointmentDiscountContrnoller extends Controller { export class ApplyAppointmentDiscountContrnoller extends Controller {
@@ -2,6 +2,8 @@ import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
import AppointmentList from "../../Models/Appointments/Appointments"; import AppointmentList from "../../Models/Appointments/Appointments";
import { import {
CreateImmediateAppointmentNotificationJobsParams, CreateImmediateAppointmentNotificationJobsParams,
AppointmentNotificationPreviewParams,
AppointmentNotificationPreviewResult,
AppointmentAdminByClientView, AppointmentAdminByClientView,
AppointmentAdminByDateView, AppointmentAdminByDateView,
CreateAppointmentParams, CreateAppointmentParams,
@@ -167,6 +169,11 @@ export class AppointmentService {
await AppointmentList.createImmediateNotificationJobs(data); 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> { public async applyDiscount(data: ApplyAppointmentDiscountParams): Promise<void> {
await connect(`${process.env.DATABASE_CONNECTION}`); await connect(`${process.env.DATABASE_CONNECTION}`);
await AppointmentList.applyDiscount(data); await AppointmentList.applyDiscount(data);
@@ -0,0 +1,26 @@
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
import { ApiValidationError } from "../../Models/Server.Error.model";
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
import { authenticateMiddleware } from "../../middleware/authentication";
import { ArcaActivitiesService, FilterArcaActivitiesParams } from "./ArcaActivities.Service";
@Route("arca-activities/filter-all")
@Middlewares(authenticateMiddleware)
export class ArcaActivitiesFilterAllController extends Controller {
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@SuccessResponse(200, "Done")
@Post()
public async allArcaActivities(
@Body() requestBody: FilterArcaActivitiesParams
): Promise<TextObjectFilterResult[] | ApiValidationError> {
try {
const activities = await new ArcaActivitiesService().textObjectFilter(requestBody);
this.setStatus(200);
return activities;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@@ -0,0 +1,12 @@
import { TextObjectFilterResult } from "../../Models/TextObjectFilter.model";
import { filterArcaActivities } from "../../Models/ArcaActivities/ArcaActivities.Catalog";
export type FilterArcaActivitiesParams = {
name?: string;
};
export class ArcaActivitiesService {
public async textObjectFilter(data: FilterArcaActivitiesParams): Promise<TextObjectFilterResult[]> {
return filterArcaActivities(data.name);
}
}
@@ -0,0 +1,142 @@
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
import { authenticateMiddleware } from "../../middleware/authentication";
import { ApiValidationError } from "../../Models/Server.Error.model";
import {
ArcaCredentialView,
ArcaWsfeDiagnosticsParams,
ArcaWsfeDiagnosticsResult,
ArcaWsfeLastVoucherParams,
ArcaWsfeLastVoucherResult,
ArcaWsaaLoginTestResult,
FindArcaCredentialsParams,
GenerateArcaCredentialCsrParams,
TestArcaWsaaLoginParams,
UploadArcaCredentialCertificateParams,
} from "../../Models/ArcaCredentials/ArcaCredentials.Interface";
import { ArcaCredentialsService } from "./ArcaCredentials.Service";
@Route("arca-credentials/generate-csr")
@Middlewares(authenticateMiddleware)
export class ArcaCredentialsGenerateCsrController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async generateCsr(
@Body() requestBody: GenerateArcaCredentialCsrParams
): Promise<ArcaCredentialView | ApiValidationError> {
try {
const credential = await new ArcaCredentialsService().generateCsr(requestBody);
this.setStatus(200);
return credential;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@Route("arca-credentials/upload-certificate")
@Middlewares(authenticateMiddleware)
export class ArcaCredentialsUploadCertificateController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async uploadCertificate(
@Body() requestBody: UploadArcaCredentialCertificateParams
): Promise<ArcaCredentialView | ApiValidationError> {
try {
const credential = await new ArcaCredentialsService().uploadCertificate(requestBody);
this.setStatus(200);
return credential;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@Route("arca-credentials/test-wsaa-login")
@Middlewares(authenticateMiddleware)
export class ArcaCredentialsTestWsaaLoginController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async testWsaaLogin(
@Body() requestBody: TestArcaWsaaLoginParams
): Promise<ArcaWsaaLoginTestResult | ApiValidationError> {
try {
const result = await new ArcaCredentialsService().testWsaaLogin(requestBody);
this.setStatus(200);
return result;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@Route("arca-credentials/wsfe-last-voucher")
@Middlewares(authenticateMiddleware)
export class ArcaCredentialsWsfeLastVoucherController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async getWsfeLastVoucher(
@Body() requestBody: ArcaWsfeLastVoucherParams
): Promise<ArcaWsfeLastVoucherResult | ApiValidationError> {
try {
const result = await new ArcaCredentialsService().getWsfeLastVoucher(requestBody);
this.setStatus(200);
return result;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@Route("arca-credentials/wsfe-diagnostics")
@Middlewares(authenticateMiddleware)
export class ArcaCredentialsWsfeDiagnosticsController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async getWsfeDiagnostics(
@Body() requestBody: ArcaWsfeDiagnosticsParams
): Promise<ArcaWsfeDiagnosticsResult | ApiValidationError> {
try {
const result = await new ArcaCredentialsService().getWsfeDiagnostics(requestBody);
this.setStatus(200);
return result;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@Route("arca-credentials/find")
@Middlewares(authenticateMiddleware)
export class ArcaCredentialsFindController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async find(
@Body() requestBody: FindArcaCredentialsParams
): Promise<ArcaCredentialView[] | ApiValidationError> {
try {
const credentials = await new ArcaCredentialsService().find(requestBody);
this.setStatus(200);
return credentials;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@@ -0,0 +1,46 @@
import { connect } from "mongoose";
import ArcaCredentials from "../../Models/ArcaCredentials/ArcaCredentials";
import {
ArcaCredentialView,
ArcaWsfeDiagnosticsParams,
ArcaWsfeDiagnosticsResult,
ArcaWsfeLastVoucherParams,
ArcaWsfeLastVoucherResult,
ArcaWsaaLoginTestResult,
FindArcaCredentialsParams,
GenerateArcaCredentialCsrParams,
TestArcaWsaaLoginParams,
UploadArcaCredentialCertificateParams,
} from "../../Models/ArcaCredentials/ArcaCredentials.Interface";
export class ArcaCredentialsService {
public async generateCsr(data: GenerateArcaCredentialCsrParams): Promise<ArcaCredentialView> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await ArcaCredentials.generateCsr(data);
}
public async uploadCertificate(data: UploadArcaCredentialCertificateParams): Promise<ArcaCredentialView> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await ArcaCredentials.uploadCertificate(data);
}
public async testWsaaLogin(data: TestArcaWsaaLoginParams): Promise<ArcaWsaaLoginTestResult> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await ArcaCredentials.testWsaaLogin(data);
}
public async getWsfeLastVoucher(data: ArcaWsfeLastVoucherParams): Promise<ArcaWsfeLastVoucherResult> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await ArcaCredentials.getWsfeLastVoucher(data);
}
public async getWsfeDiagnostics(data: ArcaWsfeDiagnosticsParams): Promise<ArcaWsfeDiagnosticsResult> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await ArcaCredentials.getWsfeDiagnostics(data);
}
public async find(data: FindArcaCredentialsParams): Promise<ArcaCredentialView[]> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await ArcaCredentials.find(data);
}
}
@@ -0,0 +1,49 @@
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
import { authenticateMiddleware } from "../../middleware/authentication";
import { ApiValidationError } from "../../Models/Server.Error.model";
import {
CreateInvoiceFromCashMovementParams,
FindInvoicesParams,
IInvoice,
} from "../../Models/Invoices/Invoices.Interface";
import { InvoicesService } from "./Invoices.Service";
@Route("invoices/create-from-cash-movement")
@Middlewares(authenticateMiddleware)
export class InvoicesCreateFromCashMovementController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async createFromCashMovement(
@Body() requestBody: CreateInvoiceFromCashMovementParams
): Promise<IInvoice | ApiValidationError> {
try {
const invoice = await new InvoicesService().createFromCashMovement(requestBody);
this.setStatus(200);
return invoice;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@Route("invoices/find")
@Middlewares(authenticateMiddleware)
export class InvoicesFindController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async find(@Body() requestBody: FindInvoicesParams): Promise<IInvoice[] | ApiValidationError> {
try {
const invoices = await new InvoicesService().find(requestBody);
this.setStatus(200);
return invoices;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@@ -0,0 +1,19 @@
import { connect } from "mongoose";
import Invoices from "../../Models/Invoices/Invoices";
import {
CreateInvoiceFromCashMovementParams,
FindInvoicesParams,
IInvoice,
} from "../../Models/Invoices/Invoices.Interface";
export class InvoicesService {
public async createFromCashMovement(data: CreateInvoiceFromCashMovementParams): Promise<IInvoice> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await Invoices.createFromCashMovement(data);
}
public async find(data: FindInvoicesParams): Promise<IInvoice[]> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await Invoices.find(data);
}
}
@@ -0,0 +1,51 @@
import { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
import { authenticateMiddleware } from "../../middleware/authentication";
import { ApiValidationError } from "../../Models/Server.Error.model";
import {
FindOrganizationFiscalProfilesParams,
IOrganizationFiscalProfile,
UpsertOrganizationFiscalProfileParams,
} from "../../Models/OrganizationFiscalProfiles/OrganizationFiscalProfiles.Interface";
import { OrganizationFiscalProfilesService } from "./OrganizationFiscalProfiles.Service";
@Route("organization-fiscal-profiles/upsert")
@Middlewares(authenticateMiddleware)
export class OrganizationFiscalProfilesUpsertController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async upsert(
@Body() requestBody: UpsertOrganizationFiscalProfileParams
): Promise<IOrganizationFiscalProfile | ApiValidationError> {
try {
const profile = await new OrganizationFiscalProfilesService().upsert(requestBody);
this.setStatus(200);
return profile;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@Route("organization-fiscal-profiles/find")
@Middlewares(authenticateMiddleware)
export class OrganizationFiscalProfilesFindController extends Controller {
@SuccessResponse(200, "Done")
@Response<ApiValidationError>(500, "Ha ocurrido un error")
@Post()
public async find(
@Body() requestBody: FindOrganizationFiscalProfilesParams
): Promise<IOrganizationFiscalProfile[] | ApiValidationError> {
try {
const profiles = await new OrganizationFiscalProfilesService().find(requestBody);
this.setStatus(200);
return profiles;
} catch (e) {
const errorOccurred: Error = e as Error;
this.setStatus(500);
return new ApiValidationError(500, errorOccurred.message);
}
}
}
@@ -0,0 +1,23 @@
import { connect } from "mongoose";
import OrganizationFiscalProfiles from "../../Models/OrganizationFiscalProfiles/OrganizationFiscalProfiles";
import {
FindOrganizationFiscalProfilesParams,
IOrganizationFiscalProfile,
UpsertOrganizationFiscalProfileParams,
} from "../../Models/OrganizationFiscalProfiles/OrganizationFiscalProfiles.Interface";
export class OrganizationFiscalProfilesService {
public async upsert(
data: UpsertOrganizationFiscalProfileParams
): Promise<IOrganizationFiscalProfile> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await OrganizationFiscalProfiles.upsert(data);
}
public async find(
data: FindOrganizationFiscalProfilesParams
): Promise<IOrganizationFiscalProfile[]> {
await connect(`${process.env.DATABASE_CONNECTION}`);
return await OrganizationFiscalProfiles.find(data);
}
}
@@ -3,6 +3,8 @@ import {
SysAdminPaginateCompaniesParams, SysAdminPaginateCompaniesParams,
SysAdminUpdateCompanyParams, SysAdminUpdateCompanyParams,
SysAdminSetCompanyBannedParams, SysAdminSetCompanyBannedParams,
SysAdminCompanyInsightsParams,
SysAdminCompanyInsightsResult,
} from "../../../Models/Companies/Companies.Interface"; } from "../../../Models/Companies/Companies.Interface";
import { ApiValidationError } from "../../../Models/Server.Error.model"; import { ApiValidationError } from "../../../Models/Server.Error.model";
import { ApiVoidResult } from "../../../Models/Api.VoidResult.type"; import { ApiVoidResult } from "../../../Models/Api.VoidResult.type";
@@ -66,4 +68,23 @@ export class SysAdminCompaniesController extends Controller {
return new ApiValidationError(500, errorOccurred.message); 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, SysAdminPaginateCompaniesParams,
SysAdminUpdateCompanyParams, SysAdminUpdateCompanyParams,
SysAdminSetCompanyBannedParams, SysAdminSetCompanyBannedParams,
SysAdminCompanyInsightsParams,
SysAdminCompanyInsightsResult,
} from "../../../Models/Companies/Companies.Interface"; } from "../../../Models/Companies/Companies.Interface";
import CompaniesList from "../../../Models/Companies/Companies"; import CompaniesList from "../../../Models/Companies/Companies";
@@ -22,4 +24,9 @@ export class SA_CompaniesService {
await connect(`${process.env.DATABASE_CONNECTION}`); await connect(`${process.env.DATABASE_CONNECTION}`);
return await CompaniesList.sysAdminSetBanned(data); 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 { import {
PaginateWapServerResults, PaginateWapServerResults,
SysAdminCreateWapServerParams,
SysAdminDeleteWapServerRequest,
SysAdminDeleteWapServerResult,
SysAdminAuditWapServerParams,
SysAdminGetWapServerParams, SysAdminGetWapServerParams,
SysAdminRecalculateWapServerCountParams,
SysAdminWapServerDeleteBotResult,
SysAdminWapServerDetachResult,
SysAdminWapServerAuditResult,
SysAdminWapServerOrganizationActionRequest,
SysAdminWapServerQrResult,
SysAdminWapServerRecalculateCountResult,
SysAdminUpdateWapServerParams,
IWapServer,
} from "../../../Models/WapServer/WapServer.Interface"; } from "../../../Models/WapServer/WapServer.Interface";
import { ApiValidationError } from "../../../Models/Server.Error.model"; 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 { Body, Controller, Middlewares, Post, Response, Route, SuccessResponse } from "tsoa";
import { SA_WapServerService } from "./SysAdminWapServer.Service"; import { SA_WapServerService } from "./SysAdminWapServer.Service";
import { sysAdminAuthMiddleware } from "../../../middleware/sysadminAuth"; 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") @Route("sysadmin/wapserver/get")
export class SysAdminWapServerGetController extends Controller { export class SysAdminWapServerGetController extends Controller {
@Response<ApiValidationError>(500, "Ha ocurrido un error") @Response<ApiValidationError>(500, "Ha ocurrido un error")
@@ -20,6 +90,69 @@ export class SysAdminWapServerGetController extends Controller {
const result = await new SA_WapServerService().sysAdminGetWapServers(requestBody); const result = await new SA_WapServerService().sysAdminGetWapServers(requestBody);
this.setStatus(200); this.setStatus(200);
return result; 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) { } catch (e) {
const errorOccurred: Error = e as Error; const errorOccurred: Error = e as Error;
this.setStatus(500); 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 { connect } from "mongoose";
import { import {
CreateWapServerParams,
PaginateWapServerParams, PaginateWapServerParams,
PaginateWapServerResults, PaginateWapServerResults,
SysAdminDeleteWapServerParams,
SysAdminDeleteWapServerResult,
SysAdminWapServerAuditParams,
SysAdminWapServerAuditResult,
SysAdminWapServerDeleteBotResult,
SysAdminWapServerDetachResult,
SysAdminWapServerOrganizationActionParams,
SysAdminWapServerQrResult,
SysAdminWapServerRecalculateCountParams,
SysAdminWapServerRecalculateCountResult,
UpdateWapServerParams,
} from "../../../Models/WapServer/WapServer.Interface"; } from "../../../Models/WapServer/WapServer.Interface";
import WapServerList from "../../../Models/WapServer/WapServer"; import WapServerList from "../../../Models/WapServer/WapServer";
@@ -11,4 +23,65 @@ export class SA_WapServerService {
await connect(`${process.env.DATABASE_CONNECTION}`); await connect(`${process.env.DATABASE_CONNECTION}`);
return await WapServerList.sysAdminGetWapServers(data); 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);
}
} }
+220
View File
@@ -174,6 +174,156 @@ export const fetchWapServers = async (filters: any) => {
return res.data; 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 // Companies API Calls
export const fetchCompanies = async (filters: any) => { export const fetchCompanies = async (filters: any) => {
const res = await sysadminApi.post('/companies/paginate', filters); const res = await sysadminApi.post('/companies/paginate', filters);
@@ -190,6 +340,76 @@ export const setCompanyBanned = async (id: string, banned: boolean) => {
return res.data; 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 // Services API Calls
export const fetchServices = async (filters: any) => { export const fetchServices = async (filters: any) => {
const res = await sysadminApi.post('/services/paginate', filters); 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>
);
};
+33
View File
@@ -160,3 +160,36 @@ button {
.animate-fade-in { .animate-fade-in {
animation: fadeIn 0.4s ease-out forwards; 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;
}
}
+5 -60
View File
@@ -1,9 +1,10 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion'; 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 { fetchCompanies, setCompanyBanned } from '../api/sysadmin';
import { EditCompanyModal } from '../components/ui/EditCompanyModal'; import { EditCompanyModal } from '../components/ui/EditCompanyModal';
import { CompanyServicesModal } from '../components/ui/CompanyServicesModal'; import { CompanyServicesModal } from '../components/ui/CompanyServicesModal';
import { OrganizationInsightsModal } from '../components/ui/OrganizationInsightsModal';
export const CompaniesPage = () => { export const CompaniesPage = () => {
const [companies, setCompanies] = useState<any[]>([]); const [companies, setCompanies] = useState<any[]>([]);
@@ -22,6 +23,7 @@ export const CompaniesPage = () => {
// Modals state // Modals state
const [editingCompany, setEditingCompany] = useState<any>(null); const [editingCompany, setEditingCompany] = useState<any>(null);
const [servicesCompany, setServicesCompany] = useState<any>(null); const [servicesCompany, setServicesCompany] = useState<any>(null);
const [insightsCompany, setInsightsCompany] = useState<any>(null);
const loadCompanies = async () => { const loadCompanies = async () => {
setLoading(true); setLoading(true);
@@ -176,6 +178,7 @@ export const CompaniesPage = () => {
</td> </td>
<td style={{ padding: '1rem', textAlign: 'right' }}> <td style={{ padding: '1rem', textAlign: 'right' }}>
<div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}> <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="Ver Servicios" onClick={() => setServicesCompany(c)}><Box size={18} /></button>
<button className="icon-btn" title="Editar Detalles" onClick={() => setEditingCompany(c)}><Edit2 size={18} /></button> <button className="icon-btn" title="Editar Detalles" onClick={() => setEditingCompany(c)}><Edit2 size={18} /></button>
</div> </div>
@@ -197,68 +200,10 @@ export const CompaniesPage = () => {
</div> </div>
</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 */} {/* Modals */}
{editingCompany && <EditCompanyModal company={editingCompany} onClose={() => setEditingCompany(null)} onSaved={loadCompanies} />} {editingCompany && <EditCompanyModal company={editingCompany} onClose={() => setEditingCompany(null)} onSaved={loadCompanies} />}
{servicesCompany && <CompanyServicesModal company={servicesCompany} onClose={() => setServicesCompany(null)} />} {servicesCompany && <CompanyServicesModal company={servicesCompany} onClose={() => setServicesCompany(null)} />}
{insightsCompany && <OrganizationInsightsModal company={insightsCompany} onClose={() => setInsightsCompany(null)} />}
</motion.div> </motion.div>
); );
}; };
+861 -7
View File
@@ -1,13 +1,39 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion'; import { motion } from 'framer-motion';
import { Search, RotateCcw, CheckCircle, XCircle, Server, ServerOff } from 'lucide-react'; import { Search, RotateCcw, CheckCircle, XCircle, Server, ServerOff, ClipboardList, Calculator, X, MoreVertical, Play, Pause, Power, Trash2, Unlink, QrCode, RotateCw, Edit3, Plus } from 'lucide-react';
import { fetchWapServers } from '../api/sysadmin'; 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 = () => { export const WapServersPage = () => {
const [servers, setServers] = useState<any[]>([]); const [servers, setServers] = useState<any[]>([]);
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1); const [totalPages, setTotalPages] = useState(1);
const [loading, setLoading] = useState(false); 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 // Filters
const [filters, setFilters] = useState({ const [filters, setFilters] = useState({
@@ -42,6 +68,18 @@ export const WapServersPage = () => {
loadServers(); loadServers();
}, [page, filters.active]); }, [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) => { const handleSearch = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
setPage(1); setPage(1);
@@ -59,16 +97,225 @@ export const WapServersPage = () => {
setPage(1); 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(() => { useEffect(() => {
if (filters.name === '' && filters.description === '' && filters.active === 'all' && filters.countBotsFrom === '' && filters.countBotsTo === '') { if (filters.name === '' && filters.description === '' && filters.active === 'all' && filters.countBotsFrom === '' && filters.countBotsTo === '') {
loadServers(); loadServers();
} }
}, [filters]); }, [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 ( 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' }}> <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 }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem', flexShrink: 0 }}>
<h1 style={{ fontSize: '2rem', fontWeight: '700' }}>Servidores WAP</h1> <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> </div>
{/* Filters Bar */} {/* 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' }}>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' }}>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' }}>Estado</th>
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'center' }}>Diagnóstico</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{loading ? ( {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 ? ( ) : 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 => ( 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"> 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' }}> <td style={{ padding: '1rem' }}>
<div style={{ fontWeight: '600', color: 'var(--text-main)', display: 'flex', alignItems: 'center', gap: '8px' }}> <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)" />} {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'} {s.active ? 'Activo' : 'Inactivo'}
</div> </div>
</td> </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> </tr>
)) </React.Fragment>
);})
)} )}
</tbody> </tbody>
</table> </table>
@@ -196,6 +481,255 @@ export const WapServersPage = () => {
</div> </div>
</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: ` <style dangerouslySetInnerHTML={{__html: `
.sticky-header { .sticky-header {
position: sticky; position: sticky;
@@ -209,6 +743,326 @@ export const WapServersPage = () => {
.table-row-hover:hover { .table-row-hover:hover {
background: rgba(255, 255, 255, 0.02); 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> </motion.div>
); );
+2
View File
@@ -1,2 +1,4 @@
API_HOST = http://localhost:3000 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 API_PRIVATE_KEY=keys/tx-sysadmin-private.key
@@ -1,5 +1,5 @@
import { Request, Response } from "express"; 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) => { export const paginate = async (req: Request, res: Response) => {
try { try {
@@ -33,3 +33,14 @@ export const setBanned = async (req: Request, res: Response) => {
res.status(500).json({ error: err }); 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 });
}
};
+144 -1
View File
@@ -1,9 +1,28 @@
import axios from "axios";
import { Request, Response } from "express"; import { Request, Response } from "express";
import { WapService } from "../services/wap.service"; 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 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 { export class WapController {
public getServers = async (req: Request, res: Response): Promise<void> => { public getServers = async (req: Request, res: Response): Promise<void> => {
try { try {
@@ -15,4 +34,128 @@ export class WapController {
res.status(500).json({ success: false, message: "Internal Server Error" }); 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 });
}
};
} }
+69
View File
@@ -35,3 +35,72 @@ export type SetCompanyBannedParams = {
id: string; id: string;
banned: boolean; 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;
};
};
+90
View File
@@ -6,6 +6,7 @@ export type FindWapServerParams = {
description?: string; description?: string;
countBots?: number; countBots?: number;
maxBots?: number; maxBots?: number;
port?: number;
active?: boolean; active?: boolean;
countBotsFrom?: number; countBotsFrom?: number;
countBotsTo?: number; countBotsTo?: number;
@@ -19,9 +20,29 @@ export interface IWapServer {
ipv6: string; ipv6: string;
countBots: number; countBots: number;
maxBots: number; maxBots: number;
port: number;
active: boolean; 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 & { export type PaginateWapServerParams = FindWapServerParams & {
page: number; page: number;
limit: number; limit: number;
@@ -36,3 +57,72 @@ export type PaginateWapServerResults = {
export type SysAdminGetWapServerParams = PaginateWapServerParams & { export type SysAdminGetWapServerParams = PaginateWapServerParams & {
payload: IPayload; 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;
};
+2 -1
View File
@@ -1,10 +1,11 @@
import { Router } from "express"; import { Router } from "express";
import { paginate, setBanned, update } from "../controllers/companies.controller"; import { insights, paginate, setBanned, update } from "../controllers/companies.controller";
const router = Router(); const router = Router();
router.post("/paginate", paginate); router.post("/paginate", paginate);
router.post("/update", update); router.post("/update", update);
router.post("/set-banned", setBanned); router.post("/set-banned", setBanned);
router.post("/insights", insights);
export default router; export default router;
+11
View File
@@ -5,5 +5,16 @@ const router = Router();
const wapController = new WapController(); const wapController = new WapController();
router.post("/paginate", wapController.getServers); 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; export default router;
@@ -5,6 +5,8 @@ import { getApiHost } from "../helpers/GetApiHost";
import { import {
PaginateCompaniesParams, PaginateCompaniesParams,
PaginateCompaniesResults, PaginateCompaniesResults,
OrganizationInsightsParams,
OrganizationInsightsResult,
SetCompanyBannedParams, SetCompanyBannedParams,
UpdateCompanyParams, UpdateCompanyParams,
} from "../models/Companies.Model"; } from "../models/Companies.Model";
@@ -35,3 +37,12 @@ export const setCompanyBanned = async (params: SetCompanyBannedParams): Promise<
}); });
return result.data; 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;
};
+111 -1
View File
@@ -2,7 +2,21 @@ import { getSysAdminNonce } from "../helpers/GetSysAdminNonce";
import { getApiHost } from "../helpers/GetApiHost"; import { getApiHost } from "../helpers/GetApiHost";
import axios from "axios"; import axios from "axios";
import { getPayload } from "../helpers/GetPayload"; 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 { export class WapService {
public async getWapServers(filters: PaginateWapServerParams): Promise<PaginateWapServerResults> { public async getWapServers(filters: PaginateWapServerParams): Promise<PaginateWapServerResults> {
@@ -20,4 +34,100 @@ export class WapService {
return resultado; 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);
}
} }
+29
View File
@@ -0,0 +1,29 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-electron
dist-ssr
release
release-portable
*.local
*.tsbuildinfo
node_modules/.tmp
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
+32
View File
@@ -0,0 +1,32 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the Oxlint configuration
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
```json
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"options": {
"typeAware": true
},
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
```
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+171
View File
@@ -0,0 +1,171 @@
import { app, BrowserWindow, dialog, ipcMain } from 'electron';
import type { OpenDialogOptions } from 'electron';
import path from 'node:path';
import fs from 'node:fs';
import crypto from 'node:crypto';
import axios from 'axios';
type Nonce = { id?: string; _id?: string; nonce: string; expiresAt?: string };
let mainWindow: BrowserWindow | null = null;
let privateKey: Buffer | null = null;
let privateKeyPath: string | null = null;
const apiHost = (process.env.API_HOST || 'https://api.turnosxpress.com.ar').replace(/\/+$/, '');
const adminRoutes: Record<string, { path: string; timeout?: number }> = {
'users/paginate': { path: '/sysadmin/users/paginate', timeout: 5000 },
'users/update': { path: '/sysadmin/users/update', timeout: 5000 },
'users/set-verified': { path: '/sysadmin/users/set-verified', timeout: 5000 },
'users/delete': { path: '/sysadmin/users/delete', timeout: 10000 },
'users/organizations-status': { path: '/sysadmin/users/organizations-status', timeout: 5000 },
'users/recalculate-plan-usage-cycle': { path: '/sysadmin/plan-usage-cycle/recalculate-user', timeout: 10000 },
'users/subscription-details': { path: '/sysadmin/subscriptions/user-details', timeout: 10000 },
'users/extend-subscription': { path: '/sysadmin/subscriptions/extend-user', timeout: 10000 },
'users/finalize-subscription': { path: '/sysadmin/subscriptions/finalize-user', timeout: 10000 },
'plans/list': { path: '/sysadmin/plans/list', timeout: 5000 },
'plans/update': { path: '/sysadmin/plans/update', timeout: 5000 },
'wap/paginate': { path: '/sysadmin/wapserver/get', timeout: 5000 },
'wap/audit': { path: '/sysadmin/wapserver/audit', timeout: 10000 },
'wap/create': { path: '/sysadmin/wapserver/create', timeout: 5000 },
'wap/update': { path: '/sysadmin/wapserver/update', timeout: 5000 },
'wap/recalculate-count': { path: '/sysadmin/wapserver/recalculate-count', timeout: 5000 },
'wap/delete': { path: '/sysadmin/wapserver/delete', timeout: 15000 },
'wap/bot/start': { path: '/sysadmin/wapserver/bot/start', timeout: 10000 },
'wap/bot/stop': { path: '/sysadmin/wapserver/bot/stop', timeout: 10000 },
'wap/bot/restart': { path: '/sysadmin/wapserver/bot/restart', timeout: 15000 },
'wap/bot/qr': { path: '/sysadmin/wapserver/bot/qr', timeout: 10000 },
'wap/bot/delete': { path: '/sysadmin/wapserver/bot/delete', timeout: 10000 },
'wap/bot/detach': { path: '/sysadmin/wapserver/bot/detach', timeout: 10000 },
'companies/paginate': { path: '/sysadmin/companies/paginate' },
'companies/update': { path: '/sysadmin/companies/update' },
'companies/set-banned': { path: '/sysadmin/companies/set-banned' },
'companies/insights': { path: '/sysadmin/companies/insights' },
'services/paginate': { path: '/sysadmin/services/paginate' },
'services/set-banned': { path: '/sysadmin/services/set-banned' },
};
const createWindow = () => {
mainWindow = new BrowserWindow({
width: 1280,
height: 820,
minWidth: 980,
minHeight: 640,
frame: false,
titleBarStyle: 'hidden',
backgroundColor: '#0f172a',
icon: path.join(__dirname, '../build/icon.png'),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
});
if (process.env.VITE_DEV_SERVER_URL) {
void mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
} else {
void mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
}
};
const loadPrivateKey = async (filePath: string) => {
const key = await fs.promises.readFile(filePath);
crypto.createPrivateKey(key);
privateKey = key;
privateKeyPath = filePath;
};
const createPayload = async () => {
if (!privateKey) {
throw new Error('Load a private key before using admin functions.');
}
const nonceResponse = await axios.get<Nonce>(`${apiHost}/sysadmin-challenges/create`, {
headers: { 'Content-Type': 'application/json' },
timeout: 5000,
});
if (nonceResponse.status !== 201 || !nonceResponse.data?.nonce) {
throw new Error('Could not create the sysadmin nonce.');
}
const signature = crypto.sign(null, Buffer.from(nonceResponse.data.nonce), privateKey);
return { nonce: nonceResponse.data, signature: signature.toString('base64') };
};
const formatError = (error: unknown) => {
if (axios.isAxiosError(error)) {
const data = error.response?.data;
const message = typeof data === 'string' ? data : data?.desc || data?.message || data?.error || error.message;
return { message, status: error.response?.status, data };
}
return { message: error instanceof Error ? error.message : 'Unknown error' };
};
ipcMain.handle('key:status', () => ({ loaded: Boolean(privateKey), path: privateKeyPath }));
ipcMain.handle('window:minimize', () => mainWindow?.minimize());
ipcMain.handle('window:toggle-maximize', () => {
if (!mainWindow) return false;
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
return false;
}
mainWindow.maximize();
return true;
});
ipcMain.handle('window:close', () => mainWindow?.close());
ipcMain.handle('key:select', async () => {
const dialogOptions: OpenDialogOptions = {
title: 'Select sysadmin private key',
properties: ['openFile'],
filters: [{ name: 'Private key', extensions: ['key', 'pem', '*'] }],
};
const result = mainWindow
? await dialog.showOpenDialog(mainWindow, dialogOptions)
: await dialog.showOpenDialog(dialogOptions);
if (result.canceled || !result.filePaths[0]) {
return { loaded: Boolean(privateKey), path: privateKeyPath };
}
await loadPrivateKey(result.filePaths[0]);
return { loaded: true, path: privateKeyPath };
});
ipcMain.handle('admin:request', async (_event, routeName: string, body: unknown) => {
if (!privateKey) {
throw new Error('Load a private key before using admin functions.');
}
const route = adminRoutes[routeName];
if (!route) {
throw new Error(`Unsupported admin route: ${routeName}`);
}
try {
const payload = await createPayload();
const response = await axios.post(`${apiHost}${route.path}`, { ...(body as object), payload }, {
headers: { 'Content-Type': 'application/json' },
timeout: route.timeout ?? 5000,
});
return response.data;
} catch (error) {
throw new Error(JSON.stringify(formatError(error)));
}
});
void app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
+10
View File
@@ -0,0 +1,10 @@
import { contextBridge, ipcRenderer } from 'electron';
contextBridge.exposeInMainWorld('txadmin', {
getKeyStatus: () => ipcRenderer.invoke('key:status'),
selectPrivateKey: () => ipcRenderer.invoke('key:select'),
request: (route: string, body: unknown) => ipcRenderer.invoke('admin:request', route, body),
minimizeWindow: () => ipcRenderer.invoke('window:minimize'),
toggleMaximizeWindow: () => ipcRenderer.invoke('window:toggle-maximize'),
closeWindow: () => ipcRenderer.invoke('window:close'),
});
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>txadmin</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+5713
View File
File diff suppressed because it is too large Load Diff
+58
View File
@@ -0,0 +1,58 @@
{
"name": "txadmin",
"private": true,
"version": "0.0.0",
"main": "dist-electron/main.js",
"scripts": {
"dev": "concurrently -k \"vite\" \"tsc -p tsconfig.electron.json --watch --preserveWatchOutput\" \"wait-on tcp:5173 dist-electron/main.js && cross-env VITE_DEV_SERVER_URL=http://localhost:5173 electron .\"",
"desktop": "npm run build && electron .",
"typecheck": "tsc -b && tsc -p tsconfig.electron.json --noEmit",
"build": "npm run typecheck && vite build && tsc -p tsconfig.electron.json",
"package:win": "npm run build && cross-env CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --win portable --config.directories.output=release-portable",
"lint": "oxlint",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.18.1",
"date-fns": "^4.4.0",
"framer-motion": "^12.42.2",
"lucide-react": "^1.24.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1"
},
"devDependencies": {
"@types/node": "^24.13.2",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.3",
"oxlint": "^1.71.0",
"typescript": "~6.0.2",
"concurrently": "^9.2.1",
"cross-env": "^10.1.0",
"electron": "^39.2.7",
"electron-builder": "^26.0.12",
"vite": "^8.1.1",
"wait-on": "^9.0.3"
},
"build": {
"appId": "com.turnosxpress.txadmin",
"productName": "txadmin",
"asar": false,
"directories": {
"output": "release"
},
"files": [
"dist/**/*",
"dist-electron/**/*",
"build/**/*",
"package.json"
],
"win": {
"icon": "build/icon.png",
"target": [
"portable"
]
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+1
View File
@@ -0,0 +1 @@
/* Removed default App.css */
+99
View File
@@ -0,0 +1,99 @@
import { useEffect, useState } from 'react';
import { HashRouter, Routes, Route } from 'react-router-dom';
import { Minus, Square, X } from 'lucide-react';
import { DashboardLayout } from './components/layout/DashboardLayout';
import { DashboardPage } from './pages/DashboardPage';
import { UsersPage } from './pages/UsersPage';
import { WapServersPage } from './pages/WapServersPage';
import { CompaniesPage } from './pages/CompaniesPage';
import { PlansPage } from './pages/PlansPage';
import txadminIcon from './assets/txadmin-icon.png';
const TitleBar = () => (
<header className="app-titlebar">
<div className="app-titlebar-brand">
<img className="app-titlebar-logo" src={txadminIcon} alt="txadmin" />
<span>txadmin</span>
</div>
<div className="app-titlebar-actions">
<button type="button" aria-label="Minimize window" onClick={() => void window.txadmin.minimizeWindow()}>
<Minus size={16} />
</button>
<button type="button" aria-label="Maximize window" onClick={() => void window.txadmin.toggleMaximizeWindow()}>
<Square size={13} />
</button>
<button type="button" className="close" aria-label="Close window" onClick={() => void window.txadmin.closeWindow()}>
<X size={16} />
</button>
</div>
</header>
);
function App() {
const [keyStatus, setKeyStatus] = useState<{ loaded: boolean; path: string | null }>({ loaded: false, path: null });
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!window.txadmin) {
setError('Desktop bridge is not available. Restart txadmin and try again.');
setLoading(false);
return;
}
window.txadmin.getKeyStatus()
.then(setKeyStatus)
.catch(() => setError('Could not read private key status.'))
.finally(() => setLoading(false));
}, []);
const selectPrivateKey = async () => {
setError(null);
try {
setKeyStatus(await window.txadmin.selectPrivateKey());
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not load the private key.');
}
};
if (loading) {
return <div className="app-shell"><TitleBar /><div className="key-gate">Loading txadmin...</div></div>;
}
if (!keyStatus.loaded) {
return (
<div className="app-shell">
<TitleBar />
<div className="key-gate">
<div className="glass-panel key-gate-card">
<img className="key-gate-logo" src={txadminIcon} alt="txadmin" />
<h1>txadmin</h1>
<p>Load the sysadmin private key to unlock admin functions.</p>
<button className="primary-button" onClick={selectPrivateKey}>Select Private Key</button>
<p className="key-gate-hint">Expected equivalent: sysadmin/keys/tx-sysadmin-private.key</p>
{error && <p className="key-gate-error">{error}</p>}
</div>
</div>
</div>
);
}
return (
<div className="app-shell">
<TitleBar />
<HashRouter>
<Routes>
<Route path="/" element={<DashboardLayout keyPath={keyStatus.path} onSelectPrivateKey={selectPrivateKey} />}>
<Route index element={<DashboardPage />} />
<Route path="users" element={<UsersPage />} />
<Route path="companies" element={<CompaniesPage />} />
<Route path="plans" element={<PlansPage />} />
<Route path="wapservers" element={<WapServersPage />} />
</Route>
</Routes>
</HashRouter>
</div>
);
}
export default App;
+405
View File
@@ -0,0 +1,405 @@
const adminRequest = async <T = any>(route: string, body: unknown): Promise<T> => {
try {
return await window.txadmin.request<T>(route, body);
} catch (error) {
if (error instanceof Error) {
try {
const parsed = JSON.parse(error.message);
throw new Error(parsed.message || error.message);
} catch {
throw error;
}
}
throw error;
}
};
// User API Calls
export const fetchUsers = async (filters: any) => {
return adminRequest('users/paginate', filters);
};
export const updateUserProfile = async (data: any) => {
return adminRequest('users/update', data);
};
export const setVerifiedStatus = async (userId: string, isVerified: boolean) => {
return adminRequest('users/set-verified', { userId, isVerified });
};
export const deleteUser = async (userId: string) => {
return adminRequest('users/delete', { userId });
};
export const getOrganizationsStatus = async (userId: string) => {
return adminRequest('users/organizations-status', { userId });
};
export type RecalculatePlanUsageCycleResult = {
userId: string;
subscriptionId: string;
planId: string;
cycleStart: string;
cycleEnd: string;
organizationsCount: number;
employeesCount: number;
servicesCount: number;
clientsCount: number;
repeatsCount: number;
appointmentsCount: number;
};
export const recalculatePlanUsageCycle = async (userId: string): Promise<RecalculatePlanUsageCycleResult> => {
return adminRequest('users/recalculate-plan-usage-cycle', { userId });
};
export type UserSubscriptionDetails = {
userId: string;
currentSubscription: {
id: string;
plan: {
id: string;
name: string;
code: string;
price: number;
} | null;
startDate: string;
endDate: string;
isActive: boolean;
mpStatus?: string;
billingMonths?: number;
pendingPaymentType?: 'extension' | 'upgrade';
pendingPaymentPreferenceId?: string;
lastPaymentStatus?: string;
} | null;
payments: {
id: string;
subscriptionId: string;
amount: number;
paymentDate: string;
paymentMethod?: string;
status: string;
transactionId?: string;
}[];
};
export const getUserSubscriptionDetails = async (userId: string): Promise<UserSubscriptionDetails> => {
return adminRequest('users/subscription-details', { userId });
};
export type ExtendUserSubscriptionPayload = {
userId: string;
mode: 'add_months' | 'set_end_date';
months?: 1 | 2;
endDate?: string;
reason?: string;
};
export type ExtendUserSubscriptionResult = {
userId: string;
subscriptionId: string;
previousEndDate: string;
newEndDate: string;
paymentId: string;
transactionId?: string;
};
export const extendUserSubscription = async (data: ExtendUserSubscriptionPayload): Promise<ExtendUserSubscriptionResult> => {
return adminRequest('users/extend-subscription', data);
};
export type FinalizeUserSubscriptionPayload = {
userId: string;
reason?: string;
};
export type FinalizeUserSubscriptionResult = {
userId: string;
subscriptionId: string;
previousEndDate: string;
newEndDate: string;
};
export const finalizeUserSubscription = async (data: FinalizeUserSubscriptionPayload): Promise<FinalizeUserSubscriptionResult> => {
return adminRequest('users/finalize-subscription', data);
};
export type Plan = {
id?: string;
_id?: string;
name: string;
description: string;
features: string[];
code: string;
price: number;
annualPrice: number;
limitOrganizations: number;
limitEmployees: number;
limitServices: number;
limitAppointments: number;
limitClients: number;
limitRepeats: number;
mailNotifications: boolean;
smsNotifications: boolean;
wapNotifications: boolean;
payments: boolean;
bot: boolean;
active: boolean;
dateLimit: boolean;
discount3Months?: number;
discount6Months?: number;
discount12Months?: number;
featured?: boolean;
};
export type UpdatePlanPayload = Partial<Omit<Plan, 'id' | '_id'>> & {
planId: string;
};
export const fetchPlans = async (): Promise<Plan[]> => {
return adminRequest('plans/list', {});
};
export const updatePlan = async (data: UpdatePlanPayload) => {
return adminRequest('plans/update', data);
};
// Wap Servers API Calls
export const fetchWapServers = async (filters: any) => {
return adminRequest('wap/paginate', filters);
};
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> => {
return adminRequest('wap/create', data);
};
export const updateWapServer = async (data: UpdateWapServerPayload): Promise<WapServer> => {
return adminRequest('wap/update', 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> => {
return adminRequest('wap/audit', { serverId });
};
export const recalculateWapServerCount = async (serverId: string): Promise<WapServerRecalculateCountResult> => {
return adminRequest('wap/recalculate-count', { serverId });
};
export const deleteWapServer = async (data: WapServerDeletePayload): Promise<WapServerDeleteResult> => {
return adminRequest('wap/delete', data);
};
export const startWapBot = async (data: WapServerOrganizationActionPayload): Promise<void> => {
await adminRequest('wap/bot/start', data);
};
export const stopWapBot = async (data: WapServerOrganizationActionPayload): Promise<void> => {
await adminRequest('wap/bot/stop', data);
};
export const restartWapBot = async (data: WapServerOrganizationActionPayload): Promise<void> => {
await adminRequest('wap/bot/restart', data);
};
export const getWapBotQr = async (data: WapServerOrganizationActionPayload): Promise<WapServerQrResult> => {
return adminRequest('wap/bot/qr', data);
};
export const deleteWapBot = async (data: WapServerOrganizationActionPayload): Promise<void> => {
await adminRequest('wap/bot/delete', data);
};
export const detachWapOrganizationServer = async (data: WapServerOrganizationActionPayload): Promise<WapServerDetachResult> => {
return adminRequest('wap/bot/detach', data);
};
// Companies API Calls
export const fetchCompanies = async (filters: any) => {
return adminRequest('companies/paginate', filters);
};
export const updateCompany = async (data: any) => {
return adminRequest('companies/update', data);
};
export const setCompanyBanned = async (id: string, banned: boolean) => {
return adminRequest('companies/set-banned', { id, banned });
};
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> => {
return adminRequest('companies/insights', { companyId });
};
// Services API Calls
export const fetchServices = async (filters: any) => {
return adminRequest('services/paginate', filters);
};
export const setServiceBanned = async (id: string, banned: boolean) => {
return adminRequest('services/set-banned', { id, banned });
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

@@ -0,0 +1,126 @@
import { Outlet, NavLink } from 'react-router-dom';
import { Users, LayoutDashboard, LogOut, Server, Building2, BadgeDollarSign } from 'lucide-react';
import { motion } from 'framer-motion';
import txadminIcon from '../../assets/txadmin-icon.png';
type DashboardLayoutProps = {
keyPath: string | null;
onSelectPrivateKey: () => void;
};
export const DashboardLayout = ({ keyPath, onSelectPrivateKey }: DashboardLayoutProps) => {
return (
<div className="dashboard-container" style={{ display: 'flex', minHeight: 'calc(100vh - 42px)', overflow: 'hidden' }}>
{/* Sidebar */}
<motion.aside
initial={{ x: -200, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
className="glass-panel sidebar"
style={{ display: 'flex', flexDirection: 'column' }}
>
<div style={{ marginBottom: '2rem', display: 'flex', alignItems: 'center', gap: '10px' }}>
<img src={txadminIcon} alt="txadmin" style={{ width: '40px', height: '40px', borderRadius: '12px', objectFit: 'cover' }} />
<h2 style={{ fontSize: '1.2rem', fontWeight: '700', letterSpacing: '1px' }}>txadmin</h2>
</div>
<nav style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
<NavLink to="/" end className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
<LayoutDashboard size={20} />
Dashboard
</NavLink>
<NavLink to="/users" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
<Users size={20} />
Users
</NavLink>
<NavLink to="/companies" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
<Building2 size={20} />
Organizations
</NavLink>
<NavLink to="/plans" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
<BadgeDollarSign size={20} />
Plans
</NavLink>
<NavLink to="/wapservers" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
<Server size={20} />
WAP Servers
</NavLink>
</nav>
<div style={{ marginTop: 'auto', paddingTop: '1rem', borderTop: '1px solid var(--glass-border)' }}>
<button className="nav-item" style={{ width: '100%', background: 'transparent', color: 'var(--text-muted)' }} onClick={onSelectPrivateKey} title={keyPath ?? undefined}>
<LogOut size={20} />
Change Key
</button>
</div>
</motion.aside>
{/* Main Content */}
<main className="main-content" style={{ flex: 1, padding: '1rem', display: 'flex', flexDirection: 'column', height: 'calc(100vh - 42px)', overflow: 'hidden' }}>
<Outlet />
</main>
{/* Global Sidebar styles */}
<style dangerouslySetInnerHTML={{__html: `
.nav-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
border-radius: 12px;
color: var(--text-muted);
transition: all 0.2s;
font-weight: 500;
}
.nav-item:hover {
background: rgba(255, 255, 255, 0.05);
color: var(--text-main);
}
.nav-item.active {
background: linear-gradient(135deg, rgba(59, 130, 246, 0.2), rgba(139, 92, 246, 0.2));
color: var(--primary);
border: 1px solid rgba(59, 130, 246, 0.3);
}
.sidebar {
width: 250px;
margin: 1rem;
padding: 1.5rem;
transition: all 0.3s;
}
@media (max-width: 768px) {
.dashboard-container {
flex-direction: column !important;
overflow-y: auto !important;
}
.sidebar {
width: auto;
margin: 1rem;
flex-direction: row !important;
align-items: center;
justify-content: space-between;
padding: 1rem;
}
.sidebar nav {
flex-direction: row !important;
flex: unset !important;
gap: 1rem;
}
.sidebar .nav-item {
padding: 8px 12px;
}
.sidebar > div:first-child {
margin-bottom: 0 !important;
}
.sidebar > div:last-child {
margin-top: 0 !important;
padding-top: 0 !important;
border-top: none !important;
}
.main-content {
height: auto !important;
overflow: visible !important;
}
}
`}} />
</div>
);
};
@@ -0,0 +1,114 @@
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { X, ShieldAlert, ShieldCheck } from 'lucide-react';
import { fetchServices, setServiceBanned } from '../../api/sysadmin';
interface CompanyServicesModalProps {
company: any;
onClose: () => void;
}
export const CompanyServicesModal: React.FC<CompanyServicesModalProps> = ({ company, onClose }) => {
const [services, setServices] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const loadServices = async () => {
setLoading(true);
try {
const res = await fetchServices({ companyId: company.id || company._id, page, limit: 10 });
setServices(res.data);
setTotalPages(res.pages);
} catch (e) {
console.error(e);
alert('Error cargando servicios');
}
setLoading(false);
};
useEffect(() => {
loadServices();
}, [page]);
const handleToggleBanned = async (service: any) => {
if (window.confirm(`¿Deseas ${service.banned ? 'quitar el ban' : 'banear'} el servicio ${service.name}?`)) {
try {
await setServiceBanned(service.id || service._id, !service.banned);
loadServices();
} catch (e: any) {
alert('Error al actualizar el estado del servicio');
}
}
};
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: '90%', maxWidth: '800px', padding: '2rem', position: 'relative', display: 'flex', flexDirection: 'column', maxHeight: '80vh' }}
>
<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: '1.5rem', fontWeight: 'bold' }}>
Servicios de {company.name}
</h2>
<div style={{ overflow: 'auto', flex: 1 }}>
<table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left' }}>
<thead style={{ position: 'sticky', top: 0, background: 'rgba(10, 10, 15, 0.95)', zIndex: 1 }}>
<tr>
<th style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Servicio</th>
<th style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Precio / Duración</th>
<th style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'right' }}>Acciones</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr><td colSpan={3} style={{ padding: '2rem', textAlign: 'center' }}>Cargando...</td></tr>
) : services.length === 0 ? (
<tr><td colSpan={3} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No se encontraron servicios</td></tr>
) : (
services.map(s => (
<tr key={s.id || s._id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
<td style={{ padding: '1rem' }}>
<div style={{ fontWeight: '600', color: 'var(--text-main)' }}>{s.name}</div>
<div style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>{s.description || '-'}</div>
</td>
<td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
${s.price} / {s.length} min
</td>
<td style={{ padding: '1rem', textAlign: 'right' }}>
<button
onClick={() => handleToggleBanned(s)}
className="btn-secondary"
style={{ display: 'inline-flex', alignItems: 'center', gap: '5px', color: s.banned ? 'var(--danger)' : 'var(--success)', padding: '6px 12px' }}
>
{s.banned ? <ShieldAlert size={16} /> : <ShieldCheck size={16} />}
{s.banned ? 'Baneado' : 'Activo'}
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Pagination */}
<div style={{ padding: '1rem 0 0 0', borderTop: '1px solid var(--glass-border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '1rem' }}>
<span style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>Página {page} de {totalPages || 1}</span>
<div style={{ display: 'flex', gap: '10px' }}>
<button className="btn-secondary" disabled={page === 1} onClick={() => setPage(p => p - 1)}>Anterior</button>
<button className="btn-secondary" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>Siguiente</button>
</div>
</div>
</motion.div>
</div>
);
};
@@ -0,0 +1,112 @@
import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { X, Save } from 'lucide-react';
import { updateCompany, setCompanyBanned } from '../../api/sysadmin';
interface EditCompanyModalProps {
company: any;
onClose: () => void;
onSaved: () => void;
}
export const EditCompanyModal: React.FC<EditCompanyModalProps> = ({ company, onClose, onSaved }) => {
const [formData, setFormData] = useState({
id: company.id || company._id,
name: company.name || '',
description: company.description || '',
categoryId: company.categoryId || '',
banned: company.banned || false
});
const [saving, setSaving] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
try {
await updateCompany({
...formData,
categoryId: parseInt(formData.categoryId.toString(), 10)
});
if (company.banned !== formData.banned) {
await setCompanyBanned(formData.id, formData.banned);
}
alert('Organización actualizada');
onSaved();
onClose();
} catch (err: any) {
alert(err.response?.data?.message || err.message || 'Error al actualizar');
}
setSaving(false);
};
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: '90%', maxWidth: '500px', padding: '2rem', position: 'relative' }}
>
<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: '1.5rem', fontWeight: 'bold' }}>Editar Organización</h2>
<form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
<div>
<label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>Nombre</label>
<input
type="text"
className="input-glass"
style={{ width: '100%' }}
value={formData.name}
onChange={e => setFormData({...formData, name: e.target.value})}
required
/>
</div>
<div>
<label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>Descripción</label>
<textarea
className="input-glass"
style={{ width: '100%', minHeight: '80px', resize: 'vertical' }}
value={formData.description}
onChange={e => setFormData({...formData, description: e.target.value})}
/>
</div>
<div>
<label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>Categoría (ID)</label>
<input
type="number"
className="input-glass"
style={{ width: '100%' }}
value={formData.categoryId}
onChange={e => setFormData({...formData, categoryId: e.target.value})}
required
/>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<input
type="checkbox"
id="banned-toggle"
checked={formData.banned}
onChange={e => setFormData({...formData, banned: e.target.checked})}
style={{ width: '18px', height: '18px', cursor: 'pointer' }}
/>
<label htmlFor="banned-toggle" style={{ fontSize: '0.9rem', color: formData.banned ? 'var(--danger)' : 'var(--text-main)', cursor: 'pointer', userSelect: 'none' }}>
Organización Baneada
</label>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem', marginTop: '1rem' }}>
<button type="button" onClick={onClose} className="btn-secondary" disabled={saving}>Cancelar</button>
<button type="submit" className="btn-primary" style={{ display: 'flex', alignItems: 'center', gap: '8px' }} disabled={saving}>
<Save size={18} /> {saving ? 'Guardando...' : 'Guardar Cambios'}
</button>
</div>
</form>
</motion.div>
</div>
);
};
+159
View File
@@ -0,0 +1,159 @@
import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { X } from 'lucide-react';
import { updatePlan } from '../../api/sysadmin';
import type { Plan } from '../../api/sysadmin';
type EditPlanModalProps = {
plan: Plan;
onClose: () => void;
onSaved: () => void;
};
const numberFields: { key: keyof Plan; label: string }[] = [
{ key: 'price', label: 'Precio mensual' },
{ key: 'annualPrice', label: 'Precio anual' },
{ key: 'limitOrganizations', label: 'Límite de organizaciones' },
{ key: 'limitEmployees', label: 'Límite de empleados' },
{ key: 'limitServices', label: 'Límite de servicios' },
{ key: 'limitAppointments', label: 'Límite de turnos' },
{ key: 'limitClients', label: 'Límite de clientes' },
{ key: 'limitRepeats', label: 'Límite de repeticiones' },
{ key: 'discount3Months', label: 'Descuento 3 meses (%)' },
{ key: 'discount6Months', label: 'Descuento 6 meses (%)' },
{ key: 'discount12Months', label: 'Descuento 12 meses (%)' },
];
const limitFields = new Set<keyof Plan>([
'limitOrganizations',
'limitEmployees',
'limitServices',
'limitAppointments',
'limitClients',
'limitRepeats',
]);
const booleanFields: { key: keyof Plan; label: string }[] = [
{ key: 'active', label: 'Activo para contratación' },
{ key: 'featured', label: 'Destacado' },
{ key: 'mailNotifications', label: 'Notificaciones por email' },
{ key: 'smsNotifications', label: 'Notificaciones SMS' },
{ key: 'wapNotifications', label: 'Notificaciones WhatsApp' },
{ key: 'payments', label: 'Pagos habilitados' },
{ key: 'bot', label: 'Bot habilitado' },
{ key: 'dateLimit', label: 'Tiene límite de fecha' },
];
export const EditPlanModal = ({ plan, onClose, onSaved }: EditPlanModalProps) => {
const [formData, setFormData] = useState<Plan>({
...plan,
features: Array.isArray(plan.features) ? plan.features : [],
});
const [featuresText, setFeaturesText] = useState(formData.features.join('\n'));
const [loading, setLoading] = useState(false);
const planId = plan._id || plan.id || '';
const setField = (key: keyof Plan, value: string | number | boolean | string[]) => {
setFormData({ ...formData, [key]: value });
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
try {
await updatePlan({
planId,
name: formData.name,
description: formData.description,
code: formData.code,
price: Number(formData.price) || 0,
annualPrice: Number(formData.annualPrice) || 0,
limitOrganizations: Number(formData.limitOrganizations) || 0,
limitEmployees: Number(formData.limitEmployees) || 0,
limitServices: Number(formData.limitServices) || 0,
limitAppointments: Number(formData.limitAppointments) || 0,
limitClients: Number(formData.limitClients) || 0,
limitRepeats: Number(formData.limitRepeats) || 0,
discount3Months: Number(formData.discount3Months) || 0,
discount6Months: Number(formData.discount6Months) || 0,
discount12Months: Number(formData.discount12Months) || 0,
active: Boolean(formData.active),
featured: Boolean(formData.featured),
mailNotifications: Boolean(formData.mailNotifications),
smsNotifications: Boolean(formData.smsNotifications),
wapNotifications: Boolean(formData.wapNotifications),
payments: Boolean(formData.payments),
bot: Boolean(formData.bot),
dateLimit: Boolean(formData.dateLimit),
features: featuresText.split('\n').map(feature => feature.trim()).filter(Boolean),
});
onSaved();
onClose();
} catch (err: any) {
alert(err.response?.data?.message || err.message || 'Error guardando el plan');
}
setLoading(false);
};
return (
<div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)' }}>
<motion.div initial={{ scale: 0.9, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className="glass-panel" style={{ width: '94%', maxWidth: '860px', maxHeight: '90vh', overflowY: 'auto', padding: '2rem', position: 'relative' }}>
<button onClick={onClose} style={{ position: 'absolute', top: '1.5rem', right: '1.5rem', background: 'transparent', color: 'var(--text-muted)' }}>
<X size={24} />
</button>
<h2 style={{ fontSize: '1.5rem', marginBottom: '1.5rem' }}>Editar plan: {plan.name}</h2>
<form onSubmit={handleSubmit} style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: '1rem' }}>
<div>
<label className="modal-label">Nombre</label>
<input className="input-glass" value={formData.name} onChange={e => setField('name', e.target.value)} required />
</div>
<div>
<label className="modal-label">Código</label>
<input className="input-glass" value={formData.code} onChange={e => setField('code', e.target.value)} required />
</div>
<div style={{ gridColumn: '1 / -1' }}>
<label className="modal-label">Descripción</label>
<textarea className="input-glass" rows={3} value={formData.description} onChange={e => setField('description', e.target.value)} required />
</div>
<h3 className="plan-modal-section">Precios, límites y descuentos</h3>
{numberFields.map(field => (
<div key={field.key}>
<label className="modal-label">{field.label}</label>
<input className="input-glass" type="number" min={limitFields.has(field.key) ? undefined : '0'} step="0.01" value={Number(formData[field.key] || 0)} onChange={e => setField(field.key, Number(e.target.value))} />
</div>
))}
<h3 className="plan-modal-section">Funciones y estado</h3>
{booleanFields.map(field => (
<label key={field.key} className="plan-toggle">
<input type="checkbox" checked={Boolean(formData[field.key])} onChange={e => setField(field.key, e.target.checked)} />
{field.label}
</label>
))}
<div style={{ gridColumn: '1 / -1' }}>
<label className="modal-label">Features visibles (una por línea)</label>
<textarea className="input-glass" rows={5} value={featuresText} onChange={e => setFeaturesText(e.target.value)} />
</div>
<div style={{ gridColumn: '1 / -1', marginTop: '1rem', display: 'flex', justifyContent: 'flex-end', gap: '1rem' }}>
<button type="button" className="btn-secondary" onClick={onClose}>Cancelar</button>
<button type="submit" className="btn-primary" disabled={loading || !planId}>{loading ? 'Guardando...' : 'Guardar cambios'}</button>
</div>
</form>
<style dangerouslySetInnerHTML={{__html: `
.modal-label { display: block; font-size: 0.85rem; color: var(--text-muted); margin-bottom: 0.5rem; }
.plan-modal-section { grid-column: 1 / -1; margin: 1rem 0 0.25rem; color: var(--primary); font-size: 1.05rem; }
.plan-toggle { display: flex; align-items: center; gap: 0.6rem; color: var(--text-main); background: rgba(255,255,255,0.04); border: 1px solid var(--glass-border); border-radius: 10px; padding: 0.75rem; }
.plan-toggle input { width: 16px; height: 16px; }
@media (max-width: 768px) { form { grid-template-columns: 1fr !important; } }
`}} />
</motion.div>
</div>
);
};
+127
View File
@@ -0,0 +1,127 @@
import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { X } from 'lucide-react';
import { updateUserProfile, setVerifiedStatus } from '../../api/sysadmin';
export const EditUserModal = ({ user, onClose, onSaved }: { user: any, onClose: () => void, onSaved: () => void }) => {
const [formData, setFormData] = useState({
firstName: user.firstName || '',
lastName: user.lastName || '',
street: user.street || '',
streetNumber: user.streetNumber || '',
city: user.city || '',
state: user.state || '',
country: user.country || '',
phoneCountryCode: user.phoneCountryCode || '',
phoneAreaCode: user.phoneAreaCode || '',
phoneNumber: user.phoneNumber || '',
verificated: user.verificated || false,
});
const [loading, setLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
try {
const promises: Promise<any>[] = [
updateUserProfile({ userId: user._id, ...formData })
];
if (formData.verificated !== user.verificated) {
promises.push(setVerifiedStatus(user._id, formData.verificated));
}
await Promise.all(promises);
onSaved();
onClose();
} catch (err) {
alert('Error guardando perfil');
}
setLoading(false);
};
return (
<div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)' }}>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="glass-panel"
style={{ width: '90%', maxWidth: '600px', maxHeight: '90vh', overflowY: 'auto', padding: '2rem', position: 'relative' }}
>
<button onClick={onClose} style={{ position: 'absolute', top: '1.5rem', right: '1.5rem', background: 'transparent', color: 'var(--text-muted)' }}>
<X size={24} />
</button>
<h2 style={{ fontSize: '1.5rem', marginBottom: '1.5rem' }}>Editar Perfil: {user.email}</h2>
<form onSubmit={handleSubmit} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
<div>
<label className="modal-label">Nombre</label>
<input className="input-glass" value={formData.firstName} onChange={e => setFormData({...formData, firstName: e.target.value})} />
</div>
<div>
<label className="modal-label">Apellido</label>
<input className="input-glass" value={formData.lastName} onChange={e => setFormData({...formData, lastName: e.target.value})} />
</div>
<div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<h3 style={{ margin: '1rem 0 0.5rem', color: 'var(--primary)', fontSize: '1.1rem' }}>Contacto</h3>
<button
type="button"
onClick={() => setFormData({...formData, verificated: !formData.verificated})}
className="btn-secondary"
style={{ display: 'flex', alignItems: 'center', gap: '8px', color: formData.verificated ? 'var(--success)' : 'var(--warning)', padding: '4px 12px' }}
>
{formData.verificated ? 'Usuario Verificado' : 'Usuario No Verificado'}
</button>
</div>
<div>
<label className="modal-label">Cód. País</label>
<input className="input-glass" value={formData.phoneCountryCode} onChange={e => setFormData({...formData, phoneCountryCode: e.target.value})} />
</div>
<div>
<label className="modal-label">Cód. Área</label>
<input className="input-glass" value={formData.phoneAreaCode} onChange={e => setFormData({...formData, phoneAreaCode: e.target.value})} />
</div>
<div style={{ gridColumn: '1 / -1' }}>
<label className="modal-label">Teléfono</label>
<input className="input-glass" value={formData.phoneNumber} onChange={e => setFormData({...formData, phoneNumber: e.target.value})} />
</div>
<div style={{ gridColumn: '1 / -1' }}>
<h3 style={{ margin: '1rem 0 0.5rem', color: 'var(--primary)', fontSize: '1.1rem' }}>Dirección</h3>
</div>
<div>
<label className="modal-label">Calle</label>
<input className="input-glass" value={formData.street} onChange={e => setFormData({...formData, street: e.target.value})} />
</div>
<div>
<label className="modal-label">Número</label>
<input className="input-glass" value={formData.streetNumber} onChange={e => setFormData({...formData, streetNumber: e.target.value})} />
</div>
<div>
<label className="modal-label">Ciudad</label>
<input className="input-glass" value={formData.city} onChange={e => setFormData({...formData, city: e.target.value})} />
</div>
<div>
<label className="modal-label">País</label>
<input className="input-glass" value={formData.country} onChange={e => setFormData({...formData, country: e.target.value})} />
</div>
<div style={{ gridColumn: '1 / -1', marginTop: '1.5rem', display: 'flex', justifyContent: 'flex-end', gap: '1rem' }}>
<button type="button" className="btn-secondary" onClick={onClose}>Cancelar</button>
<button type="submit" className="btn-primary" disabled={loading}>{loading ? 'Guardando...' : 'Guardar Cambios'}</button>
</div>
</form>
<style dangerouslySetInnerHTML={{__html: `
.modal-label {
display: block;
font-size: 0.85rem;
color: var(--text-muted);
margin-bottom: 0.5rem;
}
`}} />
</motion.div>
</div>
);
};
@@ -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>
);
};
@@ -0,0 +1,77 @@
import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { X, Building } from 'lucide-react';
import { getOrganizationsStatus } from '../../api/sysadmin';
export const OrganizationsModal = ({ user, onClose }: { user: any, onClose: () => void }) => {
const [data, setData] = useState<{ clientIn: any[], collaboratorIn: any[] } | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
getOrganizationsStatus(user._id).then(res => {
setData(res);
setLoading(false);
}).catch(() => {
alert('Error cargando organizaciones');
setLoading(false);
});
}, [user]);
return (
<div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)' }}>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="glass-panel"
style={{ width: '90%', maxWidth: '500px', maxHeight: '80vh', overflowY: 'auto', padding: '2rem', position: 'relative' }}
>
<button onClick={onClose} style={{ position: 'absolute', top: '1.5rem', right: '1.5rem', background: 'transparent', color: 'var(--text-muted)' }}>
<X size={24} />
</button>
<h2 style={{ fontSize: '1.5rem', marginBottom: '1.5rem', display: 'flex', alignItems: 'center', gap: '10px' }}>
<Building size={24} color="var(--primary)" />
Organizaciones Asociadas
</h2>
<p style={{ color: 'var(--text-muted)', marginBottom: '1.5rem' }}>Usuario: {user.email}</p>
{loading ? (
<p style={{ textAlign: 'center', padding: '2rem' }}>Cargando datos...</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
<div>
<h3 style={{ fontSize: '1.1rem', color: 'var(--text-main)', marginBottom: '1rem', borderBottom: '1px solid var(--glass-border)', paddingBottom: '0.5rem' }}>Cliente en:</h3>
{data?.clientIn.length === 0 ? (
<p style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>No es cliente de ninguna organización.</p>
) : (
<ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
{data?.clientIn.map((org, i) => (
<li key={i} style={{ background: 'rgba(255,255,255,0.03)', padding: '0.75rem', borderRadius: '8px', border: '1px solid var(--glass-border)' }}>
{org.companyName} <span style={{ color: 'var(--text-muted)', fontSize: '0.8rem', marginLeft: '10px' }}>(ID: {org.companyId})</span>
</li>
))}
</ul>
)}
</div>
<div>
<h3 style={{ fontSize: '1.1rem', color: 'var(--text-main)', marginBottom: '1rem', borderBottom: '1px solid var(--glass-border)', paddingBottom: '0.5rem' }}>Colaborador en:</h3>
{data?.collaboratorIn.length === 0 ? (
<p style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>No es colaborador de ninguna organización.</p>
) : (
<ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
{data?.collaboratorIn.map((org, i) => (
<li key={i} style={{ background: 'rgba(139, 92, 246, 0.1)', padding: '0.75rem', borderRadius: '8px', border: '1px solid rgba(139, 92, 246, 0.2)' }}>
{org.companyName} <span style={{ color: 'var(--text-muted)', fontSize: '0.8rem', marginLeft: '10px' }}>(ID: {org.companyId})</span>
</li>
))}
</ul>
)}
</div>
</div>
)}
</motion.div>
</div>
);
};
@@ -0,0 +1,114 @@
import { useState } from 'react';
import { motion } from 'framer-motion';
import { RefreshCw, X } from 'lucide-react';
import { recalculatePlanUsageCycle, type RecalculatePlanUsageCycleResult } from '../../api/sysadmin';
import { formatDateTime } from '../../utils/formatters';
export const RecalculationToolsModal = ({ initialUserId = '', onClose }: { initialUserId?: string, onClose: () => void }) => {
const [usageUserId, setUsageUserId] = useState(initialUserId);
const [usageResult, setUsageResult] = useState<RecalculatePlanUsageCycleResult | null>(null);
const [usageLoading, setUsageLoading] = useState(false);
const [usageError, setUsageError] = useState('');
const handleRecalculatePlanUsage = async () => {
const trimmedUserId = usageUserId.trim();
if (!trimmedUserId) {
setUsageError('Ingresá un userId para recalcular el uso del plan.');
return;
}
setUsageUserId(trimmedUserId);
setUsageLoading(true);
setUsageError('');
setUsageResult(null);
try {
const result = await recalculatePlanUsageCycle(trimmedUserId);
setUsageResult(result);
} catch (e: any) {
setUsageError(e.response?.data?.message || e.message || 'Error al recalcular el uso del plan');
} finally {
setUsageLoading(false);
}
};
return (
<div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)', padding: '1rem' }}>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="glass-panel"
style={{ width: '90%', maxWidth: '760px', maxHeight: '90vh', overflowY: 'auto', padding: '2rem', position: 'relative' }}
>
<button onClick={onClose} style={{ position: 'absolute', top: '1.5rem', right: '1.5rem', background: 'transparent', color: 'var(--text-muted)' }}>
<X size={24} />
</button>
<h2 style={{ fontSize: '1.5rem', marginBottom: '0.5rem', display: 'flex', alignItems: 'center', gap: '10px' }}>
<RefreshCw size={24} color="var(--primary)" />
Herramientas de recálculo
</h2>
<p style={{ color: 'var(--text-muted)', marginBottom: '1.5rem' }}>Funciones exclusivas de sysadmin para reparar o reconstruir contadores.</p>
<div style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid var(--glass-border)', borderRadius: '12px', padding: '1.25rem' }}>
<div style={{ marginBottom: '1rem' }}>
<h3 style={{ fontSize: '1.1rem', fontWeight: '700', marginBottom: '0.35rem' }}>Recalcular uso del plan</h3>
<p style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>Recuenta las reservas del ciclo actual y los contadores stock del userId seleccionado.</p>
</div>
<form onSubmit={(e) => { e.preventDefault(); handleRecalculatePlanUsage(); }} style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap', alignItems: 'flex-end' }}>
<div style={{ flex: '1 1 300px' }}>
<label className="modal-label">User ID</label>
<input
type="text"
className="input-glass"
placeholder="Pegá o seleccioná un userId"
value={usageUserId}
onChange={(e) => setUsageUserId(e.target.value)}
/>
</div>
<button type="submit" className="btn-primary" disabled={usageLoading} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<RefreshCw size={18} /> {usageLoading ? 'Recalculando...' : 'Recalcular'}
</button>
</form>
{usageError && <div style={{ marginTop: '1rem', color: 'var(--danger)', fontSize: '0.9rem' }}>{usageError}</div>}
{usageResult && (
<div style={{ marginTop: '1rem', display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
<div><strong>User ID</strong><br /><span className="long-id-value">{usageResult.userId}</span></div>
<div><strong>Subscription ID</strong><br /><span className="long-id-value">{usageResult.subscriptionId}</span></div>
<div><strong>Plan ID</strong><br /><span className="long-id-value">{usageResult.planId}</span></div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '0.75rem' }}>
<div><strong>Cycle Start</strong><br /><span style={{ color: 'var(--text-muted)' }}>{formatDateTime(usageResult.cycleStart)}</span></div>
<div><strong>Cycle End</strong><br /><span style={{ color: 'var(--text-muted)' }}>{formatDateTime(usageResult.cycleEnd)}</span></div>
<div><strong>Organizations</strong><br /><span style={{ color: 'var(--success)', fontWeight: 700 }}>{usageResult.organizationsCount}</span></div>
<div><strong>Collaborators</strong><br /><span style={{ color: 'var(--success)', fontWeight: 700 }}>{usageResult.employeesCount}</span></div>
<div><strong>Services</strong><br /><span style={{ color: 'var(--success)', fontWeight: 700 }}>{usageResult.servicesCount}</span></div>
<div><strong>Clients</strong><br /><span style={{ color: 'var(--success)', fontWeight: 700 }}>{usageResult.clientsCount}</span></div>
<div><strong>Repeats</strong><br /><span style={{ color: 'var(--success)', fontWeight: 700 }}>{usageResult.repeatsCount}</span></div>
<div><strong>Appointments</strong><br /><span style={{ color: 'var(--success)', fontWeight: 700 }}>{usageResult.appointmentsCount}</span></div>
</div>
</div>
)}
</div>
<style dangerouslySetInnerHTML={{__html: `
.modal-label {
display: block;
font-size: 0.85rem;
color: var(--text-muted);
margin-bottom: 0.5rem;
}
.long-id-value {
display: block;
color: var(--text-muted);
overflow-wrap: anywhere;
word-break: break-word;
line-height: 1.45;
}
`}} />
</motion.div>
</div>
);
};
@@ -0,0 +1,297 @@
import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { CreditCard, X } from 'lucide-react';
import { extendUserSubscription, finalizeUserSubscription, getUserSubscriptionDetails, type UserSubscriptionDetails } from '../../api/sysadmin';
import { formatDateTime } from '../../utils/formatters';
type Props = {
user: any;
onClose: () => void;
};
export const SubscriptionDetailsModal = ({ user, onClose }: Props) => {
const [details, setDetails] = useState<UserSubscriptionDetails | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [extensionDate, setExtensionDate] = useState('');
const [extensionLoading, setExtensionLoading] = useState(false);
const [extensionMessage, setExtensionMessage] = useState('');
const [extensionError, setExtensionError] = useState('');
const [finalizeLoading, setFinalizeLoading] = useState(false);
const formatAmount = (value?: number) => {
if (typeof value !== 'number') return '-';
return value.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' });
};
const loadDetails = async () => {
setLoading(true);
setError('');
try {
const result = await getUserSubscriptionDetails(user._id);
setDetails(result);
} catch (e: any) {
setError(e.response?.data?.message || e.message || 'Error cargando suscripción');
} finally {
setLoading(false);
}
};
useEffect(() => {
loadDetails();
}, [user._id]);
const handleExtend = async (payload: { mode: 'add_months' | 'set_end_date'; months?: 1 | 2; endDate?: string }) => {
if (!details?.currentSubscription) return;
setExtensionLoading(true);
setExtensionError('');
setExtensionMessage('');
try {
const result = await extendUserSubscription({
userId: user._id,
reason: 'Ajuste manual excepcional desde sysadmin-cli',
...payload,
});
setExtensionMessage(`Vencimiento actualizado hasta ${formatDateTime(result.newEndDate)}. Se registró una bonificación $0.`);
await loadDetails();
} catch (e: any) {
setExtensionError(e.response?.data?.message || e.message || 'Error extendiendo suscripción');
} finally {
setExtensionLoading(false);
}
};
const handleFinalize = async () => {
if (!details?.currentSubscription) return;
const confirmed = window.confirm('Esto establecerá el vencimiento de la suscripción a ayer para forzar el comportamiento de plan vencido. No elimina datos ni cambia el plan directamente. ¿Continuar?');
if (!confirmed) return;
setFinalizeLoading(true);
setExtensionError('');
setExtensionMessage('');
try {
const result = await finalizeUserSubscription({
userId: user._id,
reason: 'Finalización manual desde sysadmin-cli para probar expiración de plan',
});
setExtensionMessage(`Período finalizado. El vencimiento quedó en ${formatDateTime(result.newEndDate)} para forzar la expiración en la próxima lectura.`);
await loadDetails();
} catch (e: any) {
setExtensionError(e.response?.data?.message || e.message || 'Error finalizando período');
} finally {
setFinalizeLoading(false);
}
};
const subscription = details?.currentSubscription;
return (
<div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)', padding: '1rem' }}>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
className="glass-panel"
style={{ width: '90%', maxWidth: '860px', maxHeight: '90vh', overflowY: 'auto', padding: '2rem', position: 'relative' }}
>
<button onClick={onClose} style={{ position: 'absolute', top: '1.5rem', right: '1.5rem', background: 'transparent', color: 'var(--text-muted)' }}>
<X size={24} />
</button>
<h2 style={{ fontSize: '1.5rem', marginBottom: '0.5rem', display: 'flex', alignItems: 'center', gap: '10px' }}>
<CreditCard size={24} color="var(--primary)" />
Suscripción del usuario
</h2>
<p style={{ color: 'var(--text-muted)', marginBottom: '1.5rem' }}>
{user.firstName} {user.lastName} · {user.email}
</p>
{loading && <div style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>Cargando suscripción...</div>}
{error && <div style={{ padding: '1rem', color: 'var(--danger)' }}>{error}</div>}
{!loading && !error && details && (
<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
<section className="subscription-card">
<h3 className="subscription-section-title">Suscripción actual</h3>
{!subscription ? (
<p style={{ color: 'var(--text-muted)' }}>No hay suscripción registrada para este usuario.</p>
) : (
<div className="subscription-grid">
<Info label="Subscription ID" value={subscription.id} long />
<Info label="User ID" value={details.userId} long />
<Info label="Plan" value={subscription.plan ? `${subscription.plan.name} (${subscription.plan.code})` : 'Plan no encontrado'} />
<Info label="Plan ID" value={subscription.plan?.id || '-'} long />
<Info label="Precio" value={formatAmount(subscription.plan?.price)} />
<Info label="Inicio" value={formatDateTime(subscription.startDate)} />
<Info label="Válida hasta" value={formatDateTime(subscription.endDate)} />
<Info label="Activa" value={subscription.isActive ? 'Sí' : 'No'} />
<Info label="MP status" value={subscription.mpStatus || '-'} />
<Info label="Meses facturados" value={subscription.billingMonths?.toString() || '-'} />
<Info label="Pago pendiente" value={subscription.pendingPaymentType || '-'} />
<Info label="Preference pendiente" value={subscription.pendingPaymentPreferenceId || '-'} long />
<Info label="Último pago" value={subscription.lastPaymentStatus || '-'} />
</div>
)}
</section>
{subscription && (
<section className="subscription-card">
<h3 className="subscription-section-title">Ajuste manual excepcional</h3>
<p style={{ color: 'var(--text-muted)', marginBottom: '1rem' }}>
Extiende la vigencia sin pago y registra un pago de bonificación por $0 asociado a esta suscripción.
</p>
<div className="extension-actions">
<button className="btn btn-secondary" disabled={extensionLoading || finalizeLoading} onClick={() => handleExtend({ mode: 'add_months', months: 1 })}>
Extender 1 mes
</button>
<button className="btn btn-secondary" disabled={extensionLoading || finalizeLoading} onClick={() => handleExtend({ mode: 'add_months', months: 2 })}>
Extender 2 meses
</button>
<div className="extension-date-action">
<input
type="date"
value={extensionDate}
onChange={(event) => setExtensionDate(event.target.value)}
disabled={extensionLoading || finalizeLoading}
/>
<button
className="btn btn-primary"
disabled={extensionLoading || finalizeLoading || !extensionDate}
onClick={() => handleExtend({ mode: 'set_end_date', endDate: extensionDate })}
>
Establecer vencimiento
</button>
</div>
</div>
<div className="finalize-action">
<div>
<h4>Finalizar período</h4>
<p>Establece el vencimiento en ayer para forzar el comportamiento de suscripción vencida en la próxima lectura. No elimina datos ni cambia el plan directamente.</p>
</div>
<button className="btn btn-danger" disabled={extensionLoading || finalizeLoading} onClick={handleFinalize}>
Finalizar período
</button>
</div>
{(extensionLoading || finalizeLoading) && <p style={{ color: 'var(--text-muted)', marginTop: '0.75rem' }}>Aplicando ajuste...</p>}
{extensionMessage && <p style={{ color: 'var(--success)', marginTop: '0.75rem' }}>{extensionMessage}</p>}
{extensionError && <p style={{ color: 'var(--danger)', marginTop: '0.75rem' }}>{extensionError}</p>}
</section>
)}
<section className="subscription-card">
<h3 className="subscription-section-title">Pagos</h3>
{details.payments.length === 0 ? (
<p style={{ color: 'var(--text-muted)' }}>No hay pagos registrados para este usuario.</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
{details.payments.map((payment) => (
<div key={payment.id} className="payment-row">
<Info label="Payment ID" value={payment.id} long />
<Info label="Subscription ID" value={payment.subscriptionId} long />
<Info label="Monto" value={formatAmount(payment.amount)} />
<Info label="Fecha" value={formatDateTime(payment.paymentDate)} />
<Info label="Método" value={payment.paymentMethod || '-'} />
<Info label="Estado" value={payment.status} />
<Info label="Transaction ID" value={payment.transactionId || '-'} long />
</div>
))}
</div>
)}
</section>
</div>
)}
<style dangerouslySetInnerHTML={{__html: `
.subscription-card {
background: rgba(255,255,255,0.03);
border: 1px solid var(--glass-border);
border-radius: 12px;
padding: 1.25rem;
}
.subscription-section-title {
font-size: 1.1rem;
font-weight: 700;
margin-bottom: 1rem;
}
.subscription-grid,
.payment-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 0.85rem;
}
.payment-row {
border-top: 1px solid var(--glass-border);
padding-top: 0.75rem;
}
.subscription-label {
display: block;
color: var(--text-muted);
font-size: 0.78rem;
margin-bottom: 0.25rem;
}
.subscription-value {
display: block;
color: var(--text-main);
font-weight: 600;
}
.subscription-value.long {
overflow-wrap: anywhere;
word-break: break-word;
line-height: 1.45;
}
.extension-actions {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
align-items: center;
}
.extension-date-action {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
align-items: center;
}
.extension-date-action input {
background: rgba(255,255,255,0.06);
border: 1px solid var(--glass-border);
border-radius: 8px;
color: var(--text-main);
padding: 0.65rem 0.75rem;
}
.finalize-action {
display: flex;
justify-content: space-between;
gap: 1rem;
align-items: center;
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid var(--glass-border);
}
.finalize-action h4 {
color: var(--danger);
font-size: 1rem;
margin-bottom: 0.35rem;
}
.finalize-action p {
color: var(--text-muted);
margin: 0;
}
@media (max-width: 640px) {
.finalize-action {
align-items: stretch;
flex-direction: column;
}
}
`}} />
</motion.div>
</div>
);
};
const Info = ({ label, value, long = false }: { label: string; value: string; long?: boolean }) => (
<div>
<span className="subscription-label">{label}</span>
<span className={`subscription-value${long ? ' long' : ''}`}>{value}</span>
</div>
);
+307
View File
@@ -0,0 +1,307 @@
:root {
/* Colors */
--bg-dark: #0f172a; /* Slate 900 */
--bg-dark-accent: #1e293b; /* Slate 800 */
--primary: #3b82f6; /* Blue 500 */
--primary-hover: #2563eb; /* Blue 600 */
--primary-glow: rgba(59, 130, 246, 0.5);
--accent: #8b5cf6; /* Violet 500 */
--accent-glow: rgba(139, 92, 246, 0.4);
--success: #10b981; /* Emerald 500 */
--danger: #ef4444; /* Red 500 */
--warning: #f59e0b; /* Amber 500 */
--text-main: #f8fafc; /* Slate 50 */
--text-muted: #94a3b8; /* Slate 400 */
/* Glassmorphism */
--glass-bg: rgba(30, 41, 59, 0.7);
--glass-border: rgba(255, 255, 255, 0.1);
--glass-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
/* Typography */
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: var(--font-family);
background-color: var(--bg-dark);
color: var(--text-main);
min-height: 100vh;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-image:
radial-gradient(circle at 15% 50%, var(--primary-glow), transparent 25%),
radial-gradient(circle at 85% 30%, var(--accent-glow), transparent 25%);
background-attachment: fixed;
overflow: hidden;
}
.app-shell {
min-height: 100vh;
background-color: var(--bg-dark);
background-image:
radial-gradient(circle at 15% 50%, var(--primary-glow), transparent 25%),
radial-gradient(circle at 85% 30%, var(--accent-glow), transparent 25%);
}
.app-titlebar {
height: 42px;
display: flex;
align-items: center;
justify-content: space-between;
padding-left: 14px;
background: rgba(15, 23, 42, 0.82);
border-bottom: 1px solid var(--glass-border);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
color: var(--text-main);
-webkit-app-region: drag;
user-select: none;
}
.app-titlebar-brand {
display: flex;
align-items: center;
gap: 10px;
font-size: 0.9rem;
font-weight: 700;
letter-spacing: 0.04em;
}
.app-titlebar-logo {
width: 24px;
height: 24px;
border-radius: 8px;
object-fit: cover;
}
.app-titlebar-actions {
height: 100%;
display: flex;
-webkit-app-region: no-drag;
}
.app-titlebar-actions button {
width: 46px;
height: 100%;
display: inline-flex;
align-items: center;
justify-content: center;
background: transparent;
color: var(--text-muted);
transition: background 0.15s, color 0.15s;
}
.app-titlebar-actions button:hover {
background: rgba(255, 255, 255, 0.08);
color: var(--text-main);
}
.app-titlebar-actions button.close:hover {
background: var(--danger);
color: white;
}
.key-gate {
min-height: calc(100vh - 42px);
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
background: radial-gradient(circle at top left, rgba(59, 130, 246, 0.22), transparent 32rem), var(--bg-main);
color: var(--text-main);
}
.key-gate-card {
width: min(440px, 100%);
padding: 2rem;
text-align: center;
}
.key-gate-logo {
width: 56px;
height: 56px;
margin: 0 auto 1rem;
border-radius: 16px;
display: block;
object-fit: cover;
}
.primary-button {
margin-top: 1rem;
border: 0;
border-radius: 12px;
padding: 0.85rem 1.25rem;
background: linear-gradient(135deg, var(--primary), var(--accent));
color: white;
font-weight: 700;
cursor: pointer;
}
.key-gate-hint {
color: var(--text-muted);
font-size: 0.85rem;
}
.key-gate-error {
color: #fca5a5;
}
a {
color: var(--primary);
text-decoration: none;
transition: color 0.2s;
}
a:hover {
color: var(--primary-hover);
}
button {
font-family: inherit;
cursor: pointer;
border: none;
outline: none;
}
/* Utilities */
.glass-panel {
background: var(--glass-bg);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid var(--glass-border);
box-shadow: var(--glass-shadow);
border-radius: 16px;
}
.btn-primary {
background: linear-gradient(135deg, var(--primary), var(--accent));
color: white;
padding: 0.75rem 1.5rem;
border-radius: 8px;
font-weight: 600;
transition: transform 0.2s, box-shadow 0.2s;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 4px 15px var(--primary-glow);
}
.btn-danger {
background: var(--danger);
color: white;
padding: 0.5rem 1rem;
border-radius: 8px;
font-weight: 600;
transition: opacity 0.2s;
}
.btn-danger:hover {
opacity: 0.8;
}
.input-glass {
background: rgba(15, 23, 42, 0.6);
border: 1px solid var(--glass-border);
color: var(--text-main);
padding: 0.75rem 1rem;
border-radius: 8px;
width: 100%;
transition: border-color 0.2s, box-shadow 0.2s;
}
.input-glass:focus {
border-color: var(--primary);
box-shadow: 0 0 0 2px var(--primary-glow);
outline: none;
}
.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;
display: inline-flex;
align-items: center;
justify-content: center;
}
.btn-secondary:hover:not(:disabled) {
background: rgba(255,255,255,0.1);
}
.btn-secondary:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.icon-btn {
background: rgba(255,255,255,0.05);
color: var(--text-muted);
padding: 8px;
border-radius: 8px;
transition: all 0.2s;
display: inline-flex;
align-items: center;
justify-content: center;
}
.icon-btn:hover {
background: var(--primary);
color: white;
}
.icon-btn.danger:hover {
background: var(--danger);
}
/* Animations */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.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;
}
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
+209
View File
@@ -0,0 +1,209 @@
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
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[]>([]);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [loading, setLoading] = useState(false);
// Filters
const [filters, setFilters] = useState({
name: '',
banned: 'all', // all | true | false
sortBy: 'name',
sortOrder: 'asc'
});
// 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);
try {
const payload: any = { page, limit: 10, sortBy: filters.sortBy, sortOrder: filters.sortOrder };
if (filters.name) payload.name = filters.name;
if (filters.banned !== 'all') payload.banned = filters.banned === 'true';
const res = await fetchCompanies(payload);
setCompanies(res.data);
setTotalPages(res.pages);
} catch (e) {
console.error(e);
alert('Error cargando organizaciones');
}
setLoading(false);
};
useEffect(() => {
loadCompanies();
}, [page, filters.sortBy, filters.sortOrder, filters.banned]);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
setPage(1);
loadCompanies();
};
const handleResetFilters = () => {
setFilters({
name: '',
banned: 'all',
sortBy: 'name',
sortOrder: 'asc'
});
setPage(1);
};
useEffect(() => {
if (filters.name === '' && filters.banned === 'all' && filters.sortBy === 'name' && filters.sortOrder === 'asc') {
loadCompanies();
}
}, [filters]);
const toggleSort = (field: string) => {
setFilters(prev => {
if (prev.sortBy === field) {
return { ...prev, sortOrder: prev.sortOrder === 'asc' ? 'desc' : 'asc' };
}
return { ...prev, sortBy: field, sortOrder: 'asc' };
});
};
const renderSortIcon = (field: string) => {
if (filters.sortBy !== field) return null;
return filters.sortOrder === 'asc' ? <ChevronUp size={16} /> : <ChevronDown size={16} />;
};
const handleToggleBanned = async (company: any) => {
if (window.confirm(`¿Deseas ${company.banned ? 'quitar el ban' : 'banear'} a la organización ${company.name}?`)) {
try {
await setCompanyBanned(company.id || company._id, !company.banned);
loadCompanies();
} catch (e: any) {
alert('Error al actualizar estado de la organización');
}
}
};
return (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="animate-fade-in companies-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' }}>Gestión de Organizaciones</h1>
</div>
{/* Filters Bar */}
<div className="glass-panel filters-bar" style={{ padding: '1.5rem', marginBottom: '1rem', flexShrink: 0 }}>
<form onSubmit={handleSearch} style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap', alignItems: 'flex-end' }}>
<div style={{ flex: '1', minWidth: '200px' }}>
<label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Nombre</label>
<input
type="text"
className="input-glass"
placeholder="Buscar por nombre..."
value={filters.name}
onChange={(e) => setFilters({...filters, name: e.target.value})}
/>
</div>
<div style={{ width: '150px' }}>
<label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Baneado</label>
<select
className="input-glass"
value={filters.banned}
onChange={(e) => setFilters({...filters, banned: e.target.value})}
>
<option value="all">Todos</option>
<option value="true"></option>
<option value="false">No</option>
</select>
</div>
<div style={{ display: 'flex', gap: '8px' }}>
<button type="submit" className="btn-primary" style={{ display: 'flex', alignItems: 'center', gap: '8px', height: '100%' }}>
<Search size={18} /> Buscar
</button>
<button type="button" onClick={handleResetFilters} className="btn-secondary" style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '0.75rem', height: '100%' }} title="Limpiar Filtros">
<RotateCcw size={18} />
</button>
</div>
</form>
</div>
{/* Table */}
<div className="glass-panel" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column', flex: 1 }}>
<div style={{ overflow: 'auto', flex: 1 }} className="table-scroll-container">
<table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', minWidth: '700px' }}>
<thead>
<tr>
<th className="sticky-header sortable-header" onClick={() => toggleSort('name')} style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', cursor: 'pointer', userSelect: 'none' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>Organización {renderSortIcon('name')}</div>
</th>
<th className="sticky-header sortable-header" onClick={() => toggleSort('categoryId')} style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', cursor: 'pointer', userSelect: 'none' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>Categoría {renderSortIcon('categoryId')}</div>
</th>
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Estado</th>
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'right' }}>Acciones</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr><td colSpan={4} style={{ padding: '2rem', textAlign: 'center' }}>Cargando...</td></tr>
) : companies.length === 0 ? (
<tr><td colSpan={4} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No se encontraron organizaciones</td></tr>
) : (
companies.map(c => (
<tr key={c.id} 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)' }}>{c.name}</div>
<div style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>{c.description || '-'}</div>
</td>
<td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
{c.categoryId}
</td>
<td style={{ padding: '1rem' }}>
<button
onClick={() => handleToggleBanned(c)}
style={{ background: 'transparent', display: 'flex', alignItems: 'center', gap: '5px', color: c.banned ? 'var(--danger)' : 'var(--success)', cursor: 'pointer' }}
title={c.banned ? 'Click para desbanear' : 'Click para banear'}
>
{c.banned ? <ShieldAlert size={18} /> : <ShieldCheck size={18} />}
{c.banned ? 'Baneada' : 'Activa'}
</button>
</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>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Pagination */}
<div className="pagination-bar" style={{ padding: '1rem', borderTop: '1px solid var(--glass-border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0, background: 'rgba(0,0,0,0.2)' }}>
<span style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>Página {page} de {totalPages || 1}</span>
<div style={{ display: 'flex', gap: '10px' }}>
<button className="btn-secondary" disabled={page === 1} onClick={() => setPage(p => p - 1)}>Anterior</button>
<button className="btn-secondary" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>Siguiente</button>
</div>
</div>
</div>
{/* 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>
);
};

Some files were not shown because too many files have changed in this diff Show More