pdf.php 2.6 KB

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