| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- declare(strict_types=1);
- use AuditExpress\AdminNotifier;
- use AuditExpress\Analytics;
- use AuditExpress\OutboxStorage;
- use AuditExpress\Engine;
- use AuditExpress\Http;
- use AuditExpress\InputValidator;
- use AuditExpress\PackRepository;
- use AuditExpress\PdfRenderer;
- use AuditExpress\RateLimiter;
- use AuditExpress\RulesRepository;
- use AuditExpress\Security;
- ['root' => $root, 'config' => $config] = require __DIR__ . '/_bootstrap.php';
- if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
- Http::methodNotAllowed(['POST']);
- exit;
- }
- Security::validateCsrf();
- (new RateLimiter($root, $config, RateLimiter::clientIp()))->check('pdf');
- $maxBody = (int) ($config['max_body_bytes'] ?? 1_048_576);
- $body = Http::readJsonBody($maxBody > 0 ? $maxBody : null);
- $packId = InputValidator::sanitizePackId((string) ($body['pack_id'] ?? 'onboarding-v1'));
- $answers = InputValidator::validateAnswers(is_array($body['answers'] ?? null) ? $body['answers'] : []);
- $optional = InputValidator::validateOptional(is_array($body['optional'] ?? null) ? $body['optional'] : []);
- $bookingUrl = InputValidator::sanitizeUrl((string) ($body['booking_url'] ?? ''));
- try {
- $packRepo = new PackRepository($root);
- $rulesRepo = new RulesRepository($root);
- $pack = $packRepo->getPack($packId);
- $rules = $rulesRepo->getRules();
- $result = Engine::compute($pack, $answers, $optional, $rules);
- $pdf = (new PdfRenderer($root))->renderPdfBytes($pack, $result, [
- 'booking_url' => $bookingUrl,
- 'date' => date('Y-m-d'),
- ]);
- (new Analytics($root))->track(Analytics::EVENT_PDF_GENERATED, $packId);
- $filename = 'controle-technique-' . ($pack['pack_id'] ?? 'resultat') . '.pdf';
- // Stockage local (toujours) + webhook si configuré
- $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
- $userEmail = (string) ($body['email'] ?? '');
- $outbox = new OutboxStorage($root . '/storage/outbox');
- $webhookUrl = (string) ($config['admin_notify_webhook'] ?? '');
- if ($webhookUrl !== '' && filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
- (new AdminNotifier($webhookUrl, $outbox))->notify('pdf', $ctx, $filename, $pdf, $userEmail !== '' ? $userEmail : null);
- } else {
- $outbox->store('pdf', $ctx, $filename, $pdf, $userEmail !== '' ? $userEmail : null);
- }
- header('Content-Type: application/pdf');
- header('Content-Disposition: attachment; filename="' . $filename . '"');
- header('Content-Length: ' . strlen($pdf));
- echo $pdf;
- } catch (Throwable $e) {
- Http::json(['error' => $e->getMessage()], 400);
- }
|