pdf.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. declare(strict_types=1);
  3. use AuditExpress\AdminNotifier;
  4. use AuditExpress\Analytics;
  5. use AuditExpress\Engine;
  6. use AuditExpress\Http;
  7. use AuditExpress\InputValidator;
  8. use AuditExpress\PackRepository;
  9. use AuditExpress\PdfRenderer;
  10. use AuditExpress\RateLimiter;
  11. use AuditExpress\RulesRepository;
  12. use AuditExpress\Security;
  13. ['root' => $root, 'config' => $config] = require __DIR__ . '/_bootstrap.php';
  14. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  15. Http::methodNotAllowed(['POST']);
  16. exit;
  17. }
  18. Security::validateCsrf();
  19. (new RateLimiter($root, $config, RateLimiter::clientIp()))->check('pdf');
  20. $maxBody = (int) ($config['max_body_bytes'] ?? 1_048_576);
  21. $body = Http::readJsonBody($maxBody > 0 ? $maxBody : null);
  22. $packId = InputValidator::sanitizePackId((string) ($body['pack_id'] ?? 'onboarding-v1'));
  23. $answers = InputValidator::validateAnswers(is_array($body['answers'] ?? null) ? $body['answers'] : []);
  24. $optional = InputValidator::validateOptional(is_array($body['optional'] ?? null) ? $body['optional'] : []);
  25. $bookingUrl = InputValidator::sanitizeUrl((string) ($body['booking_url'] ?? ''));
  26. try {
  27. $packRepo = new PackRepository($root);
  28. $rulesRepo = new RulesRepository($root);
  29. $pack = $packRepo->getPack($packId);
  30. $rules = $rulesRepo->getRules();
  31. $result = Engine::compute($pack, $answers, $optional, $rules);
  32. $pdf = (new PdfRenderer($root))->renderPdfBytes($pack, $result, [
  33. 'booking_url' => $bookingUrl,
  34. 'date' => date('Y-m-d'),
  35. ]);
  36. (new Analytics($root))->track(Analytics::EVENT_PDF_GENERATED, $packId);
  37. $filename = 'controle-technique-' . ($pack['pack_id'] ?? 'resultat') . '.pdf';
  38. // Notification admin via webhook
  39. $webhookUrl = (string) ($config['admin_notify_webhook'] ?? '');
  40. $userEmail = (string) ($body['email'] ?? '');
  41. if ($webhookUrl !== '' && filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
  42. $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
  43. (new AdminNotifier($webhookUrl, $root . '/storage/outbox'))->notify('pdf', $ctx, $filename, $pdf, $userEmail !== '' ? $userEmail : null);
  44. }
  45. header('Content-Type: application/pdf');
  46. header('Content-Disposition: attachment; filename="' . $filename . '"');
  47. header('Content-Length: ' . strlen($pdf));
  48. echo $pdf;
  49. } catch (Throwable $e) {
  50. Http::json(['error' => $e->getMessage()], 400);
  51. }