Actualizar server.js
This commit is contained in:
282
server.js
282
server.js
@@ -7,15 +7,9 @@ import pg from "pg";
|
||||
const { Pool } = pg;
|
||||
const app = express();
|
||||
|
||||
// =========================
|
||||
// MIDDLEWARES
|
||||
// =========================
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
// =========================
|
||||
// VARIABLES DE ENTORNO
|
||||
// =========================
|
||||
const {
|
||||
DATABASE_URL,
|
||||
JWT_SECRET,
|
||||
@@ -25,28 +19,24 @@ const {
|
||||
} = process.env;
|
||||
|
||||
if (!DATABASE_URL || !JWT_SECRET) {
|
||||
console.error("❌ ERROR FATAL: Faltan variables DATABASE_URL o JWT_SECRET");
|
||||
console.error("❌ ERROR FATAL: Faltan variables de entorno");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// =========================
|
||||
// CONEXIÓN DB
|
||||
// =========================
|
||||
const pool = new Pool({
|
||||
connectionString: DATABASE_URL,
|
||||
ssl: false
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 🧠 CEREBRO DE AUTO-ACTUALIZACIÓN (NUEVO)
|
||||
// 🧠 AUTO-ACTUALIZACIÓN DE BASE DE DATOS (AISLAMIENTO DE DATOS)
|
||||
// ==========================================
|
||||
// Esta función se ejecuta sola al arrancar y repara la DB
|
||||
async function autoUpdateDB() {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
console.log("🔄 Verificando salud de la base de datos...");
|
||||
console.log("🔄 Revisando estructura de base de datos...");
|
||||
|
||||
// 1. Crear tablas base si no existen
|
||||
// 1. Crear tablas básicas
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -59,7 +49,6 @@ async function autoUpdateDB() {
|
||||
is_verified BOOLEAN DEFAULT FALSE,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS login_codes (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||
@@ -70,7 +59,16 @@ async function autoUpdateDB() {
|
||||
expires_at TIMESTAMP NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS guilds (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL, -- Ya no es UNIQUE globalmente, solo por dueño
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS user_guilds (
|
||||
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||
guild_id INT REFERENCES guilds(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (user_id, guild_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS services (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||
@@ -81,35 +79,56 @@ async function autoUpdateDB() {
|
||||
notes TEXT,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS guilds (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT UNIQUE NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_guilds (
|
||||
user_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||
guild_id INT REFERENCES guilds(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (user_id, guild_id)
|
||||
);
|
||||
`);
|
||||
|
||||
// 2. PARCHE INTELIGENTE: Añadir columna 'role' si falta
|
||||
// Este bloque es la CLAVE: comprueba si existe 'role', si no, la crea.
|
||||
// 2. AÑADIR COLUMNAS FALTANTES (PARCHES)
|
||||
|
||||
// Parche A: Roles
|
||||
await client.query(`
|
||||
DO $$
|
||||
BEGIN
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='role') THEN
|
||||
ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'operario';
|
||||
RAISE NOTICE '✅ Columna ROLE añadida automáticamente';
|
||||
END IF;
|
||||
END $$;
|
||||
`);
|
||||
|
||||
console.log("✅ Base de datos Sincronizada y Lista.");
|
||||
// Parche B: DUEÑO (owner_id) en Usuarios -> Para saber quién es tu jefe
|
||||
await client.query(`
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='owner_id') THEN
|
||||
ALTER TABLE users ADD COLUMN owner_id INT;
|
||||
-- Si owner_id es NULL, el usuario es su propio jefe (Cuenta Principal)
|
||||
END IF;
|
||||
END $$;
|
||||
`);
|
||||
|
||||
// Parche C: DUEÑO (owner_id) en Gremios -> Para que los gremios sean privados
|
||||
await client.query(`
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='guilds' AND column_name='owner_id') THEN
|
||||
ALTER TABLE guilds ADD COLUMN owner_id INT REFERENCES users(id) ON DELETE CASCADE;
|
||||
END IF;
|
||||
END $$;
|
||||
`);
|
||||
|
||||
// Parche D: DUEÑO (owner_id) en Servicios -> Para que los servicios sean de la empresa
|
||||
await client.query(`
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='owner_id') THEN
|
||||
ALTER TABLE services ADD COLUMN owner_id INT REFERENCES users(id) ON DELETE CASCADE;
|
||||
END IF;
|
||||
END $$;
|
||||
`);
|
||||
|
||||
// 3. LIMPIEZA DE RESTRICCIONES VIEJAS (Si existían)
|
||||
// Esto permite que dos empresas diferentes tengan un gremio con el mismo nombre (ej: "FONTANERIA")
|
||||
try {
|
||||
await client.query(`ALTER TABLE guilds DROP CONSTRAINT IF EXISTS guilds_name_key`);
|
||||
} catch (e) {}
|
||||
|
||||
console.log("✅ DB Sincronizada: Aislamiento de datos activado.");
|
||||
} catch (e) {
|
||||
console.error("❌ Error en auto-actualización:", e);
|
||||
console.error("❌ Error DB:", e);
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
@@ -121,19 +140,25 @@ async function autoUpdateDB() {
|
||||
function normalizePhone(phone) {
|
||||
let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, "");
|
||||
if (!p) return "";
|
||||
if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) {
|
||||
return "+34" + p;
|
||||
}
|
||||
if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) return "+34" + p;
|
||||
return p;
|
||||
}
|
||||
|
||||
function genCode6() {
|
||||
return String(Math.floor(100000 + Math.random() * 900000));
|
||||
}
|
||||
function genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); }
|
||||
|
||||
function signToken(user) {
|
||||
// LÓGICA DE AISLAMIENTO:
|
||||
// Si el usuario tiene owner_id (es empleado), usamos ese ID como "Cuenta Principal".
|
||||
// Si no tiene (es el jefe), usamos su propio ID.
|
||||
const accountId = user.owner_id || user.id;
|
||||
|
||||
return jwt.sign(
|
||||
{ sub: user.id, phone: user.phone, email: user.email, role: user.role || 'operario' },
|
||||
{
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
phone: user.phone,
|
||||
role: user.role || 'operario',
|
||||
accountId: accountId // <--- ESTO ES LA CLAVE DE TODO
|
||||
},
|
||||
JWT_SECRET,
|
||||
{ expiresIn: "30d" }
|
||||
);
|
||||
@@ -144,67 +169,30 @@ function authMiddleware(req, res, next) {
|
||||
const token = h.startsWith("Bearer ") ? h.slice(7) : "";
|
||||
if (!token) return res.status(401).json({ ok: false, error: "No token" });
|
||||
try {
|
||||
const payload = jwt.verify(token, JWT_SECRET);
|
||||
req.user = payload;
|
||||
req.user = jwt.verify(token, JWT_SECRET);
|
||||
next();
|
||||
} catch {
|
||||
return res.status(401).json({ ok: false, error: "Token inválido" });
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// WHATSAPP
|
||||
// =========================
|
||||
async function sendWhatsAppCode(phone, code) {
|
||||
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
|
||||
console.log("⚠️ Evolution no configurado. Código simulado:", code);
|
||||
return { ok: true, skipped: true };
|
||||
}
|
||||
try {
|
||||
const baseUrl = EVOLUTION_BASE_URL.replace(/\/$/, "");
|
||||
const url = `${baseUrl}/message/sendText/${EVOLUTION_INSTANCE}`;
|
||||
|
||||
const body = {
|
||||
number: phone.replace("+", ""),
|
||||
text: `🔐 Tu código IntegraRepara es: *${code}*\n\nNo lo compartas.`
|
||||
};
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const txt = await res.text();
|
||||
console.error("❌ Error Evolution:", txt);
|
||||
return { ok: false };
|
||||
}
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
console.error("❌ Error enviando WhatsApp:", e);
|
||||
return { ok: false };
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// RUTAS
|
||||
// =========================
|
||||
|
||||
// 1. REGISTRO
|
||||
// 1. REGISTRO (Crea un DUEÑO / JEFE)
|
||||
app.post("/auth/register", async (req, res) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const { fullName, phone, address, dni, email, password } = req.body;
|
||||
const p = normalizePhone(phone);
|
||||
if (!fullName || !p || !email || !password) {
|
||||
return res.status(400).json({ ok: false, error: "Faltan datos obligatorios" });
|
||||
}
|
||||
if (!fullName || !p || !email || !password) return res.status(400).json({ ok: false, error: "Faltan datos" });
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
|
||||
await client.query('BEGIN');
|
||||
|
||||
// Verificamos duplicados
|
||||
const checkUser = await client.query("SELECT * FROM users WHERE email = $1 OR phone = $2", [email, p]);
|
||||
let userId;
|
||||
|
||||
@@ -212,16 +200,15 @@ app.post("/auth/register", async (req, res) => {
|
||||
const existing = checkUser.rows[0];
|
||||
if (existing.is_verified) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(409).json({ ok: false, error: "Usuario ya registrado y verificado." });
|
||||
return res.status(409).json({ ok: false, error: "Usuario ya registrado." });
|
||||
}
|
||||
await client.query(
|
||||
"UPDATE users SET full_name=$1, address=$2, dni=$3, password_hash=$4 WHERE id=$5",
|
||||
[fullName, address, dni, passwordHash, existing.id]
|
||||
);
|
||||
// Actualizamos reintento
|
||||
await client.query("UPDATE users SET full_name=$1, address=$2, dni=$3, password_hash=$4 WHERE id=$5", [fullName, address, dni, passwordHash, existing.id]);
|
||||
userId = existing.id;
|
||||
} else {
|
||||
// Insertamos nuevo. owner_id se deja NULL porque ÉL es el jefe.
|
||||
const insert = await client.query(
|
||||
"INSERT INTO users (full_name, phone, address, dni, email, password_hash) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id",
|
||||
"INSERT INTO users (full_name, phone, address, dni, email, password_hash, role, owner_id) VALUES ($1, $2, $3, $4, $5, $6, 'admin', NULL) RETURNING id",
|
||||
[fullName, p, address, dni, email, passwordHash]
|
||||
);
|
||||
userId = insert.rows[0].id;
|
||||
@@ -232,129 +219,120 @@ app.post("/auth/register", async (req, res) => {
|
||||
const expiresAt = new Date(Date.now() + 10 * 60 * 1000);
|
||||
|
||||
await client.query("DELETE FROM login_codes WHERE user_id = $1", [userId]);
|
||||
await client.query(
|
||||
"INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1, $2, $3, $4)",
|
||||
[userId, p, codeHash, expiresAt]
|
||||
);
|
||||
await client.query("INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1, $2, $3, $4)", [userId, p, codeHash, expiresAt]);
|
||||
|
||||
await sendWhatsAppCode(p, code);
|
||||
// Enviar WhatsApp (Simulado si no hay API)
|
||||
if (EVOLUTION_BASE_URL && EVOLUTION_API_KEY) {
|
||||
const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`;
|
||||
await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY },
|
||||
body: JSON.stringify({ number: p.replace("+", ""), text: `🔐 Código IntegraRepara: *${code}*` })
|
||||
}).catch(console.error);
|
||||
} else {
|
||||
console.log("📨 Código simulado:", code);
|
||||
}
|
||||
|
||||
await client.query('COMMIT');
|
||||
res.json({ ok: true, phone: p, msg: "Código enviado" });
|
||||
res.json({ ok: true, phone: p });
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
console.error("Error en Registro:", e);
|
||||
res.status(500).json({ ok: false, error: "Error interno del servidor" });
|
||||
console.error(e);
|
||||
res.status(500).json({ ok: false, error: "Error server" });
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
});
|
||||
|
||||
// 2. VERIFICACIÓN
|
||||
// 2. VERIFICACIÓN & LOGIN
|
||||
app.post("/auth/verify", async (req, res) => {
|
||||
try {
|
||||
const { phone, code } = req.body;
|
||||
const p = normalizePhone(phone);
|
||||
|
||||
const q = await pool.query(`
|
||||
SELECT lc.*, u.id as uid, u.email, u.role
|
||||
FROM login_codes lc
|
||||
JOIN users u ON lc.user_id = u.id
|
||||
WHERE lc.phone=$1 AND lc.consumed_at IS NULL AND lc.expires_at > NOW()
|
||||
ORDER BY lc.created_at DESC LIMIT 1`,
|
||||
[p]
|
||||
);
|
||||
|
||||
if (q.rowCount === 0) return res.status(400).json({ ok: false, error: "Código inválido o expirado" });
|
||||
const q = await pool.query(`SELECT lc.*, u.id as uid, u.email, u.role, u.owner_id FROM login_codes lc JOIN users u ON lc.user_id = u.id WHERE lc.phone=$1 AND lc.consumed_at IS NULL AND lc.expires_at > NOW() ORDER BY lc.created_at DESC LIMIT 1`, [p]);
|
||||
if (q.rowCount === 0) return res.status(400).json({ ok: false, error: "Código inválido" });
|
||||
|
||||
const row = q.rows[0];
|
||||
const valid = await bcrypt.compare(String(code), row.code_hash);
|
||||
|
||||
if (!valid) return res.status(400).json({ ok: false, error: "Código incorrecto" });
|
||||
if (!(await bcrypt.compare(String(code), row.code_hash))) return res.status(400).json({ ok: false, error: "Código incorrecto" });
|
||||
|
||||
await pool.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1", [row.id]);
|
||||
await pool.query("UPDATE users SET is_verified=TRUE WHERE id=$1", [row.uid]);
|
||||
|
||||
const token = signToken({ id: row.uid, email: row.email, phone: p, role: row.role });
|
||||
res.json({ ok: true, token });
|
||||
} catch (e) {
|
||||
console.error("Error Verify:", e);
|
||||
res.status(500).json({ ok: false, error: "Error verificando código" });
|
||||
}
|
||||
res.json({ ok: true, token: signToken({ id: row.uid, email: row.email, phone: p, role: row.role, owner_id: row.owner_id }) });
|
||||
} catch (e) { res.status(500).json({ ok: false, error: "Error verify" }); }
|
||||
});
|
||||
|
||||
// 3. LOGIN
|
||||
app.post("/auth/login", async (req, res) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
const q = await pool.query("SELECT * FROM users WHERE email=$1", [email]);
|
||||
|
||||
if (q.rowCount === 0) return res.status(401).json({ ok: false, error: "Credenciales inválidas" });
|
||||
|
||||
if (q.rowCount === 0) return res.status(401).json({ ok: false, error: "Datos incorrectos" });
|
||||
const u = q.rows[0];
|
||||
const match = await bcrypt.compare(password, u.password_hash);
|
||||
|
||||
if (!match) return res.status(401).json({ ok: false, error: "Credenciales inválidas" });
|
||||
if (!u.is_verified) return res.status(403).json({ ok: false, error: "Cuenta no verificada" });
|
||||
if (!(await bcrypt.compare(password, u.password_hash))) return res.status(401).json({ ok: false, error: "Datos incorrectos" });
|
||||
|
||||
res.json({ ok: true, token: signToken(u) });
|
||||
} catch(e) {
|
||||
console.error("Error Login:", e);
|
||||
res.status(500).json({ ok: false, error: "Error en login" });
|
||||
}
|
||||
} catch(e) { res.status(500).json({ ok: false, error: "Error login" }); }
|
||||
});
|
||||
|
||||
// 4. SERVICIOS (PROTEGIDO)
|
||||
// ==========================================
|
||||
// 🔒 RUTAS PROTEGIDAS (DATOS AISLADOS)
|
||||
// ==========================================
|
||||
|
||||
// GET SERVICIOS (Solo los de MI empresa)
|
||||
app.get("/services", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const q = await pool.query("SELECT * FROM services WHERE user_id=$1 ORDER BY created_at DESC", [req.user.sub]);
|
||||
// Filtramos por owner_id (Mi empresa)
|
||||
const q = await pool.query("SELECT * FROM services WHERE owner_id=$1 ORDER BY created_at DESC", [req.user.accountId]);
|
||||
res.json({ ok: true, services: q.rows });
|
||||
} catch (e) {
|
||||
res.status(500).json({ ok: false, error: "Error al obtener servicios" });
|
||||
}
|
||||
} catch (e) { res.status(500).json({ ok: false, error: "Error servicios" }); }
|
||||
});
|
||||
|
||||
// 5. GESTIÓN DE GREMIOS
|
||||
// GET GREMIOS (Solo los de MI empresa)
|
||||
app.get("/guilds", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const q = await pool.query("SELECT * FROM guilds ORDER BY name ASC");
|
||||
const q = await pool.query("SELECT * FROM guilds WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]);
|
||||
res.json({ ok: true, guilds: q.rows });
|
||||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||||
});
|
||||
|
||||
// POST GREMIOS (Se guardan en MI empresa)
|
||||
app.post("/guilds", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const { name } = req.body;
|
||||
if (!name) return res.status(400).json({ ok: false, error: "Falta nombre" });
|
||||
const q = await pool.query("INSERT INTO guilds (name) VALUES ($1) RETURNING *", [name.toUpperCase()]);
|
||||
|
||||
// Guardamos con el accountId (Mi ID o el de mi jefe)
|
||||
const q = await pool.query("INSERT INTO guilds (name, owner_id) VALUES ($1, $2) RETURNING *", [name.toUpperCase(), req.user.accountId]);
|
||||
res.json({ ok: true, guild: q.rows[0] });
|
||||
} catch (e) { res.status(500).json({ ok: false, error: "Error o gremio duplicado" }); }
|
||||
} catch (e) { res.status(500).json({ ok: false, error: "Gremio duplicado" }); }
|
||||
});
|
||||
|
||||
app.delete("/guilds/:id", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
await pool.query("DELETE FROM guilds WHERE id = $1", [req.params.id]);
|
||||
// Solo borro si el gremio es MÍO
|
||||
await pool.query("DELETE FROM guilds WHERE id = $1 AND owner_id = $2", [req.params.id, req.user.accountId]);
|
||||
res.json({ ok: true });
|
||||
} catch (e) { res.status(500).json({ ok: false, error: e.message }); }
|
||||
});
|
||||
|
||||
// 6. CREAR USUARIO (ADMIN)
|
||||
// CREAR USUARIO (Se vincula a MI empresa)
|
||||
app.post("/admin/users", authMiddleware, async (req, res) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const { fullName, email, password, role, guilds } = req.body;
|
||||
|
||||
if (!email || !password || !fullName) return res.status(400).json({ ok: false, error: "Faltan datos" });
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
const dummyPhone = `manual_${Date.now()}`;
|
||||
const dummyPhone = `manual_${Date.now()}_${Math.floor(Math.random()*1000)}`;
|
||||
|
||||
await client.query('BEGIN');
|
||||
|
||||
// AQUÍ ESTÁ LA MAGIA: owner_id = req.user.accountId
|
||||
// El nuevo usuario pertenece a mi cuenta (yo soy su jefe)
|
||||
const insert = await client.query(
|
||||
`INSERT INTO users (full_name, email, password_hash, role, phone, is_verified)
|
||||
VALUES ($1, $2, $3, $4, $5, TRUE) RETURNING id`,
|
||||
[fullName, email, passwordHash, role || 'operario', dummyPhone]
|
||||
`INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id)
|
||||
VALUES ($1, $2, $3, $4, $5, TRUE, $6) RETURNING id`,
|
||||
[fullName, email, passwordHash, role || 'operario', dummyPhone, req.user.accountId]
|
||||
);
|
||||
const userId = insert.rows[0].id;
|
||||
|
||||
@@ -375,14 +353,8 @@ app.post("/admin/users", authMiddleware, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// =========================
|
||||
// ARRANCAR SERVIDOR Y AUTO-UPDATE
|
||||
// =========================
|
||||
// ARRANCAR
|
||||
const port = process.env.PORT || 3000;
|
||||
|
||||
// Primero ejecutamos la actualización, y SOLO CUANDO TERMINE, arrancamos el server
|
||||
autoUpdateDB().then(() => {
|
||||
app.listen(port, "0.0.0.0", () => {
|
||||
console.log(`🚀 Server OK en puerto ${port} (DB Sincronizada)`);
|
||||
});
|
||||
app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port} (Multitenant)`));
|
||||
});
|
||||
Reference in New Issue
Block a user