6 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
84 changed files with 16330 additions and 111 deletions
+10
View File
@@ -24,6 +24,16 @@ server/*.local
server/build
# 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
.vscode/*
!.vscode/extensions.json
+5
View File
@@ -69,3 +69,8 @@ FILE_SERVER_URL = http://localhost:4000/
FILE_SERVER_URL_prod = https://files.turnosxpress.com.ar/
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/
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",
"mongoose": "8.8.3",
"multer": "^1.4.5-lts.2",
"node-forge": "^1.4.0",
"nodemailer": "^6.10.1",
"sanitize-html": "^2.17.6",
"sharp": "^0.33.5",
@@ -33,6 +34,7 @@
"@types/express": "^4.17.25",
"@types/jest": "^30.0.0",
"@types/jsonwebtoken": "^9.0.10",
"@types/node-forge": "^1.3.14",
"@types/nodemailer": "^6.4.24",
"@types/sanitize-html": "^2.16.1",
"@types/socket.io": "^3.0.2",
@@ -775,9 +777,6 @@
"cpu": [
"arm"
],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -794,9 +793,6 @@
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -813,9 +809,6 @@
"cpu": [
"s390x"
],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -832,9 +825,6 @@
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -851,9 +841,6 @@
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -870,9 +857,6 @@
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@@ -889,9 +873,6 @@
"cpu": [
"arm"
],
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -914,9 +895,6 @@
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -939,9 +917,6 @@
"cpu": [
"s390x"
],
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -964,9 +939,6 @@
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -989,9 +961,6 @@
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -1014,9 +983,6 @@
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@@ -2119,6 +2085,16 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.2.tgz",
"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": {
"version": "6.4.24",
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.24.tgz",
@@ -6672,6 +6648,38 @@
"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": {
"version": "6.10.0",
"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",
"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": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz",
@@ -6892,6 +6950,15 @@
"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": {
"version": "0.4.0",
"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/jest": "^30.0.0",
"@types/jsonwebtoken": "^9.0.10",
"@types/node-forge": "^1.3.14",
"@types/nodemailer": "^6.4.24",
"@types/sanitize-html": "^2.16.1",
"@types/socket.io": "^3.0.2",
@@ -42,6 +43,7 @@
"jsonwebtoken": "^9.0.3",
"mongoose": "8.8.3",
"multer": "^1.4.5-lts.2",
"node-forge": "^1.4.0",
"nodemailer": "^6.10.1",
"sanitize-html": "^2.17.6",
"sharp": "^0.33.5",
@@ -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();
@@ -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();
@@ -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();
@@ -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);
}
}
+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>
);
};
+121
View File
@@ -0,0 +1,121 @@
import { motion } from 'framer-motion';
import { Building2, CreditCard, RefreshCw, Server, Shield, Tags, Users } from 'lucide-react';
import { Link } from 'react-router-dom';
export const DashboardPage = () => {
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
style={{ padding: '2rem 0' }}
>
<header style={{ marginBottom: '3rem' }}>
<h1 style={{ fontSize: '2.5rem', fontWeight: '800', background: 'linear-gradient(to right, var(--text-main), var(--text-muted))', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>
Bienvenido al Panel SysAdmin
</h1>
<p style={{ color: 'var(--text-muted)', marginTop: '0.5rem', fontSize: '1.1rem' }}>
Gestión centralizada del puente TurnosXpress.
</p>
</header>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '2rem' }}>
{/* Card Users */}
<Link to="/users" style={{ display: 'block' }}>
<motion.div
whileHover={{ y: -5, scale: 1.02 }}
className="glass-panel"
style={{ padding: '2rem', display: 'flex', flexDirection: 'column', gap: '1rem', cursor: 'pointer', height: '100%' }}
>
<div style={{ width: '60px', height: '60px', borderRadius: '16px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--primary)', border: '1px solid rgba(59, 130, 246, 0.2)' }}>
<Users size={30} />
</div>
<div>
<h3 style={{ fontSize: '1.3rem', fontWeight: '600', marginBottom: '0.5rem', color: 'var(--text-main)' }}>Gestión de Usuarios</h3>
<p style={{ color: 'var(--text-muted)', lineHeight: '1.5' }}>Administra perfiles, verifica cuentas, consulta organizaciones, suscripciones, pagos y herramientas de recálculo.</p>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', marginTop: '1rem' }}>
<span className="dashboard-tag"><CreditCard size={14} /> Suscripciones</span>
<span className="dashboard-tag"><RefreshCw size={14} /> Recálculos</span>
</div>
</div>
</motion.div>
</Link>
{/* Card Companies */}
<Link to="/companies" style={{ display: 'block' }}>
<motion.div
whileHover={{ y: -5, scale: 1.02 }}
className="glass-panel"
style={{ padding: '2rem', display: 'flex', flexDirection: 'column', gap: '1rem', cursor: 'pointer', height: '100%' }}
>
<div style={{ width: '60px', height: '60px', borderRadius: '16px', background: 'rgba(16, 185, 129, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--success)', border: '1px solid rgba(16, 185, 129, 0.2)' }}>
<Building2 size={30} />
</div>
<div>
<h3 style={{ fontSize: '1.3rem', fontWeight: '600', marginBottom: '0.5rem', color: 'var(--text-main)' }}>Gestión de Organizaciones</h3>
<p style={{ color: 'var(--text-muted)', lineHeight: '1.5' }}>Consulta organizaciones, revisa estado operativo y administra bloqueos desde el panel central.</p>
</div>
</motion.div>
</Link>
{/* Card Plans */}
<Link to="/plans" style={{ display: 'block' }}>
<motion.div
whileHover={{ y: -5, scale: 1.02 }}
className="glass-panel"
style={{ padding: '2rem', display: 'flex', flexDirection: 'column', gap: '1rem', cursor: 'pointer', height: '100%' }}
>
<div style={{ width: '60px', height: '60px', borderRadius: '16px', background: 'rgba(245, 158, 11, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--warning)', border: '1px solid rgba(245, 158, 11, 0.2)' }}>
<Tags size={30} />
</div>
<div>
<h3 style={{ fontSize: '1.3rem', fontWeight: '600', marginBottom: '0.5rem', color: 'var(--text-main)' }}>Gestión de Planes</h3>
<p style={{ color: 'var(--text-muted)', lineHeight: '1.5' }}>Visualiza y edita precios, límites, descuentos, funciones y disponibilidad de los planes contratables.</p>
</div>
</motion.div>
</Link>
{/* Card Wap Servers */}
<Link to="/wapservers" style={{ display: 'block' }}>
<motion.div whileHover={{ y: -5, scale: 1.02 }} className="glass-panel" style={{ padding: '2rem', display: 'flex', flexDirection: 'column', gap: '1rem', cursor: 'pointer', height: '100%' }}>
<div style={{ width: '60px', height: '60px', borderRadius: '16px', background: 'rgba(139, 92, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--accent)', border: '1px solid rgba(139, 92, 246, 0.2)' }}>
<Server size={30} />
</div>
<div>
<h3 style={{ fontSize: '1.3rem', fontWeight: '600', marginBottom: '0.5rem', color: 'var(--text-main)' }}>Servidores WAP</h3>
<p style={{ color: 'var(--text-muted)', lineHeight: '1.5' }}>Consulta servidores de WhatsApp puente y su estado operativo.</p>
</div>
</motion.div>
</Link>
{/* Card Config */}
<div style={{ opacity: 0.6 }}>
<div className="glass-panel" style={{ padding: '2rem', display: 'flex', flexDirection: 'column', gap: '1rem', height: '100%' }}>
<div style={{ width: '60px', height: '60px', borderRadius: '16px', background: 'rgba(16, 185, 129, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--success)', border: '1px solid rgba(16, 185, 129, 0.2)' }}>
<Shield size={30} />
</div>
<div>
<h3 style={{ fontSize: '1.3rem', fontWeight: '600', marginBottom: '0.5rem' }}>Seguridad</h3>
<p style={{ color: 'var(--text-muted)', lineHeight: '1.5' }}>[Próximamente] Gestión de llaves, logs de auditoría y configuración del middleware.</p>
</div>
</div>
</div>
</div>
<style dangerouslySetInnerHTML={{__html: `
.dashboard-tag {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.25rem 0.55rem;
border-radius: 999px;
background: rgba(255, 255, 255, 0.06);
color: var(--text-muted);
font-size: 0.78rem;
font-weight: 700;
border: 1px solid rgba(255, 255, 255, 0.08);
}
`}} />
</motion.div>
);
};
+181
View File
@@ -0,0 +1,181 @@
import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { CheckCircle, Edit2, RefreshCw, Star, XCircle } from 'lucide-react';
import { fetchPlans } from '../api/sysadmin';
import type { Plan } from '../api/sysadmin';
import { EditPlanModal } from '../components/ui/EditPlanModal';
const formatMoney = (value: number) => new Intl.NumberFormat('es-AR', { style: 'currency', currency: 'ARS' }).format(value || 0);
const getFeatureTags = (plan: Plan) => [
{ label: 'Mail', enabled: plan.mailNotifications },
{ label: 'SMS', enabled: plan.smsNotifications },
{ label: 'WAP', enabled: plan.wapNotifications },
{ label: 'Pagos', enabled: plan.payments },
{ label: 'Bot', enabled: plan.bot },
{ label: 'Fecha límite', enabled: plan.dateLimit },
];
const getLimitTags = (plan: Plan) => [
{ label: 'Org', value: plan.limitOrganizations },
{ label: 'Emp', value: plan.limitEmployees },
{ label: 'Serv', value: plan.limitServices },
{ label: 'Turnos', value: plan.limitAppointments },
{ label: 'Clientes', value: plan.limitClients },
{ label: 'Rep', value: plan.limitRepeats },
];
const formatLimit = (value: number) => value === -1 ? '∞' : value;
export const PlansPage = () => {
const [plans, setPlans] = useState<Plan[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [editingPlan, setEditingPlan] = useState<Plan | null>(null);
const [planIdFilter, setPlanIdFilter] = useState('');
const filteredPlans = plans.filter((plan) => {
const normalizedFilter = planIdFilter.trim().toLowerCase();
if (!normalizedFilter) return true;
return [plan.id, plan._id].some((planId) => planId?.toLowerCase().includes(normalizedFilter));
});
const loadPlans = async () => {
setLoading(true);
setError('');
try {
const data = await fetchPlans();
setPlans(data);
} catch (err: any) {
setError(err.response?.data?.message || err.message || 'Error cargando planes');
}
setLoading(false);
};
useEffect(() => {
loadPlans();
}, []);
return (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="animate-fade-in plans-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>
<h1 style={{ fontSize: '2rem', fontWeight: '700' }}>Gestión de Planes</h1>
<p style={{ color: 'var(--text-muted)', marginTop: '0.35rem' }}>Visualizá y editá precios, límites y funciones contratables.</p>
</div>
<button className="btn-secondary" onClick={loadPlans} disabled={loading} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<RefreshCw size={18} /> Actualizar
</button>
</div>
<div className="glass-panel" style={{ padding: '1rem', marginBottom: '1rem', flexShrink: 0 }}>
<label style={{ display: 'block', color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: '0.5rem' }}>
Filtrar por ID de plan
</label>
<input
className="input-glass"
type="text"
placeholder="Pegá el id del plan"
value={planIdFilter}
onChange={(event) => setPlanIdFilter(event.target.value)}
/>
</div>
{error && (
<div className="glass-panel" style={{ padding: '1rem', marginBottom: '1rem', color: 'var(--danger)', borderColor: 'rgba(239,68,68,0.35)' }}>
{error}
</div>
)}
<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: '920px' }}>
<thead>
<tr>
<th className="sticky-header">Plan</th>
<th className="sticky-header">Precio</th>
<th className="sticky-header">Límites</th>
<th className="sticky-header">Funciones</th>
<th className="sticky-header">Estado</th>
<th className="sticky-header" style={{ textAlign: 'right' }}>Acciones</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr><td colSpan={6} style={{ padding: '2rem', textAlign: 'center' }}>Cargando planes...</td></tr>
) : filteredPlans.length === 0 ? (
<tr><td colSpan={6} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No se encontraron planes</td></tr>
) : (
filteredPlans.map(plan => (
<tr key={plan._id || plan.id || plan.code} className="table-row-hover" style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
<td style={{ padding: '1rem' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontWeight: 700 }}>
{plan.name} {plan.featured && <Star size={16} color="var(--warning)" fill="var(--warning)" />}
</div>
<div style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>{plan.code}</div>
<div style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginTop: '0.35rem', maxWidth: '280px' }}>{plan.description}</div>
</td>
<td style={{ padding: '1rem' }}>
<div>{formatMoney(plan.price)} / mes</div>
<div style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>{formatMoney(plan.annualPrice)} / año</div>
</td>
<td style={{ padding: '1rem' }}>
<div className="limit-tags">
{getLimitTags(plan).map((limit) => (
<span key={limit.label} className={`limit-tag ${limit.value === -1 ? 'unlimited' : ''}`}>
<small>{limit.label}</small>
<strong>{formatLimit(limit.value)}</strong>
</span>
))}
</div>
</td>
<td style={{ padding: '1rem' }}>
<div className="feature-tags">
{getFeatureTags(plan).map((feature) => (
<span key={feature.label} className={`feature-tag ${feature.enabled ? 'enabled' : 'disabled'}`}>
{feature.label}
</span>
))}
</div>
</td>
<td style={{ padding: '1rem' }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.35rem', color: plan.active ? 'var(--success)' : 'var(--warning)' }}>
{plan.active ? <CheckCircle size={18} /> : <XCircle size={18} />}
{plan.active ? 'Activo' : 'Inactivo'}
</span>
</td>
<td style={{ padding: '1rem', textAlign: 'right' }}>
<button className="icon-btn" title="Editar plan" aria-label={`Editar ${plan.name}`} onClick={() => setEditingPlan(plan)}>
<Edit2 size={18} />
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</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); padding: 1rem; color: var(--text-muted); font-weight: 600; }
.table-row-hover:hover { background: rgba(255, 255, 255, 0.02); }
.limit-tags { display: flex; flex-wrap: wrap; gap: 0.4rem; max-width: 300px; }
.limit-tag { display: inline-flex; align-items: center; gap: 0.3rem; border-radius: 999px; padding: 0.25rem 0.55rem; background: rgba(59, 130, 246, 0.12); border: 1px solid rgba(59, 130, 246, 0.24); color: #bfdbfe; }
.limit-tag small { color: #93c5fd; font-weight: 800; font-size: 0.7rem; text-transform: uppercase; }
.limit-tag strong { color: #f8fafc; font-size: 0.82rem; }
.limit-tag.unlimited { background: rgba(168, 85, 247, 0.16); border-color: rgba(168, 85, 247, 0.32); }
.limit-tag.unlimited small { color: #d8b4fe; }
.limit-tag.unlimited strong { color: #f5d0fe; font-size: 0.95rem; }
.feature-tags { display: flex; flex-wrap: wrap; gap: 0.4rem; max-width: 260px; }
.feature-tag { display: inline-flex; align-items: center; border-radius: 999px; padding: 0.25rem 0.55rem; font-size: 0.75rem; font-weight: 700; border: 1px solid transparent; }
.feature-tag.enabled { background: rgba(34, 197, 94, 0.14); color: #86efac; border-color: rgba(34, 197, 94, 0.28); }
.feature-tag.disabled { background: rgba(148, 163, 184, 0.1); color: #94a3b8; border-color: rgba(148, 163, 184, 0.18); text-decoration: line-through; opacity: 0.75; }
@media (max-width: 768px) { .plans-page-container { height: auto !important; overflow: visible !important; } .table-scroll-container { overflow-x: auto; } }
`}} />
{editingPlan && <EditPlanModal plan={editingPlan} onClose={() => setEditingPlan(null)} onSaved={loadPlans} />}
</motion.div>
);
};
+404
View File
@@ -0,0 +1,404 @@
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Search, Edit2, Trash2, CheckCircle, XCircle, Building2, ChevronUp, ChevronDown, RotateCcw, RefreshCw, MoreVertical, CreditCard } from 'lucide-react';
import { fetchUsers, deleteUser, setVerifiedStatus } from '../api/sysadmin';
import { EditUserModal } from '../components/ui/EditUserModal';
import { OrganizationsModal } from '../components/ui/OrganizationsModal';
import { RecalculationToolsModal } from '../components/ui/RecalculationToolsModal';
import { SubscriptionDetailsModal } from '../components/ui/SubscriptionDetailsModal';
import { formatDate } from '../utils/formatters';
export const UsersPage = () => {
const [users, setUsers] = useState<any[]>([]);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [loading, setLoading] = useState(false);
const [recalculationUserId, setRecalculationUserId] = useState('');
const [openActionsUserId, setOpenActionsUserId] = useState<string | null>(null);
// Filters
const [filters, setFilters] = useState({
name: '',
email: '',
isVerified: 'all', // all | true | false
sortBy: 'createdAt',
sortOrder: 'desc'
});
// Modals state
const [editingUser, setEditingUser] = useState<any>(null);
const [orgUser, setOrgUser] = useState<any>(null);
const [subscriptionUser, setSubscriptionUser] = useState<any>(null);
const [recalculationToolsOpen, setRecalculationToolsOpen] = useState(false);
const loadUsers = 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.email) payload.email = filters.email;
if (filters.isVerified !== 'all') payload.isVerified = filters.isVerified === 'true';
const res = await fetchUsers(payload);
setUsers(res.data);
setTotalPages(res.pages);
} catch (e) {
console.error(e);
alert('Error cargando usuarios');
}
setLoading(false);
};
useEffect(() => {
loadUsers();
}, [page, filters.sortBy, filters.sortOrder, filters.isVerified]);
useEffect(() => {
if (!openActionsUserId) return;
const closeActionsMenu = () => setOpenActionsUserId(null);
document.addEventListener('click', closeActionsMenu);
return () => document.removeEventListener('click', closeActionsMenu);
}, [openActionsUserId]);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
setPage(1);
loadUsers();
};
const handleResetFilters = () => {
setFilters({
name: '',
email: '',
isVerified: 'all',
sortBy: 'createdAt',
sortOrder: 'desc'
});
setPage(1);
};
// Efecto para recargar si se limpian los filtros manualmente
useEffect(() => {
if (filters.name === '' && filters.email === '' && filters.isVerified === 'all' && filters.sortBy === 'createdAt' && filters.sortOrder === 'desc') {
loadUsers();
}
}, [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 handleDelete = async (user: any) => {
if (window.confirm(`¿Estás seguro de que deseas eliminar permanentemente al usuario ${user.email}? Esto fallará si el usuario es dueño de organizaciones.`)) {
try {
await deleteUser(user._id);
alert('Usuario eliminado correctamente');
loadUsers();
} catch (e: any) {
alert(e.response?.data?.message || e.message || 'Error al eliminar');
}
}
};
const handleToggleVerified = async (user: any) => {
if (window.confirm(`¿Deseas cambiar el estado de verificación de ${user.email}?`)) {
try {
await setVerifiedStatus(user._id, !user.verificated);
loadUsers();
} catch (e: any) {
alert('Error al actualizar estado');
}
}
};
const openRecalculationTools = (userId = '') => {
setRecalculationUserId(userId);
setRecalculationToolsOpen(true);
};
const runRowAction = (action: () => void) => {
setOpenActionsUserId(null);
action();
};
return (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="animate-fade-in users-page-container" style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem', flexShrink: 0 }}>
<h1 style={{ fontSize: '2rem', fontWeight: '700' }}>Gestión de Usuarios</h1>
<button className="btn-secondary" onClick={() => openRecalculationTools()} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<RefreshCw size={18} /> Recalcular
</button>
</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 / Apellido</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={{ flex: '1', minWidth: '200px' }}>
<label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Email</label>
<input
type="text"
className="input-glass"
placeholder="Buscar por email..."
value={filters.email}
onChange={(e) => setFilters({...filters, email: e.target.value})}
/>
</div>
<div style={{ width: '150px' }}>
<label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Verificado</label>
<select
className="input-glass"
value={filters.isVerified}
onChange={(e) => setFilters({...filters, isVerified: 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' }}>Usuario {renderSortIcon('name')}</div>
</th>
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Contacto</th>
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Verificado</th>
<th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Cód. Verif.</th>
<th className="sticky-header sortable-header" onClick={() => toggleSort('createdAt')} style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', cursor: 'pointer', userSelect: 'none' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>Registro {renderSortIcon('createdAt')}</div>
</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={6} style={{ padding: '2rem', textAlign: 'center' }}>Cargando...</td></tr>
) : users.length === 0 ? (
<tr><td colSpan={6} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No se encontraron usuarios</td></tr>
) : (
users.map(u => (
<tr key={u._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)' }}>{u.firstName} {u.lastName}</div>
<div style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>{u.email}</div>
</td>
<td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
{u.phoneCountryCode && `+${u.phoneCountryCode}`} {u.phoneAreaCode} {u.phoneNumber}
</td>
<td style={{ padding: '1rem' }}>
<button
onClick={() => handleToggleVerified(u)}
style={{ background: 'transparent', display: 'flex', alignItems: 'center', gap: '5px', color: u.verificated ? 'var(--success)' : 'var(--warning)', cursor: 'pointer' }}
>
{u.verificated ? <CheckCircle size={18} /> : <XCircle size={18} />}
{u.verificated ? 'Sí' : 'No'}
</button>
</td>
<td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
{u.verificationCode || '-'}
</td>
<td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
{formatDate(u.creationDate)}
</td>
<td style={{ padding: '1rem', textAlign: 'right' }}>
<div className="actions-menu-wrapper" onClick={(e) => e.stopPropagation()}>
<button
className="icon-btn"
title="Acciones"
aria-label={`Acciones para ${u.email}`}
aria-haspopup="menu"
aria-expanded={openActionsUserId === u._id}
onClick={() => setOpenActionsUserId(openActionsUserId === u._id ? null : u._id)}
>
<MoreVertical size={18} />
</button>
{openActionsUserId === u._id && (
<div className="actions-menu" role="menu">
<button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => setOrgUser(u))}>
<Building2 size={16} /> Ver organizaciones
</button>
<button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => setSubscriptionUser(u))}>
<CreditCard size={16} /> Ver suscripción
</button>
<button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => openRecalculationTools(u._id))}>
<RefreshCw size={16} /> Recalcular uso del plan
</button>
<button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => handleToggleVerified(u))}>
{u.verificated ? <XCircle size={16} /> : <CheckCircle size={16} />}
{u.verificated ? 'Marcar como no verificado' : 'Marcar como verificado'}
</button>
<button type="button" className="actions-menu-item" role="menuitem" onClick={() => runRowAction(() => setEditingUser(u))}>
<Edit2 size={16} /> Editar perfil
</button>
<button type="button" className="actions-menu-item danger" role="menuitem" onClick={() => runRowAction(() => handleDelete(u))}>
<Trash2 size={16} /> Eliminar
</button>
</div>
)}
</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>
<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);
}
.actions-menu-wrapper {
position: relative;
display: inline-flex;
justify-content: flex-end;
}
.actions-menu {
position: absolute;
top: calc(100% + 8px);
right: 0;
z-index: 30;
min-width: 230px;
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: #fca5a5;
}
.actions-menu-item.danger:hover {
background: rgba(239, 68, 68, 0.18);
color: #fecaca;
}
.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) {
.users-page-container {
height: auto !important;
overflow: visible !important;
}
.filters-bar form > div {
flex: 1 1 100% !important;
}
.table-scroll-container {
overflow-x: auto;
}
}
`}} />
{/* Modals */}
{editingUser && <EditUserModal user={editingUser} onClose={() => setEditingUser(null)} onSaved={loadUsers} />}
{orgUser && <OrganizationsModal user={orgUser} onClose={() => setOrgUser(null)} />}
{subscriptionUser && <SubscriptionDetailsModal user={subscriptionUser} onClose={() => setSubscriptionUser(null)} />}
{recalculationToolsOpen && <RecalculationToolsModal initialUserId={recalculationUserId} onClose={() => setRecalculationToolsOpen(false)} />}
</motion.div>
);
};
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
export {};
declare global {
interface Window {
txadmin: {
getKeyStatus: () => Promise<{ loaded: boolean; path: string | null }>;
selectPrivateKey: () => Promise<{ loaded: boolean; path: string | null }>;
request: <T = unknown>(route: string, body: unknown) => Promise<T>;
minimizeWindow: () => Promise<void>;
toggleMaximizeWindow: () => Promise<boolean>;
closeWindow: () => Promise<void>;
};
}
}
+18
View File
@@ -0,0 +1,18 @@
import { format, isValid, parseISO } from 'date-fns';
import { es } from 'date-fns/locale';
const parseDate = (value?: string) => {
if (!value) return null;
const parsedDate = parseISO(value);
return isValid(parsedDate) ? parsedDate : null;
};
export const formatDate = (value?: string) => {
const parsedDate = parseDate(value);
return parsedDate ? format(parsedDate, 'dd MMM yyyy', { locale: es }) : value || '-';
};
export const formatDateTime = (value?: string) => {
const parsedDate = parseDate(value);
return parsedDate ? format(parsedDate, "dd MMM yyyy, HH:mm 'hs'", { locale: es }) : value || '-';
};
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2023",
"module": "CommonJS",
"moduleResolution": "Node",
"ignoreDeprecations": "6.0",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist-electron",
"rootDir": "electron",
"types": ["node"]
},
"include": ["electron/**/*.ts"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "ESNext",
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
base: './',
plugins: [react()],
})
+1
View File
@@ -72,6 +72,7 @@ export type DeleteByClientAccountMovementParams = {
export interface ICashFlow {
id: string;
_id?: string;
companyId: string;
paymentId?: string;
clientId?: string;
@@ -183,14 +183,72 @@ export default function ClientAccountMovementsList() {
const pdfFonts = (await import("pdfmake/build/vfs_fonts")) as any;
pdfMake.vfs = pdfFonts.pdfMake ? pdfFonts.pdfMake.vfs : pdfFonts.vfs;
// Simplified report generation for brevity
let logoDataUrl = "";
try {
const response = await fetch("/favicon512.png");
const blob = await response.blob();
logoDataUrl = await new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.readAsDataURL(blob);
});
} catch (e) { }
const finalBalance = report.data.length > 0
? report.data[report.data.length - 1].balance
: report.balance;
const tableBody = [
[
{ text: "Fecha", bold: true },
{ text: "Descripción", bold: true },
{ text: "Crédito", bold: true, alignment: "right" },
{ text: "Débito", bold: true, alignment: "right" },
{ text: "Saldo", bold: true, alignment: "right" },
],
...report.data.map((item) => [
dayjs(item.date).format("DD/MM/YYYY"),
item.description || "-",
{ text: item.credit ? formatPrice(item.credit) : "-", alignment: "right" },
{ text: item.debit ? formatPrice(item.debit) : "-", alignment: "right" },
{ text: formatPrice(item.balance), alignment: "right" },
]),
];
const docDefinition: any = {
pageOrientation: "landscape",
pageMargins: [30, 30, 30, 30],
defaultStyle: {
fontSize: 9,
},
content: [
{ text: "Resumen de Cuenta Corriente", fontSize: 18, bold: true, margin: [0, 0, 0, 10] },
{
columns: [
{ text: "Resumen de Cuenta Corriente", fontSize: 18, bold: true, margin: [0, 0, 0, 10], width: "*" },
...(logoDataUrl ? [{ image: logoDataUrl, width: 45, margin: [0, 0, 0, 10], alignment: "right" }] : []),
],
},
{ text: report.organizacionName, margin: [0, 0, 0, 5] },
{ text: `Cliente: ${report.clientName}`, margin: [0, 0, 0, 5] },
{ text: `Período: ${filterDateFrom.format("DD/MM/YYYY")} al ${filterDateTo.format("DD/MM/YYYY")}`, margin: [0, 0, 0, 20] },
{ text: "PDF Generado con Éxito", bold: true }
]
report.data.length > 0
? {
table: {
headerRows: 1,
widths: ["auto", "*", "auto", "auto", "auto"],
body: tableBody,
},
layout: "lightHorizontalLines",
margin: [0, 0, 0, 16],
}
: { text: "No hay movimientos en el período seleccionado.", italics: true, margin: [0, 0, 0, 16] },
{
columns: [
{ text: "" },
{ text: `Saldo final del período: ${formatPrice(finalBalance)}`, bold: true, alignment: "right" },
],
},
],
};
if ((window as any).Android && (window as any).Android.savePdf) {
@@ -13,6 +13,106 @@ import {
import { ApiError } from "@core/Models/Server.Error.model";
import * as Yup from "yup";
export type ArcaWsfeLastVoucherParams = {
companyId: string;
sessionUser: string;
};
export type ArcaWsfeLastVoucherResult = {
environment: "homologation" | "production";
service: "wsfe";
endpoints?: {
wsaaHost?: string;
wsfeHost?: string;
};
pointOfSale: number;
voucherType: 11;
lastVoucherNumber: number;
};
export type CreateInvoiceFromCashMovementParams = {
cashMovementId: string;
billingDate: string | Date;
servicePeriodFrom: string | Date;
servicePeriodTo: string | Date;
paymentDueDate: string | Date;
activityCode: string;
activityDescription: string;
receiverIvaCondition?: 5;
receiverDocumentType?: string | number;
receiverDocumentNumber?: string | number;
receiverName?: string;
receiverAddress?: string;
receiverEmail?: string;
saleCondition: string;
itemDescription: string;
itemQuantity?: number;
itemUnit?: string;
itemUnitPrice: number;
itemDiscountPercent?: number;
itemDiscountAmount?: number;
itemSubtotal: number;
sessionUser: string;
};
export type FindInvoicesParams = {
companyId?: string;
cashMovementId?: string;
cashMovementIds?: string[];
sessionUser: string;
};
export type InvoiceStatus = "PENDING_ARCA" | "APPROVED" | "PENDING_VERIFICATION" | "REJECTED" | "FAILED";
export type Invoice = {
id?: string;
cashMovementId: string;
companyId: string;
amount: number;
type: "FACTURA_C";
status: InvoiceStatus;
billingDate: Date;
servicePeriodFrom: Date;
servicePeriodTo: Date;
paymentDueDate: Date;
activityCode: string;
activityDescription: string;
receiverIvaCondition: 5;
receiverDocumentType?: string | number;
receiverDocumentNumber?: string | number;
receiverName?: string;
receiverAddress?: string;
receiverEmail?: string;
saleCondition: 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;
arcaErrorMessage?: string;
};
export type OrganizationFiscalProfile = {
cuit?: string;
legalName?: string;
taxCondition?: "MONOTRIBUTO" | "EXENTO";
pointOfSale?: number;
activityCode?: string;
activityDescription?: string;
};
export type FindOrganizationFiscalProfilesParams = {
companyId: string;
sessionUser: string;
};
const schemaCreateCashFlowMovement = Yup.object().shape({
paymentMethod: Yup.string().required("Debe introducir el tipo de movimiento."),
companyId: Yup.string().required("La organización no es valida."),
@@ -72,3 +172,25 @@ export const cashFlowPaginate = async (
export const cashFlowPaginateBalance = async (data: FindCashFlowBalanceParams): Promise<number> => {
return ApiRequest.post<number>("cashflow/paginate-balance", data);
};
export const getArcaWsfeLastVoucher = async (
data: ArcaWsfeLastVoucherParams
): Promise<ArcaWsfeLastVoucherResult> => {
return ApiRequest.post<ArcaWsfeLastVoucherResult>("arca-credentials/wsfe-last-voucher", data);
};
export const createInvoiceFromCashMovement = async (
data: CreateInvoiceFromCashMovementParams
): Promise<Invoice> => {
return ApiRequest.post<Invoice>("invoices/create-from-cash-movement", data);
};
export const findInvoices = async (data: FindInvoicesParams): Promise<Invoice[]> => {
return ApiRequest.post<Invoice[]>("invoices/find", data);
};
export const findOrganizationFiscalProfiles = async (
data: FindOrganizationFiscalProfilesParams
): Promise<OrganizationFiscalProfile[]> => {
return ApiRequest.post<OrganizationFiscalProfile[]>("organization-fiscal-profiles/find", data);
};
@@ -0,0 +1,490 @@
.movementsPage {
padding: 16px;
padding-bottom: 32px;
}
.movementsList {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
}
.movementCard {
border: 1px solid var(--gray-light);
border-radius: 18px;
background: linear-gradient(135deg, var(--white) 0%, #f9fafb 100%);
box-shadow: 0 14px 34px rgba(15, 23, 42, 0.08);
overflow: hidden;
padding: 16px;
position: relative;
}
.movementCard::before {
background: radial-gradient(circle, rgba(255, 255, 255, 0.9) 0%, transparent 68%);
border-radius: 999px;
content: "";
height: 150px;
position: absolute;
right: -74px;
top: -80px;
width: 150px;
}
.movementCardIcon {
color: var(--movement-card-accent, var(--gray-dark));
height: 74px;
opacity: 0.2;
pointer-events: none;
position: absolute;
right: 24px;
bottom: 14px;
width: 74px;
z-index: 0;
}
.movementContent {
position: relative;
z-index: 1;
}
.movementCardCash {
--movement-card-accent: #16803f;
background: linear-gradient(135deg, #ffffff 0%, #f0fbf4 100%);
}
.movementCardBankTransfer {
--movement-card-accent: #2563eb;
background: linear-gradient(135deg, #ffffff 0%, #eef5ff 100%);
}
.movementCardCreditCard {
--movement-card-accent: #7c3aed;
background: linear-gradient(135deg, #ffffff 0%, #f5f0ff 100%);
}
.movementCardDebitCard {
--movement-card-accent: #0f766e;
background: linear-gradient(135deg, #ffffff 0%, #edfbf9 100%);
}
.movementCardClientAccount {
--movement-card-accent: #b45309;
background: linear-gradient(135deg, #ffffff 0%, #fff7ed 100%);
}
.movementCardOther {
--movement-card-accent: #64748b;
background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
}
.movementHeader {
display: flex;
flex-direction: column;
gap: 14px;
}
.movementSummary {
min-width: 0;
}
.movementDescription {
color: var(--black-light);
font-size: 16px;
line-height: 1.25;
margin: 0 0 6px;
}
.movementDate {
color: var(--gray-dark);
display: block;
font-size: 13px;
}
.movementAmount {
align-self: flex-start;
border-radius: 999px;
font-size: 18px;
font-weight: 800;
padding: 8px 12px;
}
.movementAmountPositive {
background: rgba(29, 141, 75, 0.12);
color: var(--green-darkestX2);
}
.movementAmountNegative {
background: rgba(188, 32, 42, 0.12);
color: var(--red);
}
.movementMeta {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 14px;
}
.movementMetaItem {
background: rgba(255, 255, 255, 0.72);
border-radius: 999px;
border: 1px solid rgba(148, 163, 184, 0.22);
color: var(--gray-dark);
font-size: 12px;
font-weight: 600;
backdrop-filter: blur(8px);
padding: 6px 10px;
}
.movementActionsSlot {
display: flex;
gap: 8px;
margin-top: 16px;
}
.movementInvoiceButton {
background: var(--movement-card-accent, var(--black-light));
border: 0;
border-radius: 999px;
color: var(--white);
cursor: pointer;
font-size: 13px;
font-weight: 700;
padding: 8px 14px;
}
.movementInvoiceButton:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.movementInvoiceBadge {
background: rgba(22, 128, 63, 0.12);
border: 1px solid rgba(22, 128, 63, 0.24);
border-radius: 999px;
color: #166534;
font-size: 12px;
font-weight: 700;
padding: 7px 10px;
}
.movementInvoicePdfButton {
background: var(--white);
border: 1px solid rgba(22, 128, 63, 0.24);
border-radius: 999px;
color: #166534;
cursor: pointer;
font-size: 12px;
font-weight: 800;
padding: 7px 10px;
}
.emptyState {
background: var(--white);
border: 1px dashed var(--gray-light);
border-radius: 18px;
color: var(--gray-dark);
padding: 28px 16px;
text-align: center;
}
.paginationWrapper {
display: flex;
justify-content: center;
margin-top: 18px;
}
.invoiceModalBackdrop {
align-items: flex-end;
background: rgba(15, 23, 42, 0.48);
display: flex;
inset: 0;
justify-content: center;
padding: 72px 14px 14px;
position: fixed;
z-index: 1000;
}
.invoiceModal {
background: var(--white);
border-radius: 24px 24px 18px 18px;
box-shadow: 0 24px 70px rgba(15, 23, 42, 0.28);
display: flex;
flex-direction: column;
max-height: calc(100dvh - 86px);
min-height: 0;
overflow: hidden;
padding: 18px;
width: 100%;
}
.invoiceModalBody {
min-height: 0;
overflow-y: auto;
padding-right: 2px;
scrollbar-width: none;
}
.invoiceModalBody::-webkit-scrollbar {
display: none;
}
.invoiceModalHeader {
align-items: flex-start;
background: var(--white);
display: flex;
flex-shrink: 0;
gap: 12px;
justify-content: space-between;
margin-bottom: 16px;
position: relative;
z-index: 3;
}
.invoiceModalHeader h2 {
color: var(--black-light);
font-size: 20px;
line-height: 1.2;
margin: 0;
}
.invoiceModalClose {
align-items: center;
background: #f1f5f9;
border: 0;
border-radius: 999px;
color: var(--gray-dark);
cursor: pointer;
display: flex;
font-size: 24px;
height: 36px;
justify-content: center;
line-height: 1;
width: 36px;
}
.invoiceAmountBox {
background: linear-gradient(135deg, #f0fbf4 0%, #ffffff 100%);
border: 1px solid rgba(22, 128, 63, 0.16);
border-radius: 18px;
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 16px;
padding: 14px;
}
.invoiceAmountBox span {
color: var(--gray-dark);
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
}
.invoiceAmountBox strong {
color: var(--green-darkestX2);
font-size: 22px;
}
.invoiceSteps {
background: var(--white);
display: flex;
gap: 8px;
margin-bottom: 14px;
overflow-x: auto;
padding-bottom: 8px;
position: sticky;
top: 0;
z-index: 2;
scrollbar-width: none;
}
.invoiceSteps::-webkit-scrollbar {
display: none;
}
.invoiceSteps span {
background: #f1f5f9;
border-radius: 999px;
color: var(--gray-dark);
flex: 0 0 auto;
font-size: 12px;
font-weight: 700;
padding: 7px 10px;
}
.invoiceSteps .invoiceStepActive {
background: rgba(22, 128, 63, 0.14);
color: #166534;
}
.invoiceGrid {
display: grid;
gap: 12px;
grid-template-columns: 1fr;
}
.invoiceField {
color: var(--black-light);
display: flex;
flex-direction: column;
font-size: 13px;
font-weight: 700;
gap: 7px;
margin-bottom: 14px;
}
.invoiceFieldFull {
composes: invoiceField;
}
.invoiceField input,
.invoiceField select,
.invoiceField textarea {
background: var(--white);
border: 1px solid var(--gray-light);
border-radius: 14px;
color: var(--black-light);
font: inherit;
font-weight: 500;
padding: 11px 12px;
width: 100%;
}
.invoiceField textarea {
min-height: 104px;
resize: vertical;
}
.invoiceToggle {
align-items: center;
color: var(--black-light);
display: flex;
font-size: 13px;
font-weight: 700;
gap: 10px;
margin-bottom: 4px;
}
.invoiceToggle input {
height: 18px;
width: 18px;
}
.invoiceSummaryBox {
background: #f8fafc;
border: 1px solid var(--gray-light);
border-radius: 18px;
color: var(--black-light);
display: grid;
gap: 8px;
padding: 14px;
}
.invoiceSummaryBox p {
font-size: 13px;
line-height: 1.35;
margin: 0;
}
.invoiceModalActions {
background: var(--white);
display: flex;
flex-direction: column;
flex-shrink: 0;
gap: 10px;
margin-top: 18px;
padding-top: 12px;
}
.invoiceModalActions .invoiceConfirmButton {
order: -1;
}
.invoiceCancelButton,
.invoiceConfirmButton {
border: 0;
border-radius: 999px;
cursor: pointer;
font-size: 14px;
font-weight: 800;
padding: 12px 16px;
}
.invoiceCancelButton {
background: #f1f5f9;
color: var(--gray-dark);
}
.invoiceConfirmButton {
background: var(--green-darkestX2);
color: var(--white);
}
.invoiceCancelButton:disabled,
.invoiceConfirmButton:disabled,
.invoiceModalClose:disabled {
cursor: not-allowed;
opacity: 0.55;
}
@media (min-width: 768px) {
.movementsPage {
padding: 22px;
}
.movementsList {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.movementHeader {
align-items: flex-start;
flex-direction: row;
justify-content: space-between;
}
.movementAmount {
align-self: auto;
text-align: right;
white-space: nowrap;
}
.movementCardIcon {
height: 82px;
right: 28px;
width: 82px;
}
.invoiceModalBackdrop {
align-items: center;
}
.invoiceModal {
border-radius: 24px;
max-width: 680px;
}
.invoiceGrid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.invoiceFieldFull {
grid-column: 1 / -1;
}
.invoiceModalActions {
flex-direction: row;
justify-content: flex-end;
}
.invoiceModalActions .invoiceConfirmButton {
order: initial;
}
}
@media (min-width: 1200px) {
.movementsList {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@@ -7,7 +7,11 @@ import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import AccountBalanceOutlinedIcon from "@mui/icons-material/AccountBalanceOutlined";
import AccountMovementsIcon from "@mui/icons-material/CurrencyExchangeOutlined";
import DataGrid, { DataGridColumn } from "@core/app/components/DataGrid/DataGrid";
import AccountBalanceWalletOutlinedIcon from "@mui/icons-material/AccountBalanceWalletOutlined";
import CreditCardOutlinedIcon from "@mui/icons-material/CreditCardOutlined";
import MoreHorizOutlinedIcon from "@mui/icons-material/MoreHorizOutlined";
import PaymentOutlinedIcon from "@mui/icons-material/PaymentOutlined";
import PointOfSaleOutlinedIcon from "@mui/icons-material/PointOfSaleOutlined";
import { formatPrice } from "@core/app/helpers/Numbers";
import dayjs from "dayjs";
import {
@@ -15,7 +19,7 @@ import {
PaginateCashFlowParams,
PaginateCashFlowResults,
} from "@core/Models/CashFlow.model";
import { cashFlowPaginate } from "../Cash.Service";
import { cashFlowPaginate, createInvoiceFromCashMovement, findInvoices, findOrganizationFiscalProfiles, Invoice, OrganizationFiscalProfile } from "../Cash.Service";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";
import Filterable from "@core/app/components/Filterable/Filterable";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
@@ -26,7 +30,18 @@ import { useFilterStore } from "@core/Store/Filter.Store";
import { FindEmployeesParams } from "@core/Models/Collaborators.model";
import filterObjects from "@components/TextObjectFilter/Filter.Service";
import { FindClientsParams } from "@core/Models/Clients.model";
import { paymentMethods, PAYMENT_METHODS } from "@core/Models/Payments.model";
import {
paymentMethods,
PAYMENT_METHODS,
PAYMENT_METHODS_CLIENT_ACCOUNT,
} from "@core/Models/Payments.model";
import {
CLIENT_ACCOUNT_MOVEMENT_TYPES,
CLIENT_ACCOUNT_PAYMENT_METHODS,
} from "@core/Models/ClientAccountMovements.model";
import PaginationControls from "@components/PaginationControls/PaginationControls";
import { useAlert } from "@core/Store/Alert.Store";
import style from "./page.module.css";
type UrlData = {
id: string;
@@ -161,6 +176,258 @@ const FilterContent = (props: FilterContentProps) => {
);
};
const movementTypeLabels: Record<string, string> = {
deposit: "Ingreso",
withdrawal: "Egreso",
};
const getPaymentMethodName = (paymentMethod: string) => {
return paymentMethods.find((method) => method.id === paymentMethod)?.name || paymentMethod;
};
const getMovementId = (movement: ICashFlow) => movement.id || movement._id || "";
const todayInputValue = () => dayjs().format("YYYY-MM-DD");
const saleConditionOptions = [
{ id: "cash", name: "Contado" },
{ id: "debit_card", name: "Tarjeta de débito" },
{ id: "credit_card", name: "Tarjeta de crédito" },
{ id: "current_account", name: "Cuenta corriente" },
{ id: "check", name: "Cheque" },
{ id: "bank_transfer", name: "Transferencia bancaria" },
{ id: "other", name: "Otra" },
{ id: "electronic_payment", name: "Otros medios de pago electrónicos" },
];
const receiverDocumentTypeOptions = [
{ id: "96", name: "DNI" },
{ id: "99", name: "Consumidor Final / sin documento" },
];
const isSaleCondition = (saleCondition?: string) => {
return saleConditionOptions.some((option) => option.id === saleCondition);
};
const getInvoiceSaleCondition = (paymentMethod?: string) => {
if (paymentMethod && isSaleCondition(paymentMethod)) {
return paymentMethod;
}
return "cash";
};
const getInvoiceServiceDescription = (movement: ICashFlow) => {
const description = (movement.description || "").trim();
if (!description) {
return "Servicio facturado";
}
const serviceMatch = description.match(/^[^-]+ - (.+?)(?: \([^)]+\))?$/);
return serviceMatch?.[1]?.trim() || description;
};
const formatInvoiceDate = (value?: string | Date) => value ? dayjs(value).format("DD/MM/YYYY") : "-";
const formatInvoiceNumber = (value?: number, length = 5) => String(value || 0).padStart(length, "0");
const formatInvoiceAmount = (value?: number) => new Intl.NumberFormat("es-AR", { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value || 0);
const getInvoiceSaleConditionLabel = (saleCondition?: string) => saleConditionOptions.find((option) => option.id === saleCondition)?.name || "Contado";
const getInvoiceTaxConditionLabel = (taxCondition?: string) => taxCondition === "EXENTO" ? "IVA Exento" : "Responsable Monotributo";
const buildInvoiceCopyPage = (copyLabel: string, invoice: Invoice, fiscalProfile: OrganizationFiscalProfile) => {
const legalName = fiscalProfile.legalName || "-";
const cuit = fiscalProfile.cuit || "-";
const pointOfSale = formatInvoiceNumber(invoice.pointOfSale || fiscalProfile.pointOfSale, 5);
const voucherNumber = formatInvoiceNumber(invoice.voucherNumber, 8);
const total = formatInvoiceAmount(invoice.itemSubtotal || invoice.amount);
const taxCondition = getInvoiceTaxConditionLabel(fiscalProfile.taxCondition);
const itemDescription = invoice.itemDescription || "Servicio facturado";
const itemUnit = invoice.itemUnit || "unidades";
return [
{
table: { widths: ["*"], body: [[{ text: copyLabel, style: "copyTitle" }]] },
margin: [0, 0, 0, 0],
},
{
table: {
widths: ["*", 54, "*"],
body: [[
{ stack: [
{ text: legalName, style: "issuerName" },
{ text: [{ text: "Razón Social: ", bold: true }, legalName], margin: [0, 24, 0, 0] },
{ text: [{ text: "Domicilio Comercial: ", bold: true }, "-"], margin: [0, 10, 0, 0] },
{ text: [{ text: "Condición frente al IVA: ", bold: true }, taxCondition], margin: [0, 10, 0, 0] },
], border: [true, true, false, true], margin: [6, 8, 6, 6] },
{ stack: [{ text: "C", style: "voucherLetter" }, { text: "COD. 011", style: "voucherCode" }], alignment: "center", border: [true, true, true, true], margin: [0, 6, 0, 4] },
{ stack: [
{ text: "FACTURA", style: "invoiceTitle" },
{ text: [{ text: "Punto de Venta: ", bold: true }, pointOfSale, { text: " Comp. Nro: ", bold: true }, voucherNumber], margin: [0, 8, 0, 0] },
{ text: [{ text: "Fecha de Emisión: ", bold: true }, formatInvoiceDate(invoice.billingDate)], margin: [0, 7, 0, 0] },
{ text: [{ text: "CUIT: ", bold: true }, cuit], margin: [0, 10, 0, 0] },
{ text: [{ text: "Ingresos Brutos: ", bold: true }, cuit], margin: [0, 2, 0, 0] },
{ text: [{ text: "Fecha de Inicio de Actividades: ", bold: true }, "-"], margin: [0, 2, 0, 0] },
], border: [false, true, true, true], margin: [18, 8, 6, 6] },
]],
},
layout: "noPadding",
},
{
table: { widths: ["33%", "28%", "39%"], body: [[
{ text: [{ text: "Período Facturado Desde: ", bold: true }, formatInvoiceDate(invoice.servicePeriodFrom)] },
{ text: [{ text: "Hasta: ", bold: true }, formatInvoiceDate(invoice.servicePeriodTo)] },
{ text: [{ text: "Fecha de Vto. para el pago: ", bold: true }, formatInvoiceDate(invoice.paymentDueDate)] },
]] },
style: "smallTable",
},
{
table: { widths: ["34%", "33%", "33%"], body: [
[{ text: "Doc.: -", bold: true }, { text: "Apellido y Nombre / Razón Social:", bold: true }, { text: "" }],
[{ text: [{ text: "Condición frente al IVA: ", bold: true }, "Consumidor Final"] }, { text: "Domicilio:", bold: true }, { text: invoice.receiverAddress || "" }],
[{ text: [{ text: "Condición de venta: ", bold: true }, getInvoiceSaleConditionLabel(invoice.saleCondition)], colSpan: 3 }, {}, {}],
] },
margin: [0, 0, 0, 2],
},
{
table: {
headerRows: 1,
widths: [42, "*", 58, 52, 78, 45, 70, 78],
body: [
["Código", "Producto / Servicio", "Cantidad", "U. Medida", "Precio Unit.", "% Bonif", "Imp. Bonif.", "Subtotal"].map((text) => ({ text, bold: true, fillColor: "#d7d7d7", alignment: "center" })),
["", itemDescription, formatInvoiceAmount(invoice.itemQuantity || 1), itemUnit, formatInvoiceAmount(invoice.itemUnitPrice || invoice.amount), formatInvoiceAmount(invoice.itemDiscountPercent), formatInvoiceAmount(invoice.itemDiscountAmount), total],
],
},
fontSize: 7,
},
{ text: " ", margin: [0, 154, 0, 0] },
{
table: { widths: ["*"], body: [[{ stack: [
{ text: [{ text: "Subtotal: $ ", bold: true }, total], alignment: "right", margin: [0, 8, 0, 0] },
{ text: [{ text: "Importe Otros Tributos: $ ", bold: true }, "0,00"], alignment: "right", margin: [0, 8, 0, 0] },
{ text: [{ text: "Importe Total: $ ", bold: true }, total], alignment: "right", margin: [0, 8, 0, 8] },
] }]] },
},
{
columns: [
{ columns: [
{ qr: buildArcaQrUrl(invoice, fiscalProfile), fit: 66, width: 78, margin: [0, 13, 0, 0] },
{ stack: [{ text: "ARCA", style: "arcaLogo" }, { text: "AGENCIA DE RECAUDACIÓN\nY CONTROL ADUANERO", fontSize: 5, color: "#6b7280", margin: [0, -3, 0, 0] }, { text: "Comprobante Autorizado", bold: true, italics: true, margin: [0, 11, 0, 0] }, { text: "Esta Agencia no se responsabiliza por los datos ingresados en el detalle de la operación", fontSize: 6, italics: true, margin: [0, 8, 0, 0] }], width: "*" },
], width: "40%" },
{ text: "Pág. 1/1", bold: true, alignment: "center", width: "20%", margin: [0, 34, 0, 0] },
{ stack: [{ text: [{ text: "CAE N°: ", bold: true }, invoice.cae || "-"] }, { text: [{ text: "Fecha de Vto. de CAE: ", bold: true }, formatInvoiceDate(invoice.caeExpiresAt)], margin: [0, 8, 0, 0] }], width: "40%", alignment: "right", margin: [0, 30, 0, 0] },
],
margin: [0, 30, 0, 0],
pageBreak: copyLabel === "TRIPLICADO" ? undefined : "after",
},
];
};
const buildArcaQrUrl = (invoice: Invoice, fiscalProfile: OrganizationFiscalProfile) => {
const payload = {
ver: 1,
fecha: dayjs(invoice.billingDate).format("YYYY-MM-DD"),
cuit: Number(fiscalProfile.cuit || 0),
ptoVta: invoice.pointOfSale || fiscalProfile.pointOfSale || 0,
tipoCmp: 11,
nroCmp: invoice.voucherNumber || 0,
importe: Number(invoice.itemSubtotal || invoice.amount || 0),
moneda: "PES",
ctz: 1,
tipoDocRec: Number(invoice.receiverDocumentType || 99),
nroDocRec: Number(invoice.receiverDocumentNumber || 0),
tipoCodAut: "E",
codAut: Number(invoice.cae || 0),
};
return `https://www.afip.gob.ar/fe/qr/?p=${btoa(JSON.stringify(payload))}`;
};
const invoiceWizardSteps = ["Datos de emisión", "Datos del receptor", "Datos de la operación", "Resumen"];
type InvoiceDraft = {
movement: ICashFlow;
movementId: string;
billingDate: string;
servicePeriodFrom: string;
servicePeriodTo: string;
paymentDueDate: string;
activityCode: string;
activityDescription: string;
saleCondition: string;
includeReceiverData: boolean;
receiverDocumentType: string;
receiverDocumentNumber: string;
receiverName: string;
receiverAddress: string;
receiverEmail: string;
itemDescription: string;
itemQuantity: number;
itemUnit: string;
itemUnitPrice: number;
itemDiscountPercent: number;
itemDiscountAmount: number;
itemSubtotal: number;
};
const getPaymentMethodCardVisual = (paymentMethod?: PAYMENT_METHODS | string) => {
switch (paymentMethod) {
case CLIENT_ACCOUNT_PAYMENT_METHODS.CASH:
return {
Icon: PointOfSaleOutlinedIcon,
className: style.movementCardCash,
};
case CLIENT_ACCOUNT_PAYMENT_METHODS.BANK_TRANSFER:
return {
Icon: AccountBalanceOutlinedIcon,
className: style.movementCardBankTransfer,
};
case CLIENT_ACCOUNT_PAYMENT_METHODS.CREDIT_CARD:
return {
Icon: CreditCardOutlinedIcon,
className: style.movementCardCreditCard,
};
case CLIENT_ACCOUNT_PAYMENT_METHODS.DEBIT_CARD:
return {
Icon: PaymentOutlinedIcon,
className: style.movementCardDebitCard,
};
case PAYMENT_METHODS_CLIENT_ACCOUNT.CLIENT_ACCOUNT:
return {
Icon: AccountBalanceWalletOutlinedIcon,
className: style.movementCardClientAccount,
};
default:
return {
Icon: MoreHorizOutlinedIcon,
className: style.movementCardOther,
};
}
};
const getInvoiceStatusMessage = (invoice: Invoice) => {
const voucher = invoice.pointOfSale && invoice.voucherNumber
? ` Comprobante intentado: ${invoice.pointOfSale}-${invoice.voucherNumber}.`
: "";
switch (invoice.status) {
case "APPROVED":
return "Factura emitida correctamente.";
case "PENDING_ARCA":
case "PENDING_VERIFICATION":
return `${invoice.arcaErrorMessage || "La factura quedó pendiente de verificación en ARCA."}${voucher}`;
case "REJECTED":
case "FAILED":
return invoice.arcaErrorMessage || "ARCA no autorizó la factura.";
default:
return "No se pudo confirmar el estado de la factura.";
}
};
export default function CashFlowMovementsList() {
const data = useParams<UrlData>();
const id = data.id;
@@ -168,6 +435,7 @@ export default function CashFlowMovementsList() {
const SessionInfo = useSessionStore();
const location = useLocationStore();
const eventHandler = useEventHandlerStore();
const alert = useAlert();
const filter = useFilterStore();
const [clientFilterData, setClientFilterData] = useState<TextObjectFilterResult[]>([]);
@@ -181,52 +449,6 @@ export default function CashFlowMovementsList() {
const [methodFilterData, setMethodFilterData] = useState<TextObjectFilterResult[]>([]);
const [methodId, setMethodId] = useState<string>("");
const [dataGridColumns] = useState<DataGridColumn<ICashFlow>[]>([
{
field: "description",
title: "Detalle",
width: null,
render: (value: ICashFlow) => (
<>
<div
style={{
paddingLeft: "10px",
paddingRight: "10px",
paddingTop: "10px",
}}
>
{value.description}
</div>
<div
style={{
paddingLeft: "10px",
paddingRight: "10px",
color: "var(--gray-dark)",
}}
>
{dayjs(value.createdAt).format("DD MMMM YYYY - HH:mm")}
</div>
</>
),
},
{
field: "amount",
title: "Importe",
width: 150,
render: (value: ICashFlow) => (
<div
style={{
padding: "10px",
textAlign: "right",
color: value.amount > 0 ? "var(--green-darkestX2)" : "var(--red)",
}}
>
{formatPrice(value.amount)}
</div>
),
},
]);
const [pageSize] = useState<number>(
parseInt(
process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE
@@ -235,6 +457,12 @@ export default function CashFlowMovementsList() {
)
);
const [movements, setMovements] = useState<PaginateCashFlowResults>();
const [invoicesByMovementId, setInvoicesByMovementId] = useState<Record<string, Invoice>>({});
const [invoicingMovementId, setInvoicingMovementId] = useState<string>("");
const [invoiceDraft, setInvoiceDraft] = useState<InvoiceDraft | null>(null);
const [invoiceDraftsByMovementId, setInvoiceDraftsByMovementId] = useState<Record<string, InvoiceDraft>>({});
const [fiscalProfile, setFiscalProfile] = useState<OrganizationFiscalProfile>({ activityCode: "", activityDescription: "" });
const [invoiceStep, setInvoiceStep] = useState(0);
const movementsRef = useRef(movements);
const loadMovements = (page: number = 1, pageSize: number = 30) => {
@@ -262,6 +490,20 @@ export default function CashFlowMovementsList() {
cashFlowPaginate(filterData)
.then((res) => {
setMovements(res);
const movementIds = res.data
.map((movement) => getMovementId(movement))
.filter((movementId): movementId is string => Boolean(movementId));
if (movementIds.length > 0) {
return findInvoices({ companyId: id, cashMovementIds: movementIds, sessionUser: SessionInfo.userId }).then((invoices) => {
setInvoicesByMovementId((current) => ({
...current,
...Object.fromEntries(
invoices.map((invoice) => [String(invoice.cashMovementId), invoice])
),
}));
}).catch(() => undefined);
}
})
.finally(() => {
eventHandler.setEventType(EVENT_TYPES.CLEAR);
@@ -345,6 +587,270 @@ export default function CashFlowMovementsList() {
loadMovements(loadPage, pageSize);
}, [clientId, collaboratorId, methodId]);
useEffect(() => {
if (!SessionInfo.userId) return;
findOrganizationFiscalProfiles({ companyId: id, sessionUser: SessionInfo.userId })
.then((profiles) => {
const profile = profiles[0];
setFiscalProfile(profile || { activityCode: "", activityDescription: "" });
})
.catch(() => {
setFiscalProfile({ activityCode: "", activityDescription: "" });
});
}, [SessionInfo.userId]);
const renderMovementMeta = (movement: ICashFlow) => {
const details = [
movement.paymentMethod ? getPaymentMethodName(movement.paymentMethod) : null,
movement.type ? movementTypeLabels[movement.type] || movement.type : null,
movement.reference ? `Ref. ${movement.reference}` : null,
].filter((detail): detail is string => Boolean(detail));
if (details.length === 0) {
return null;
}
return (
<div className={style.movementMeta}>
{details.map((detail) => (
<span key={detail} className={style.movementMetaItem}>
{detail}
</span>
))}
</div>
);
};
const canInvoiceMovement = (movement: ICashFlow) => {
return movement.type === CLIENT_ACCOUNT_MOVEMENT_TYPES.DEPOSIT && movement.amount > 0;
};
const openInvoiceModal = (movement: ICashFlow) => {
const movementId = getMovementId(movement);
if (!canInvoiceMovement(movement) || !movementId || invoicingMovementId) {
return;
}
const savedDraft = invoiceDraftsByMovementId[movementId];
const defaultDate = todayInputValue();
setInvoiceStep(0);
setInvoiceDraft(savedDraft ? { ...savedDraft, movement } : {
movement,
movementId,
billingDate: defaultDate,
servicePeriodFrom: defaultDate,
servicePeriodTo: defaultDate,
paymentDueDate: defaultDate,
activityCode: fiscalProfile.activityCode || "",
activityDescription: fiscalProfile.activityDescription || "",
saleCondition: getInvoiceSaleCondition(movement.paymentMethod),
includeReceiverData: false,
receiverDocumentType: "",
receiverDocumentNumber: "",
receiverName: "",
receiverAddress: "",
receiverEmail: "",
itemDescription: getInvoiceServiceDescription(movement),
itemQuantity: 1,
itemUnit: "",
itemUnitPrice: movement.amount,
itemDiscountPercent: 0,
itemDiscountAmount: 0,
itemSubtotal: movement.amount,
});
};
const closeInvoiceModal = () => {
if (!invoicingMovementId) {
setInvoiceDraftsByMovementId((current) => {
if (!invoiceDraft) {
return current;
}
const { [invoiceDraft.movementId]: _discarded, ...remaining } = current;
return remaining;
});
setInvoiceDraft(null);
setInvoiceStep(0);
}
};
const validateInvoiceStep = (step: number) => {
if (!invoiceDraft) return false;
if (step === 0) {
if (!invoiceDraft.billingDate || !invoiceDraft.servicePeriodFrom || !invoiceDraft.servicePeriodTo || !invoiceDraft.paymentDueDate) {
alert.showError("Debe completar las fechas de emisión, período y vencimiento.");
return false;
}
if (invoiceDraft.servicePeriodFrom > invoiceDraft.servicePeriodTo) {
alert.showError("El inicio del período facturado no puede ser posterior al fin.");
return false;
}
if (!invoiceDraft.activityCode.trim() || !invoiceDraft.activityDescription.trim()) {
alert.showError("Debe completar el código y la descripción de actividad.");
return false;
}
}
if (step === 1 && !invoiceDraft.saleCondition) {
alert.showError("Debe seleccionar la condición de venta.");
return false;
}
if (step === 1 && invoiceDraft.includeReceiverData) {
if (!invoiceDraft.receiverDocumentType) {
alert.showError("Debe seleccionar el tipo de documento del receptor.");
return false;
}
if (invoiceDraft.receiverDocumentType === "99" && invoiceDraft.receiverDocumentNumber.trim() !== "0") {
alert.showError("El número de documento debe ser 0 para Consumidor Final sin documento.");
return false;
}
}
if (step === 2) {
if (!invoiceDraft.itemDescription.trim()) {
alert.showError("Debe ingresar la descripción del servicio facturado.");
return false;
}
if (Math.abs(invoiceDraft.itemSubtotal - invoiceDraft.movement.amount) > 0.01) {
alert.showError("El total del ítem debe coincidir con el importe del movimiento.");
return false;
}
}
return true;
};
const goToNextInvoiceStep = () => {
if (validateInvoiceStep(invoiceStep)) {
setInvoiceStep((current) => Math.min(current + 1, invoiceWizardSteps.length - 1));
}
};
const handleInvoiceMovement = () => {
if (!invoiceDraft || invoicingMovementId) {
return;
}
if (!invoiceDraft.billingDate) {
alert.showError("Debe seleccionar la fecha del comprobante.");
return;
}
if (!invoiceWizardSteps.every((_, index) => validateInvoiceStep(index))) {
return;
}
setInvoicingMovementId(invoiceDraft.movementId);
eventHandler.setEventType(EVENT_TYPES.LOADING);
createInvoiceFromCashMovement({
cashMovementId: invoiceDraft.movementId,
billingDate: invoiceDraft.billingDate,
servicePeriodFrom: invoiceDraft.servicePeriodFrom,
servicePeriodTo: invoiceDraft.servicePeriodTo,
paymentDueDate: invoiceDraft.paymentDueDate,
activityCode: invoiceDraft.activityCode.trim(),
activityDescription: invoiceDraft.activityDescription.trim(),
receiverIvaCondition: 5,
receiverDocumentType: invoiceDraft.includeReceiverData ? invoiceDraft.receiverDocumentType : undefined,
receiverDocumentNumber: invoiceDraft.includeReceiverData ? invoiceDraft.receiverDocumentNumber.trim() : undefined,
receiverName: invoiceDraft.includeReceiverData ? invoiceDraft.receiverName.trim() : undefined,
receiverAddress: invoiceDraft.includeReceiverData ? invoiceDraft.receiverAddress.trim() : undefined,
receiverEmail: invoiceDraft.includeReceiverData ? invoiceDraft.receiverEmail.trim() : undefined,
saleCondition: invoiceDraft.saleCondition,
itemDescription: invoiceDraft.itemDescription.trim(),
itemQuantity: invoiceDraft.itemQuantity,
itemUnit: invoiceDraft.itemUnit.trim(),
itemUnitPrice: invoiceDraft.itemUnitPrice,
itemDiscountPercent: invoiceDraft.itemDiscountPercent,
itemDiscountAmount: invoiceDraft.itemDiscountAmount,
itemSubtotal: invoiceDraft.itemSubtotal,
sessionUser: SessionInfo.userId,
})
.then((invoice) => {
setInvoicesByMovementId((current) => ({
...current,
[invoiceDraft.movementId]: invoice,
}));
if (invoice.status === "APPROVED") {
setInvoiceDraftsByMovementId((current) => {
const { [invoiceDraft.movementId]: _discarded, ...remaining } = current;
return remaining;
});
alert.showSuccess(getInvoiceStatusMessage(invoice));
return;
}
if (invoice.status === "REJECTED" || invoice.status === "FAILED") {
setInvoiceDraftsByMovementId((current) => ({
...current,
[invoiceDraft.movementId]: invoiceDraft,
}));
}
alert.showError(getInvoiceStatusMessage(invoice));
})
.catch((error: Error) => {
setInvoiceDraftsByMovementId((current) => ({
...current,
[invoiceDraft.movementId]: invoiceDraft,
}));
alert.showError(error.message || "No se pudo emitir la factura.");
})
.finally(() => {
setInvoicingMovementId("");
setInvoiceDraft(null);
setInvoiceStep(0);
eventHandler.setEventType(EVENT_TYPES.CLEAR);
});
};
const handleDownloadInvoicePdf = async (invoice: Invoice) => {
if (invoice.status !== "APPROVED") {
alert.showError("Solo se puede descargar el PDF de facturas aprobadas.");
return;
}
try {
const pdfMake = await import("pdfmake/build/pdfmake");
const pdfFonts = (await import("pdfmake/build/vfs_fonts")) as any;
pdfMake.vfs = pdfFonts.pdfMake ? pdfFonts.pdfMake.vfs : pdfFonts.vfs;
const content = ["ORIGINAL", "DUPLICADO", "TRIPLICADO"].flatMap((copyLabel) => buildInvoiceCopyPage(copyLabel, invoice, fiscalProfile));
const documentDefinition: any = {
pageSize: "A4",
pageMargins: [24, 14, 24, 18],
defaultStyle: { fontSize: 8, color: "#111111" },
styles: {
copyTitle: { fontSize: 15, bold: true, alignment: "center", margin: [0, 4, 0, 4] },
issuerName: { bold: true, alignment: "center", margin: [0, 14, 0, 0] },
voucherLetter: { fontSize: 27, bold: true },
voucherCode: { fontSize: 8, bold: true },
invoiceTitle: { fontSize: 22, bold: true, margin: [0, 6, 0, 0] },
smallTable: { margin: [0, 0, 0, 0] },
arcaLogo: { fontSize: 20, bold: true, color: "#4b5563", margin: [0, 13, 0, 0] },
},
};
(pdfMake as any).createPdf({ ...documentDefinition, content }).download(`factura-c-${invoice.pointOfSale || fiscalProfile.pointOfSale || 0}-${invoice.voucherNumber || 0}.pdf`);
} catch (error) {
console.error("Error generating invoice PDF:", error);
alert.showError("No pudimos generar el PDF de la factura.");
}
};
return (
<>
<Location />
@@ -352,28 +858,252 @@ export default function CashFlowMovementsList() {
<SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
<>
<div
style={{
position: "absolute",
top: "80px",
left: "0px",
right: "0px",
bottom: "30px",
}}
<div className={style.movementsPage}>
<section className={style.movementsList} aria-label="Movimientos de caja">
{movements && movements.data.length === 0 && (
<div className={style.emptyState}>
No se encontraron movimientos con los filtros aplicados.
</div>
)}
{(movements ? movements.data : []).map((movement, index) => {
const visual = getPaymentMethodCardVisual(movement.paymentMethod);
const PaymentMethodIcon = visual.Icon;
const movementId = getMovementId(movement);
const movementKey = movementId || `${movement.createdAt}-${movement.reference}-${index}`;
const invoice = movementId ? invoicesByMovementId[movementId] : undefined;
const isInvoiced = invoice?.status === "APPROVED";
const isPendingInvoice = invoice?.status === "PENDING_ARCA" || invoice?.status === "PENDING_VERIFICATION";
return (
<article
key={movementKey}
className={`${style.movementCard} ${visual.className}`}
>
<DataGrid
columns={dataGridColumns}
data={movements ? movements.data : []}
pagination={true}
page={movements?.page}
pages={movements?.pages}
pageSize={pageSize}
handleRefresh={loadMovements}
handleRowClick={() => { }}
<PaymentMethodIcon
className={style.movementCardIcon}
aria-hidden="true"
/>
<div className={style.movementContent}>
<div className={style.movementHeader}>
<div className={style.movementSummary}>
<h3 className={style.movementDescription}>
{movement.description}
</h3>
<time className={style.movementDate}>
{dayjs(movement.createdAt).format("DD MMMM YYYY - HH:mm")}
</time>
</div>
<div
className={`${style.movementAmount} ${
movement.amount > 0
? style.movementAmountPositive
: style.movementAmountNegative
}`}
>
{formatPrice(movement.amount)}
</div>
</div>
{renderMovementMeta(movement)}
<div className={style.movementActionsSlot}>
{isInvoiced ? (
<>
<span className={style.movementInvoiceBadge}>
Factura C {invoice?.pointOfSale}-{invoice?.voucherNumber}
</span>
{invoice && (
<button type="button" className={style.movementInvoicePdfButton} onClick={() => handleDownloadInvoicePdf(invoice)}>
PDF
</button>
)}
</>
) : isPendingInvoice ? (
<span className={style.movementInvoiceBadge} title={getInvoiceStatusMessage(invoice)}>
Factura pendiente
</span>
) : !canInvoiceMovement(movement) ? null : (
<button
type="button"
className={style.movementInvoiceButton}
disabled={invoicingMovementId === movementId}
onClick={() => openInvoiceModal(movement)}
>
{invoicingMovementId === movementId ? "Facturando..." : "Facturar"}
</button>
)}
</div>
</div>
</article>
);
})}
</section>
{movements && movements.pages > 1 && (
<div className={style.paginationWrapper}>
<PaginationControls
current={movements.page}
size={pageSize}
max={movements.pages}
onChange={loadMovements}
/>
</div>
)}
</div>
<div style={{ marginTop: "15px" }}></div>
{invoiceDraft && (
<div className={style.invoiceModalBackdrop} role="presentation">
<section
className={style.invoiceModal}
role="dialog"
aria-modal="true"
aria-labelledby="invoice-modal-title"
>
<div className={style.invoiceModalHeader}>
<h2 id="invoice-modal-title">Emitir Factura C</h2>
<button
type="button"
className={style.invoiceModalClose}
onClick={closeInvoiceModal}
disabled={Boolean(invoicingMovementId)}
aria-label="Cerrar"
>
×
</button>
</div>
<div className={style.invoiceModalBody}>
<div className={style.invoiceSteps}>
{invoiceWizardSteps.map((step, index) => (
<span key={step} className={index === invoiceStep ? style.invoiceStepActive : ""}>
{index + 1}. {step}
</span>
))}
</div>
<div className={style.invoiceAmountBox}>
<span>Total del comprobante</span>
<strong>{formatPrice(invoiceDraft.itemSubtotal)}</strong>
</div>
{invoiceStep === 0 && (
<div className={style.invoiceGrid}>
<label className={style.invoiceField}>
<span>Fecha de comprobante</span>
<input type="date" value={invoiceDraft.billingDate} max={todayInputValue()} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, billingDate: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} />
</label>
<label className={style.invoiceField}>
<span>Concepto</span>
<input type="text" value="Servicios" disabled />
</label>
<label className={style.invoiceField}>
<span>Período facturado desde</span>
<input type="date" value={invoiceDraft.servicePeriodFrom} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, servicePeriodFrom: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} />
</label>
<label className={style.invoiceField}>
<span>Período facturado hasta</span>
<input type="date" value={invoiceDraft.servicePeriodTo} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, servicePeriodTo: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} />
</label>
<label className={style.invoiceField}>
<span>Vencimiento de pago</span>
<input type="date" value={invoiceDraft.paymentDueDate} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, paymentDueDate: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} />
</label>
<label className={style.invoiceField}>
<span>Código de actividad</span>
<input type="text" value={invoiceDraft.activityCode} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, activityCode: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} />
</label>
<label className={style.invoiceFieldFull}>
<span>Descripción de actividad</span>
<input type="text" value={invoiceDraft.activityDescription} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, activityDescription: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} placeholder="Integración futura con perfil fiscal" />
</label>
</div>
)}
{invoiceStep === 1 && (
<div className={style.invoiceGrid}>
<label className={style.invoiceField}>
<span>Condición frente al IVA</span>
<input type="text" value="Consumidor Final" disabled />
</label>
<label className={style.invoiceField}>
<span>Condición de venta</span>
<select value={invoiceDraft.saleCondition} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, saleCondition: event.target.value } : current)} disabled={Boolean(invoicingMovementId)}>
{saleConditionOptions.map((option) => <option key={option.id} value={option.id}>{option.name}</option>)}
</select>
</label>
<label className={style.invoiceToggle}>
<input type="checkbox" checked={invoiceDraft.includeReceiverData} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, includeReceiverData: event.target.checked } : current)} disabled={Boolean(invoicingMovementId)} />
<span>Agregar datos del consumidor final</span>
</label>
{invoiceDraft.includeReceiverData && (
<>
<label className={style.invoiceField}>
<span>Tipo documento</span>
<select value={invoiceDraft.receiverDocumentType} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, receiverDocumentType: event.target.value, receiverDocumentNumber: event.target.value === "99" ? "0" : current.receiverDocumentNumber } : current)} disabled={Boolean(invoicingMovementId)}>
<option value="">Seleccionar</option>
{receiverDocumentTypeOptions.map((option) => <option key={option.id} value={option.id}>{option.name}</option>)}
</select>
</label>
<label className={style.invoiceField}><span>Nro. documento</span><input type="text" value={invoiceDraft.receiverDocumentNumber} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, receiverDocumentNumber: event.target.value } : current)} disabled={Boolean(invoicingMovementId) || invoiceDraft.receiverDocumentType === "99"} /></label>
<label className={style.invoiceField}><span>Nombre / razón social</span><input type="text" value={invoiceDraft.receiverName} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, receiverName: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} /></label>
<label className={style.invoiceField}><span>Domicilio comercial</span><input type="text" value={invoiceDraft.receiverAddress} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, receiverAddress: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} /></label>
<label className={style.invoiceFieldFull}><span>Email</span><input type="email" value={invoiceDraft.receiverEmail} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, receiverEmail: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} /></label>
</>
)}
</div>
)}
{invoiceStep === 2 && (
<div className={style.invoiceGrid}>
<label className={style.invoiceFieldFull}>
<span>Descripción del servicio</span>
<textarea value={invoiceDraft.itemDescription} rows={4} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, itemDescription: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} />
</label>
<label className={style.invoiceField}><span>Cantidad</span><input type="number" value={invoiceDraft.itemQuantity} disabled /></label>
<label className={style.invoiceField}><span>Unidad</span><input type="text" value={invoiceDraft.itemUnit} onChange={(event) => setInvoiceDraft((current) => current ? { ...current, itemUnit: event.target.value } : current)} disabled={Boolean(invoicingMovementId)} /></label>
<label className={style.invoiceField}><span>Precio unitario</span><input type="number" value={invoiceDraft.itemUnitPrice} disabled /></label>
<label className={style.invoiceField}><span>Subtotal</span><input type="number" value={invoiceDraft.itemSubtotal} disabled /></label>
</div>
)}
{invoiceStep === 3 && (
<div className={style.invoiceSummaryBox}>
<p><strong>Comprobante:</strong> Factura C de servicios, fecha {invoiceDraft.billingDate}</p>
<p><strong>Período:</strong> {invoiceDraft.servicePeriodFrom} al {invoiceDraft.servicePeriodTo}</p>
<p><strong>Vencimiento:</strong> {invoiceDraft.paymentDueDate}</p>
<p><strong>Actividad:</strong> {invoiceDraft.activityCode} - {invoiceDraft.activityDescription}</p>
<p><strong>Receptor:</strong> Consumidor Final{invoiceDraft.includeReceiverData && invoiceDraft.receiverName ? ` - ${invoiceDraft.receiverName}` : ""}</p>
<p><strong>Condición de venta:</strong> {saleConditionOptions.find((option) => option.id === invoiceDraft.saleCondition)?.name}</p>
<p><strong>Ítem:</strong> {invoiceDraft.itemDescription}</p>
<p><strong>Total:</strong> {formatPrice(invoiceDraft.itemSubtotal)}</p>
</div>
)}
</div>
<div className={style.invoiceModalActions}>
<button
type="button"
className={style.invoiceCancelButton}
onClick={closeInvoiceModal}
disabled={Boolean(invoicingMovementId)}
>
Cancelar
</button>
{invoiceStep > 0 && <button type="button" className={style.invoiceCancelButton} onClick={() => setInvoiceStep((current) => current - 1)} disabled={Boolean(invoicingMovementId)}>Atrás</button>}
{invoiceStep < invoiceWizardSteps.length - 1 ? (
<button type="button" className={style.invoiceConfirmButton} onClick={goToNextInvoiceStep} disabled={Boolean(invoicingMovementId)}>Siguiente</button>
) : (
<button type="button" className={style.invoiceConfirmButton} onClick={handleInvoiceMovement} disabled={Boolean(invoicingMovementId)}>
{invoicingMovementId ? "Facturando..." : "Emitir factura"}
</button>
)}
</div>
</section>
</div>
)}
</>
</SecureByPlan>
</>
@@ -13,7 +13,7 @@ import ButtonMaterial from "@mui/material/Button";
import { useNavigation } from "@core/app/hooks/goto";
import { PaginateCashFlowParams, PaginateCashFlowResults } from "@core/Models/CashFlow.model";
import { useSessionStore } from "@core/Store/Sesion.Store";
import { cashFlowPaginate } from "./Cash.Service";
import { ArcaWsfeLastVoucherResult, cashFlowPaginate, getArcaWsfeLastVoucher } from "./Cash.Service";
import { useAlert } from "@core/Store/Alert.Store";
import { IconButton } from "@mui/material";
import RetirarIcon from "@mui/icons-material/CallMadeOutlined";
@@ -42,6 +42,10 @@ export default function OrganizationCashFlowDetail() {
const [dateFrom, setDateFrom] = useState<Dayjs>(dayjs().startOf("day"));
const [dateTo, setDateTo] = useState<Dayjs>(dayjs().endOf("day"));
const [view, setView] = useState<PaginateCashFlowResults | null>(null);
const [arcaLastVoucher, setArcaLastVoucher] = useState<ArcaWsfeLastVoucherResult | null>(null);
const [arcaLastVoucherLoading, setArcaLastVoucherLoading] = useState(false);
const [arcaLastVoucherError, setArcaLastVoucherError] = useState(false);
const [arcaLastVoucherErrorMessage, setArcaLastVoucherErrorMessage] = useState("");
useEffect(() => {
eventHandler.setEventType(EVENT_TYPES.SLEEP);
@@ -73,6 +77,10 @@ export default function OrganizationCashFlowDetail() {
cargarDatos();
}, [SessionInfo.userId, id, dateFrom, dateTo]);
useEffect(() => {
loadArcaLastVoucher();
}, [SessionInfo.userId, id]);
const cargarDatos = async () => {
eventHandler.setEventType(EVENT_TYPES.LOADING);
@@ -110,6 +118,34 @@ export default function OrganizationCashFlowDetail() {
});
};
const loadArcaLastVoucher = async () => {
if (!SessionInfo.userId || !id) {
return;
}
setArcaLastVoucherLoading(true);
setArcaLastVoucherError(false);
setArcaLastVoucherErrorMessage("");
getArcaWsfeLastVoucher({
companyId: id,
sessionUser: SessionInfo.userId,
})
.then((data) => {
setArcaLastVoucher(data);
})
.catch((error) => {
setArcaLastVoucher(null);
setArcaLastVoucherError(true);
setArcaLastVoucherErrorMessage(
error?.desc || error?.message || "No pudimos consultar ARCA"
);
})
.finally(() => {
setArcaLastVoucherLoading(false);
});
};
const add = (type: CLIENT_ACCOUNT_MOVEMENT_TYPES) => {
goTo("/admin/org/profile/" + id + "/cash/add/" + type);
};
@@ -175,6 +211,40 @@ export default function OrganizationCashFlowDetail() {
>
{formatPrice(view.balance)}
</div>
<div
style={{
marginBottom: "10px",
padding: "8px 12px",
borderRadius: "8px",
backgroundColor: "var(--white)",
color: arcaLastVoucherError
? "var(--gray-dark)"
: "var(--wine-dark)",
fontSize: "13px",
textAlign: "center",
}}
>
{arcaLastVoucherLoading ? (
"Consultando último comprobante ARCA..."
) : arcaLastVoucher ? (
<>
Última Factura C autorizada ARCA: #{" "}
<strong>{arcaLastVoucher.lastVoucherNumber}</strong>
{" · "}PV {arcaLastVoucher.pointOfSale}
</>
) : arcaLastVoucherError ? (
<>
No pudimos consultar ARCA
{arcaLastVoucherErrorMessage && (
<div style={{ marginTop: "4px" }}>
{arcaLastVoucherErrorMessage}
</div>
)}
</>
) : (
"ARCA: esperando consulta del último comprobante"
)}
</div>
<div
style={{
display: "flex",
@@ -0,0 +1,47 @@
import ApiRequest from "@services/Api.Service";
import { TextObjectFilterResult } from "@models/TextObjectFilter.model";
export type OrganizationFiscalProfileTaxCondition = "MONOTRIBUTO" | "EXENTO";
export type OrganizationFiscalProfile = {
id?: string;
companyId: string;
cuit: string;
legalName: string;
taxCondition: OrganizationFiscalProfileTaxCondition;
pointOfSale: number;
activityCode?: string;
activityDescription?: string;
};
export type FindOrganizationFiscalProfilesParams = {
companyId: string;
sessionUser: string;
};
export type UpsertOrganizationFiscalProfileParams = {
companyId: string;
cuit: string;
legalName: string;
taxCondition: OrganizationFiscalProfileTaxCondition;
pointOfSale: number;
activityCode?: string;
activityDescription?: string;
sessionUser: string;
};
export const findOrganizationFiscalProfiles = async (
data: FindOrganizationFiscalProfilesParams
): Promise<OrganizationFiscalProfile[]> => {
return ApiRequest.post<OrganizationFiscalProfile[]>("organization-fiscal-profiles/find", data);
};
export const upsertOrganizationFiscalProfile = async (
data: UpsertOrganizationFiscalProfileParams
): Promise<OrganizationFiscalProfile> => {
return ApiRequest.post<OrganizationFiscalProfile>("organization-fiscal-profiles/upsert", data);
};
export const findArcaActivities = async (): Promise<TextObjectFilterResult[]> => {
return ApiRequest.post<TextObjectFilterResult[]>("arca-activities/filter-all", {});
};
@@ -0,0 +1,7 @@
"use client";
import Saveable from "@components/Saveable/Saveable";
export default function OrgFiscalLayout({ children }: { children: React.ReactNode }) {
return <Saveable>{children}</Saveable>;
}
@@ -0,0 +1,136 @@
.pageContainer {
display: flex;
flex-direction: column;
gap: 18px;
margin: 12px auto 0;
max-width: 860px;
padding: 0 14px 40px;
width: 100%;
}
.heroCard {
align-items: flex-start;
background: linear-gradient(135deg, #4b6cb7 0%, #182848 100%);
border-radius: 22px;
box-shadow: 0 14px 34px rgba(24, 40, 72, 0.18);
color: var(--white);
display: flex;
gap: 14px;
padding: 20px;
}
.heroCard h2 {
font-size: 22px;
line-height: 1.2;
margin: 0 0 8px;
}
.heroCard p {
font-size: 14px;
line-height: 1.45;
margin: 0;
opacity: 0.86;
}
.heroIcon {
align-items: center;
background: rgba(255, 255, 255, 0.14);
border-radius: 16px;
display: flex;
flex: 0 0 48px;
height: 48px;
justify-content: center;
}
.heroIcon svg {
font-size: 30px;
}
.formSection {
background: var(--white);
border: 1px solid rgba(15, 23, 42, 0.08);
border-radius: 20px;
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.06);
padding: 18px;
}
.formSection h3 {
color: var(--black-light);
font-size: 16px;
margin: 0 0 16px;
}
.sectionHeader {
margin-bottom: 14px;
}
.sectionHeader h3 {
margin-bottom: 4px;
}
.sectionHeader p {
color: var(--gray-dark);
font-size: 13px;
margin: 0;
}
.optionGroup {
display: grid;
gap: 10px;
grid-template-columns: 1fr;
}
.optionCard {
background: #f8fafc;
border: 1px solid rgba(100, 116, 139, 0.22);
border-radius: 18px;
color: var(--black-light);
cursor: pointer;
padding: 14px 16px;
text-align: left;
transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease, background 0.2s ease;
}
.optionCard:hover {
border-color: rgba(124, 58, 237, 0.38);
box-shadow: 0 8px 20px rgba(124, 58, 237, 0.12);
transform: translateY(-1px);
}
.optionCardSelected {
background: linear-gradient(135deg, rgba(124, 58, 237, 0.14) 0%, rgba(75, 108, 183, 0.1) 100%);
border-color: #7c3aed;
box-shadow: 0 10px 24px rgba(124, 58, 237, 0.16);
}
.optionTitle {
display: block;
font-size: 14px;
font-weight: 800;
margin-bottom: 4px;
}
.optionDescription {
color: var(--gray-dark);
display: block;
font-size: 12px;
line-height: 1.35;
}
.helpText {
color: var(--gray-dark);
font-size: 13px;
line-height: 1.5;
margin: 10px 0 0;
}
@media (min-width: 720px) {
.pageContainer {
padding-left: 24px;
padding-right: 24px;
}
.optionGroup {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@@ -0,0 +1,310 @@
"use client";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import Textbox from "@components/Textbox/Textbox";
import TextObjectFilter from "@components/TextObjectFilter/TextObjectFilter";
import TextObjectFilterItem from "@components/TextObjectFilterItem/TextObjectFilterItem";
import { TextObjectFilterResult } from "@models/TextObjectFilter.model";
import { TextObjectModalContent } from "@store/TextObjectModal.Store";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import { useSessionStore } from "@store/Sesion.Store";
import { useAlert } from "@store/Alert.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import ReceiptLongOutlinedIcon from "@mui/icons-material/ReceiptLongOutlined";
import { Grid2 } from "@mui/material";
import { ApiError } from "@models/Server.Error.model";
import style from "./page.module.css";
import {
findArcaActivities,
findOrganizationFiscalProfiles,
OrganizationFiscalProfileTaxCondition,
upsertOrganizationFiscalProfile,
} from "./Fiscal.Service";
type UrlData = {
id: string;
};
export default function OrganizationFiscalProfileEdit() {
const data = useParams<UrlData>();
const id = data.id;
const location = useLocationStore();
const eventHandler = useEventHandlerStore();
const SessionInfo = useSessionStore();
const alert = useAlert();
const [cuit, setCuit] = useState("");
const [legalName, setLegalName] = useState("");
const [taxCondition, setTaxCondition] = useState<OrganizationFiscalProfileTaxCondition>("MONOTRIBUTO");
const [pointOfSale, setPointOfSale] = useState("1");
const [activityCode, setActivityCode] = useState("");
const [activityDescription, setActivityDescription] = useState("");
const [arcaActivities, setArcaActivities] = useState<TextObjectFilterResult[]>([]);
const [fiscalDataLoaded, setFiscalDataLoaded] = useState(false);
const [activityFilterContent] = useState<TextObjectModalContent>({
header: (
<div>
<div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
Seleccionar actividad ARCA/CLAE
</div>
<p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
Buscá por código o descripción de la actividad declarada.
</p>
</div>
),
bottom: <div>&nbsp;</div>,
renderResult: (result: TextObjectFilterResult, index: number) => (
<TextObjectFilterItem key={index} data={result} />
),
});
const markNeedsSave = () => eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
const fiscalConditionOptions: Array<{
id: OrganizationFiscalProfileTaxCondition;
title: string;
description: string;
}> = [
{
id: "MONOTRIBUTO",
title: "Monotributo",
description: "Para organizaciones adheridas al régimen simplificado.",
},
];
useEffect(() => {
location.clear();
location.add({
url: "/admin/org",
title: "Organizaciones",
icon: null,
});
location.add({
url: "/admin/org/profile/" + id,
title: "Perfil",
icon: <StorefrontOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
});
location.add({
url: "/admin/org/profile/" + id + "/fiscal",
title: "Datos fiscales",
icon: <ReceiptLongOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
});
}, []);
useEffect(() => {
if (!SessionInfo.userId) return;
eventHandler.setEventType(EVENT_TYPES.LOADING);
Promise.all([
findOrganizationFiscalProfiles({ companyId: id, sessionUser: SessionInfo.userId }),
findArcaActivities(),
])
.then(([profiles, activities]) => {
setArcaActivities(activities);
const profile = profiles[0];
if (!profile) return;
setCuit(profile.cuit || "");
setLegalName(profile.legalName || "");
setTaxCondition(profile.taxCondition || "MONOTRIBUTO");
setPointOfSale(profile.pointOfSale ? String(profile.pointOfSale) : "1");
const profileActivity = activities.find((activity) => activity.id === profile.activityCode);
setActivityCode(profile.activityCode || "");
setActivityDescription(profile.activityDescription || profileActivity?.name || "");
})
.catch((error: ApiError) => {
alert.showError(error.format());
})
.finally(() => {
setFiscalDataLoaded(true);
eventHandler.setEventType(EVENT_TYPES.SLEEP);
});
}, [SessionInfo.userId]);
useEffect(() => {
if (eventHandler.eventType !== EVENT_TYPES.SAVE) return;
if (!/^\d{11}$/.test(cuit)) {
alert.showError("El CUIT debe contener 11 dígitos.");
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
return;
}
if (!legalName.trim()) {
alert.showError("La razón social es requerida.");
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
return;
}
if (!Number(pointOfSale) || Number(pointOfSale) <= 0) {
alert.showError("El punto de venta debe ser mayor a 0.");
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
return;
}
if (activityCode.trim() && !arcaActivities.some((activity) => activity.id === activityCode.trim())) {
alert.showError("Seleccioná una actividad ARCA/CLAE válida.");
eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
return;
}
eventHandler.setEventType(EVENT_TYPES.LOADING);
const selectedActivity = arcaActivities.find((activity) => activity.id === activityCode.trim());
upsertOrganizationFiscalProfile({
companyId: id,
cuit: cuit.trim(),
legalName: legalName.trim(),
taxCondition,
pointOfSale: Number(pointOfSale),
activityCode: activityCode.trim() || undefined,
activityDescription: selectedActivity?.name || activityDescription.trim() || undefined,
sessionUser: SessionInfo.userId,
})
.then((profile) => {
const savedActivity = arcaActivities.find((activity) => activity.id === profile.activityCode);
setActivityCode(profile.activityCode || "");
setActivityDescription(profile.activityDescription || savedActivity?.name || "");
alert.showSuccess("Datos fiscales actualizados.");
})
.catch((error: ApiError) => {
alert.showError(error.format());
})
.finally(() => {
eventHandler.setEventType(EVENT_TYPES.SLEEP);
});
}, [eventHandler.eventType]);
return (
<>
<Location />
<div className={style.pageContainer}>
<section className={style.heroCard}>
<div className={style.heroIcon}>
<ReceiptLongOutlinedIcon />
</div>
<div>
<h2>Configuración fiscal</h2>
<p>
Estos datos se usan para emitir Factura C desde los movimientos de caja y para precargar el asistente ARCA.
</p>
</div>
</section>
<section className={style.formSection}>
<h3>Datos del emisor</h3>
<Grid2 container spacing={2}>
<Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox
name="cuit"
placeholder="CUIT"
type="text"
value={cuit}
width="100%"
onChange={(event) => {
setCuit(event.target.value.replace(/\D/g, ""));
markNeedsSave();
}}
/>
</Grid2>
<Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox
name="legalName"
placeholder="Razón social"
type="text"
value={legalName}
width="100%"
onChange={(event) => {
setLegalName(event.target.value);
markNeedsSave();
}}
/>
</Grid2>
</Grid2>
</section>
<section className={style.formSection}>
<div className={style.sectionHeader}>
<h3>Condición fiscal</h3>
<p>Seleccioná la condición declarada para esta organización.</p>
</div>
<div className={style.optionGroup} role="radiogroup" aria-label="Condición fiscal">
{fiscalConditionOptions.map((option) => {
const selected = taxCondition === option.id;
return (
<button
key={option.id}
type="button"
className={`${style.optionCard} ${selected ? style.optionCardSelected : ""}`}
onClick={() => {
setTaxCondition(option.id);
markNeedsSave();
}}
aria-pressed={selected}
>
<span className={style.optionTitle}>{option.title}</span>
<span className={style.optionDescription}>{option.description}</span>
</button>
);
})}
</div>
</section>
<section className={style.formSection}>
<h3>Facturación ARCA</h3>
<Grid2 container spacing={2}>
<Grid2 size={{ xs: 12, sm: 6 }}>
<Textbox
name="pointOfSale"
placeholder="Punto de venta"
type="text"
value={pointOfSale}
width="100%"
onChange={(event) => {
setPointOfSale(event.target.value.replace(/\D/g, ""));
markNeedsSave();
}}
/>
</Grid2>
</Grid2>
{fiscalDataLoaded && (
<TextObjectFilter
key={`${activityCode}-${arcaActivities.length}`}
placeholder="Actividad ARCA/CLAE"
content={activityFilterContent}
data={arcaActivities}
selectedId={activityCode}
onChange={(selectedActivityCode) => {
const selectedActivity = arcaActivities.find(
(activity) => activity.id === selectedActivityCode
);
setActivityCode(selectedActivity?.id || "");
setActivityDescription(selectedActivity?.name || "");
markNeedsSave();
}}
/>
)}
<p className={style.helpText}>
{activityCode && activityDescription
? `${activityCode} - ${activityDescription}`
: "Seleccioná la actividad principal declarada en ARCA."}
</p>
</section>
</div>
</>
);
}
@@ -17,6 +17,7 @@ import PendingActionsOutlinedIcon from "@mui/icons-material/PendingActionsOutlin
import TodayOutlinedIcon from "@mui/icons-material/TodayOutlined";
import PaymentsIcon from "@mui/icons-material/CurrencyExchangeOutlined";
import CashIcon from "@mui/icons-material/AccountBalanceOutlined";
import FiscalIcon from "@mui/icons-material/ReceiptLongOutlined";
import DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
import TemplatesIcon from "@mui/icons-material/SpeakerNotesOutlined";
import AssistanceIcon from "@mui/icons-material/HeadsetMicOutlined";
@@ -137,6 +138,11 @@ export default function OrganizationProfile() {
text: "Caja",
onClick: () => goTo("/admin/org/profile/" + id + "/cash"),
},
{
icon: <FiscalIcon />,
text: "Datos fiscales",
onClick: () => goTo("/admin/org/profile/" + id + "/fiscal"),
},
{
icon: <DiscountsIcon />,
text: "Descuentos",
@@ -19,6 +19,7 @@ import ReviewsIcon from '@mui/icons-material/Reviews';
import NotificationsIcon from '@mui/icons-material/Notifications';
import WhatsAppIcon from '@mui/icons-material/WhatsApp';
import QrCode2Icon from '@mui/icons-material/QrCode2';
import ReceiptLongIcon from '@mui/icons-material/ReceiptLong';
import API from "@services/Api.Service";
import { ReservationPeriodsSummary } from "@models/SchedulesEnabled.type";
@@ -88,6 +89,24 @@ const AVAILABLE_FLOWS: FlowDefinition[] = [
keywords: ["link", "enlace", "url", "slug", "qr", "codigo qr", "publico", "reservas"],
icon: QrCode2Icon
},
{
id: "arca-onboarding",
flowId: "arca-onboarding",
title: "Conectar ARCA",
description: "Configurá los datos fiscales y el certificado para emitir Factura C.",
category: "Integraciones",
keywords: ["arca", "afip", "factura", "factura c", "fiscal", "certificado", "csr", "monotributo"],
icon: ReceiptLongIcon
},
{
id: "arca-test-connection",
flowId: "arca-test-connection",
title: "Probar conexión ARCA",
description: "Validá el certificado y la conexión con el servicio WSFE de ARCA.",
category: "Integraciones",
keywords: ["arca", "afip", "wsaa", "wsfe", "conexion", "certificado", "factura"],
icon: ReceiptLongIcon
},
{
id: "notifications",
flowId: "notifications",
@@ -27,6 +27,8 @@ import NotificationsFlow from "./flows/NotificationsFlow";
import NewCollaboratorFlow from "./flows/NewCollaboratorFlow";
import SetupCollaboratorFlow from "./flows/SetupCollaboratorFlow";
import ReservationPeriodFlow from "./flows/ReservationPeriodFlow";
import ArcaOnboardingFlow from "./flows/ArcaOnboardingFlow";
import ArcaTestConnectionFlow, { ArcaWsaaTestResult, ArcaWsfeDiagnosticsResult } from "./flows/ArcaTestConnectionFlow";
import SuccessScreen from "./components/SuccessScreen";
import OrganizationPicker from "./components/OrganizationPicker";
import { reservationPeriodOptions } from "./constants/reservationPeriods";
@@ -178,6 +180,22 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
const [wapQr, setWapQr] = useState<string | null>(null);
const [wapError, setWapError] = useState<string | null>(null);
// State for ARCA onboarding flow
const [arcaCuit, setArcaCuit] = useState("");
const [arcaLegalName, setArcaLegalName] = useState("");
const [arcaTaxCondition, setArcaTaxCondition] = useState<"MONOTRIBUTO" | "EXENTO">("MONOTRIBUTO");
const [arcaPointOfSale, setArcaPointOfSale] = useState("1");
const [arcaActivityCode, setArcaActivityCode] = useState("");
const [arcaActivityDescription, setArcaActivityDescription] = useState("");
const [arcaCsrPem, setArcaCsrPem] = useState("");
const [arcaCertificatePem, setArcaCertificatePem] = useState("");
const [arcaStatusLabel, setArcaStatusLabel] = useState("");
const [arcaLoading, setArcaLoading] = useState(false);
const [arcaDiagnosticsLoading, setArcaDiagnosticsLoading] = useState(false);
const [arcaError, setArcaError] = useState<string | null>(null);
const [arcaTestResult, setArcaTestResult] = useState<ArcaWsaaTestResult | null>(null);
const [arcaDiagnosticsResult, setArcaDiagnosticsResult] = useState<ArcaWsfeDiagnosticsResult | null>(null);
// State for Setup Collaborator Flow
const [collaboratorToSetup, setCollaboratorToSetup] = useState<any | null>(null);
const [setupMissingServices, setSetupMissingServices] = useState(false);
@@ -392,11 +410,45 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
setWapView(null);
setWapQr(null);
setWapError(null);
} else if (flowId === "arca-onboarding") {
setCurrentStepIndex(0);
setArcaError(null);
setArcaLoading(false);
setArcaTestResult(null);
setArcaCertificatePem("");
API.post<any[]>("organization-fiscal-profiles/find", {
companyId: org.id || org._id,
sessionUser: SessionInfo.userId
}).then(res => {
const profile = res?.[0];
if (!profile) return;
setArcaCuit(profile.cuit || "");
setArcaLegalName(profile.legalName || "");
setArcaTaxCondition(profile.taxCondition || "MONOTRIBUTO");
setArcaPointOfSale(profile.pointOfSale ? String(profile.pointOfSale) : "1");
setArcaActivityCode(profile.activityCode || "");
setArcaActivityDescription(profile.activityDescription || "");
}).catch(console.error);
API.post<any[]>("arca-credentials/find", {
companyId: org.id || org._id,
sessionUser: SessionInfo.userId
}).then(res => {
const credential = res?.[0];
if (!credential) return;
setArcaCsrPem(credential.csrPem || "");
setArcaStatusLabel(getArcaStatusLabel(credential.status));
}).catch(console.error);
} else if (flowId === "arca-test-connection") {
setCurrentStepIndex(0);
setArcaError(null);
setArcaLoading(false);
setArcaTestResult(null);
setArcaDiagnosticsResult(null);
}
};
React.useEffect(() => {
if (flowId === "new-collaborator" || flowId === "setup-collaborator" || flowId === "public-visibility" || flowId === "public-link" || flowId === "notifications" || flowId === "whatsapp-bot" || flowId.startsWith("onboarding") || flowId === "update-schedule" || flowId === "override-schedule" || flowId === "disable-schedule" || flowId === "open-reservation-periods") {
if (flowId === "new-collaborator" || flowId === "setup-collaborator" || flowId === "public-visibility" || flowId === "public-link" || flowId === "notifications" || flowId === "whatsapp-bot" || flowId === "arca-onboarding" || flowId === "arca-test-connection" || flowId.startsWith("onboarding") || flowId === "update-schedule" || flowId === "override-schedule" || flowId === "disable-schedule" || flowId === "open-reservation-periods") {
setIsResuming(true);
API.post<any[]>("companies/get-by-user", { sessionUser: SessionInfo.userId })
.then(response => {
@@ -417,7 +469,7 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
.finally(() => setIsResuming(false));
}
if (flowId === "onboarding-service" || flowId === "onboarding-schedule" || flowId === "setup-collaborator" || flowId === "public-visibility" || flowId === "public-link" || flowId === "notifications" || flowId === "whatsapp-bot" || flowId === "open-reservation-periods" || (flowId === "onboarding-org" && action === "new-org")) {
if (flowId === "onboarding-service" || flowId === "onboarding-schedule" || flowId === "setup-collaborator" || flowId === "public-visibility" || flowId === "public-link" || flowId === "notifications" || flowId === "whatsapp-bot" || flowId === "arca-onboarding" || flowId === "arca-test-connection" || flowId === "open-reservation-periods" || (flowId === "onboarding-org" && action === "new-org")) {
setCurrentStepIndex(0);
}
}, [flowId, SessionInfo.metrics.organizationsCount, SessionInfo.userId, router]);
@@ -758,6 +810,191 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
/>
);
const getArcaStatusLabel = (status?: string) => {
if (status === "READY") return "Certificado validado. La conexión con ARCA quedó lista.";
if (status === "CERTIFICATE_UPLOADED") return "Certificado cargado. Estamos listos para validar la conexión.";
if (status === "CSR_GENERATED") return "CSR generado. Descargalo y subilo en ARCA para obtener el certificado.";
if (status === "INVALID") return "El certificado cargado no pudo validarse. Revisá que corresponda al CSR generado.";
return "";
};
const handleSaveArcaFiscalProfile = async () => {
if (!createdCompanyId || arcaLoading) return;
setArcaLoading(true);
setArcaError(null);
try {
await API.post<any>("organization-fiscal-profiles/upsert", {
companyId: createdCompanyId,
cuit: arcaCuit,
legalName: arcaLegalName,
taxCondition: arcaTaxCondition,
pointOfSale: Number(arcaPointOfSale),
activityCode: arcaActivityCode.trim() || undefined,
activityDescription: arcaActivityDescription.trim() || undefined,
sessionUser: SessionInfo.userId
});
handleNext();
} catch (error: any) {
console.error("Error guardando datos fiscales ARCA:", error);
setArcaError(error?.message || "No pudimos guardar los datos fiscales. Revisá la información y volvé a intentar.");
} finally {
setArcaLoading(false);
}
};
const handleGenerateArcaCsr = async () => {
if (!createdCompanyId || arcaLoading) return;
setArcaLoading(true);
setArcaError(null);
try {
const credential = await API.post<any>("arca-credentials/generate-csr", {
companyId: createdCompanyId,
sessionUser: SessionInfo.userId
});
const generatedCsr = credential?.csrPem || "";
setArcaCsrPem(generatedCsr);
setArcaStatusLabel(getArcaStatusLabel(credential?.status));
if (generatedCsr) {
downloadArcaCsr(generatedCsr);
}
} catch (error: any) {
console.error("Error generando CSR ARCA:", error);
setArcaError(error?.message || "No pudimos generar el CSR. Intentá nuevamente.");
} finally {
setArcaLoading(false);
}
};
const downloadArcaCsr = (csrPem: string) => {
const blob = new Blob([csrPem], { type: "application/pkcs10" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `turnosxpress-arca-${arcaCuit || createdCompanyId}.csr`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
const handleDownloadArcaCsr = () => {
if (!arcaCsrPem) return;
downloadArcaCsr(arcaCsrPem);
};
const handleArcaCertificateFile = (file: File | null) => {
if (!file) return;
const reader = new FileReader();
reader.onload = () => setArcaCertificatePem(String(reader.result || ""));
reader.onerror = () => setArcaError("No pudimos leer el archivo. Probá pegando el contenido del certificado.");
reader.readAsText(file);
};
const handleUploadArcaCertificate = async () => {
if (!createdCompanyId || arcaLoading || !arcaCertificatePem.trim()) return;
setArcaLoading(true);
setArcaError(null);
try {
const credential = await API.post<any>("arca-credentials/upload-certificate", {
companyId: createdCompanyId,
certificatePem: arcaCertificatePem,
sessionUser: SessionInfo.userId
});
setArcaStatusLabel(getArcaStatusLabel(credential?.status));
setCurrentStepIndex(5);
} catch (error: any) {
console.error("Error cargando certificado ARCA:", error);
setArcaError(error?.message || "No pudimos guardar el certificado. Revisá que sea el archivo emitido por ARCA.");
} finally {
setArcaLoading(false);
}
};
const handleTestArcaConnection = async () => {
if (!createdCompanyId || arcaLoading) return;
setArcaLoading(true);
setArcaError(null);
setArcaTestResult(null);
setArcaDiagnosticsResult(null);
try {
const result = await API.post<ArcaWsaaTestResult>("arca-credentials/test-wsaa-login", {
companyId: createdCompanyId,
sessionUser: SessionInfo.userId
});
setArcaTestResult(result);
setCurrentStepIndex(1);
setArcaDiagnosticsLoading(true);
try {
const diagnostics = await API.post<ArcaWsfeDiagnosticsResult>("arca-credentials/wsfe-diagnostics", {
companyId: createdCompanyId,
sessionUser: SessionInfo.userId
});
setArcaDiagnosticsResult(diagnostics);
} catch (diagnosticsError: any) {
console.error("Error consultando diagnóstico WSFE ARCA:", diagnosticsError);
setArcaDiagnosticsResult({
dummy: { ok: false, error: diagnosticsError?.message || "No pudimos consultar WSFE." },
voucherTypes: { ok: false, error: diagnosticsError?.message || "No pudimos consultar tipos de comprobante." },
pointsOfSale: { ok: false, error: diagnosticsError?.message || "No pudimos consultar puntos de venta." },
lastVoucher: { ok: false, error: diagnosticsError?.message || "No pudimos consultar el último comprobante." }
});
} finally {
setArcaDiagnosticsLoading(false);
}
} catch (error: any) {
console.error("Error probando conexión ARCA:", error);
setArcaError(error?.message || "No pudimos validar la conexión con ARCA. Revisá el certificado y volvé a intentar.");
setCurrentStepIndex(1);
} finally {
setArcaLoading(false);
}
};
const renderArcaTestConnectionFlow = () => (
<ArcaTestConnectionFlow
currentStepIndex={currentStepIndex}
loading={arcaLoading}
diagnosticsLoading={arcaDiagnosticsLoading}
error={arcaError}
result={arcaTestResult}
diagnostics={arcaDiagnosticsResult}
handleTestConnection={handleTestArcaConnection}
handleFinish={handleActionSuccess}
/>
);
const renderArcaOnboardingFlow = () => (
<ArcaOnboardingFlow
currentStepIndex={currentStepIndex}
cuit={arcaCuit}
setCuit={setArcaCuit}
legalName={arcaLegalName}
setLegalName={setArcaLegalName}
taxCondition={arcaTaxCondition}
setTaxCondition={setArcaTaxCondition}
pointOfSale={arcaPointOfSale}
setPointOfSale={setArcaPointOfSale}
activityCode={arcaActivityCode}
setActivityCode={setArcaActivityCode}
activityDescription={arcaActivityDescription}
setActivityDescription={setArcaActivityDescription}
csrPem={arcaCsrPem}
certificatePem={arcaCertificatePem}
setCertificatePem={setArcaCertificatePem}
statusLabel={arcaStatusLabel}
arcaLoading={arcaLoading}
arcaError={arcaError}
handleNext={handleNext}
handleSaveFiscalProfile={handleSaveArcaFiscalProfile}
handleGenerateCsr={handleGenerateArcaCsr}
handleDownloadCsr={handleDownloadArcaCsr}
handleCertificateFile={handleArcaCertificateFile}
handleUploadCertificate={handleUploadArcaCertificate}
handleEditFiscalProfile={() => setCurrentStepIndex(1)}
handleFinish={handleActionSuccess}
/>
);
const renderOnboardingOrgFlow = () => (
<OnboardingOrgFlow
currentStepIndex={currentStepIndex}
@@ -1678,6 +1915,8 @@ export default function StepEngine({ flowId, action, initialCompanyId, initialEm
if (flowId === "public-link") return renderPublicLinkFlow();
if (flowId === "notifications") return renderNotificationsFlow();
if (flowId === "whatsapp-bot") return renderWhatsAppBotFlow();
if (flowId === "arca-onboarding") return renderArcaOnboardingFlow();
if (flowId === "arca-test-connection") return renderArcaTestConnectionFlow();
if (flowId === "disable-schedule") return renderDisableScheduleFlow();
if (flowId === "open-reservation-periods") return renderReservationPeriodFlow();
if (flowId === "override-schedule") return renderOverrideScheduleFlow();
@@ -0,0 +1,256 @@
import React, { useEffect, useMemo, useState } from "react";
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
import QuestionCard from "../../QuestionCard/QuestionCard";
import QuestionInput from "../../QuestionCard/QuestionInput";
import API from "@services/Api.Service";
type ArcaTaxCondition = "MONOTRIBUTO" | "EXENTO";
type ArcaActivityOption = {
id: string;
name: string;
description?: string;
};
type Props = {
currentStepIndex: number;
cuit: string;
setCuit: (value: string) => void;
legalName: string;
setLegalName: (value: string) => void;
taxCondition: ArcaTaxCondition;
setTaxCondition: (value: ArcaTaxCondition) => void;
pointOfSale: string;
setPointOfSale: (value: string) => void;
activityCode: string;
setActivityCode: (value: string) => void;
activityDescription: string;
setActivityDescription: (value: string) => void;
csrPem: string;
certificatePem: string;
setCertificatePem: (value: string) => void;
statusLabel: string;
arcaLoading: boolean;
arcaError: string | null;
handleNext: () => void;
handleSaveFiscalProfile: () => void;
handleGenerateCsr: () => void;
handleDownloadCsr: () => void;
handleCertificateFile: (file: File | null) => void;
handleUploadCertificate: () => void;
handleEditFiscalProfile: () => void;
handleFinish: () => void;
};
export default function ArcaOnboardingFlow(props: Props) {
const { currentStepIndex, cuit, setCuit, legalName, setLegalName, taxCondition, setTaxCondition, pointOfSale, setPointOfSale, activityCode, setActivityCode, activityDescription, setActivityDescription, csrPem, certificatePem, setCertificatePem, statusLabel, arcaLoading, arcaError, handleNext, handleSaveFiscalProfile, handleGenerateCsr, handleDownloadCsr, handleCertificateFile, handleUploadCertificate, handleEditFiscalProfile, handleFinish } = props;
const canSaveFiscalProfile = cuit.trim().length >= 11 && legalName.trim().length >= 3 && Number(pointOfSale) > 0 && /^\d{6}$/.test(activityCode.trim()) && activityDescription.trim().length > 0;
const [csrCopyStatus, setCsrCopyStatus] = useState<string | null>(null);
const [activities, setActivities] = useState<ArcaActivityOption[]>([]);
const [activitySearch, setActivitySearch] = useState("");
const [activitiesLoading, setActivitiesLoading] = useState(false);
const [activitiesLoaded, setActivitiesLoaded] = useState(false);
const [activitiesError, setActivitiesError] = useState<string | null>(null);
const [isActivityPickerOpen, setIsActivityPickerOpen] = useState(false);
useEffect(() => {
if (currentStepIndex !== 1 || activitiesLoaded || activitiesLoading) return;
setActivitiesLoading(true);
setActivitiesError(null);
API.post<ArcaActivityOption[]>("arca-activities/filter-all", {})
.then((response) => {
setActivities(response || []);
setActivitiesLoaded(true);
})
.catch((error) => {
console.error("Error loading ARCA activities:", error);
setActivitiesError("No pudimos cargar el catálogo de actividades. Volvé a intentar en unos segundos.");
})
.finally(() => setActivitiesLoading(false));
}, [activitiesLoaded, activitiesLoading, currentStepIndex]);
useEffect(() => {
if (activityCode && activityDescription && !activitySearch) {
setActivitySearch(`${activityCode} ${activityDescription}`);
}
}, [activityCode, activityDescription, activitySearch]);
const filteredActivities = useMemo(() => {
const normalizedSearch = normalizeActivityText(activitySearch);
const selectedCode = activityCode.trim();
if (!normalizedSearch) {
return activities.slice(0, 8);
}
const selectedActivity = activities.find((activity) => activity.id === selectedCode);
const matches = activities.filter((activity) => {
const searchableText = normalizeActivityText(`${activity.id} ${activity.name} ${activity.description || ""}`);
return normalizedSearch.split(" ").every((term) => searchableText.includes(term));
});
if (selectedActivity && !matches.some((activity) => activity.id === selectedActivity.id)) {
return [selectedActivity, ...matches].slice(0, 8);
}
return matches.slice(0, 8);
}, [activities, activityCode, activitySearch]);
const handleActivitySearchChange = (value: string) => {
setActivitySearch(value);
if (activityCode || activityDescription) {
setActivityCode("");
setActivityDescription("");
}
};
const handleActivitySelect = (activity: ArcaActivityOption) => {
setActivityCode(activity.id);
setActivityDescription(activity.name);
setActivitySearch(`${activity.id} ${activity.name}`);
setIsActivityPickerOpen(false);
};
const handleCopyCsr = async () => {
if (!csrPem) return;
try {
await navigator.clipboard.writeText(csrPem);
setCsrCopyStatus("CSR copiado. Pegalo en ARCA cuando te lo pida.");
} catch (error) {
setCsrCopyStatus("No pudimos copiarlo automáticamente. Seleccioná el texto de abajo y copialo manualmente.");
}
};
return (
<>
<QuestionCard isActive={currentStepIndex === 0} title="Conectar ARCA" description="Te voy a guiar para dejar lista la emisión de Factura C. Primero guardamos tus datos fiscales, después generamos el pedido de certificado y al final cargás el certificado que te entrega ARCA." onNext={handleNext} nextLabel="Empezar" topAccessory={<ReceiptLongIcon style={{ fontSize: 52, color: "var(--wine-red)" }} />}>
<InfoPanel>Vas a necesitar tener acceso a ARCA con clave fiscal y permisos para administrar certificados del servicio de facturación electrónica.</InfoPanel>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 1} title="Datos fiscales" description="Completá los datos que van a identificar a tu organización cuando emitas Factura C." onNext={handleSaveFiscalProfile} disableNext={!canSaveFiscalProfile || arcaLoading} nextLabel={arcaLoading ? "Guardando..." : "Guardar datos fiscales"}>
<div style={{ display: "flex", flexDirection: "column", gap: "14px", width: "100%" }}>
<QuestionInput label="CUIT" value={cuit} onChange={(event) => setCuit(event.target.value.replace(/\D/g, ""))} placeholder="Sin guiones, por ejemplo 20123456789" inputMode="numeric" />
<QuestionInput label="Razón social" value={legalName} onChange={(event) => setLegalName(event.target.value)} placeholder="Nombre fiscal o razón social" />
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: "10px" }}>
<OptionButton active={taxCondition === "MONOTRIBUTO"} onClick={() => setTaxCondition("MONOTRIBUTO")}>Monotributo</OptionButton>
</div>
<QuestionInput label="Punto de venta" value={pointOfSale} onChange={(event) => setPointOfSale(event.target.value.replace(/\D/g, ""))} placeholder="Ejemplo: 1" inputMode="numeric" />
<ActivityPicker search={activitySearch} selectedCode={activityCode} selectedDescription={activityDescription} activities={filteredActivities} loading={activitiesLoading} error={activitiesError} isOpen={isActivityPickerOpen} onOpen={() => setIsActivityPickerOpen(true)} onClose={() => setIsActivityPickerOpen(false)} onSearchChange={handleActivitySearchChange} onSelect={handleActivitySelect} />
<StatusMessage error={arcaError} />
</div>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 2} title="Pedido de certificado" description="Ahora generamos el archivo CSR. Ese archivo se descarga desde TurnosXpress y luego se sube en ARCA para que te devuelvan el certificado." onNext={csrPem ? handleNext : handleGenerateCsr} disableNext={arcaLoading} nextLabel={csrPem ? "Continuar con ARCA" : arcaLoading ? "Generando..." : "Generar y descargar CSR"}>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
<InfoPanel>{statusLabel || "Todavía no generamos el CSR para esta organización."}</InfoPanel>
{csrPem && <InfoPanel>Ya generamos el CSR. ARCA puede pedirte subir el archivo o pegar el contenido completo, incluyendo BEGIN y END CERTIFICATE REQUEST.</InfoPanel>}
{csrPem && (
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<textarea value={csrPem} readOnly rows={9} aria-label="Contenido CSR para copiar en ARCA" onFocus={(event) => event.target.select()} style={{ width: "100%", boxSizing: "border-box", borderRadius: "12px", border: "1px solid rgba(255,255,255,0.16)", background: "rgba(255,255,255,0.05)", color: "white", padding: "14px", fontFamily: "monospace", fontSize: "12px", lineHeight: 1.4, resize: "vertical" }} />
{csrCopyStatus && <InfoPanel>{csrCopyStatus}</InfoPanel>}
<SecondaryButton onClick={handleCopyCsr}>Copiar CSR</SecondaryButton>
</div>
)}
{csrPem && <SecondaryButton onClick={handleDownloadCsr}>Descargar archivo .csr</SecondaryButton>}
{csrPem && <SecondaryButton onClick={handleGenerateCsr}>Regenerar CSR</SecondaryButton>}
<StatusMessage error={arcaError} />
</div>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 3} title="Subir el CSR en ARCA" description="Con el archivo descargado, entrá a ARCA y generá el certificado para facturación electrónica." onNext={handleNext} nextLabel="Ya tengo el certificado">
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
<StepItem number="1">Ingresá a ARCA con clave fiscal y abrí el administrador de certificados digitales.</StepItem>
<StepItem number="2">Creá un nuevo certificado y subí el archivo .csr que descargaste desde TurnosXpress.</StepItem>
<StepItem number="3">Asociá el certificado al servicio de facturación electrónica WSFE.</StepItem>
<StepItem number="4">Descargá el certificado emitido por ARCA en formato .crt o .pem.</StepItem>
</div>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 4} title="Cargar certificado" description="Pegá el contenido del certificado o seleccioná el archivo que descargaste desde ARCA." onNext={handleUploadCertificate} disableNext={!certificatePem.trim() || arcaLoading} nextLabel={arcaLoading ? "Validando..." : "Guardar certificado"}>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
<input type="file" accept=".crt,.pem,text/plain" onChange={(event) => handleCertificateFile(event.target.files?.[0] || null)} style={{ color: "rgba(255,255,255,0.75)" }} />
<textarea value={certificatePem} onChange={(event) => setCertificatePem(event.target.value)} placeholder="-----BEGIN CERTIFICATE-----" rows={8} style={{ width: "100%", boxSizing: "border-box", borderRadius: "12px", border: "1px solid rgba(255,255,255,0.16)", background: "rgba(255,255,255,0.05)", color: "white", padding: "14px", fontFamily: "monospace", resize: "vertical" }} />
<StatusMessage error={arcaError} />
</div>
</QuestionCard>
<QuestionCard isActive={currentStepIndex === 5} title="ARCA conectado" description="Tu organización ya tiene los datos fiscales y el certificado guardados para avanzar con Factura C." onNext={handleFinish} nextLabel="Finalizar" topAccessory={<div style={{ fontSize: 48 }}></div>}>
<InfoPanel>{statusLabel || "Configuración lista."}</InfoPanel>
<div style={{ marginTop: "12px" }}>
<SecondaryButton onClick={handleEditFiscalProfile}>Editar datos fiscales</SecondaryButton>
</div>
</QuestionCard>
</>
);
}
function InfoPanel({ children }: { children: React.ReactNode }) {
return <div style={{ padding: "14px", borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)", color: "rgba(255,255,255,0.75)", fontSize: "14px", lineHeight: 1.5 }}>{children}</div>;
}
function OptionButton({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
return <button type="button" onClick={onClick} style={{ padding: "12px 16px", borderRadius: "10px", border: active ? "1px solid var(--wine-red)" : "1px solid rgba(255,255,255,0.16)", background: active ? "rgba(255,42,127,0.16)" : "rgba(255,255,255,0.05)", color: "white", cursor: "pointer", fontWeight: 700, fontFamily: "inherit" }}>{children}</button>;
}
function SecondaryButton({ onClick, children }: { onClick: () => void; children: React.ReactNode }) {
return <button type="button" onClick={onClick} style={{ padding: "12px 16px", borderRadius: "10px", background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.16)", color: "white", cursor: "pointer", fontWeight: 700, fontFamily: "inherit" }}>{children}</button>;
}
function ActivityPicker({ search, selectedCode, selectedDescription, activities, loading, error, isOpen, onOpen, onClose, onSearchChange, onSelect }: { search: string; selectedCode: string; selectedDescription: string; activities: ArcaActivityOption[]; loading: boolean; error: string | null; isOpen: boolean; onOpen: () => void; onClose: () => void; onSearchChange: (value: string) => void; onSelect: (activity: ArcaActivityOption) => void; }) {
return (
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<label style={{ color: "rgba(255,255,255,0.82)", fontSize: "14px", fontWeight: 700 }}>Actividad ARCA/CLAE</label>
<button type="button" onClick={onOpen} style={{ width: "100%", textAlign: "left", padding: "12px 16px", borderRadius: "10px", border: selectedCode ? "1px solid var(--wine-red)" : "1px solid rgba(255,255,255,0.16)", background: selectedCode ? "rgba(255,42,127,0.16)" : "rgba(255,255,255,0.05)", color: selectedCode ? "white" : "rgba(255,255,255,0.58)", cursor: "pointer", fontWeight: 700, fontFamily: "inherit", lineHeight: 1.35 }}>
{selectedCode ? selectedDescription : "Seleccionar actividad"}
</button>
{isOpen && (
<div role="dialog" aria-modal="true" aria-label="Buscar actividad ARCA/CLAE" style={{ position: "fixed", inset: 0, zIndex: 3000, display: "flex", alignItems: "center", justifyContent: "center", padding: "18px", background: "rgba(0,0,0,0.62)" }} onClick={onClose}>
<div style={{ width: "min(620px, 100%)", maxHeight: "min(760px, 88vh)", display: "flex", flexDirection: "column", padding: "18px", borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)", boxShadow: "0 28px 80px rgba(0,0,0,0.45)", backdropFilter: "blur(12px)" }} onClick={(event) => event.stopPropagation()}>
<div style={{ display: "flex", justifyContent: "space-between", gap: "14px", alignItems: "flex-start", marginBottom: "14px" }}>
<div>
<h3 style={{ margin: 0, color: "white", fontSize: "20px" }}>Buscar actividad ARCA/CLAE</h3>
<p style={{ margin: "6px 0 0", color: "rgba(255,255,255,0.62)", fontSize: "13px", lineHeight: 1.4 }}>Buscá por código o nombre y seleccioná la actividad fiscal de la organización.</p>
</div>
<button type="button" onClick={onClose} aria-label="Cerrar buscador" style={{ width: "36px", height: "36px", borderRadius: "10px", border: "1px solid rgba(255,255,255,0.16)", background: "rgba(255,255,255,0.05)", color: "white", cursor: "pointer", fontSize: "18px" }}>×</button>
</div>
<input autoFocus value={search} onChange={(event) => onSearchChange(event.target.value)} placeholder="Ejemplo: 855000 o educación" style={{ width: "100%", boxSizing: "border-box", borderRadius: "12px", border: "1px solid rgba(255,255,255,0.16)", background: "rgba(255,255,255,0.05)", color: "white", padding: "14px 16px", fontFamily: "inherit", outline: "none" }} />
<div style={{ display: "flex", flexDirection: "column", gap: "8px", marginTop: "14px", overflowY: "auto", paddingRight: "2px" }}>
{loading && <InfoPanel>Cargando actividades ARCA...</InfoPanel>}
{error && <StatusMessage error={error} />}
{!loading && !error && activities.length === 0 && <InfoPanel>No encontramos actividades para esa búsqueda.</InfoPanel>}
{!loading && !error && activities.map((activity) => {
const isSelected = activity.id === selectedCode;
return (
<button key={activity.id} type="button" onClick={() => onSelect(activity)} style={{ display: "grid", gridTemplateColumns: "78px 1fr", gap: "12px", textAlign: "left", padding: "13px", borderRadius: "12px", border: isSelected ? "1px solid var(--wine-red)" : "1px solid rgba(255,255,255,0.12)", background: isSelected ? "rgba(255,42,127,0.16)" : "rgba(255,255,255,0.05)", color: "white", cursor: "pointer", fontFamily: "inherit" }}>
<strong style={{ fontSize: "13px" }}>{activity.id}</strong>
<span style={{ color: "rgba(255,255,255,0.78)", fontSize: "13px", lineHeight: 1.35 }}>{activity.name}</span>
</button>
);
})}
</div>
</div>
</div>
)}
</div>
);
}
function StepItem({ number, children }: { number: string; children: React.ReactNode }) {
return <div style={{ display: "flex", gap: "12px", alignItems: "flex-start", padding: "14px", borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)", color: "rgba(255,255,255,0.78)", lineHeight: 1.5 }}><strong style={{ color: "white" }}>{number}.</strong><span>{children}</span></div>;
}
function StatusMessage({ error }: { error: string | null }) {
if (!error) return null;
return <div style={{ padding: "12px 14px", borderRadius: "10px", background: "rgba(255,60,60,0.1)", border: "1px solid rgba(255,60,60,0.3)", color: "#ff9999", fontSize: "13px", lineHeight: 1.4 }}>{error}</div>;
}
function normalizeActivityText(value: string) {
return value
.toLowerCase()
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/\s+/g, " ")
.trim();
}
@@ -0,0 +1,150 @@
import React from "react";
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
import QuestionCard from "../../QuestionCard/QuestionCard";
export type ArcaWsaaTestResult = {
status?: string;
environment?: "homologation" | "production";
service?: string;
endpoints?: ArcaEndpointMetadata;
expirationTime?: string;
cached?: boolean;
};
type ArcaEndpointMetadata = {
wsaaHost?: string;
wsfeHost?: string;
};
export type ArcaWsfeDiagnosticsResult = {
environment?: "homologation" | "production";
service?: string;
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;
};
};
type Props = {
currentStepIndex: number;
loading: boolean;
diagnosticsLoading: boolean;
error: string | null;
result: ArcaWsaaTestResult | null;
diagnostics: ArcaWsfeDiagnosticsResult | null;
handleTestConnection: () => void;
handleFinish: () => void;
};
export default function ArcaTestConnectionFlow({ currentStepIndex, loading, diagnosticsLoading, error, result, diagnostics, handleTestConnection, handleFinish }: Props) {
return (
<>
<QuestionCard
isActive={currentStepIndex === 0}
title="Probar conexión ARCA"
description="Vamos a validar que el certificado de esta organización pueda iniciar sesión en WSAA para usar el servicio WSFE."
onNext={handleTestConnection}
disableNext={loading}
nextLabel={loading ? "Probando..." : "Probar conexión"}
topAccessory={<ReceiptLongIcon style={{ fontSize: 52, color: "var(--wine-red)" }} />}
>
<div style={{ display: "flex", flexDirection: "column", gap: "12px", width: "100%" }}>
<InfoPanel>Esta prueba no emite facturas. Solo confirma que ARCA acepta el certificado y devuelve un token válido para WSFE.</InfoPanel>
<StatusMessage error={error} />
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 1 && Boolean(result)}
title="Conexión ARCA validada"
description="ARCA respondió correctamente el login WSAA. También consultamos WSFE para aislar problemas del servicio de facturación electrónica."
onNext={handleFinish}
disableNext={diagnosticsLoading}
nextLabel={diagnosticsLoading ? "Consultando WSFE..." : "Finalizar"}
topAccessory={<div style={{ fontSize: 48 }}></div>}
>
<div style={{ display: "flex", flexDirection: "column", gap: "10px", width: "100%" }}>
<InfoPanel>WSAA está OK. El diagnóstico WSFE no emite comprobantes: solo consulta salud, puntos de venta, tipos de comprobante y último número autorizado.</InfoPanel>
<InfoRow label="Ambiente" value={result?.environment || "homologation"} />
<InfoRow label="Servicio" value={result?.service || "wsfe"} />
{result?.endpoints?.wsaaHost ? <InfoRow label="WSAA host" value={result.endpoints.wsaaHost} /> : null}
<InfoRow label="Vencimiento" value={formatExpiration(result?.expirationTime)} />
<InfoRow label="Token" value={result?.cached ? "Reutilizado desde caché" : "Creado en esta prueba"} />
{diagnosticsLoading && <InfoPanel>Consultando FEDummy, puntos de venta, tipos de comprobante y último comprobante autorizado...</InfoPanel>}
{diagnostics && <WsfeDiagnosticsPanel diagnostics={diagnostics} />}
</div>
</QuestionCard>
<QuestionCard
isActive={currentStepIndex === 1 && Boolean(error) && !result}
title="No pudimos conectar con ARCA"
description="Revisá que el certificado esté cargado, corresponda al CSR generado y tenga el servicio WSFE asociado en ARCA."
onNext={handleTestConnection}
disableNext={loading}
nextLabel={loading ? "Probando..." : "Reintentar"}
topAccessory={<div style={{ fontSize: 48 }}></div>}
>
<StatusMessage error={error} />
</QuestionCard>
</>
);
}
function formatExpiration(value?: string) {
if (!value) return "No informado";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return date.toLocaleString("es-AR", { dateStyle: "short", timeStyle: "short" });
}
function InfoPanel({ children }: { children: React.ReactNode }) {
return <div style={{ padding: "14px", borderRadius: "12px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)", color: "rgba(255,255,255,0.75)", fontSize: "14px", lineHeight: 1.5 }}>{children}</div>;
}
function InfoRow({ label, value }: { label: string; value: string }) {
return <div style={{ display: "flex", justifyContent: "space-between", gap: "12px", padding: "12px 14px", borderRadius: "10px", background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.12)", color: "rgba(255,255,255,0.78)", fontSize: "14px" }}><strong style={{ color: "white" }}>{label}</strong><span>{value}</span></div>;
}
function WsfeDiagnosticsPanel({ diagnostics }: { diagnostics: ArcaWsfeDiagnosticsResult }) {
return (
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<InfoRow label="WSFE FEDummy" value={diagnostics.dummy?.ok ? `OK (${[diagnostics.dummy.appServer, diagnostics.dummy.dbServer, diagnostics.dummy.authServer].filter(Boolean).join(" / ") || "sin detalle"})` : `Error: ${diagnostics.dummy?.error || "sin detalle"}`} />
{diagnostics.endpoints?.wsfeHost ? <InfoRow label="WSFE host" value={diagnostics.endpoints.wsfeHost} /> : null}
<InfoRow label="Punto de venta configurado" value={diagnostics.pointsOfSale?.includesConfiguredPointOfSale ? `OK (${diagnostics.pointsOfSale.configuredPointOfSale})` : `No aparece (${diagnostics.pointsOfSale?.configuredPointOfSale || "sin configurar"})`} />
{diagnostics.pointsOfSale?.points?.length ? <InfoRow label="Puntos de venta ARCA" value={diagnostics.pointsOfSale.points.join(", ")} /> : null}
{diagnostics.pointsOfSale?.error ? <StatusMessage error={diagnostics.pointsOfSale.error} /> : null}
<InfoRow label="Factura C tipo 11" value={diagnostics.voucherTypes?.includesFacturaC ? `OK (${diagnostics.voucherTypes.count || 0} tipos)` : `No aparece (${diagnostics.voucherTypes?.count || 0} tipos)`} />
{diagnostics.voucherTypes?.error ? <StatusMessage error={diagnostics.voucherTypes.error} /> : null}
<InfoRow label="Último comprobante Factura C" value={diagnostics.lastVoucher?.ok ? String(diagnostics.lastVoucher.lastVoucherNumber ?? 0) : `Error: ${diagnostics.lastVoucher?.error || "sin detalle"}`} />
</div>
);
}
function StatusMessage({ error }: { error: string | null }) {
if (!error) return null;
return <div style={{ padding: "12px 14px", borderRadius: "10px", background: "rgba(255,60,60,0.1)", border: "1px solid rgba(255,60,60,0.3)", color: "#ff9999", fontSize: "13px", lineHeight: 1.4 }}>{error}</div>;
}