score.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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('score');
  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. 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. (new Analytics($root))->track(Analytics::EVENT_DIA_COMPLETED, $packId);
  33. // Stockage local (toujours) + webhook si configuré
  34. $pdfBytes = (new PdfRenderer($root))->renderPdfBytes($pack, $result, [
  35. 'booking_url' => '',
  36. 'date' => date('Y-m-d'),
  37. ]);
  38. $filename = 'controle-technique-' . ($pack['pack_id'] ?? 'resultat') . '.pdf';
  39. $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
  40. $outbox = new OutboxStorage($root . '/storage/outbox');
  41. $webhookUrl = (string) ($config['admin_notify_webhook'] ?? '');
  42. if ($webhookUrl !== '' && filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
  43. (new AdminNotifier($webhookUrl, $outbox))->notify('score', $ctx, $filename, $pdfBytes, null);
  44. } else {
  45. $outbox->store('score', $ctx, $filename, $pdfBytes, null);
  46. }
  47. Http::json(['result' => $result]);
  48. } catch (Throwable $e) {
  49. Http::json(['error' => $e->getMessage()], 400);
  50. }