feat: encuesta de satisfacción post-finalizar toma de muestras
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
4a4cbc31b8
commit
2455417bb4
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
/**
|
||||
* POST /modules/turnero/api/enviar_encuesta.php
|
||||
* Envía la plantilla "encuesta" al paciente del turno vía WhatsApp turnero.
|
||||
* Body JSON: { turno_id: int }
|
||||
*/
|
||||
require_once __DIR__ . '/_helpers.php';
|
||||
require_once __DIR__ . '/../../../services/WhatsAppService.php';
|
||||
requireMethod('POST');
|
||||
requireTurnero();
|
||||
|
||||
$body = inputJson();
|
||||
$turnoId = (int)($body['turno_id'] ?? 0);
|
||||
if (!$turnoId) jsonError('turno_id requerido.');
|
||||
|
||||
$pdo = db();
|
||||
|
||||
// Obtener user_id y teléfono del paciente vía turnero_turnos → lab_pacientes → users
|
||||
$row = $pdo->prepare(
|
||||
"SELECT u.id AS user_id, u.phone_number, t.paciente_cel, t.paciente_nombre
|
||||
FROM turnero_turnos t
|
||||
LEFT JOIN lab_pacientes lp ON lp.id = t.paciente_id
|
||||
LEFT JOIN users u ON u.id = lp.user_id
|
||||
WHERE t.id = ? LIMIT 1"
|
||||
);
|
||||
$row->execute([$turnoId]);
|
||||
$pac = $row->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$pac) jsonError('Turno no encontrado.', 404);
|
||||
|
||||
$userId = $pac['user_id'] ? (int)$pac['user_id'] : null;
|
||||
$phone = $pac['phone_number'] ?? null;
|
||||
|
||||
// Fallback: buscar por paciente_cel si no hay user_id
|
||||
if (!$userId && !empty($pac['paciente_cel'])) {
|
||||
$cel = preg_replace('/\D/', '', $pac['paciente_cel']);
|
||||
$u2 = $pdo->prepare("SELECT id, phone_number FROM users WHERE REPLACE(phone_number,'+','') LIKE ? LIMIT 1");
|
||||
$u2->execute(['%' . substr($cel, -10)]);
|
||||
$uRow = $u2->fetch(PDO::FETCH_ASSOC);
|
||||
if ($uRow) { $userId = (int)$uRow['id']; $phone = $uRow['phone_number']; }
|
||||
}
|
||||
|
||||
if (!$userId || !$phone) jsonError('El paciente no tiene número de WhatsApp registrado.');
|
||||
|
||||
try {
|
||||
$wa = new WhatsAppService('turnero');
|
||||
$meta = ['canal' => 'turnero', 'operator_id' => adminId()];
|
||||
$wa->sendTemplateMessage($phone, 'encuesta', 'es_CO', [], [], null, $meta);
|
||||
jsonOk(['mensaje' => 'Encuesta enviada a ' . ($pac['paciente_nombre'] ?? $phone)]);
|
||||
} catch (\Throwable $e) {
|
||||
jsonError('Error al enviar: ' . $e->getMessage());
|
||||
}
|
||||
Reference in New Issue
Block a user