score.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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('score');
  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. try {
  26. $packRepo = new PackRepository($root);
  27. $rulesRepo = new RulesRepository($root);
  28. $pack = $packRepo->getPack($packId);
  29. $rules = $rulesRepo->getRules();
  30. $result = Engine::compute($pack, $answers, $optional, $rules);
  31. (new Analytics($root))->track(Analytics::EVENT_DIA_COMPLETED, $packId);
  32. // Notification admin via webhook
  33. $webhookUrl = (string) ($config['admin_notify_webhook'] ?? '');
  34. if ($webhookUrl !== '' && filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
  35. $pdfBytes = (new PdfRenderer($root))->renderPdfBytes($pack, $result, [
  36. 'booking_url' => '',
  37. 'date' => date('Y-m-d'),
  38. ]);
  39. $filename = 'controle-technique-' . ($pack['pack_id'] ?? 'resultat') . '.pdf';
  40. $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
  41. (new AdminNotifier($webhookUrl, $root . '/storage/outbox'))->notify('score', $ctx, $filename, $pdfBytes, null);
  42. }
  43. Http::json(['result' => $result]);
  44. } catch (Throwable $e) {
  45. Http::json(['error' => $e->getMessage()], 400);
  46. }