Envio de PDF por Telegram

- Agregado comando /pdf y boton Mi PDF en el menu
- Genera y envia automaticamente el PDF con todos los horarios y turnos
- PDF incluye: Turnos de Ayudantes, Horarios por Semana, Horarios de Apertura
This commit is contained in:
nickpons666
2026-01-20 16:58:07 -06:00
parent 96985f3d8c
commit 488f25b568
2 changed files with 293 additions and 2 deletions

View File

@@ -53,6 +53,9 @@ class TelegramBot {
['text' => 'Ver Turnos', 'callback_data' => 'ver_turnos'], ['text' => 'Ver Turnos', 'callback_data' => 'ver_turnos'],
['text' => 'Semana Actual', 'callback_data' => 'semana_actual'] ['text' => 'Semana Actual', 'callback_data' => 'semana_actual']
], ],
[
['text' => '📄 Mi PDF', 'callback_data' => 'mi_pdf']
],
[ [
['text' => '🔍 Buscar por Nombre', 'callback_data' => 'buscar_nombre'] ['text' => '🔍 Buscar por Nombre', 'callback_data' => 'buscar_nombre']
] ]
@@ -203,4 +206,262 @@ class TelegramBot {
$ayudantes = (new Asignacion())->getAyudantesPorOrden(); $ayudantes = (new Asignacion())->getAyudantesPorOrden();
return array_map(fn($a) => $a['nombre'], $ayudantes); return array_map(fn($a) => $a['nombre'], $ayudantes);
} }
public function sendPDF($chatId, $userId) {
require_once __DIR__ . '/../src/PDFGenerator.php';
require_once __DIR__ . '/../src/User.php';
require_once __DIR__ . '/../src/DiasHorarios.php';
require_once __DIR__ . '/../src/Asignacion.php';
require_once __DIR__ . '/../src/Database.php';
$userModel = new User();
$userData = $userModel->getById($userId);
if (!$userData) {
$this->sendMessage($chatId, "Usuario no encontrado.");
return;
}
$horariosModel = new DiasHorarios();
$asignacionModel = new Asignacion();
$db = \Database::getInstance()->getConnection();
$horarios = $horariosModel->getActivos();
$ayudantes = $userModel->getAyudantesActivos();
$semanasFuturas = [];
$hoy = new DateTime();
$diaSemana = (int)$hoy->format('w');
$domingoEstaSemana = clone $hoy;
$domingoEstaSemana->modify('-' . $diaSemana . ' days');
for ($i = 0; $i <= 4; $i++) {
$semanaDomingo = clone $domingoEstaSemana;
$semanaDomingo->modify("+{$i} weeks");
$semanaInicio = $semanaDomingo->format('Y-m-d');
$asignacionesSemana = $asignacionModel->getTodasAsignacionesPorSemana($semanaInicio);
$semanasFuturas[] = [
'inicio' => $semanaInicio,
'fin' => date('Y-m-d', strtotime('+5 days', strtotime($semanaInicio))),
'asignaciones' => $asignacionesSemana,
];
}
$diasNombres = [
'domingo' => 'Domingo', 'lunes' => 'Lunes', 'martes' => 'Martes',
'miercoles' => 'Miercoles', 'jueves' => 'Jueves', 'viernes' => 'Viernes', 'sabado' => 'Sabado'
];
$diasOrden = ['domingo', 'lunes', 'martes', 'miercoles', 'jueves', 'viernes', 'sabado'];
$html = PDFGenerator::getStyles();
$html .= PDFGenerator::getHeader('Horarios y Turnos - ' . $userData['nombre']);
$html .= '<h2>Mis Turnos</h2>';
$html .= '<table><thead><tr><th>Semana</th><th>Periodo</th><th>Estado</th></tr></thead><tbody>';
foreach ($semanasFuturas as $index => $semana) {
$esMiTurno = !empty($semana['asignaciones']) && in_array($userId, array_column($semana['asignaciones'], 'id'));
$html .= '<tr class="' . ($esMiTurno ? 'table-success' : '') . '">';
$html .= '<td>' . date('d/m/Y', strtotime($semana['inicio']));
if ($index === 0) {
$html .= ' <span class="badge badge-primary">Actual</span>';
}
if ($esMiTurno) {
$html .= ' <span class="badge badge-success">Tu turno</span>';
}
$html .= '</td>';
$html .= '<td>' . date('d/m/Y', strtotime($semana['inicio'])) . ' - ' . date('d/m/Y', strtotime($semana['fin'])) . '</td>';
$html .= '<td>' . ($esMiTurno ? 'Asignado' : 'Sin asignar') . '</td>';
$html .= '</tr>';
}
$html .= '</tbody></table>';
$html .= '<h2>Horarios por Semana</h2>';
$html .= '<table><thead><tr><th>Semana</th>';
foreach ($diasOrden as $dia) {
$html .= '<th class="text-center">' . $diasNombres[$dia] . '</th>';
}
$html .= '</tr></thead><tbody>';
foreach ($semanasFuturas as $index => $semana) {
$esMiTurno = !empty($semana['asignaciones']) && in_array($userId, array_column($semana['asignaciones'], 'id'));
$html .= '<tr class="' . ($esMiTurno ? 'table-success' : '') . '">';
$html .= '<td>' . date('d/m', strtotime($semana['inicio']));
if ($index === 0) {
$html .= ' <span class="badge badge-primary">Actual</span>';
}
$html .= '</td>';
foreach ($diasOrden as $dia) {
$horarioDia = null;
foreach ($horarios as $h) {
if ($h['dia_semana'] === $dia) {
$horarioDia = $h;
break;
}
}
$esActivo = $horarioDia && $horarioDia['activo'];
if ($esMiTurno && $esActivo) {
$html .= '<td class="text-center" style="background-color: #198754; color: white;">';
$html .= date('H:i', strtotime($horarioDia['hora_apertura'])) . '<br>' . date('H:i', strtotime($horarioDia['hora_cierre']));
$html .= '</td>';
} elseif (!$esActivo) {
$html .= '<td class="text-center text-muted">Cerrado</td>';
} else {
$html .= '<td class="text-center">' . date('H:i', strtotime($horarioDia['hora_apertura'])) . '<br>' . date('H:i', strtotime($horarioDia['hora_cierre'])) . '</td>';
}
}
$html .= '</tr>';
}
$html .= '</tbody></table>';
$html .= PDFGenerator::getFooter();
$pdfGenerator = new PDFGenerator();
$pdfContent = $pdfGenerator->generateFromHtml($html);
$pdfFile = tempnam(sys_get_temp_dir(), 'turnos');
file_put_contents($pdfFile, $pdfContent);
$this->sendDocument($chatId, $pdfFile, 'mis-turnos-' . date('Y-m-d') . '.pdf');
unlink($pdfFile);
}
public function sendDocument($chatId, $documentPath, $filename) {
$url = "{$this->apiUrl}/sendDocument";
$postFields = [
'chat_id' => $chatId,
'document' => new CURLFile($documentPath, 'application/pdf', $filename)
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
}
public function sendPDFGeneral($chatId) {
require_once __DIR__ . '/../src/PDFGenerator.php';
require_once __DIR__ . '/../src/User.php';
require_once __DIR__ . '/../src/DiasHorarios.php';
require_once __DIR__ . '/../src/Asignacion.php';
require_once __DIR__ . '/../src/Database.php';
$userModel = new User();
$horariosModel = new DiasHorarios();
$asignacionModel = new Asignacion();
$db = \Database::getInstance()->getConnection();
$horarios = $horariosModel->getActivos();
$ayudantes = $userModel->getAyudantesActivos();
$semanasFuturas = [];
$hoy = new DateTime();
$diaSemana = (int)$hoy->format('w');
$domingoEstaSemana = clone $hoy;
$domingoEstaSemana->modify('-' . $diaSemana . ' days');
for ($i = 0; $i <= 4; $i++) {
$semanaDomingo = clone $domingoEstaSemana;
$semanaDomingo->modify("+{$i} weeks");
$semanaInicio = $semanaDomingo->format('Y-m-d');
$asignacionesSemana = $asignacionModel->getTodasAsignacionesPorSemana($semanaInicio);
$semanasFuturas[] = [
'inicio' => $semanaInicio,
'fin' => date('Y-m-d', strtotime('+5 days', strtotime($semanaInicio))),
'asignaciones' => $asignacionesSemana,
];
}
$diasNombres = [
'domingo' => 'Domingo', 'lunes' => 'Lunes', 'martes' => 'Martes',
'miercoles' => 'Miercoles', 'jueves' => 'Jueves', 'viernes' => 'Viernes', 'sabado' => 'Sabado'
];
$diasOrden = ['domingo', 'lunes', 'martes', 'miercoles', 'jueves', 'viernes', 'sabado'];
$html = PDFGenerator::getStyles();
$html .= PDFGenerator::getHeader('Horarios y Turnos - Todos los Ayudantes');
$html .= '<h2>Turnos de Ayudantes</h2>';
$html .= '<table><thead><tr><th>Ayudante</th><th>Fecha 1</th><th>Fecha 2</th><th>Fecha 3</th><th>Fecha 4</th></tr></thead><tbody>';
foreach ($ayudantes as $ayudante) {
$stmt = $db->prepare("SELECT semana_inicio, semana_fin FROM asignaciones_turnos WHERE user_id = ? AND semana_inicio >= CURDATE() ORDER BY semana_inicio LIMIT 4");
$stmt->execute([$ayudante['id']]);
$turnos = $stmt->fetchAll();
$html .= '<tr>';
$html .= '<td>' . htmlspecialchars($ayudante['nombre']) . '</td>';
for ($i = 0; $i < 4; $i++) {
if (isset($turnos[$i])) {
$html .= '<td class="text-center">' . date('d/m/Y', strtotime($turnos[$i]['semana_inicio'])) . ' - ' . date('d/m/Y', strtotime($turnos[$i]['semana_fin'])) . '</td>';
} else {
$html .= '<td class="text-center text-muted">-</td>';
}
}
$html .= '</tr>';
}
$html .= '</tbody></table>';
$html .= '<h2>Horarios por Semana</h2>';
$html .= '<table><thead><tr><th>Semana</th>';
foreach ($diasOrden as $dia) {
$html .= '<th class="text-center">' . $diasNombres[$dia] . '</th>';
}
$html .= '</tr></thead><tbody>';
foreach ($semanasFuturas as $index => $semana) {
$html .= '<tr>';
$html .= '<td>' . date('d/m', strtotime($semana['inicio']));
if ($index === 0) {
$html .= ' <span class="badge badge-primary">Actual</span>';
}
$html .= '</td>';
foreach ($diasOrden as $dia) {
$horarioDia = null;
foreach ($horarios as $h) {
if ($h['dia_semana'] === $dia) {
$horarioDia = $h;
break;
}
}
$esActivo = $horarioDia && $horarioDia['activo'];
if ($esActivo) {
$html .= '<td class="text-center">' . date('H:i', strtotime($horarioDia['hora_apertura'])) . '<br>' . date('H:i', strtotime($horarioDia['hora_cierre'])) . '</td>';
} else {
$html .= '<td class="text-center text-muted">Cerrado</td>';
}
}
$html .= '</tr>';
}
$html .= '</tbody></table>';
$html .= '<h2>Horarios de Apertura</h2>';
$html .= '<table><thead><tr><th>Dia</th><th>Hora Apertura</th><th>Hora Cierre</th><th>Estado</th></tr></thead><tbody>';
foreach ($horarios as $h) {
$html .= '<tr>';
$html .= '<td>' . ucfirst($h['dia_semana']) . '</td>';
$html .= '<td>' . date('H:i', strtotime($h['hora_apertura'])) . '</td>';
$html .= '<td>' . date('H:i', strtotime($h['hora_cierre'])) . '</td>';
$html .= '<td>' . ($h['activo'] ? 'Abierto' : 'Cerrado') . '</td>';
$html .= '</tr>';
}
$html .= '</tbody></table>';
$html .= PDFGenerator::getFooter();
$pdfGenerator = new PDFGenerator();
$pdfContent = $pdfGenerator->generateFromHtml($html);
$pdfFile = tempnam(sys_get_temp_dir(), 'turnos');
file_put_contents($pdfFile, $pdfContent);
$this->sendDocument($chatId, $pdfFile, 'turnos-contenedor-' . date('Y-m-d') . '.pdf');
unlink($pdfFile);
}
} }

