Skip to content

Commit

Permalink
[Add] fixing url and better code
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeanpigi committed Sep 5, 2023
1 parent 8dd07a7 commit 216cff4
Show file tree
Hide file tree
Showing 11 changed files with 304 additions and 453 deletions.
29 changes: 29 additions & 0 deletions database/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const mysql = require("mysql2/promise");
require("dotenv").config();

// Configuración de la conexión a la base de datos MySQL utilizando un pool
const pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
connectionLimit: 20, // Número máximo de conexiones en el db
waitForConnections: true,
queueLimit: 0,
});

const getAgendasForToday = async () => {
try {
// Obtenemos la fecha actual en formato MySQL (YYYY-MM-DD)
const currentDate = new Date().toISOString().split("T")[0];
const query = `SELECT * FROM AgendaPeriodica WHERE DATE(Fechaini) = ?`;
const [rows] = await pool.execute(query, [currentDate]);

return rows;
} catch (error) {
console.error(`Error al realizar la consulta y es el siguiente ${error}`);
throw new Error("Error al obtener los datos de la agenda");
}
};

module.exports = getAgendasForToday;
71 changes: 38 additions & 33 deletions handlers/sendSMSHandler.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,58 @@
const request = require("request");
require("dotenv").config();

const formatTime = (date) => {
const horas = date.getHours();
const minutos = date.getMinutes();
const amOrPmInicio = horas >= 12 ? "PM" : "AM";
return `${(horas % 12 || 12).toString().padStart(2, "0")}:${minutos
.toString()
.padStart(2, "0")} ${amOrPmInicio}`;
};

const buildMessage = (fechaInicio, mensaje) => {
const dateObject = new Date(fechaInicio);
const year = dateObject.getFullYear();
const month = dateObject.getMonth() + 1;
const day = dateObject.getDate();
const horaFormateada = formatTime(dateObject);
return `${mensaje} ${day}/${month}/${year} a la hora: ${horaFormateada}`;
};

const sendSMSHandler = async (req, res) => {
try {
const { fechaInicio, celular, mensaje } = req.body;

const currentDay = new Date();

console.log("------------------------------------------");
console.log(`Mensaje enviado el dia: ${currentDay}`);
console.log(
`fecha y hora del mensaje ${fechaInicio}, celular a enviar ${celular} el mensaje ${mensaje}`
);
if (!fechaInicio || !celular || !mensaje) {
throw new Error("Los datos de entrada son inválidos.");
}

const dateObject = new Date(fechaInicio);
const year = dateObject.getFullYear();
const month = dateObject.getMonth() + 1;
const day = dateObject.getDate();
const horas = dateObject.getHours();
const minutos = dateObject.getMinutes();
const amOrPmInicio = horas >= 12 ? "PM" : "AM";
const horaFormateada = `${(horas % 12 || 12)
.toString()
.padStart(2, "0")}:${minutos
.toString()
.padStart(2, "0")} ${amOrPmInicio}`;

const message = `${mensaje} ${day}/${month}/${year} a la hora: ${horaFormateada}`;
const message = buildMessage(fechaInicio, mensaje);

const options = {
method: "POST",
url: "https://www.onurix.com/api/v1/send-sms",
headers: { "content-type": "application/x-www-form-urlencoded" },
form: {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
key: process.env.MYKEY,
client: process.env.MYCLIENT,
phone: celular,
sms: message,
"country-code": "CO",
},
}),
};

request(options, function (error, body) {
if (error) {
res.status(500).json({ error: error.message });
} else {
res.status(200).json({ response: body });
}
});
const response = await fetch(
"https://www.onurix.com/api/v1/send-sms",
options
);
const responseData = await response.json();

if (!response.ok) {
throw new Error(responseData.message);
}

res.status(200).json({ response: responseData });
} catch (error) {
res.status(500).json({ error: error.message });
}
Expand Down
62 changes: 27 additions & 35 deletions handlers/sendWhatsAppHandler.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,36 @@
const request = require("request");
require("dotenv").config();

const sendWhatsApphandler = async (req, res) => {
const formatTime = (date) => {
const horas = date.getHours();
const minutos = date.getMinutes();
const amOrPmInicio = horas >= 12 ? "PM" : "AM";
return `${(horas % 12 || 12).toString().padStart(2, "0")}:${minutos
.toString()
.padStart(2, "0")} ${amOrPmInicio}`;
};

const buildMessage = (fechaInicio, mensaje) => {
const dateObject = new Date(fechaInicio);
const year = dateObject.getFullYear();
const month = dateObject.getMonth() + 1;
const day = dateObject.getDate();
const horaFormateada = formatTime(dateObject);
return `${mensaje} ${day}/${month}/${year} a la hora: ${horaFormateada}`;
};

const sendWhatsAppHandler = async (req, res) => {
if (req.method === "POST") {
try {
const { fechaInicio, celular, mensaje } = req.body;

const currentDay = new Date();

console.log("------------------------------------------");
console.log(`Mensaje enviado el dia: ${currentDay}`);
console.log(
`fecha y hora del mensaje ${fechaInicio}, celular a enviar ${celular} el mensaje ${mensaje}`
);

const dateObject = new Date(fechaInicio);

const year = dateObject.getFullYear();
const month = dateObject.getMonth() + 1;
const day = dateObject.getDate();
const horas = dateObject.getHours();
const minutos = dateObject.getMinutes();

const amOrPmInicio = horas >= 12 ? "PM" : "AM";

const horaFormateada = `${(horas % 12 || 12)
.toString()
.padStart(2, "0")}:${minutos
.toString()
.padStart(2, "0")} ${amOrPmInicio}`;
if (!fechaInicio || !celular || !mensaje) {
throw new Error("Los datos de entrada son inválidos.");
}

const message = `${mensaje} ${day}/${month}/${year} a la hora: ${horaFormateada}`;
const message = buildMessage(fechaInicio, mensaje);

const options = {
method: "POST",
url: process.env.APIWHATSAPP,
headers: {
Authorization: process.env.TOKENWHATSAPP,
"Content-Type": "application/json",
Expand Down Expand Up @@ -72,13 +68,9 @@ const sendWhatsApphandler = async (req, res) => {
}),
};

request(options, function (error, response, body) {
if (error) {
throw new Error(`Existe un error: ${error}`);
} else {
res.status(200).json({ data: body });
}
});
const response = await fetch(process.env.APIWHATSAPP, options);
const data = await response.json();
res.status(200).json({ data });
} catch (error) {
res.status(500).json({ error: error.message });
}
Expand All @@ -87,4 +79,4 @@ const sendWhatsApphandler = async (req, res) => {
}
};

module.exports = sendWhatsApphandler;
module.exports = sendWhatsAppHandler;
14 changes: 14 additions & 0 deletions handlers/testHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const getAgendasForToday = require("../database/db");

const testHandler = async (req, res) => {
try {
const todayAgendas = await getAgendasForToday();
console.log("Agendas para el día actual:");
console.log(todayAgendas);
res.send("Probando a ver si trae las agendas");
} catch (error) {
console.error("Error al obtener las agendas para el día actual:", error);
}
};

module.exports = testHandler;
Loading

0 comments on commit 216cff4

Please sign in to comment.