first commit

This commit is contained in:
2026-07-16 20:48:43 -03:00
commit 5696cee264
1111 changed files with 322270 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
resources*
node_modules
dist
*.log
+36
View File
@@ -0,0 +1,36 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
client/node_modules
client/dist
client/dist-ssr
client/*.local
server/node_modules
server/dist
server/dist-ssr
server/*.local
server/build
# server/uploads
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+49
View File
@@ -0,0 +1,49 @@
# Utilizamos Node.js como base
FROM node:22-bookworm
# Configurar entorno global
ENV NODEJS_ORG_MIRROR=https://nodejs.org/dist \
NODE_ENV=production
# Instalar herramientas necesarias del sistema
RUN apt-get update && \
apt-get install -y locales tzdata && \
rm -rf /var/lib/apt/lists/*
RUN npm install -g typescript
# Configurar timezone a "America/Argentina/Buenos_Aires"
ENV TZ=America/Argentina/Buenos_Aires
RUN ln -sf /usr/share/zoneinfo/America/Argentina/Buenos_Aires /etc/localtime && \
dpkg-reconfigure -f noninteractive tzdata
# Configurar locale en español (Argentina)
RUN sed -i 's/# es_AR.UTF-8 UTF-8/es_AR.UTF-8 UTF-8/' /etc/locale.gen && \
locale-gen
ENV LANG=es_AR.UTF-8
ENV LC_ALL=es_AR.UTF-8
# Crear carpetas de trabajo separadas para server y client
WORKDIR /app
# Copiar y construir el servidor
WORKDIR /app/server
COPY server/package*.json ./
RUN npm install --omit=dev=false
COPY server ./
RUN npx tsoa spec-and-routes
RUN npm run build
# Copiar y construir el cliente
WORKDIR /app/txclient
COPY txclient/package*.json ./
RUN npm install --omit=dev=false
COPY txclient ./
RUN npm run build
# Configurar puertos expuestos
EXPOSE 3000 3001 3021
# Comando de inicio que lanza tanto el server como el client
CMD [ "sh", "-c", "npm --prefix /app/server start & npm --prefix /app/txclient start" ]
+61
View File
@@ -0,0 +1,61 @@
# Etapa 1: Build del servidor
FROM node:22-alpine AS build-server
WORKDIR /app/server
COPY server/package*.json ./
RUN npm install --production --omit=dev \
&& npm cache clean --force \
&& rm -rf /root/.npm /tmp/* # Limpiar caché de npm y archivos temporales
COPY server ./
RUN npx tsoa spec-and-routes && npm run build \
&& rm -rf /app/server/src /app/server/tests # Eliminar archivos innecesarios de source y test
# Etapa 2: Build del cliente
FROM node:22-alpine AS build-client
WORKDIR /app/txclient
COPY txclient/package*.json ./
RUN npm install --production --omit=dev \
&& npm cache clean --force \
&& rm -rf /root/.npm /tmp/* # Limpiar caché de npm y archivos temporales
COPY txclient ./
RUN npm run build \
&& rm -rf /app/txclient/src /app/txclient/tests /app/txclient/node_modules # Eliminar archivos innecesarios de source y test
# Etapa final: Solo lo necesario para correr
FROM node:22-alpine AS production
ENV NODE_ENV=production \
TZ=America/Argentina/Buenos_Aires
# Configurar timezone y bash
RUN apk add --no-cache tzdata bash && \
cp /usr/share/zoneinfo/${TZ} /etc/localtime && \
echo "${TZ}" > /etc/timezone
# Crear estructura final
WORKDIR /app
# Copiar sólo los archivos de distribución y node_modules necesarios
# Server
COPY --from=build-server /app/server/build ./server/build
COPY --from=build-server /app/server/package.json ./server/
COPY --from=build-server /app/server/node_modules ./server/node_modules
# Cliente
COPY --from=build-client /app/txclient/.next ./txclient/.next
COPY --from=build-client /app/txclient/package.json ./txclient/
# Limpiar los archivos innecesarios del entorno de producción
RUN rm -rf /app/txclient/tests /app/server/tests /app/txclient/src /app/server/src \
&& rm -rf /app/server/package*.json /app/txclient/package*.json \
&& rm -rf /app/txclient/node_modules /app/server/node_modules \
&& rm -rf /app/server/.npm /app/txclient/.npm /tmp/* # Limpiar caches y node_modules no necesarios
# Puertos que usas
EXPOSE 3000 3001 3021
# Comando de inicio
CMD [ "sh", "-c", "npm --prefix /app/server start & npm --prefix /app/txclient start" ]
+37
View File
@@ -0,0 +1,37 @@
# Utilizamos Node.js como base
FROM node:22-bookworm
# Configurar entorno global
ENV NODEJS_ORG_MIRROR=https://nodejs.org/dist \
NODE_ENV=production
RUN npm install -g typescript
# Configurar timezone a "America/Argentina/Buenos_Aires"
ENV TZ=America/Argentina/Buenos_Aires
RUN ln -sf /usr/share/zoneinfo/America/Argentina/Buenos_Aires /etc/localtime && \
dpkg-reconfigure -f noninteractive tzdata
# Crear carpetas de trabajo separadas para server y client
WORKDIR /app
# Copiar y construir el servidor
WORKDIR /app/server
COPY server/package*.json ./
RUN npm install --omit=dev=false
COPY server ./
RUN npx tsoa spec-and-routes
RUN npm run build
# Copiar y construir el cliente
WORKDIR /app/txclient
COPY txclient/package*.json ./
RUN npm install --omit=dev=false
COPY txclient ./
RUN npm run build
# Configurar puertos expuestos
EXPOSE 3000 3001 3021
# Comando de inicio que lanza tanto el server como el client
CMD [ "sh", "-c", "npm --prefix /app/server start & npm --prefix /app/txclient start" ]
+2
View File
@@ -0,0 +1,2 @@
# turnosxpress
+54
View File
@@ -0,0 +1,54 @@
FROM debian:bookworm-slim
# Instala herramientas necesarias, incluyendo mongodump
RUN apt-get update && apt-get install -y \
gzip \
tar \
curl \
unzip \
fuse \
cron \
&& rm -rf /var/lib/apt/lists/*
# Instala dependencias necesarias
RUN apt-get update && apt-get install -y \
gnupg \
curl \
ca-certificates \
lsb-release \
apt-transport-https
# Añade la clave GPG del repositorio de MongoDB
RUN curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
gpg --dearmor -o /usr/share/keyrings/mongodb-server-8.0.gpg
# Añade el repositorio de MongoDB
RUN echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] http://repo.mongodb.org/apt/debian bookworm/mongodb-org/8.0 main" \
> /etc/apt/sources.list.d/mongodb-org-8.0.list
# Instala mongodump (mongo-tools)
RUN apt-get update && apt-get install -y mongodb-database-tools
# Instala rclone
RUN curl https://rclone.org/install.sh | bash
# Crea los directorios necesarios
RUN mkdir -p /backup /data-uploads /root/.config/rclone
# Declaramos los volúmenes
VOLUME ["/data-uploads", "/backup", "/root/.config/rclone"]
# Copia el script de backup
COPY backup.sh /usr/local/bin/backup.sh
RUN chmod +x /usr/local/bin/backup.sh
# Copia el cron job
COPY backup-cron /etc/cron.d/backup-cron
RUN chmod 0644 /etc/cron.d/backup-cron && \
crontab /etc/cron.d/backup-cron
# Necesario para cron
RUN touch /var/log/cron.log
# Comando de inicio: corre cron y muestra logs
CMD cron && tail -f /var/log/cron.log
+3
View File
@@ -0,0 +1,3 @@
# Ejecutar el script todos los días a las 3:00 AM
#*/5 * * * * root /usr/local/bin/backup.sh >> /var/log/cron.log 2>&1
0 3 * * * root /usr/local/bin/backup.sh >> /var/log/cron.log 2>&1
+29
View File
@@ -0,0 +1,29 @@
#!/bin/bash
set -e
DATE=$(date +"%Y-%m-%d_%H-%M")
BACKUP_DIR="/backup"
DATA_SRC="/data-uploads"
DUMP_DIR="$BACKUP_DIR/mongo_$DATE"
ARCHIVE="$BACKUP_DIR/backup_$DATE.tar.gz"
echo "1. Realizando backup de MongoDB..."
mongodump \
--host mongodb \
--username txuser \
--password hdR2102Frx8us2WkuN21quAn12 \
--authenticationDatabase turnosxpress \
--db turnosxpress \
--out "$DUMP_DIR"
echo "2. Comprimendo datos..."
tar -czf "$ARCHIVE" "$DATA_SRC" "$DUMP_DIR"
echo "3. Subiendo a Mega con rclone..."
rclone copy "$ARCHIVE" hdrdevs-mega:
echo "4. Eliminando archivos temporales..."
rm -rf "$DUMP_DIR"
echo "✅ Backup finalizado correctamente: $ARCHIVE"
+7
View File
@@ -0,0 +1,7 @@
docker run -d \
--name backupper \
--restart unless-stopped \
-v /root/my-docker-images/uploads:/data-uploads \
-v /root/my-docker-images/backups:/backup \
-v /root/my-docker-images/rclone:/root/.config/rclone \
backupper
+10
View File
@@ -0,0 +1,10 @@
Esto ejecuta un contenedor con rclone y permite autorizar la conexion con google drive.
docker run -it --rm rclone/rclone config
Una vez generada la configuracion sera almacenada en el home del usuario del host que ejecuto el comando.
si es root, en /root/.config/rclone/rclone.conf
la vamos a copiar a /root/hdr/tx-data/rclone/rclone.conf
para que el contenedor backupper tenga acceso a esta configuracion.
+5
View File
@@ -0,0 +1,5 @@
[hdrdevs-mega]
type = mega
user = hdrdevs@gmail.com
pass = uB_5v7fUEtxSd-Fifkno7AGXLoM6vxTKT0XY66QYJQ
+7
View File
@@ -0,0 +1,7 @@
DATABASE_CONNECTION = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
DATABASE_CONNECTION_ATLAS = mongodb+srv://horacio:frx8us2w@reservar.a2cgd.mongodb.net/reservar
DATABASE_CONNECTION_LOCAL = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
DEFAULT_ADMIN_PORT = 3005
DEFAULT_BOT_START_PORT = 3010
CONTAINER_API_URL = http://localhost
+7
View File
@@ -0,0 +1,7 @@
DATABASE_CONNECTION = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
DATABASE_CONNECTION_ATLAS = mongodb+srv://horacio:frx8us2w@reservar.a2cgd.mongodb.net/reservar
DATABASE_CONNECTION_LOCAL = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
DEFAULT_ADMIN_PORT = 3005
DEFAULT_BOT_START_PORT = 3010
CONTAINER_API_URL = http://localhost
+7
View File
@@ -0,0 +1,7 @@
DATABASE_CONNECTION = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
DATABASE_CONNECTION_ATLAS = mongodb+srv://horacio:frx8us2w@reservar.a2cgd.mongodb.net/reservar
DATABASE_CONNECTION_LOCAL = mongodb://horacio:frx8us2w@192.168.1.50:20215/turnosxpress
DEFAULT_ADMIN_PORT = 3005
DEFAULT_BOT_START_PORT = 3010
CONTAINER_API_URL = http://localhost
+26
View File
@@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+28
View File
@@ -0,0 +1,28 @@
# Usamos Node.js con Alpine para menor tamaño
FROM node:22-alpine
# Configurar entorno global
ENV NODEJS_ORG_MIRROR=https://nodejs.org/dist \
NODE_ENV=production
# Instalar TypeScript y limpiar cache
RUN npm install -g typescript && npm cache clean --force
# Crear carpetas de trabajo separadas para server y client
WORKDIR /app
ARG DOCKER_GID=1001 # Valor por defecto
RUN addgroup -g ${DOCKER_GID} docker && \
addgroup node docker
WORKDIR /app/bot-admin-api
COPY package*.json ./
RUN npm install --omit=dev=false
COPY . ./
RUN npm run build
# Configurar puertos expuestos
EXPOSE 3005
# Comando de inicio que lanza tanto el server como el client
CMD [ "sh", "-c", "npm --prefix /app/bot-admin-api start" ]
+18
View File
@@ -0,0 +1,18 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const dotenv_1 = __importDefault(require("dotenv"));
const containers_1 = __importDefault(require("./routes/containers"));
dotenv_1.default.config();
const app = (0, express_1.default)();
const PORT = process.env.DEFAULT_ADMIN_PORT || 3000;
app.use(express_1.default.json());
// Rutas
app.use("/containers", containers_1.default);
// Iniciar el servidor
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
+158
View File
@@ -0,0 +1,158 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SERVER_STATE = exports.BOT_STATE = void 0;
const express_1 = require("express");
const dockerService_1 = require("../services/dockerService");
const axios_1 = __importDefault(require("axios"));
var BOT_STATE;
(function (BOT_STATE) {
BOT_STATE["EXISTS"] = "exists";
BOT_STATE["NOT_EXISTS"] = "not_exists";
})(BOT_STATE = exports.BOT_STATE || (exports.BOT_STATE = {}));
var SERVER_STATE;
(function (SERVER_STATE) {
SERVER_STATE["RUNNING"] = "running";
SERVER_STATE["NOT_WORKING"] = "not_working";
})(SERVER_STATE = exports.SERVER_STATE || (exports.SERVER_STATE = {}));
const router = (0, express_1.Router)();
const getContainerApiUrl = (port) => {
const baseUrl = process.env.CONTAINER_API_URL ? process.env.CONTAINER_API_URL : "http://localhost";
const url = `${baseUrl}:${port}/`;
return url;
};
// Obtener todos los contenedores
router.get("/", async (req, res) => {
try {
const containers = await (0, dockerService_1.listContainers)();
res.json(containers);
}
catch (error) {
res.status(500).json({ error: error.message });
}
});
// Iniciar un contenedor por ID
router.post("/:id/start", async (req, res) => {
try {
const organizationId = req.params.id;
const containerInfo = await (0, dockerService_1.getContainerByOrganization)(organizationId);
await (0, dockerService_1.startContainer)(containerInfo.Id);
res.json({ message: `El bot ${containerInfo.Id} ha sido iniciado` });
}
catch (error) {
if (error.message.indexOf("already started") >= 0) {
res.json({ message: `El bot se encontraba iniciado anteriormente.` });
return;
}
res.status(500).json({ error: error.message });
}
});
// Obtener el QR de conexion para el bot de una organization.
router.get("/:id/qr", async (req, res) => {
try {
const organizationId = req.params.id;
const containerInfo = await (0, dockerService_1.getContainerByOrganization)(organizationId);
const url = getContainerApiUrl(containerInfo.Ports[0].PublicPort.toString()); // "http://localhost:" + containerInfo.Ports[0].PublicPort + "/";
const response = await axios_1.default.get(url, { responseType: "arraybuffer" });
res.setHeader("Content-type", "image/png");
res.send(response.data);
}
catch (error) {
res.status(500).json({ error: error.message });
}
});
// Detener un contenedor por ID
router.post("/:id/stop", async (req, res) => {
try {
const organizationId = req.params.id;
const containerInfo = await (0, dockerService_1.getContainerByOrganization)(organizationId);
await (0, dockerService_1.stopContainer)(containerInfo.Id);
res.json({ message: `El bot de la organizacion ${organizationId} ha sido detenido` });
}
catch (error) {
console.log(error.message);
res.status(500).json({ error: error.message });
}
});
// Eliminar un contenedor por ID
router.delete("/:id", async (req, res) => {
try {
const organizationId = req.params.id;
const containerInfo = await (0, dockerService_1.getContainerByOrganization)(organizationId);
await (0, dockerService_1.removeContainer)(containerInfo.Id);
res.json({ message: `El bot de la organizacion ${organizationId} removed` });
}
catch (error) {
res.status(500).json({ error: error.message });
}
});
// Crear un nuevo contenedor
router.post("/create", async (req, res) => {
try {
const { organizationId } = req.body;
const port = await (0, dockerService_1.getAvailablePort)();
if (!port) {
res.status(400).json({ error: "Port is required" });
return;
}
if (await (0, dockerService_1.existsContainer)(organizationId)) {
res.json({ message: `Ya existe un bot de whatsapp creado para esta organizacion` });
return;
}
const containerName = `${organizationId}_bot_${port}`;
const imageName = "txbot";
const containerId = await (0, dockerService_1.createContainer)(port, containerName, imageName);
console.log(`Se ha creado un nuevo bot en el contenedor ${containerId} para la organizacion ${organizationId}`);
res.json({ message: `El bot ha sido creado con exito`, port, organizationId });
}
catch (error) {
res.status(500).json({ error: error.message });
}
});
// Consultar el estado de un contenedor par auna organizationId
router.post("/:id/status", async (req, res) => {
try {
const organizationId = req.params.id;
const info = await (0, dockerService_1.getContainerByOrganization)(organizationId);
res.json({ state: BOT_STATE.EXISTS, status: info.Status, serverState: SERVER_STATE.RUNNING });
}
catch (error) {
res.status(500).json({ error: error.message, code: 404 });
}
});
router.post("/:id/send", async (req, res) => {
try {
const organizationId = req.params.id;
const data = req.body;
const info = await (0, dockerService_1.getContainerByOrganization)(organizationId);
const url = getContainerApiUrl(info.Ports[0].PublicPort.toString());
const result = await axios_1.default.post(url + "v1/messages", data);
if (result.status !== 200) {
throw new Error("Ha ocurrido un error al enviar el mensaje" + result);
}
res.json({ message: `Mensaje enviado` });
}
catch (error) {
res.status(500).json({ error: error.message });
}
});
router.post("/:id/session", async (req, res) => {
try {
const organizationId = req.params.id;
const data = req.body;
const info = await (0, dockerService_1.getContainerByOrganization)(organizationId);
const url = getContainerApiUrl(info.Ports[0].PublicPort.toString());
const result = await axios_1.default.post(url + "v1/session", data);
if (result.status !== 200) {
throw new Error("Ha ocurrido un error al enviar el mensaje" + result);
}
const resultData = result.data;
res.json({ message: `${resultData}` });
}
catch (error) {
res.status(500).json({ error: error.message });
}
});
exports.default = router;
@@ -0,0 +1,127 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getContainerByOrganization = exports.removeContainer = exports.createContainer = exports.stopContainer = exports.startContainer = exports.getAvailablePort = exports.getOrganizationBotPort = exports.existsContainer = exports.listContainers = void 0;
const dockerode_1 = __importDefault(require("dockerode"));
const docker = new dockerode_1.default();
/**
* Listar todos los contenedores.
*/
const listContainers = async () => {
return docker.listContainers({ all: true });
};
exports.listContainers = listContainers;
const existsContainer = async (organizationId) => {
const contenedores = await (0, exports.listContainers)();
const contenedoresNombres = Array.from(contenedores, (item) => item.Names[0].split("_bot")[0].substring(1));
if (contenedoresNombres.includes(organizationId)) {
return true;
}
return false;
};
exports.existsContainer = existsContainer;
const getOrganizationBotPort = async (organizationId) => {
const contenedores = await (0, exports.listContainers)();
for (const contenedor of contenedores) {
if (contenedor.Names.includes(organizationId)) {
const port = contenedor.Ports[0].PublicPort;
return port;
}
}
return -1;
};
exports.getOrganizationBotPort = getOrganizationBotPort;
const getAvailablePort = async () => {
const contenedores = await (0, exports.listContainers)();
let defaultPort = process.env.DEFAULT_BOT_START_PORT ? parseInt(process.env.DEFAULT_BOT_START_PORT) : -1;
if (contenedores.length == 0) {
return defaultPort;
}
contenedores.sort((a, b) => b.Created - a.Created);
//Obtengo el contenedor mas reciente.
const lastContainerCreated = contenedores.shift();
if (!lastContainerCreated) {
return defaultPort;
}
const lastPort = lastContainerCreated.Ports;
if (!lastPort) {
return defaultPort;
}
if (lastPort.length == 0) {
return defaultPort;
}
return lastPort[0].PublicPort + 1;
};
exports.getAvailablePort = getAvailablePort;
/**
* Iniciar un contenedor por ID.
*/
const startContainer = async (containerId) => {
const container = docker.getContainer(containerId);
await container.start();
};
exports.startContainer = startContainer;
/**
* Detener un contenedor por ID.
*/
const stopContainer = async (containerId) => {
const container = docker.getContainer(containerId);
await container.stop();
};
exports.stopContainer = stopContainer;
const createContainer = async (port, name, image) => {
try {
// Crear un contenedor con las configuraciones especificadas
const container = await docker.createContainer({
Image: image,
name,
Env: [`PORT=${port}`],
ExposedPorts: {
[`${port}/tcp`]: {}, // Define el puerto expuesto
},
HostConfig: {
PortBindings: {
[`${port}/tcp`]: [{ HostPort: `${port}` }], // Mapea el puerto entre el host y el contenedor
},
},
});
// Iniciar el contenedor creado
await container.start();
// Devolver el ID del contenedor como resultado
return container.id;
}
catch (error) {
throw new Error(`Error al crear el contenedor: ${error.message}`);
}
};
exports.createContainer = createContainer;
const removeContainer = async (containerId) => {
try {
// Obtiene el contenedor por su ID
const container = docker.getContainer(containerId);
// Verifica si el contenedor existe antes de intentar eliminarlo
const containerInfo = await container.inspect();
if (containerInfo.State.Running) {
// Si el contenedor está corriendo, debe detenerse primero
await container.stop();
}
// Elimina el contenedor
await container.remove();
}
catch (error) {
throw new Error(`Error al eliminar el contenedor: ${error.message}`);
}
};
exports.removeContainer = removeContainer;
const getContainerByOrganization = async (organizationId) => {
const contenedores = await (0, exports.listContainers)();
for (const contenedor of contenedores) {
if (contenedor.Names.some((item) => item.includes(organizationId))) {
return contenedor;
}
}
throw new Error("Container not found");
};
exports.getContainerByOrganization = getContainerByOrganization;
+17
View File
@@ -0,0 +1,17 @@
version: "3.8"
services:
bot-admin-api:
image: bot-admin-api
container_name: bot-admin-api
restart: unless-stopped
volumes:
- /var/run/docker.sock:/var/run/docker.sock
ports:
- 3005:3005
networks:
- tx-net
networks:
tx-net:
driver: bridge
+2587
View File
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "bot-admin-api",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "ts-node-dev src/index.ts",
"build": "tsc",
"start": "node build/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"axios": "^1.8.2",
"cors": "^2.8.5",
"dockerode": "^4.0.3",
"dotenv": "^16.0.3",
"express": "^4.21.2"
},
"devDependencies": {
"@types/axios": "^0.9.36",
"@types/dockerode": "^3.3.34",
"@types/dotenv": "^6.1.1",
"@types/express": "^5.0.0",
"@types/node": "^22.10.5",
"ts-node-dev": "^2.0.0",
"typescript": "5.0.4"
}
}
+18
View File
@@ -0,0 +1,18 @@
import express from "express";
import dotenv from "dotenv";
import containerRoutes from "./routes/containers";
dotenv.config();
const app = express()
const PORT = process.env.DEFAULT_ADMIN_PORT || 3000;
app.use(express.json());
// Rutas
app.use("/containers", containerRoutes);
// Iniciar el servidor
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
+194
View File
@@ -0,0 +1,194 @@
import { Router } from "express";
import {
createContainer,
listContainers,
removeContainer,
startContainer,
stopContainer,
getAvailablePort,
existsContainer,
getContainerByOrganization,
} from "../services/dockerService";
import axios from "axios";
export enum BOT_STATE {
"EXISTS" = "exists",
"NOT_EXISTS" = "not_exists",
}
export enum SERVER_STATE {
"RUNNING" = "running",
"NOT_WORKING" = "not_working",
}
const router = Router();
const getContainerApiUrl = (name: string, port: string): string => {
const isProduction = process.env.NODE_ENV === "production";
const baseUrl = isProduction ? name : "localhost";
const url = `http:/${baseUrl}:${port}/`;
return url;
};
// Obtener todos los contenedores
router.get("/", async (req, res) => {
try {
const containers = await listContainers();
res.json(containers);
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Iniciar un contenedor por ID
router.post("/:id/start", async (req, res) => {
try {
const organizationId = req.params.id;
const containerInfo = await getContainerByOrganization(organizationId);
await startContainer(containerInfo.Id);
res.json({ message: `El bot ${containerInfo.Id} ha sido iniciado` });
} catch (error: any) {
if (error.message.indexOf("already started") >= 0) {
res.json({ message: `El bot se encontraba iniciado anteriormente.` });
return;
}
res.status(500).json({ error: error.message });
}
});
// Obtener el QR de conexion para el bot de una organization.
router.get("/:id/qr", async (req, res) => {
try {
const organizationId = req.params.id;
const containerInfo = await getContainerByOrganization(organizationId);
const containerName = containerInfo.Names[0].toString();
const containerPort = containerInfo.Ports[0].PublicPort.toString();
const url = getContainerApiUrl(containerName, containerPort);
const response = await axios.get(url, { responseType: "arraybuffer" });
res.setHeader("Content-type", "image/png");
res.send(response.data);
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Detener un contenedor por ID
router.post("/:id/stop", async (req, res) => {
try {
const organizationId = req.params.id;
const containerInfo = await getContainerByOrganization(organizationId);
await stopContainer(containerInfo.Id);
res.json({ message: `El bot de la organizacion ${organizationId} ha sido detenido` });
} catch (error: any) {
console.log(error.message);
res.status(500).json({ error: error.message });
}
});
// Eliminar un contenedor por ID
router.delete("/:id", async (req, res) => {
try {
const organizationId = req.params.id;
const containerInfo = await getContainerByOrganization(organizationId);
await removeContainer(containerInfo.Id);
res.json({ message: `El bot de la organizacion ${organizationId} removed` });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Crear un nuevo contenedor
router.post("/create", async (req, res) => {
try {
const { organizationId } = req.body;
const port = await getAvailablePort();
if (!port) {
res.status(400).json({ error: "Port is required" });
return;
}
if (await existsContainer(organizationId)) {
res.json({ message: `Ya existe un bot de whatsapp creado para esta organizacion` });
return;
}
const containerName = `${organizationId}_bot_${port}`;
const imageName = "txbot";
const containerId = await createContainer(port, containerName, imageName);
console.log(
`Se ha creado un nuevo bot en el contenedor ${containerId} para la organizacion ${organizationId}`
);
res.json({ message: `El bot ha sido creado con exito`, port, organizationId });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Consultar el estado de un contenedor par auna organizationId
router.post("/:id/status", async (req, res) => {
try {
const organizationId = req.params.id;
const info = await getContainerByOrganization(organizationId);
res.json({
state: BOT_STATE.EXISTS,
status: info.Status,
serverState: SERVER_STATE.RUNNING,
});
} catch (error: any) {
res.status(500).json({ error: error.message, code: 404 });
}
});
export interface MessageData {
number: string;
message: string;
}
router.post("/:id/send", async (req, res) => {
try {
const organizationId = req.params.id;
const data = req.body as MessageData;
const info = await getContainerByOrganization(organizationId);
const containerName = info.Names[0].toString();
const containerPort = info.Ports[0].PublicPort.toString();
const url = getContainerApiUrl(containerName, containerPort);
const result = await axios.post(url + "v1/messages", data);
if (result.status !== 200) {
throw new Error("Ha ocurrido un error al enviar el mensaje" + result);
}
res.json({ message: `Mensaje enviado` });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
router.post("/:id/session", async (req, res) => {
try {
const organizationId = req.params.id;
const data = req.body as MessageData;
const info = await getContainerByOrganization(organizationId);
const containerName = info.Names[0].toString();
const containerPort = info.Ports[0].PublicPort.toString();
const url = getContainerApiUrl(containerName, containerPort);
const result = await axios.post(url + "v1/session", data);
if (result.status !== 200) {
throw new Error("Ha ocurrido un error al enviar el mensaje" + result);
}
const resultData = result.data;
res.json({ message: `${resultData}` });
} catch (error: any) {
console.log(error);
res.status(500).json({ error: error.message });
}
});
export default router;
+152
View File
@@ -0,0 +1,152 @@
import Docker from "dockerode";
const docker = new Docker();
/**
* Listar todos los contenedores.
*/
export const listContainers = async () => {
return docker.listContainers({ all: true, filters: { ancestor: ["txbot:latest"] } });
};
export const existsContainer = async (organizationId: string): Promise<boolean> => {
const contenedores = await listContainers();
const contenedoresNombres = Array.from(contenedores, (item) =>
item.Names[0].split("_bot")[0].substring(1)
);
if (contenedoresNombres.includes(organizationId)) {
return true;
}
return false;
};
export const getOrganizationBotPort = async (organizationId: string): Promise<number> => {
const contenedores = await listContainers();
for (const contenedor of contenedores) {
if (contenedor.Names.includes(organizationId)) {
const port = contenedor.Ports[0].PublicPort;
return port;
}
}
return -1;
};
export const getAvailablePort = async (): Promise<number> => {
const contenedores = await listContainers();
let defaultPort = process.env.DEFAULT_BOT_START_PORT
? parseInt(process.env.DEFAULT_BOT_START_PORT)
: -1;
if (contenedores.length == 0) {
return defaultPort;
}
contenedores.sort((a, b) => b.Created - a.Created);
//Obtengo el contenedor mas reciente.
const lastContainerCreated = contenedores.shift();
if (!lastContainerCreated) {
return defaultPort;
}
const lastPort = lastContainerCreated.Ports;
if (!lastPort) {
return defaultPort;
}
if (lastPort.length == 0) {
return defaultPort;
}
return lastPort[0].PublicPort + 1;
};
/**
* Iniciar un contenedor por ID.
*/
export const startContainer = async (containerId: string) => {
const container = docker.getContainer(containerId);
await container.start();
};
/**
* Detener un contenedor por ID.
*/
export const stopContainer = async (containerId: string) => {
const container = docker.getContainer(containerId);
await container.stop();
};
export const createContainer = async (
port: number,
name: string,
image: string
): Promise<string> => {
try {
// Crear un contenedor con las configuraciones especificadas
const container = await docker.createContainer({
Image: image,
name,
Env: [`PORT=${port}`],
ExposedPorts: {
[`${port}/tcp`]: {}, // Define el puerto expuesto
},
HostConfig: {
PortBindings: {
[`${port}/tcp`]: [{ HostPort: `${port}` }], // Mapea el puerto entre el host y el contenedor
},
},
NetworkingConfig: {
EndpointsConfig: {
"bot-admin-api_tx-net": {}, // importante: debe coincidir con el nombre exacto de la red
},
},
});
// Iniciar el contenedor creado
await container.start();
// Devolver el ID del contenedor como resultado
return container.id;
} catch (error: any) {
throw new Error(`Error al crear el contenedor: ${error.message}`);
}
};
export const removeContainer = async (containerId: string): Promise<void> => {
try {
// Obtiene el contenedor por su ID
const container = docker.getContainer(containerId);
// Verifica si el contenedor existe antes de intentar eliminarlo
const containerInfo = await container.inspect();
if (containerInfo.State.Running) {
// Si el contenedor está corriendo, debe detenerse primero
await container.stop();
}
// Elimina el contenedor
await container.remove();
} catch (error: any) {
throw new Error(`Error al eliminar el contenedor: ${error.message}`);
}
};
export const getContainerByOrganization = async (
organizationId: string
): Promise<Docker.ContainerInfo> => {
const contenedores = await listContainers();
for (const contenedor of contenedores) {
if (contenedor.Names.some((item) => item.includes(organizationId))) {
return contenedor;
}
}
throw new Error("Container not found");
};
+103
View File
@@ -0,0 +1,103 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
"experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
"emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
//"rootDir": "./src", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
"baseUrl": ".", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
"resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./build", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
//"noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
//"noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
+40
View File
@@ -0,0 +1,40 @@
# --- Android Studio ---
*.iml
.gradle
.idea/
build/
captures/
local.properties
*.keystore
*.jks
# --- Archivos generados ---
/bin/
/gen/
/release/
/proguard/
*.apk
*.aab
*.ap_
*.aar
*.class
# --- Logs y caché ---
*.log
*.swp
.DS_Store
*.orig
thumbs.db
# --- Módulos ---
/app/build/
*/build/
# --- Archivos temporales ---
*.tmp
*.bak
# --- Firebase y configuración sensible ---
google-services.json
app/google-services.json
*.json
+2
View File
@@ -0,0 +1,2 @@
# TurnosXpress
+1
View File
@@ -0,0 +1 @@
/build
+41
View File
@@ -0,0 +1,41 @@
plugins {
id 'com.android.application'
}
android {
namespace 'com.hdrdevs.turnosxpress'
compileSdk 33
defaultConfig {
applicationId "com.hdrdevs.turnosxpress"
minSdk 21
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'com.github.angads25:filepicker:1.1.1'
implementation 'com.google.android.gms:play-services-auth:20.2.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,26 @@
package com.chdrdevs.turnosxpress;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.hdrdevs.turnosxpress", appContext.getPackageName());
}
}
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.TurnosXpress"
tools:targetApi="31">
<activity
android:name="com.hdrdevs.turnosxpress.MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.hdrdevs.turnosxpress.LoginActivity" />
</application>
</manifest>
Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

@@ -0,0 +1,61 @@
package com.hdrdevs.turnosxpress;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
public class LoginActivity extends AppCompatActivity {
private static final int RC_SIGN_IN = 9001;
private GoogleSignInClient mGoogleSignInClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String idToken = account.getIdToken();
Intent resultIntent = new Intent();
resultIntent.putExtra("token", idToken);
setResult(RESULT_OK, resultIntent);
finish();
} catch (ApiException e) {
Log.w("LoginActivity", "signInResult:failed code=" + e.getStatusCode());
setResult(RESULT_CANCELED);
finish();
}
}
}
@@ -0,0 +1,233 @@
package com.hdrdevs.turnosxpress;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.os.Environment;
import android.util.Base64;
import android.content.ContentValues;
import android.provider.MediaStore;
import android.content.ContentResolver;
public class MainActivity extends AppCompatActivity {
private static final int LOGIN_REQUEST_CODE = 1;
private WebView webView;
private ValueCallback<Uri[]> fileChooserCallback;
private String tokenResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tokenResult = "";
// For Android Emulator, use 10.0.2.2 to access localhost on your development machine.
// If testing on a physical device, replace 10.0.2.2 with your development machine's actual local IP address.
//Uri home = Uri.parse("http://10.0.2.2:3021");
Uri home = Uri.parse("https://turnosxpress.com.ar");
webView = new WebView(this);
webView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
WebSettings settings = webView.getSettings();
settings.setAllowContentAccess(true);
settings.setAllowFileAccess(true);
settings.setDatabaseEnabled(true);
settings.setDomStorageEnabled(true);
settings.setGeolocationEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setJavaScriptEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setMediaPlaybackRequiresUserGesture(false);
settings.setSupportMultipleWindows(true);
webView.setWebContentsDebuggingEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(), "Android");
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView vw, WebResourceRequest request) {
if (request.getUrl().toString().contains(home.getHost())) {
vw.loadUrl(request.getUrl().toString());
} else {
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
vw.getContext().startActivity(intent);
}
return true;
}
});
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onPermissionRequest(final PermissionRequest request) {
request.grant(request.getResources());
}
@Override
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d("WEBVIEW", cm.message() + " (line "
+ cm.lineNumber() + " of " + cm.sourceId() + ")");
return true;
}
@Override
public boolean onShowFileChooser(WebView vw, ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams) {
if (fileChooserCallback != null) {
fileChooserCallback.onReceiveValue(null);
}
fileChooserCallback = filePathCallback;
Intent selectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
selectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
selectionIntent.setType("*/*");
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, selectionIntent);
startActivityForResult(chooserIntent, 0);
return true;
}
});
webView.setOnKeyListener((v, keyCode, event) ->
{
WebView vw = (WebView) v;
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK && vw.canGoBack()) {
vw.goBack();
return true;
}
return false;
});
webView.setDownloadListener((uri, userAgent, contentDisposition, mimetype, contentLength) -> handleURI(uri));
webView.setOnLongClickListener(v -> {
handleURI(((WebView) v).getHitTestResult().getExtra());
return true;
});
webView.loadUrl(home.toString());
setContentView(webView);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == LOGIN_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
tokenResult = intent.getStringExtra("token");
//Log.w("MainActivity", "Received token: " + token);
webView.evaluateJavascript("javascript:window.dispatchEvent(new CustomEvent('androidTokenReceived', { detail: '" + tokenResult + "' }));", null);
} else {
tokenResult = "";
// Google login was cancelled or failed. Do nothing or log a message.
// The 'intent' might be null here, so avoid accessing it.
//android.util.Log.w("MainActivity", "Google login cancelled or failed.");
}
} else if (requestCode == 0) { // This is for the file chooser
if (fileChooserCallback != null) {
Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData();
fileChooserCallback.onReceiveValue(result != null ? new Uri[]{result} : null);
fileChooserCallback = null;
}
}
}
private void handleURI(String uri) {
if (uri != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(uri.replaceFirst("^blob:", "")));
startActivity(i);
}
}
public class WebAppInterface {
@JavascriptInterface
public void startGoogleLogin() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivityForResult(intent, LOGIN_REQUEST_CODE);
}
@JavascriptInterface
public String getLoginToken() {
//Log.w("getLoginToken", "getLoginToken token: " + tokenResult);
return tokenResult;
}
@JavascriptInterface
public void savePdf(String base64Data, String filename) {
try {
byte[] pdfAsBytes = Base64.decode(base64Data, 0);
boolean isSaved = false;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
Uri uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
if (uri != null) {
try (OutputStream outputStream = resolver.openOutputStream(uri)) {
outputStream.write(pdfAsBytes);
isSaved = true;
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, filename);
try (FileOutputStream os = new FileOutputStream(file)) {
os.write(pdfAsBytes);
isSaved = true;
} catch (IOException e) {
e.printStackTrace();
}
}
if (isSaved) {
runOnUiThread(() -> Toast.makeText(MainActivity.this, "PDF guardado en Descargas", Toast.LENGTH_LONG).show());
} else {
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error al guardar el PDF", Toast.LENGTH_LONG).show());
}
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show());
}
}
}
}
@@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<vector
android:height="108dp"
android:width="108dp"
android:viewportHeight="108"
android:viewportWidth="108"
xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z"/>
<path android:fillColor="#00000000" android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
</vector>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,16 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.TurnosXpress" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor">@color/wine_darkest</item>
<!-- Customize your theme here. -->
</style>
</resources>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="wine_darkest">#FF330080</color>
</resources>
@@ -0,0 +1,4 @@
<resources>
<string name="app_name">TurnosXpress</string>
<string name="default_web_client_id">252287289364-bu8mquhttsaa282egh8su2sumvkjqe58.apps.googleusercontent.com</string>
</resources>
@@ -0,0 +1,16 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.TurnosXpress" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor">@color/wine_darkest</item>
<!-- Customize your theme here. -->
</style>
</resources>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older that API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>
@@ -0,0 +1,17 @@
package com.hdrdevs.turnosxpress;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
+6
View File
@@ -0,0 +1,6 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '8.9.1' apply false
id 'com.android.library' version '8.9.1' apply false
id 'com.google.gms.google-services' version '4.3.10' apply false
}
@@ -0,0 +1,23 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.defaults.buildfeatures.buildconfig=true
android.nonFinalResIds=false
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+252
View File
@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+16
View File
@@ -0,0 +1,16 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "TurnosXpress"
include ':app'
+11
View File
@@ -0,0 +1,11 @@
PORT = 4000
MONGO_URI = mongodb://horacio:frx8us2w@localhost:20215/turnosxpress
TENANCY_OCID = ocid1.tenancy.oc1..aaaaaaaaauyqhe53wuopce3w4f4n6bbrwq4oagkdc5iz5fbgdk2yqqzrkhoa
USER_OCID = ocid1.user.oc1..aaaaaaaaogwd4dyl4kgxbqaoorck2yjq7dvb5nyd3bijffwmesq72hqy3qha
FINGERPRINT = 24:2e:45:e0:70:1a:7e:cf:c3:db:a2:db:eb:0a:21:ac
PRIVATE_KEY_PATH=./keys/oci_api_key_rsa.pem
NAMESPACE = grvzezwnyhx9
BUCKET_NAME = tx-files
RATE_LIMIT_WINDOW_MINUTES = 15
RATE_LIMIT_MAX_REQUESTS = 100
JWT_SECRET = k34lklJ4HKJ2j3kj@kl23
+11
View File
@@ -0,0 +1,11 @@
PORT = 4000
MONGO_URI = mongodb://txuser:hdR2102Frx8us2WkuN21quAn12@mongodb:27017/turnosxpress
TENANCY_OCID = ocid1.tenancy.oc1..aaaaaaaaauyqhe53wuopce3w4f4n6bbrwq4oagkdc5iz5fbgdk2yqqzrkhoa
USER_OCID = ocid1.user.oc1..aaaaaaaaogwd4dyl4kgxbqaoorck2yjq7dvb5nyd3bijffwmesq72hqy3qha
FINGERPRINT = 24:2e:45:e0:70:1a:7e:cf:c3:db:a2:db:eb:0a:21:ac
PRIVATE_KEY_PATH=./keys/oci_api_key_rsa.pem
NAMESPACE = grvzezwnyhx9
BUCKET_NAME = tx-files
RATE_LIMIT_WINDOW_MINUTES = 15
RATE_LIMIT_MAX_REQUESTS = 100
JWT_SECRET = k34lklJ4HKJ2j3kj@kl23
+11
View File
@@ -0,0 +1,11 @@
PORT = 4000
MONGO_URI = mongodb://horacio:frx8us2w@mongodb:27017/turnosxpress
TENANCY_OCID = ocid1.tenancy.oc1..aaaaaaaaauyqhe53wuopce3w4f4n6bbrwq4oagkdc5iz5fbgdk2yqqzrkhoa
USER_OCID = ocid1.user.oc1..aaaaaaaaogwd4dyl4kgxbqaoorck2yjq7dvb5nyd3bijffwmesq72hqy3qha
FINGERPRINT = 24:2e:45:e0:70:1a:7e:cf:c3:db:a2:db:eb:0a:21:ac
PRIVATE_KEY_PATH=./keys/oci_api_key_rsa.pem
NAMESPACE = grvzezwnyhx9
BUCKET_NAME = tx-files
RATE_LIMIT_WINDOW_MINUTES = 15
RATE_LIMIT_MAX_REQUESTS = 100
JWT_SECRET = k34lklJ4HKJ2j3kj@kl23
+38
View File
@@ -0,0 +1,38 @@
# --- Etapa 1: Build ---
FROM node:20-alpine AS builder
WORKDIR /app
# Instalar dependencias de desarrollo
COPY package*.json ./
RUN npm install
# Copiar el código fuente y archivos de entorno
COPY . .
COPY .env* .
# Compilar TypeScript
RUN npm run build
# --- Etapa 2: Runtime mínimo ---
FROM node:20-alpine
WORKDIR /app
# Instalar solo dependencias de producción
COPY package*.json ./
RUN npm install --omit=dev
# Copiar la carpeta compilada desde la etapa de build
COPY --from=builder /app/dist ./dist
# Copiar archivos de entorno a la raíz /app
COPY --from=builder /app/.env* ./
# Copiar la carpeta de claves
COPY --from=builder /app/keys ./keys
EXPOSE 4000
# Comando de inicio que lanza tanto el server como el client
CMD [ "sh", "-c", "npm --prefix /app start" ]
+29
View File
@@ -0,0 +1,29 @@
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDHCcx/dF07YGeW
3UQpnEFtaJwxg5cU89nR7OZwssajp99l9oL75uw2tNGeEVFMADiW7K4ie36xsFqT
irt86arUNGX1qnZlfi8BtnXDmGgcZ8ZL7ClhXJvXAJ1Z8RGYuz8sXibhwL7RqBB/
y3W128CPe34U2Ohz3AfqflpKY3JYILSGRMIgPC3BjJL7O03IXxxTZ8BORyeJf2nP
7t4BqOqYveRiXMNQEhl553EncS6KZdj9iCwFCdGB69woOW2q/AJ4B4pWX7yZKgVB
yGfbTGIjSQ3lcBWG9Ntof8ypyd4Qi8sDLv2bnk6u9Ddh29Fh5MzCpGP/+1gwy/w+
EZm2Wx2/AgMBAAECggEACHnSLmKfWRjKYIIiAHRJ1FBo8lzXBrU5reGyOyi0d8yo
IUNFoazcRe9zoRETZAf7C5ue8L355QmMWeMbB9SQNJgvTVkJ0K72bn1oIhZakfcY
r9ap48kEo+ZqolAMk/NJWz4pLAzqs1U+WqAomOrM65nygmMYRwge2C1dnUmt2V3R
Kvi+sStI0iL8PUO9g4LofpzfIjiLSL9KrihqrgB6gZ3nUI87KNUsVDc5waJMF+kx
Wlo8ncsd+76w6exOO5nE+N6yUhM6HOZhOIYel0MgNAJE7899YNuQcqpoeEIxUZea
lO9ZI7fYgsE1jYZ978YzSCCxYB6dX3W5wZ2zsnU7YQKBgQD73ZQWFC3pcf1qgGzP
yo2s0GEw/zsv1CRh2V3CB3/8FY5/iPh0Ztsd3k+324pL2Pg35C9HhtL6v6ESm4EW
KAs1CsI4LVWYHcDwXbywOLuuIdY9yDxmvjy0ZXtkqmAP3T9Jl39STavUAJ66sbqw
YLqFWGpvZgmHnsLfSx6MStg6nwKBgQDKTjkO0P/xWWhC3AKw4L9Ju56MFvvuDNe6
VaZzfnbayDBVMpA57gfVrDyIV2ixDHVLhvCRsI1Mbd7K5l1smjlqGi31Xe6nB/xT
cYWJvE5PVg48uqFzGQxsVnU0ffA6H7Tghk8tyGBB99G0ouqVlTP3bYfsuth3uWS+
5UU2eCFo4QKBgBzoZ7DJDCP5I17v8o0+8FffauhWwxJQRQS+EBbPCY+DYeGddPbX
P1sEQx4VIqBl/Mddd1e8T8bb677Y/k3utqqV24jbGzHkaFquR5PqTxBDbfWVX+li
+FC0PR9mtrPbbwIhU0m9BHXGxHElKQpJb98SMNUsXvej7zX1x0HO7VZ9AoGAWSJL
225URjc5S7P574qmXUsv2NNLnp/D8NJJ6zr+DPkE6pTDnPJ2OzuO1BeHBfLSPzuu
BNK//rut3MHQycfNoiT0uNXxD2DiWLV8u6ne6u+kiDdGaRrRMW6KZ11RmZpcrEwg
2LAfURFqMOdS6iL56Xs11ySfuWhSrhUAALa/KaECgYA+i8TlQjxOyjYlyVjnvLN0
IE+UvwRk+Iz2FUIP9YRsscmpZT3UFI9EYt08Vj4YHjTGEbFNRGxaGXMKUmDBtfg7
HPeo6M9AhZfP++kc4oUFd2SCIQ68U5qz+qaNQz6ivnbQQsbGCKE2yeg9+U+m7YC3
HO52419TG1+8xf9hZODkSQ==
-----END PRIVATE KEY-----
OCI_API_KEY
+4572
View File
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
{
"name": "files",
"version": "1.0.0",
"main": "index.js",
"type": "commonjs",
"scripts": {
"dev": "ts-node src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^17.2.2",
"express": "^5.1.0",
"express-rate-limit": "^8.1.0",
"helmet": "^8.1.0",
"mongoose": "^8.18.2",
"multer": "^2.0.2",
"oci-sdk": "^2.117.1",
"sharp": "^0.34.4"
},
"devDependencies": {
"@types/cors": "^2.8.19",
"@types/express": "^5.0.3",
"@types/multer": "^2.0.0",
"@types/node": "^24.5.2",
"nodemon": "^3.1.10",
"ts-node": "^10.9.2",
"typescript": "^5.9.2"
}
}
+21
View File
@@ -0,0 +1,21 @@
import express from "express";
import helmet from "helmet";
import cors from "cors";
import archivosRoutes from "./routes/archivos";
const app = express();
app.use(helmet());
app.use(cors());
app.use(express.json()); // por si mandás JSON en otras rutas
app.use("/", archivosRoutes);
// manejo básico de errores
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error(err);
if (res.headersSent) return next(err);
res.status(err.status ?? 500).json({ error: err.message ?? "Error interno" });
});
export default app;
@@ -0,0 +1,48 @@
import type { Request, Response } from "express";
import * as oracleService from "../services/oracleStorageService";
const BUCKET = process.env.BUCKET_NAME!;
if (!BUCKET) throw new Error("Faltan variables de entorno: BUCKET_NAME");
const streamToBuffer = async (
stream: ReadableStream<any> | NodeJS.ReadableStream
): Promise<Buffer> => {
if ("getReader" in stream) {
// Es un ReadableStream web
const reader = stream.getReader();
const chunks: Uint8Array[] = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));
} else {
// Es un NodeJS ReadableStream
const chunks: Buffer[] = [];
return new Promise((resolve, reject) => {
stream.on("data", (chunk) =>
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
);
stream.on("end", () => resolve(Buffer.concat(chunks)));
stream.on("error", reject);
});
}
};
export const downloadFile = async (req: Request, res: Response) => {
try {
const { nombre } = req.params;
if (!nombre) return res.status(400).json({ error: "Falta parámetro nombre" });
const obj = await oracleService.descargarArchivo(BUCKET, nombre);
// obj.value es un ReadableStream web estándar
const body: Buffer = await streamToBuffer(obj.value);
res.setHeader("Content-Disposition", `attachment; filename="${nombre}"`);
res.send(body);
} catch (err) {
console.error("Error en downloadArchivo:", err);
res.status(500).json({ error: "Error al descargar archivo" });
}
};
@@ -0,0 +1,36 @@
import type { Request, Response } from "express";
import DataProfile from "../models/dataprofile";
import { processFile } from "../services/processFile";
import { validateOrganization } from "../services/validateOrganization";
import type { FileUploadParams } from "../models/types";
export const uploadOrganizationFile = async (req: Request, res: Response) => {
try {
const data = await validateOrganization(req, res);
const procesados: FileUploadParams[] = [];
for (const file of data.files) {
const result = await processFile(file);
const { objectName, originalName, bufferToUpload, mimeType } = result;
await DataProfile.create({
objectName,
originalName,
size: bufferToUpload.length,
mimeType,
userId: data.sessionUser,
organizationId: data.organizationId,
});
procesados.push({ originalName, objectName });
}
return res.status(200).json({
message: `${procesados.length} archivos subidos y registrados`,
files: procesados,
});
} catch (err) {
console.error("Error en uploadArchivos:", err);
return res.status(500).json({ error: "Error al subir archivos" });
}
};
+22
View File
@@ -0,0 +1,22 @@
import dotenv from "dotenv";
dotenv.config();
import mongoose from "mongoose";
import app from "./app";
const PORT = process.env.PORT ?? 4000;
const MONGO_URI = `${process.env.MONGO_URI}`;
(async () => {
try {
await mongoose.connect(MONGO_URI);
console.log("MongoDB conectada");
} catch (err) {
console.error("Error conectando MongoDB:", err);
process.exit(1);
}
app.listen(PORT, () => {
console.log(`Servidor corriendo en puerto ${PORT}`);
});
})();
+26
View File
@@ -0,0 +1,26 @@
import type { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) throw new Error("Falta JWT_SECRET en .env");
export interface AuthRequest extends Request {
user?: any; // Puedes tiparlo mejor según tu payload
}
export const verifyToken = (req: AuthRequest, res: Response, next: NextFunction) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).json({ error: "Token no proporcionado" });
}
const token = authHeader.split(" ")[1];
try {
const decoded = jwt.verify(`${token}`, JWT_SECRET);
req.user = decoded; // Puedes guardar el payload en req.user
next();
} catch (err) {
return res.status(401).json({ error: "Token inválido" });
}
};
@@ -0,0 +1,12 @@
import rateLimit from "express-rate-limit";
const windowMs = (parseInt(process.env.RATE_LIMIT_WINDOW_MINUTES ?? "15", 10) || 15) * 60 * 1000;
const max = parseInt(process.env.RATE_LIMIT_MAX_REQUESTS ?? "100", 10) || 100;
export const archivosRateLimiter = rateLimit({
windowMs,
max,
standardHeaders: true,
legacyHeaders: false,
message: "Demasiadas solicitudes, por favor intente más tarde.",
});
+11
View File
@@ -0,0 +1,11 @@
import mongoose, { Schema, Document } from "mongoose";
export interface ICompany extends Document {
name: string;
}
const CompanySchema = new Schema<ICompany>({
name: { type: String, required: true },
});
export default mongoose.model<ICompany>("Companie", CompanySchema);
+29
View File
@@ -0,0 +1,29 @@
import mongoose, { Schema, Document } from "mongoose";
export interface IFile extends Document {
objectName: string;
originalName: string;
size: number;
mimeType: string;
userId: string;
organizationId: string;
employeeId: string;
serviceId: string;
appointmentId: string;
createdAt: Date;
}
const DataFileSchema = new Schema<IFile>({
objectName: { type: String, required: true },
originalName: { type: String, required: true },
size: { type: Number, required: true },
mimeType: { type: String, required: true },
userId: { type: String, required: false },
organizationId: { type: String, required: false },
employeeId: { type: String, required: false },
serviceId: { type: String, required: false },
appointmentId: { type: String, required: false },
createdAt: { type: Date, default: Date.now },
});
export default mongoose.model<IFile>("File", DataFileSchema);
+14
View File
@@ -0,0 +1,14 @@
import mongoose, { Schema, Document } from "mongoose";
export interface IEmployee extends Document {
name: string;
userId: Schema.Types.ObjectId;
companyId: Schema.Types.ObjectId;
}
const EmployeeSchema = new Schema<IEmployee>({
userId: { type: Schema.Types.ObjectId, required: true, ref: "User" },
companyId: { type: Schema.Types.ObjectId, required: true, ref: "Companie" },
});
export default mongoose.model<IEmployee>("Employee", EmployeeSchema);
+4
View File
@@ -0,0 +1,4 @@
export type FileUploadParams = {
originalName: string;
objectName: string;
};
+13
View File
@@ -0,0 +1,13 @@
import mongoose, { Schema, Document } from "mongoose";
export interface IUser extends Document {
firstName: string;
lastName: string;
}
const UserSchema = new Schema<IUser>({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
});
export default mongoose.model<IUser>("User", UserSchema);
+23
View File
@@ -0,0 +1,23 @@
import { Router } from "express";
import multer from "multer";
import { archivosRateLimiter } from "../middlewares/rateLimiter";
import { downloadFile } from "../controllers/downloadController";
import { uploadOrganizationFile } from "../controllers/uploadOrganizationController";
import { verifyToken } from "../middlewares/auth";
const upload = multer(); // memoria
const router = Router();
router.post(
"/upload-by-organization",
verifyToken,
archivosRateLimiter,
upload.array("files"),
uploadOrganizationFile
);
// GET /archivos/download/:nombre (nombre = objectName guardado en DB)
router.get("/download/:nombre", archivosRateLimiter, downloadFile);
export default router;
@@ -0,0 +1,51 @@
import sharp from "sharp";
const MAX_SIZE_BYTES = 512 * 1024; // 512 KB
/**
* Convierte una imagen a WebP y asegura que no supere MAX_SIZE_BYTES.
* Mantiene el aspect ratio y ajusta calidad si la reducción supera el 50%.
* @param inputBuffer Buffer con la imagen original
* @returns Buffer de la imagen en WebP
*/
export const processImageToWebP = async (inputBuffer: Buffer): Promise<Buffer> => {
let quality = 80;
let width: number | null = null;
const metadata = await sharp(inputBuffer).metadata();
const originalWidth = metadata.width || 0;
if (!originalWidth) throw new Error("No se pudo obtener el ancho de la imagen original");
let outputBuffer: Buffer;
while (true) {
const transformer = sharp(inputBuffer).webp({ quality });
if (width) {
transformer.resize({ width, withoutEnlargement: true });
}
outputBuffer = await transformer.toBuffer();
if (outputBuffer.length <= MAX_SIZE_BYTES) break;
// Reducimos width progresivamente
if (!width) {
width = Math.floor(originalWidth * 0.9); // reducimos 10% la primera vez
} else {
width = Math.floor(width * 0.9); // reducciones sucesivas
}
// Calculamos porcentaje de reducción respecto al tamaño original
const reductionPercent = (originalWidth - width) / originalWidth;
// Si se redujo más del 50%, empezamos a bajar la calidad
if (reductionPercent >= 0.5 && quality > 40) {
quality -= 5;
width = null; // volvemos a tamaño original pero con menor calidad
}
// Evitamos bucle infinito
if (width && width < 10) break;
}
return outputBuffer;
};
@@ -0,0 +1,49 @@
import { readFileSync } from "fs";
import { SimpleAuthenticationDetailsProvider, Region } from "oci-common";
import { ObjectStorageClient } from "oci-objectstorage";
const userOcId = process.env.USER_OCID!;
const tenancyOcId = process.env.TENANCY_OCID!;
const privateKeyPath = process.env.PRIVATE_KEY_PATH!;
const fingerprint = process.env.FINGERPRINT!;
const namespace = process.env.NAMESPACE!;
if (!userOcId || !tenancyOcId || !privateKeyPath || !fingerprint || !namespace) {
throw new Error(
"Faltan variables de entorno de Oracle (USER_OCID, TENANCY_OCID, PRIVATE_KEY_PATH, FINGERPRINT, NAMESPACE)"
);
}
const privateKey = readFileSync(privateKeyPath, "utf-8");
const region = Region.fromRegionId("sa-saopaulo-1");
const provider = new SimpleAuthenticationDetailsProvider(
tenancyOcId,
userOcId,
fingerprint,
privateKey,
null,
region
);
const client = new ObjectStorageClient({ authenticationDetailsProvider: provider });
export const subirArchivo = async (bucketName: string, objectName: string, data: Buffer) => {
const request = {
namespaceName: namespace,
bucketName,
objectName,
putObjectBody: data,
};
return client.putObject(request);
};
export const descargarArchivo = async (bucketName: string, objectName: string) => {
const request = {
namespaceName: namespace,
bucketName,
objectName,
};
return client.getObject(request);
};
+40
View File
@@ -0,0 +1,40 @@
import { processImageToWebP } from "./imageCompresionService";
import * as oracleService from "../services/oracleStorageService";
const BUCKET = process.env.BUCKET_NAME!;
if (!BUCKET) throw new Error("Faltan variables de entorno: BUCKET_NAME");
export type ProcessFileResult = {
objectName: string;
originalName: string;
bufferToUpload: Buffer<ArrayBufferLike>;
mimeType: string;
};
export const processFile = async (file: Express.Multer.File) => {
let bufferToUpload = file.buffer;
let mimeType = file.mimetype;
const originalName = file.originalname;
// Si es imagen, procesar con sharp (resize + convertir a jpeg)
if (mimeType.startsWith("image/")) {
bufferToUpload = await processImageToWebP(bufferToUpload);
mimeType = "image/webp";
}
// Generar objectName único para evitar colisiones
const timestamp = Date.now();
// escapamos/normalizamos el originalName ligeramente
const safeOriginal = originalName.replace(/\s+/g, "_");
const objectName = `${timestamp}-${safeOriginal}`;
// Subir a Oracle
await oracleService.subirArchivo(BUCKET, objectName, bufferToUpload);
return {
objectName,
originalName,
bufferToUpload,
mimeType,
};
};
@@ -0,0 +1,14 @@
import type { Request, Response } from "express";
export type ValidateFilesResult = {
files: Express.Multer.File[];
};
export const validateFiles = async (req: Request, res: Response): Promise<ValidateFilesResult> => {
const files = req.files as Express.Multer.File[] | undefined;
if (!files || files.length === 0) throw new Error("No se encontraron archivos");
return {
files,
};
};
@@ -0,0 +1,47 @@
import type { Request, Response } from "express";
import { validateFiles } from "./validateFiles";
import { validateSessionUser } from "./validateUser";
import CompanySchema from "../models/companies";
import EmployeeSchema from "../models/employees";
export type ValidateOrganizationResult = {
files: Express.Multer.File[];
organizationId: string;
sessionUser: string;
};
export const validateOrganization = async (
req: Request,
res: Response
): Promise<ValidateOrganizationResult> => {
const filesResul = await validateFiles(req, res);
const { sessionUser, organizationId } = req.body;
if (!organizationId || !sessionUser) {
throw new Error("Faltan campos obligatorios: userId o profileId");
}
await validateSessionUser(sessionUser);
const company = await CompanySchema.findOne({
_id: organizationId,
});
if (!company) {
throw new Error("No se ha encontrado la organización");
}
const employee = await EmployeeSchema.findOne({
userId: sessionUser,
companyId: organizationId,
});
if (!employee) {
throw new Error("El usuario no pertenece a la organización");
}
return {
files: filesResul.files,
organizationId,
sessionUser,
};
};
+16
View File
@@ -0,0 +1,16 @@
import mongoose from "mongoose";
import UserSchema from "../models/users";
export const validateSessionUser = async (sessionUser: string): Promise<void> => {
const user = await UserSchema.findOne({
_id: new mongoose.Types.ObjectId(sessionUser),
});
console.log(new mongoose.Types.ObjectId(sessionUser));
if (!user) {
throw new Error(
"No se ha encontrado el usuario o no tiene permisos para realizar esta acción"
);
}
};
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es2020",
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"outDir": "./dist",
"sourceMap": true,
"declaration": true,
"declarationMap": true,
// Stricter Typechecking
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
},
"include": ["src"]
}
+11
View File
@@ -0,0 +1,11 @@
#/bin/bash
docker run -d \
--name mongodb \
--restart unless-stopped \
-e MONGO_INITDB_ROOT_USERNAME=root \
-e MONGO_INITDB_ROOT_PASSWORD=frx8us2w \
-e MONGO_INITDB_DATABASE=turnosxpress \
-v $(pwd)/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro \
-p 20215:27017 \
mongo:4.2.14
+190
View File
@@ -0,0 +1,190 @@
{
"_id" : ObjectId("6782e54ff6c386d803fece68"),
"companyId" : ObjectId("676eb70d0a0a65d36507ac7c"),
"serviceId" : ObjectId("676ebd470a0a65d36507ad85"),
"employeeId" : ObjectId("676eb70d0a0a65d36507ac87"),
"clientId" : ObjectId("6782d5431fd7d07bcf7c0b24"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"start" : ISODate("2025-01-14T12:00:00.000+0000"),
"startHour" : NumberInt(9),
"endHour" : NumberInt(10),
"dateDay" : ISODate("2025-01-14T03:00:00.000+0000"),
"price" : NumberInt(7000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "",
"creationDate" : ISODate("2025-01-11T21:40:31.656+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("6788481cd02ee20f7795b84f"),
"companyId" : ObjectId("676eb70d0a0a65d36507ac7c"),
"serviceId" : ObjectId("676ebd470a0a65d36507ad85"),
"employeeId" : ObjectId("676eb70d0a0a65d36507ac87"),
"clientId" : ObjectId("676fff5a2e7507337ee33e39"),
"userId" : ObjectId("6712698f2011184a1f1d5d62"),
"start" : ISODate("2025-01-16T12:00:00.000+0000"),
"startHour" : NumberInt(9),
"endHour" : NumberInt(10),
"dateDay" : ISODate("2025-01-16T03:00:00.000+0000"),
"price" : NumberInt(7000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "",
"creationDate" : ISODate("2025-01-15T23:43:24.506+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67898c3e746b34d48c047fa9"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"serviceId" : ObjectId("672fc1479c43f150d7bf7ae5"),
"employeeId" : ObjectId("672b5e582775969c6068306a"),
"clientId" : ObjectId("67898c3e746b34d48c047fa3"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"start" : ISODate("2025-01-20T11:00:00.000+0000"),
"startHour" : NumberInt(8),
"endHour" : NumberInt(9),
"dateDay" : ISODate("2025-01-20T03:00:00.000+0000"),
"price" : NumberInt(5000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "",
"creationDate" : ISODate("2025-01-16T22:46:22.120+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67898c87746b34d48c04803a"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"serviceId" : ObjectId("672972f0a587237908ab79b7"),
"employeeId" : ObjectId("6713c762b65ea3558a1e87cf"),
"clientId" : ObjectId("67898c3e746b34d48c047fa3"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"start" : ISODate("2025-01-21T11:00:00.000+0000"),
"startHour" : NumberInt(8),
"endHour" : NumberInt(10),
"dateDay" : ISODate("2025-01-21T03:00:00.000+0000"),
"price" : NumberInt(10000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "",
"creationDate" : ISODate("2025-01-16T22:47:35.621+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67e7227c5d69e33b7d300921"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"serviceId" : ObjectId("672972f0a587237908ab79b7"),
"employeeId" : ObjectId("6713c762b65ea3558a1e87cf"),
"clientId" : ObjectId("67898c3e746b34d48c047fa3"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"start" : ISODate("2025-03-28T11:00:00.000+0000"),
"startHour" : NumberInt(8),
"endHour" : NumberInt(10),
"dateDay" : ISODate("2025-03-28T03:00:00.000+0000"),
"price" : NumberInt(10000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "",
"creationDate" : ISODate("2025-03-28T22:28:12.126+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67ebd6b20c55bcbc2ac36da1"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"serviceId" : ObjectId("672972f0a587237908ab79b7"),
"employeeId" : ObjectId("6713c762b65ea3558a1e87cf"),
"clientId" : ObjectId("67898c3e746b34d48c047fa3"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"start" : ISODate("2025-04-01T22:00:00.000+0000"),
"startHour" : NumberInt(19),
"endHour" : NumberInt(21),
"dateDay" : ISODate("2025-04-01T03:00:00.000+0000"),
"price" : NumberInt(10000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "",
"creationDate" : ISODate("2025-04-01T12:06:10.578+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67f1477040a2594a7295430b"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"serviceId" : ObjectId("672972f0a587237908ab79b7"),
"employeeId" : ObjectId("6713c762b65ea3558a1e87cf"),
"clientId" : ObjectId("67898c3e746b34d48c047fa3"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"start" : ISODate("2025-04-05T18:00:00.000+0000"),
"startHour" : NumberInt(15),
"endHour" : 15.016666666666667,
"dateDay" : ISODate("2025-04-05T03:00:00.000+0000"),
"price" : NumberInt(1000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "Cambio de precio",
"creationDate" : ISODate("2025-04-05T15:08:32.456+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67f40b42d406eaf59e73ae9f"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"serviceId" : ObjectId("672972f0a587237908ab79b7"),
"employeeId" : ObjectId("6713c762b65ea3558a1e87cf"),
"clientId" : ObjectId("67898c3e746b34d48c047fa3"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"start" : ISODate("2025-04-08T00:00:00.000+0000"),
"startHour" : NumberInt(21),
"endHour" : NumberInt(23),
"dateDay" : ISODate("2025-04-07T03:00:00.000+0000"),
"price" : NumberInt(10000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "",
"creationDate" : ISODate("2025-04-07T17:28:34.274+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67f436c2646c36c7596a6fee"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"serviceId" : ObjectId("672972f0a587237908ab79b7"),
"employeeId" : ObjectId("6713c762b65ea3558a1e87cf"),
"clientId" : ObjectId("67898c3e746b34d48c047fa3"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"start" : ISODate("2025-04-08T11:00:00.000+0000"),
"startHour" : NumberInt(8),
"endHour" : NumberInt(10),
"dateDay" : ISODate("2025-04-08T03:00:00.000+0000"),
"price" : NumberInt(10000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "",
"creationDate" : ISODate("2025-04-07T20:34:10.743+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67f6c091bb8328e7b4e47b23"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"serviceId" : ObjectId("672972f0a587237908ab79b7"),
"employeeId" : ObjectId("6713c762b65ea3558a1e87cf"),
"clientId" : ObjectId("67898c3e746b34d48c047fa3"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"start" : ISODate("2025-04-12T00:00:00.000+0000"),
"startHour" : NumberInt(21),
"endHour" : NumberInt(23),
"dateDay" : ISODate("2025-04-11T03:00:00.000+0000"),
"price" : NumberInt(10000),
"length" : NumberInt(1),
"present" : true,
"payment" : false,
"comments" : "",
"creationDate" : ISODate("2025-04-09T18:46:41.124+0000"),
"__v" : NumberInt(0)
}
+171
View File
@@ -0,0 +1,171 @@
{
"_id" : ObjectId("676fff5a2e7507337ee33e39"),
"userId" : ObjectId("6712698f2011184a1f1d5d62"),
"companyId" : ObjectId("676eb70d0a0a65d36507ac7c"),
"status" : true,
"firstName" : "Horacio",
"lastName" : "Ros",
"phoneNumber" : "23902059",
"phoneAreaCode" : "11",
"email" : "horaciodrs@gmail.com",
"creationDate" : ISODate("2024-12-28T13:38:34.309+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("6782d5431fd7d07bcf7c0b24"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"companyId" : ObjectId("676eb70d0a0a65d36507ac7c"),
"status" : true,
"firstName" : "Esteban",
"lastName" : "Dido",
"phoneNumber" : "12345678",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "tamina9425@pofmagic.com",
"creationDate" : ISODate("2025-01-11T20:32:03.880+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67898c3e746b34d48c047fa3"),
"userId" : ObjectId("676d426e44e778ebd6eaa821"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Esteban",
"lastName" : "Dido",
"phoneNumber" : "23923420",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "tamina9425@pofmagic.com",
"creationDate" : ISODate("2025-01-16T22:46:22.094+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc2371356fb915d616ce00"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Uno",
"phoneNumber" : "123354564",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente1@gmail.com",
"creationDate" : ISODate("2025-04-13T20:49:53.147+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc2383356fb915d616ce2a"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Dos",
"phoneNumber" : "12345678",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente2@gmail.com",
"creationDate" : ISODate("2025-04-13T20:50:11.882+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc239b356fb915d616ce5a"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Tres",
"phoneNumber" : "12345678",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente3@gmail.com",
"creationDate" : ISODate("2025-04-13T20:50:35.302+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc23b2356fb915d616ce96"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Cuatro",
"phoneNumber" : "12345678",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente4@gmail.com",
"creationDate" : ISODate("2025-04-13T20:50:58.790+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc23c5356fb915d616ceba"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Cinco",
"phoneNumber" : "12345678",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente5@gmail.com",
"creationDate" : ISODate("2025-04-13T20:51:17.656+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc23d7356fb915d616cee4"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Seis",
"phoneNumber" : "12345678",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente6@gmail.com",
"creationDate" : ISODate("2025-04-13T20:51:35.547+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc23eb356fb915d616cf1a"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Siete",
"phoneNumber" : "1234566778",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente7@gmail.com",
"creationDate" : ISODate("2025-04-13T20:51:55.785+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc23ff356fb915d616cf44"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Ocho",
"phoneNumber" : "12345678",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente8@gmail.com",
"creationDate" : ISODate("2025-04-13T20:52:15.718+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc2414356fb915d616cf6e"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Nueve",
"phoneNumber" : "12345678",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente9@gmail.com",
"creationDate" : ISODate("2025-04-13T20:52:36.265+0000"),
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("67fc2427356fb915d616cfa4"),
"companyId" : ObjectId("6713c762b65ea3558a1e87c9"),
"status" : true,
"firstName" : "Cliente",
"lastName" : "Diez",
"phoneNumber" : "12345678",
"phoneCountryCode" : "549",
"phoneAreaCode" : "11",
"email" : "cliente10@gmail.com",
"creationDate" : ISODate("2025-04-13T20:52:55.558+0000"),
"__v" : NumberInt(0)
}

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