View File

@@ -50,9 +50,33 @@ class TurnoBot {
} elseif ($textLower === '/ayudantes' || $textLower === 'ayudantes') { } elseif ($textLower === '/ayudantes' || $textLower === 'ayudantes') {
$ayudantes = $this->bot->getListaAyudantesParaBusqueda(); $ayudantes = $this->bot->getListaAyudantesParaBusqueda();
$this->bot->sendMessage($chatId, "<b>AYUDANTES DISPONIBLES:</b>\n\n" . implode("\n", $ayudantes)); $this->bot->sendMessage($chatId, "<b>AYUDANTES DISPONIBLES:</b>\n\n" . implode("\n", $ayudantes));
} elseif ($textLower === '/pdf' || $textLower === 'pdf' || $textLower === 'mi pdf') {
$this->bot->sendPDFGeneral($chatId);
} else { } else {
// Buscar por nombre // Buscar por nombre - verificar si existe el usuario
$this->bot->sendMessage($chatId, $this->bot->getTurnosAyudante($text)); $config = require __DIR__ . '/../config/config.php';
try {
$pdo = new PDO(
"mysql:host={$config['db']['host']};port={$config['db']['port']};dbname={$config['db']['database']};charset=utf8mb4",
$config['db']['username'],
$config['db']['password'],
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
} catch (Exception $e) {
$this->bot->sendMessage($chatId, "Error de conexion.");
return;
}
$stmt = $pdo->prepare("SELECT * FROM users WHERE (nombre LIKE ? OR username LIKE ?) AND rol = 'ayudante' AND activo = 1 LIMIT 1");
$stmt->execute(["%$text%", "%$text%"]);
$user = $stmt->fetch();
if ($user) {
$this->bot->sendMessage($chatId, "Generando PDF de turnos...");
$this->bot->sendPDF($chatId, $user['id']);
} else {
$this->bot->sendMessage($chatId, $this->bot->getTurnosAyudante($text));
}
} }
} catch (Exception $e) { } catch (Exception $e) {
error_log("Error en handleUpdate: " . $e->getMessage()); error_log("Error en handleUpdate: " . $e->getMessage());
@@ -81,6 +105,11 @@ class TurnoBot {
$this->bot->editMessage($chatId, $messageId, $this->bot->getSemanaActual()); $this->bot->editMessage($chatId, $messageId, $this->bot->getSemanaActual());
break; break;
case 'mi_pdf':
$this->bot->answerCallback($callbackId, 'Generando PDF...');
$this->bot->sendPDFGeneral($chatId);
break;
case 'buscar_nombre': case 'buscar_nombre':
$this->bot->answerCallback($callbackId, ''); $this->bot->answerCallback($callbackId, '');
$this->bot->deleteMessage($chatId, $messageId); $this->bot->deleteMessage($chatId, $messageId);
@@ -105,6 +134,7 @@ class TurnoBot {
$mensaje .= "Selecciona una opcion del menu:\n\n"; $mensaje .= "Selecciona una opcion del menu:\n\n";
$mensaje .= "Ver Turnos - Tabla completa de asignaciones\n"; $mensaje .= "Ver Turnos - Tabla completa de asignaciones\n";
$mensaje .= "Semana Actual - Quien tiene turno esta semana\n"; $mensaje .= "Semana Actual - Quien tiene turno esta semana\n";
$mensaje .= "Mi PDF - Descargar horarios en PDF\n";
$mensaje .= "Buscar por Nombre - Consultar un ayudante especifico\n"; $mensaje .= "Buscar por Nombre - Consultar un ayudante especifico\n";
$mensaje .= "Mi Turno - Ver tu proximo turno"; $mensaje .= "Mi Turno - Ver tu proximo turno";