Files
crm_ecosplay/tests/Controller/Admin/SyncControllerTest.php

529 lines
20 KiB
PHP
Raw Normal View History

refactor: sécurité Discord webhook, tests 100% coverage, factorisation templates PDF et DNS Sécurité - Discord Webhook : - Suppression de l'URL Discord webhook en dur dans CheckDnsCommand (ligne 34) - Ajout de la variable d'environnement DISCORD_WEBHOOK dans .env (vide par défaut) - Injection via #[Autowire(env: 'DISCORD_WEBHOOK')] dans le constructeur - Vérification que le webhook est configuré avant envoi ('' !== $this->discordWebhook) - Remplacement de l'URL en dur dans discord-notify.yml par ${{ secrets.DISCORD_WEBHOOK }} Factorisation DNS (suppression duplication SonarQube) : - Création de src/Service/DnsInfraHelper.php avec les méthodes partagées : enrichWithCloudflare, enrichLastCheck, loadCloudflareRecords, getActualDnsValue, getMxValues, getFirstTxtValue, getSrvValue, checkMxExists, checkTxtContains, checkDnsRecordExists, getTxtSpfValue - Constantes DOMAINS et EXPECTED_MX centralisées dans DnsInfraHelper - Refactorisation de CheckDnsCommand pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) - Refactorisation de DnsReportController pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) Factorisation templates PDF (suppression duplication lignes 6-22) : - Création de templates/pdf/_base.html.twig comme layout commun avec : CSS partagé (banner, container, info-grid, verify-box, hmac, contact-box, data tables), blocs Twig configurables (title, font_size, extra_styles, content, verify_box, hmac_section, footer_contact, signature_box, footer_legal) - Refactorisation de rgpd_access.html.twig : extends _base, accent #4338ca, bloc content avec sessions/events, styles session-meta et no-data - Refactorisation de rgpd_deletion.html.twig : extends _base, accent #dc2626, font 11px, bloc content avec attestation-box et warning - Refactorisation de rgpd_no_data.html.twig : extends _base, accent #fabf04/#111827, font 11px, bloc content avec attestation absence - Refactorisation de admin/logs/pdf.html.twig : extends _base, accent #4338ca, bloc content avec tables utilisateur/requête et HMAC verification box, suppression du bloc signature, footer légal avec Siret/TVA Tests - Couverture 100% (469 tests, 857 assertions, 0 failures) : AnalyticsControllerTest (8 tests) : - testTrackInvalidToken : token incorrect retourne 404 - testTrackEmptyPayload : payload sans clé 'd' retourne 400 - testTrackInvalidEncryptedData : données chiffrées invalides retourne 403 - testTrackNewVisitorCreation : création visiteur avec screen/language/UA, retourne uid+hash - testTrackPageViewWithValidHash : page view avec uid/hash valides retourne 204 - testTrackSetUserWithValidHash : setUser avec uid/hash valides retourne 204 - testTrackWithInvalidHash : hash incorrect retourne 403 - testTrackWithMissingHash : hash absent retourne 403 AttestationControllerTest (8 tests) : - testVerifyNotFound : référence inconnue retourne 200 (template not_found) - testVerifyFound : attestation trouvée retourne 200 (template verify) - testDownloadNotFound : référence inconnue lance NotFoundHttpException - testDownloadNoPdf : attestation sans PDF lance NotFoundHttpException - testDownloadWithPdf : attestation avec PDF signé retourne BinaryFileResponse 200 - testAuditNotFound : référence inconnue lance NotFoundHttpException - testAuditNoCertificate : attestation sans certificat lance NotFoundHttpException - testAuditWithCertificate : attestation avec certificat retourne BinaryFileResponse 200 CspReportControllerTest (13 tests) : - testGetReturns204 : GET /my-csp-report retourne 204 - testReportEmptyPayload : payload vide retourne 400 - testReportInvalidJson : JSON invalide retourne 400 - testReportIgnoredExtension : chrome-extension ignoré, retourne 204 - testReportIgnoredMozExtension : moz-extension ignoré, retourne 204 - testReportIgnoredLocalhost : localhost ignoré, retourne 204 - testReportIgnoredLocalDomain : .local ignoré, retourne 204 - testReportIgnoredWasmEval : wasm-eval ignoré, retourne 204 - testReportIgnoredAboutBlank : about:blank ignoré, retourne 204 - testReportIgnoredNodeModulesInline : node_modules inline ignoré, retourne 204 - testReportRealViolationSendsEmail : violation réelle envoie email, retourne 204 - testReportRealViolationEmailFailure : échec email ne bloque pas, retourne 204 - testReportWithoutCspReportWrapper : payload sans wrapper csp-report fonctionne EmailTrackingControllerTest (10 tests) : - testTrackWithExistingTracking : tracking trouvé, markAsOpened appelé, état 'opened' - testTrackWithNonExistingTracking : tracking absent, retourne image sans erreur - testViewNotFound : messageId inconnu lance NotFoundHttpException - testViewNoHtmlBody : tracking sans htmlBody lance NotFoundHttpException - testViewWithHtmlBody : retourne HTML du tracking - testViewWithAttachments : retourne HTML avec section pièces jointes - testAttachmentNotFoundEmail : email inconnu lance NotFoundHttpException - testAttachmentIndexNotFound : index absent lance NotFoundHttpException - testAttachmentFileNotExists : fichier supprimé lance NotFoundHttpException - testAttachmentSuccess : téléchargement pièce jointe retourne BinaryFileResponse StatsControllerTest (4 tests) : - testIndexCurrentPeriod : période 'current', dates du mois en cours - testIndexCustomPeriod : période 'custom' avec from/to explicites - testIndexMonthsPeriod : période '3', dateFrom = -3 mois - testIndexDefaultPeriod : pas de paramètre, défaut 'current' StatusControllerTest (20 tests) : - testIndexEmpty : catégories vides retourne 200 - testIndexWithServices : catégorie avec service, appel getHistoryForDays/getDailyStatus - testManage : page gestion retourne 200 - testCategoryCreateEmptyName : nom vide redirige avec flash error - testCategoryCreateSuccess : création catégorie avec position redirige avec flash success - testCategoryDelete : suppression catégorie redirige avec flash success - testServiceCreateEmptyName : nom vide redirige avec flash error - testServiceCreateCategoryNotFound : catégorie inexistante redirige avec flash error - testServiceCreateSuccess : création service avec URL redirige avec flash success - testServiceCreateWithExternalType : création service externe avec type http_check - testServiceDelete : suppression service redirige avec flash success - testUpdateValidStatus : statut 'down' avec message, setStatus appelé - testUpdateInvalidStatus : statut invalide redirige avec flash error - testUpdateStatusWithEmptyMessage : statut 'up' sans message (null passé) - testMessageCreateEmptyFields : champs vides redirige avec flash error - testMessageCreateServiceNotFound : service inexistant redirige avec flash error - testMessageCreateSuccessNoUser : message créé sans utilisateur connecté - testMessageCreateSuccessWithUser : message créé avec User injecté via tokenStorage - testMessageResolve : message résolu, isActive=false, resolvedAt non null - testApiDaily : retourne JsonResponse avec données getDailyStatus SyncControllerTest (14 tests) : - testIndexWithMixedPrices : prix avec/sans stripeId, compteurs stripeSynced/stripeNotSynced - testSyncCustomersSuccess : indexation 1 client dans Meilisearch - testSyncCustomersError : exception findAll, flash error - testSyncRevendeursSuccess : indexation 1 revendeur dans Meilisearch - testSyncRevendeursError : exception findAll, flash error - testSyncPricesSuccess : indexation 1 tarif dans Meilisearch - testSyncPricesError : exception findAll, flash error - testSyncStripeWebhooksEmptyUrl : WEBHOOK_BASE_URL vide, flash error - testSyncStripeWebhooksCreatedNew : webhook créé + webhook existant, persist nouveau secret - testSyncStripeWebhooksUpdateExisting : mise à jour secret existant + erreurs Stripe - testSyncStripePricesNoErrors : sync sans erreurs, flash success - testSyncStripePricesWithErrors : sync avec erreurs, flash success + flash errors - testSyncAllSuccess : sync all avec données, flash success - testSyncAllError : exception setupIndexes, flash error ServiceMessageTest (3 tests) : - testConstructorDefaults : valeurs par défaut (info, active, null author/resolvedAt) - testConstructorWithSeverityAndAuthor : severity custom + User author - testResolve : isActive=false, resolvedAt DateTimeImmutable, fluent return StripeWebhookSecretTest (4 tests) : - testConstructorDefaults : type/secret, endpointId null, createdAt DateTimeImmutable - testConstructorWithEndpointId : constructeur avec 3 arguments - testSetSecret : modification du secret - testSetEndpointId : set/unset endpointId (nullable) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 00:42:07 +02:00
<?php
namespace App\Tests\Controller\Admin;
use App\Controller\Admin\SyncController;
use App\Entity\Customer;
use App\Entity\PriceAutomatic;
use App\Entity\Revendeur;
use App\Entity\StripeWebhookSecret;
use App\Repository\CustomerRepository;
use App\Repository\PriceAutomaticRepository;
use App\Repository\RevendeurRepository;
use App\Repository\StripeWebhookSecretRepository;
use App\Service\MeilisearchService;
use App\Service\StripePriceService;
use App\Service\StripeWebhookService;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Twig\Environment;
class SyncControllerTest extends TestCase
{
private function createContainer(): ContainerInterface
{
$session = new Session(new MockArraySessionStorage());
$stack = $this->createStub(RequestStack::class);
$stack->method('getSession')->willReturn($session);
$twig = $this->createStub(Environment::class);
$twig->method('render')->willReturn('<html></html>');
$router = $this->createStub(RouterInterface::class);
$router->method('generate')->willReturn('/admin/sync');
$container = $this->createStub(ContainerInterface::class);
$container->method('has')->willReturn(true);
$container->method('get')->willReturnMap([
['twig', $twig],
['router', $router],
['security.authorization_checker', $this->createStub(AuthorizationCheckerInterface::class)],
['security.token_storage', $this->createStub(TokenStorageInterface::class)],
['request_stack', $stack],
['parameter_bag', $this->createStub(\Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface::class)],
]);
return $container;
}
private function createPriceWithStripe(): PriceAutomatic
{
$price = new PriceAutomatic();
$price->setType('esy-web');
$price->setTitle('Esy-Web');
$price->setPriceHt('100.00');
$price->setStripeId('price_abc123');
return $price;
}
private function createPriceWithoutStripe(): PriceAutomatic
{
$price = new PriceAutomatic();
$price->setType('esy-mail');
$price->setTitle('Esy-Mail');
$price->setPriceHt('50.00');
return $price;
}
public function testIndexWithMixedPrices(): void
{
$customerRepo = $this->createStub(CustomerRepository::class);
$customerRepo->method('count')->willReturn(10);
$revendeurRepo = $this->createStub(RevendeurRepository::class);
$revendeurRepo->method('count')->willReturn(3);
$priceRepo = $this->createStub(PriceAutomaticRepository::class);
$priceRepo->method('findAll')->willReturn([
$this->createPriceWithStripe(),
$this->createPriceWithoutStripe(),
]);
$secretRepo = $this->createStub(StripeWebhookSecretRepository::class);
$secretRepo->method('findAll')->willReturn([]);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$contactRepo = $this->createStub(\Doctrine\ORM\EntityRepository::class);
$contactRepo->method('count')->willReturn(0);
$em = $this->createStub(\Doctrine\ORM\EntityManagerInterface::class);
$em->method('getRepository')->willReturn($contactRepo);
2026-04-07 23:50:19 +02:00
$meilisearch = $this->createStub(MeilisearchService::class);
$response = $controller->index($customerRepo, $revendeurRepo, $priceRepo, $secretRepo, $em, $meilisearch);
refactor: sécurité Discord webhook, tests 100% coverage, factorisation templates PDF et DNS Sécurité - Discord Webhook : - Suppression de l'URL Discord webhook en dur dans CheckDnsCommand (ligne 34) - Ajout de la variable d'environnement DISCORD_WEBHOOK dans .env (vide par défaut) - Injection via #[Autowire(env: 'DISCORD_WEBHOOK')] dans le constructeur - Vérification que le webhook est configuré avant envoi ('' !== $this->discordWebhook) - Remplacement de l'URL en dur dans discord-notify.yml par ${{ secrets.DISCORD_WEBHOOK }} Factorisation DNS (suppression duplication SonarQube) : - Création de src/Service/DnsInfraHelper.php avec les méthodes partagées : enrichWithCloudflare, enrichLastCheck, loadCloudflareRecords, getActualDnsValue, getMxValues, getFirstTxtValue, getSrvValue, checkMxExists, checkTxtContains, checkDnsRecordExists, getTxtSpfValue - Constantes DOMAINS et EXPECTED_MX centralisées dans DnsInfraHelper - Refactorisation de CheckDnsCommand pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) - Refactorisation de DnsReportController pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) Factorisation templates PDF (suppression duplication lignes 6-22) : - Création de templates/pdf/_base.html.twig comme layout commun avec : CSS partagé (banner, container, info-grid, verify-box, hmac, contact-box, data tables), blocs Twig configurables (title, font_size, extra_styles, content, verify_box, hmac_section, footer_contact, signature_box, footer_legal) - Refactorisation de rgpd_access.html.twig : extends _base, accent #4338ca, bloc content avec sessions/events, styles session-meta et no-data - Refactorisation de rgpd_deletion.html.twig : extends _base, accent #dc2626, font 11px, bloc content avec attestation-box et warning - Refactorisation de rgpd_no_data.html.twig : extends _base, accent #fabf04/#111827, font 11px, bloc content avec attestation absence - Refactorisation de admin/logs/pdf.html.twig : extends _base, accent #4338ca, bloc content avec tables utilisateur/requête et HMAC verification box, suppression du bloc signature, footer légal avec Siret/TVA Tests - Couverture 100% (469 tests, 857 assertions, 0 failures) : AnalyticsControllerTest (8 tests) : - testTrackInvalidToken : token incorrect retourne 404 - testTrackEmptyPayload : payload sans clé 'd' retourne 400 - testTrackInvalidEncryptedData : données chiffrées invalides retourne 403 - testTrackNewVisitorCreation : création visiteur avec screen/language/UA, retourne uid+hash - testTrackPageViewWithValidHash : page view avec uid/hash valides retourne 204 - testTrackSetUserWithValidHash : setUser avec uid/hash valides retourne 204 - testTrackWithInvalidHash : hash incorrect retourne 403 - testTrackWithMissingHash : hash absent retourne 403 AttestationControllerTest (8 tests) : - testVerifyNotFound : référence inconnue retourne 200 (template not_found) - testVerifyFound : attestation trouvée retourne 200 (template verify) - testDownloadNotFound : référence inconnue lance NotFoundHttpException - testDownloadNoPdf : attestation sans PDF lance NotFoundHttpException - testDownloadWithPdf : attestation avec PDF signé retourne BinaryFileResponse 200 - testAuditNotFound : référence inconnue lance NotFoundHttpException - testAuditNoCertificate : attestation sans certificat lance NotFoundHttpException - testAuditWithCertificate : attestation avec certificat retourne BinaryFileResponse 200 CspReportControllerTest (13 tests) : - testGetReturns204 : GET /my-csp-report retourne 204 - testReportEmptyPayload : payload vide retourne 400 - testReportInvalidJson : JSON invalide retourne 400 - testReportIgnoredExtension : chrome-extension ignoré, retourne 204 - testReportIgnoredMozExtension : moz-extension ignoré, retourne 204 - testReportIgnoredLocalhost : localhost ignoré, retourne 204 - testReportIgnoredLocalDomain : .local ignoré, retourne 204 - testReportIgnoredWasmEval : wasm-eval ignoré, retourne 204 - testReportIgnoredAboutBlank : about:blank ignoré, retourne 204 - testReportIgnoredNodeModulesInline : node_modules inline ignoré, retourne 204 - testReportRealViolationSendsEmail : violation réelle envoie email, retourne 204 - testReportRealViolationEmailFailure : échec email ne bloque pas, retourne 204 - testReportWithoutCspReportWrapper : payload sans wrapper csp-report fonctionne EmailTrackingControllerTest (10 tests) : - testTrackWithExistingTracking : tracking trouvé, markAsOpened appelé, état 'opened' - testTrackWithNonExistingTracking : tracking absent, retourne image sans erreur - testViewNotFound : messageId inconnu lance NotFoundHttpException - testViewNoHtmlBody : tracking sans htmlBody lance NotFoundHttpException - testViewWithHtmlBody : retourne HTML du tracking - testViewWithAttachments : retourne HTML avec section pièces jointes - testAttachmentNotFoundEmail : email inconnu lance NotFoundHttpException - testAttachmentIndexNotFound : index absent lance NotFoundHttpException - testAttachmentFileNotExists : fichier supprimé lance NotFoundHttpException - testAttachmentSuccess : téléchargement pièce jointe retourne BinaryFileResponse StatsControllerTest (4 tests) : - testIndexCurrentPeriod : période 'current', dates du mois en cours - testIndexCustomPeriod : période 'custom' avec from/to explicites - testIndexMonthsPeriod : période '3', dateFrom = -3 mois - testIndexDefaultPeriod : pas de paramètre, défaut 'current' StatusControllerTest (20 tests) : - testIndexEmpty : catégories vides retourne 200 - testIndexWithServices : catégorie avec service, appel getHistoryForDays/getDailyStatus - testManage : page gestion retourne 200 - testCategoryCreateEmptyName : nom vide redirige avec flash error - testCategoryCreateSuccess : création catégorie avec position redirige avec flash success - testCategoryDelete : suppression catégorie redirige avec flash success - testServiceCreateEmptyName : nom vide redirige avec flash error - testServiceCreateCategoryNotFound : catégorie inexistante redirige avec flash error - testServiceCreateSuccess : création service avec URL redirige avec flash success - testServiceCreateWithExternalType : création service externe avec type http_check - testServiceDelete : suppression service redirige avec flash success - testUpdateValidStatus : statut 'down' avec message, setStatus appelé - testUpdateInvalidStatus : statut invalide redirige avec flash error - testUpdateStatusWithEmptyMessage : statut 'up' sans message (null passé) - testMessageCreateEmptyFields : champs vides redirige avec flash error - testMessageCreateServiceNotFound : service inexistant redirige avec flash error - testMessageCreateSuccessNoUser : message créé sans utilisateur connecté - testMessageCreateSuccessWithUser : message créé avec User injecté via tokenStorage - testMessageResolve : message résolu, isActive=false, resolvedAt non null - testApiDaily : retourne JsonResponse avec données getDailyStatus SyncControllerTest (14 tests) : - testIndexWithMixedPrices : prix avec/sans stripeId, compteurs stripeSynced/stripeNotSynced - testSyncCustomersSuccess : indexation 1 client dans Meilisearch - testSyncCustomersError : exception findAll, flash error - testSyncRevendeursSuccess : indexation 1 revendeur dans Meilisearch - testSyncRevendeursError : exception findAll, flash error - testSyncPricesSuccess : indexation 1 tarif dans Meilisearch - testSyncPricesError : exception findAll, flash error - testSyncStripeWebhooksEmptyUrl : WEBHOOK_BASE_URL vide, flash error - testSyncStripeWebhooksCreatedNew : webhook créé + webhook existant, persist nouveau secret - testSyncStripeWebhooksUpdateExisting : mise à jour secret existant + erreurs Stripe - testSyncStripePricesNoErrors : sync sans erreurs, flash success - testSyncStripePricesWithErrors : sync avec erreurs, flash success + flash errors - testSyncAllSuccess : sync all avec données, flash success - testSyncAllError : exception setupIndexes, flash error ServiceMessageTest (3 tests) : - testConstructorDefaults : valeurs par défaut (info, active, null author/resolvedAt) - testConstructorWithSeverityAndAuthor : severity custom + User author - testResolve : isActive=false, resolvedAt DateTimeImmutable, fluent return StripeWebhookSecretTest (4 tests) : - testConstructorDefaults : type/secret, endpointId null, createdAt DateTimeImmutable - testConstructorWithEndpointId : constructeur avec 3 arguments - testSetSecret : modification du secret - testSetEndpointId : set/unset endpointId (nullable) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 00:42:07 +02:00
$this->assertSame(200, $response->getStatusCode());
}
public function testSyncCustomersSuccess(): void
{
$customer = $this->createStub(Customer::class);
$customerRepo = $this->createStub(CustomerRepository::class);
$customerRepo->method('findAll')->willReturn([$customer]);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncCustomers($customerRepo, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncCustomersError(): void
{
$customerRepo = $this->createStub(CustomerRepository::class);
$customerRepo->method('findAll')->willThrowException(new \RuntimeException('Connection refused'));
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncCustomers($customerRepo, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncRevendeursSuccess(): void
{
$revendeur = $this->createStub(Revendeur::class);
$revendeurRepo = $this->createStub(RevendeurRepository::class);
$revendeurRepo->method('findAll')->willReturn([$revendeur]);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncRevendeurs($revendeurRepo, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncRevendeursError(): void
{
$revendeurRepo = $this->createStub(RevendeurRepository::class);
$revendeurRepo->method('findAll')->willThrowException(new \RuntimeException('Timeout'));
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncRevendeurs($revendeurRepo, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncPricesSuccess(): void
{
$price = $this->createPriceWithStripe();
$priceRepo = $this->createStub(PriceAutomaticRepository::class);
$priceRepo->method('findAll')->willReturn([$price]);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncPrices($priceRepo, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncPricesError(): void
{
$priceRepo = $this->createStub(PriceAutomaticRepository::class);
$priceRepo->method('findAll')->willThrowException(new \RuntimeException('Error'));
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncPrices($priceRepo, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncStripeWebhooksEmptyUrl(): void
{
$webhookService = $this->createStub(StripeWebhookService::class);
$secretRepo = $this->createStub(StripeWebhookSecretRepository::class);
$em = $this->createStub(EntityManagerInterface::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncStripeWebhooks($webhookService, $secretRepo, $em, '');
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncStripeWebhooksCreatedNew(): void
{
$webhookService = $this->createStub(StripeWebhookService::class);
$webhookService->method('createAllWebhooks')->willReturn([
'created' => [
['type' => 'Main Light', 'id' => 'we_123', 'status' => 'created', 'secret' => 'whsec_abc'],
['type' => 'Main Instant', 'id' => 'we_456', 'status' => 'exists'],
],
'errors' => [],
]);
$secretRepo = $this->createStub(StripeWebhookSecretRepository::class);
$secretRepo->method('findByType')->willReturn(null);
$em = $this->createStub(EntityManagerInterface::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
feat: comptabilite + prestataires + rapport financier + stats dynamiques Comptabilite (Super Admin) : - ComptabiliteController avec 7 exports CSV/JSON compatibles SAGE (journal ventes, grand livre, FEC, balance agee, reglements, commissions Stripe 1.5%+0.25E, couts services) - Export PDF via ComptaPdf (FPDF) avec bloc legal pre-rempli, tableau pagine, champ signature DocuSeal - Signature electronique DocuSeal + callback + envoi email signe avec template dedie (compta_export_signed.html.twig) - Rapport financier public (RapportFinancierPdf) : recettes par service, depenses (Stripe, infra, prestataires), bilan excedent/deficit - Codes comptables clients EC-XXXX (plus de 411xxx) Prestataires (Super Admin) : - Entite Prestataire (raisonSociale, siret, email, phone, adresse) - Entite FacturePrestataire (numFacture, montantHt, montantTtc, year, month, isPaid, PDF via Vich) - CRUD complet avec recherche SIRET via proxy API data.gouv.fr - Commande cron app:reminder:factures-prestataire (5 du mois) - Factures prestataires integrees dans export couts services - Sidebar Super Admin : entree Prestataires + Comptabilite Stats (/admin/stats) : - Cout prestataire dynamique depuis FacturePrestataire - Fusion Infra + Prestataire en "Cout de fonctionnement" - Commission Stripe corrigee (1.5% + 0.25E par transaction) Divers : - DocuSealService::sendComptaForSignature() + getApi() - Customer::generateCodeComptable() format EC-XXXX-XXXXX - Protection double prefixe EC- a la creation client - Bouton regenerer PDF cache quand advert state=accepted - Modals sans script inline (data-modal-open/close dans app.js) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 23:39:31 +02:00
$response = $controller->syncStripeWebhooks($webhookService, $secretRepo, $em, 'https://crm.e-cosplay.fr');
refactor: sécurité Discord webhook, tests 100% coverage, factorisation templates PDF et DNS Sécurité - Discord Webhook : - Suppression de l'URL Discord webhook en dur dans CheckDnsCommand (ligne 34) - Ajout de la variable d'environnement DISCORD_WEBHOOK dans .env (vide par défaut) - Injection via #[Autowire(env: 'DISCORD_WEBHOOK')] dans le constructeur - Vérification que le webhook est configuré avant envoi ('' !== $this->discordWebhook) - Remplacement de l'URL en dur dans discord-notify.yml par ${{ secrets.DISCORD_WEBHOOK }} Factorisation DNS (suppression duplication SonarQube) : - Création de src/Service/DnsInfraHelper.php avec les méthodes partagées : enrichWithCloudflare, enrichLastCheck, loadCloudflareRecords, getActualDnsValue, getMxValues, getFirstTxtValue, getSrvValue, checkMxExists, checkTxtContains, checkDnsRecordExists, getTxtSpfValue - Constantes DOMAINS et EXPECTED_MX centralisées dans DnsInfraHelper - Refactorisation de CheckDnsCommand pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) - Refactorisation de DnsReportController pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) Factorisation templates PDF (suppression duplication lignes 6-22) : - Création de templates/pdf/_base.html.twig comme layout commun avec : CSS partagé (banner, container, info-grid, verify-box, hmac, contact-box, data tables), blocs Twig configurables (title, font_size, extra_styles, content, verify_box, hmac_section, footer_contact, signature_box, footer_legal) - Refactorisation de rgpd_access.html.twig : extends _base, accent #4338ca, bloc content avec sessions/events, styles session-meta et no-data - Refactorisation de rgpd_deletion.html.twig : extends _base, accent #dc2626, font 11px, bloc content avec attestation-box et warning - Refactorisation de rgpd_no_data.html.twig : extends _base, accent #fabf04/#111827, font 11px, bloc content avec attestation absence - Refactorisation de admin/logs/pdf.html.twig : extends _base, accent #4338ca, bloc content avec tables utilisateur/requête et HMAC verification box, suppression du bloc signature, footer légal avec Siret/TVA Tests - Couverture 100% (469 tests, 857 assertions, 0 failures) : AnalyticsControllerTest (8 tests) : - testTrackInvalidToken : token incorrect retourne 404 - testTrackEmptyPayload : payload sans clé 'd' retourne 400 - testTrackInvalidEncryptedData : données chiffrées invalides retourne 403 - testTrackNewVisitorCreation : création visiteur avec screen/language/UA, retourne uid+hash - testTrackPageViewWithValidHash : page view avec uid/hash valides retourne 204 - testTrackSetUserWithValidHash : setUser avec uid/hash valides retourne 204 - testTrackWithInvalidHash : hash incorrect retourne 403 - testTrackWithMissingHash : hash absent retourne 403 AttestationControllerTest (8 tests) : - testVerifyNotFound : référence inconnue retourne 200 (template not_found) - testVerifyFound : attestation trouvée retourne 200 (template verify) - testDownloadNotFound : référence inconnue lance NotFoundHttpException - testDownloadNoPdf : attestation sans PDF lance NotFoundHttpException - testDownloadWithPdf : attestation avec PDF signé retourne BinaryFileResponse 200 - testAuditNotFound : référence inconnue lance NotFoundHttpException - testAuditNoCertificate : attestation sans certificat lance NotFoundHttpException - testAuditWithCertificate : attestation avec certificat retourne BinaryFileResponse 200 CspReportControllerTest (13 tests) : - testGetReturns204 : GET /my-csp-report retourne 204 - testReportEmptyPayload : payload vide retourne 400 - testReportInvalidJson : JSON invalide retourne 400 - testReportIgnoredExtension : chrome-extension ignoré, retourne 204 - testReportIgnoredMozExtension : moz-extension ignoré, retourne 204 - testReportIgnoredLocalhost : localhost ignoré, retourne 204 - testReportIgnoredLocalDomain : .local ignoré, retourne 204 - testReportIgnoredWasmEval : wasm-eval ignoré, retourne 204 - testReportIgnoredAboutBlank : about:blank ignoré, retourne 204 - testReportIgnoredNodeModulesInline : node_modules inline ignoré, retourne 204 - testReportRealViolationSendsEmail : violation réelle envoie email, retourne 204 - testReportRealViolationEmailFailure : échec email ne bloque pas, retourne 204 - testReportWithoutCspReportWrapper : payload sans wrapper csp-report fonctionne EmailTrackingControllerTest (10 tests) : - testTrackWithExistingTracking : tracking trouvé, markAsOpened appelé, état 'opened' - testTrackWithNonExistingTracking : tracking absent, retourne image sans erreur - testViewNotFound : messageId inconnu lance NotFoundHttpException - testViewNoHtmlBody : tracking sans htmlBody lance NotFoundHttpException - testViewWithHtmlBody : retourne HTML du tracking - testViewWithAttachments : retourne HTML avec section pièces jointes - testAttachmentNotFoundEmail : email inconnu lance NotFoundHttpException - testAttachmentIndexNotFound : index absent lance NotFoundHttpException - testAttachmentFileNotExists : fichier supprimé lance NotFoundHttpException - testAttachmentSuccess : téléchargement pièce jointe retourne BinaryFileResponse StatsControllerTest (4 tests) : - testIndexCurrentPeriod : période 'current', dates du mois en cours - testIndexCustomPeriod : période 'custom' avec from/to explicites - testIndexMonthsPeriod : période '3', dateFrom = -3 mois - testIndexDefaultPeriod : pas de paramètre, défaut 'current' StatusControllerTest (20 tests) : - testIndexEmpty : catégories vides retourne 200 - testIndexWithServices : catégorie avec service, appel getHistoryForDays/getDailyStatus - testManage : page gestion retourne 200 - testCategoryCreateEmptyName : nom vide redirige avec flash error - testCategoryCreateSuccess : création catégorie avec position redirige avec flash success - testCategoryDelete : suppression catégorie redirige avec flash success - testServiceCreateEmptyName : nom vide redirige avec flash error - testServiceCreateCategoryNotFound : catégorie inexistante redirige avec flash error - testServiceCreateSuccess : création service avec URL redirige avec flash success - testServiceCreateWithExternalType : création service externe avec type http_check - testServiceDelete : suppression service redirige avec flash success - testUpdateValidStatus : statut 'down' avec message, setStatus appelé - testUpdateInvalidStatus : statut invalide redirige avec flash error - testUpdateStatusWithEmptyMessage : statut 'up' sans message (null passé) - testMessageCreateEmptyFields : champs vides redirige avec flash error - testMessageCreateServiceNotFound : service inexistant redirige avec flash error - testMessageCreateSuccessNoUser : message créé sans utilisateur connecté - testMessageCreateSuccessWithUser : message créé avec User injecté via tokenStorage - testMessageResolve : message résolu, isActive=false, resolvedAt non null - testApiDaily : retourne JsonResponse avec données getDailyStatus SyncControllerTest (14 tests) : - testIndexWithMixedPrices : prix avec/sans stripeId, compteurs stripeSynced/stripeNotSynced - testSyncCustomersSuccess : indexation 1 client dans Meilisearch - testSyncCustomersError : exception findAll, flash error - testSyncRevendeursSuccess : indexation 1 revendeur dans Meilisearch - testSyncRevendeursError : exception findAll, flash error - testSyncPricesSuccess : indexation 1 tarif dans Meilisearch - testSyncPricesError : exception findAll, flash error - testSyncStripeWebhooksEmptyUrl : WEBHOOK_BASE_URL vide, flash error - testSyncStripeWebhooksCreatedNew : webhook créé + webhook existant, persist nouveau secret - testSyncStripeWebhooksUpdateExisting : mise à jour secret existant + erreurs Stripe - testSyncStripePricesNoErrors : sync sans erreurs, flash success - testSyncStripePricesWithErrors : sync avec erreurs, flash success + flash errors - testSyncAllSuccess : sync all avec données, flash success - testSyncAllError : exception setupIndexes, flash error ServiceMessageTest (3 tests) : - testConstructorDefaults : valeurs par défaut (info, active, null author/resolvedAt) - testConstructorWithSeverityAndAuthor : severity custom + User author - testResolve : isActive=false, resolvedAt DateTimeImmutable, fluent return StripeWebhookSecretTest (4 tests) : - testConstructorDefaults : type/secret, endpointId null, createdAt DateTimeImmutable - testConstructorWithEndpointId : constructeur avec 3 arguments - testSetSecret : modification du secret - testSetEndpointId : set/unset endpointId (nullable) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 00:42:07 +02:00
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncStripeWebhooksUpdateExisting(): void
{
$existing = new StripeWebhookSecret(StripeWebhookSecret::TYPE_MAIN_LIGHT, 'old_secret', 'we_old');
$webhookService = $this->createStub(StripeWebhookService::class);
$webhookService->method('createAllWebhooks')->willReturn([
'created' => [
['type' => 'Main Light', 'id' => 'we_new', 'status' => 'created', 'secret' => 'whsec_new'],
],
'errors' => ['Connect webhook failed'],
]);
$secretRepo = $this->createStub(StripeWebhookSecretRepository::class);
$secretRepo->method('findByType')->willReturn($existing);
$em = $this->createStub(EntityManagerInterface::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
feat: comptabilite + prestataires + rapport financier + stats dynamiques Comptabilite (Super Admin) : - ComptabiliteController avec 7 exports CSV/JSON compatibles SAGE (journal ventes, grand livre, FEC, balance agee, reglements, commissions Stripe 1.5%+0.25E, couts services) - Export PDF via ComptaPdf (FPDF) avec bloc legal pre-rempli, tableau pagine, champ signature DocuSeal - Signature electronique DocuSeal + callback + envoi email signe avec template dedie (compta_export_signed.html.twig) - Rapport financier public (RapportFinancierPdf) : recettes par service, depenses (Stripe, infra, prestataires), bilan excedent/deficit - Codes comptables clients EC-XXXX (plus de 411xxx) Prestataires (Super Admin) : - Entite Prestataire (raisonSociale, siret, email, phone, adresse) - Entite FacturePrestataire (numFacture, montantHt, montantTtc, year, month, isPaid, PDF via Vich) - CRUD complet avec recherche SIRET via proxy API data.gouv.fr - Commande cron app:reminder:factures-prestataire (5 du mois) - Factures prestataires integrees dans export couts services - Sidebar Super Admin : entree Prestataires + Comptabilite Stats (/admin/stats) : - Cout prestataire dynamique depuis FacturePrestataire - Fusion Infra + Prestataire en "Cout de fonctionnement" - Commission Stripe corrigee (1.5% + 0.25E par transaction) Divers : - DocuSealService::sendComptaForSignature() + getApi() - Customer::generateCodeComptable() format EC-XXXX-XXXXX - Protection double prefixe EC- a la creation client - Bouton regenerer PDF cache quand advert state=accepted - Modals sans script inline (data-modal-open/close dans app.js) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 23:39:31 +02:00
$response = $controller->syncStripeWebhooks($webhookService, $secretRepo, $em, 'https://crm.e-cosplay.fr/');
refactor: sécurité Discord webhook, tests 100% coverage, factorisation templates PDF et DNS Sécurité - Discord Webhook : - Suppression de l'URL Discord webhook en dur dans CheckDnsCommand (ligne 34) - Ajout de la variable d'environnement DISCORD_WEBHOOK dans .env (vide par défaut) - Injection via #[Autowire(env: 'DISCORD_WEBHOOK')] dans le constructeur - Vérification que le webhook est configuré avant envoi ('' !== $this->discordWebhook) - Remplacement de l'URL en dur dans discord-notify.yml par ${{ secrets.DISCORD_WEBHOOK }} Factorisation DNS (suppression duplication SonarQube) : - Création de src/Service/DnsInfraHelper.php avec les méthodes partagées : enrichWithCloudflare, enrichLastCheck, loadCloudflareRecords, getActualDnsValue, getMxValues, getFirstTxtValue, getSrvValue, checkMxExists, checkTxtContains, checkDnsRecordExists, getTxtSpfValue - Constantes DOMAINS et EXPECTED_MX centralisées dans DnsInfraHelper - Refactorisation de CheckDnsCommand pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) - Refactorisation de DnsReportController pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) Factorisation templates PDF (suppression duplication lignes 6-22) : - Création de templates/pdf/_base.html.twig comme layout commun avec : CSS partagé (banner, container, info-grid, verify-box, hmac, contact-box, data tables), blocs Twig configurables (title, font_size, extra_styles, content, verify_box, hmac_section, footer_contact, signature_box, footer_legal) - Refactorisation de rgpd_access.html.twig : extends _base, accent #4338ca, bloc content avec sessions/events, styles session-meta et no-data - Refactorisation de rgpd_deletion.html.twig : extends _base, accent #dc2626, font 11px, bloc content avec attestation-box et warning - Refactorisation de rgpd_no_data.html.twig : extends _base, accent #fabf04/#111827, font 11px, bloc content avec attestation absence - Refactorisation de admin/logs/pdf.html.twig : extends _base, accent #4338ca, bloc content avec tables utilisateur/requête et HMAC verification box, suppression du bloc signature, footer légal avec Siret/TVA Tests - Couverture 100% (469 tests, 857 assertions, 0 failures) : AnalyticsControllerTest (8 tests) : - testTrackInvalidToken : token incorrect retourne 404 - testTrackEmptyPayload : payload sans clé 'd' retourne 400 - testTrackInvalidEncryptedData : données chiffrées invalides retourne 403 - testTrackNewVisitorCreation : création visiteur avec screen/language/UA, retourne uid+hash - testTrackPageViewWithValidHash : page view avec uid/hash valides retourne 204 - testTrackSetUserWithValidHash : setUser avec uid/hash valides retourne 204 - testTrackWithInvalidHash : hash incorrect retourne 403 - testTrackWithMissingHash : hash absent retourne 403 AttestationControllerTest (8 tests) : - testVerifyNotFound : référence inconnue retourne 200 (template not_found) - testVerifyFound : attestation trouvée retourne 200 (template verify) - testDownloadNotFound : référence inconnue lance NotFoundHttpException - testDownloadNoPdf : attestation sans PDF lance NotFoundHttpException - testDownloadWithPdf : attestation avec PDF signé retourne BinaryFileResponse 200 - testAuditNotFound : référence inconnue lance NotFoundHttpException - testAuditNoCertificate : attestation sans certificat lance NotFoundHttpException - testAuditWithCertificate : attestation avec certificat retourne BinaryFileResponse 200 CspReportControllerTest (13 tests) : - testGetReturns204 : GET /my-csp-report retourne 204 - testReportEmptyPayload : payload vide retourne 400 - testReportInvalidJson : JSON invalide retourne 400 - testReportIgnoredExtension : chrome-extension ignoré, retourne 204 - testReportIgnoredMozExtension : moz-extension ignoré, retourne 204 - testReportIgnoredLocalhost : localhost ignoré, retourne 204 - testReportIgnoredLocalDomain : .local ignoré, retourne 204 - testReportIgnoredWasmEval : wasm-eval ignoré, retourne 204 - testReportIgnoredAboutBlank : about:blank ignoré, retourne 204 - testReportIgnoredNodeModulesInline : node_modules inline ignoré, retourne 204 - testReportRealViolationSendsEmail : violation réelle envoie email, retourne 204 - testReportRealViolationEmailFailure : échec email ne bloque pas, retourne 204 - testReportWithoutCspReportWrapper : payload sans wrapper csp-report fonctionne EmailTrackingControllerTest (10 tests) : - testTrackWithExistingTracking : tracking trouvé, markAsOpened appelé, état 'opened' - testTrackWithNonExistingTracking : tracking absent, retourne image sans erreur - testViewNotFound : messageId inconnu lance NotFoundHttpException - testViewNoHtmlBody : tracking sans htmlBody lance NotFoundHttpException - testViewWithHtmlBody : retourne HTML du tracking - testViewWithAttachments : retourne HTML avec section pièces jointes - testAttachmentNotFoundEmail : email inconnu lance NotFoundHttpException - testAttachmentIndexNotFound : index absent lance NotFoundHttpException - testAttachmentFileNotExists : fichier supprimé lance NotFoundHttpException - testAttachmentSuccess : téléchargement pièce jointe retourne BinaryFileResponse StatsControllerTest (4 tests) : - testIndexCurrentPeriod : période 'current', dates du mois en cours - testIndexCustomPeriod : période 'custom' avec from/to explicites - testIndexMonthsPeriod : période '3', dateFrom = -3 mois - testIndexDefaultPeriod : pas de paramètre, défaut 'current' StatusControllerTest (20 tests) : - testIndexEmpty : catégories vides retourne 200 - testIndexWithServices : catégorie avec service, appel getHistoryForDays/getDailyStatus - testManage : page gestion retourne 200 - testCategoryCreateEmptyName : nom vide redirige avec flash error - testCategoryCreateSuccess : création catégorie avec position redirige avec flash success - testCategoryDelete : suppression catégorie redirige avec flash success - testServiceCreateEmptyName : nom vide redirige avec flash error - testServiceCreateCategoryNotFound : catégorie inexistante redirige avec flash error - testServiceCreateSuccess : création service avec URL redirige avec flash success - testServiceCreateWithExternalType : création service externe avec type http_check - testServiceDelete : suppression service redirige avec flash success - testUpdateValidStatus : statut 'down' avec message, setStatus appelé - testUpdateInvalidStatus : statut invalide redirige avec flash error - testUpdateStatusWithEmptyMessage : statut 'up' sans message (null passé) - testMessageCreateEmptyFields : champs vides redirige avec flash error - testMessageCreateServiceNotFound : service inexistant redirige avec flash error - testMessageCreateSuccessNoUser : message créé sans utilisateur connecté - testMessageCreateSuccessWithUser : message créé avec User injecté via tokenStorage - testMessageResolve : message résolu, isActive=false, resolvedAt non null - testApiDaily : retourne JsonResponse avec données getDailyStatus SyncControllerTest (14 tests) : - testIndexWithMixedPrices : prix avec/sans stripeId, compteurs stripeSynced/stripeNotSynced - testSyncCustomersSuccess : indexation 1 client dans Meilisearch - testSyncCustomersError : exception findAll, flash error - testSyncRevendeursSuccess : indexation 1 revendeur dans Meilisearch - testSyncRevendeursError : exception findAll, flash error - testSyncPricesSuccess : indexation 1 tarif dans Meilisearch - testSyncPricesError : exception findAll, flash error - testSyncStripeWebhooksEmptyUrl : WEBHOOK_BASE_URL vide, flash error - testSyncStripeWebhooksCreatedNew : webhook créé + webhook existant, persist nouveau secret - testSyncStripeWebhooksUpdateExisting : mise à jour secret existant + erreurs Stripe - testSyncStripePricesNoErrors : sync sans erreurs, flash success - testSyncStripePricesWithErrors : sync avec erreurs, flash success + flash errors - testSyncAllSuccess : sync all avec données, flash success - testSyncAllError : exception setupIndexes, flash error ServiceMessageTest (3 tests) : - testConstructorDefaults : valeurs par défaut (info, active, null author/resolvedAt) - testConstructorWithSeverityAndAuthor : severity custom + User author - testResolve : isActive=false, resolvedAt DateTimeImmutable, fluent return StripeWebhookSecretTest (4 tests) : - testConstructorDefaults : type/secret, endpointId null, createdAt DateTimeImmutable - testConstructorWithEndpointId : constructeur avec 3 arguments - testSetSecret : modification du secret - testSetEndpointId : set/unset endpointId (nullable) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 00:42:07 +02:00
$this->assertSame(302, $response->getStatusCode());
$this->assertSame('whsec_new', $existing->getSecret());
$this->assertSame('we_new', $existing->getEndpointId());
}
public function testSyncStripePricesNoErrors(): void
{
$stripePriceService = $this->createStub(StripePriceService::class);
$stripePriceService->method('syncAll')->willReturn(['synced' => 5, 'errors' => []]);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncStripePrices($stripePriceService);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncStripePricesWithErrors(): void
{
$stripePriceService = $this->createStub(StripePriceService::class);
$stripePriceService->method('syncAll')->willReturn(['synced' => 3, 'errors' => ['Price X failed', 'Price Y failed']]);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncStripePrices($stripePriceService);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncAllSuccess(): void
{
$customerRepo = $this->createStub(CustomerRepository::class);
$customerRepo->method('findAll')->willReturn([$this->createStub(Customer::class)]);
$revendeurRepo = $this->createStub(RevendeurRepository::class);
$revendeurRepo->method('findAll')->willReturn([$this->createStub(Revendeur::class)]);
$priceRepo = $this->createStub(PriceAutomaticRepository::class);
$priceRepo->method('findAll')->willReturn([$this->createPriceWithStripe()]);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncAll($customerRepo, $revendeurRepo, $priceRepo, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncAllError(): void
{
$customerRepo = $this->createStub(CustomerRepository::class);
$customerRepo->method('findAll')->willReturn([]);
$revendeurRepo = $this->createStub(RevendeurRepository::class);
$revendeurRepo->method('findAll')->willReturn([]);
$priceRepo = $this->createStub(PriceAutomaticRepository::class);
$priceRepo->method('findAll')->willReturn([]);
$meilisearch = $this->createStub(MeilisearchService::class);
$meilisearch->method('setupIndexes')->willThrowException(new \RuntimeException('Meilisearch down'));
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncAll($customerRepo, $revendeurRepo, $priceRepo, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
test: couverture 83% methodes (1046 tests, 2135 assertions) Entites completes a 100% : - AdvertTest : 12 nouveaux (state, customer, totals, hmac, lines, payments) - CustomerTest : 3 nouveaux (isPendingDelete, revendeurCode, updatedAt) - DevisTest : 6 nouveaux (customer, submissionId, lines, state constants) - FactureTest : 10 nouveaux (state, totals, isPaid, lines, hmac, splitIndex) - OrderNumberTest : 1 nouveau (markAsUnused) - WebsiteTest : 1 nouveau (revendeurCode) Services completes/ameliores : - DocuSealServiceTest : 30 nouveaux (sendDevis, resendDevis, download, compta) - AdvertServiceTest : 6 nouveaux (isTvaEnabled, getTvaRate, computeTotals) - DevisServiceTest : 6 nouveaux (idem) - FactureServiceTest : 8 nouveaux (idem + createPaidFactureFromAdvert) - MailerServiceTest : 7 nouveaux (unsubscribe headers, VCF, formatFileSize) - MeilisearchServiceTest : 42 nouveaux (index/remove/search tous types) - RgpdServiceTest : 6 nouveaux (sendVerificationCode, verifyCode) - OrderNumberServiceTest : 2 nouveaux (preview/generate unused) - TarificationServiceTest : 1 nouveau (stripe error logger) - ComptaPdfTest : 4 nouveaux (totaux, colonnes numeriques, signature) - FacturePdfTest : 6 nouveaux (QR code, RIB, CGV Twig, footer skip) Controllers ameliores : - ComptabiliteControllerTest : 13 nouveaux (JSON, PDF, sign, callback) - StatsControllerTest : 2 nouveaux (rich data, 6-month evolution) - SyncControllerTest : 13 nouveaux (sync 6 types + purge) - ClientsControllerTest : 7 nouveaux (show, delete, resendWelcome) - FactureControllerTest : 2 nouveaux (generatePdf 404, send success) - LegalControllerTest : 6 nouveaux (rgpdVerify GET/POST) - TarificationControllerTest : 3 nouveaux (purge paths) - AdminControllersTest : 9 nouveaux (dashboard search, services) - WebhookStripeControllerTest : 3 nouveaux (invalid signatures) - KeycloakAuthenticatorTest : 4 nouveaux (groups, domain check) Commands : - PaymentReminderCommandTest : 1 nouveau (formalNotice step) - TestMailCommandTest : 2 nouveaux (force-dsn success/failure) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 00:13:00 +02:00
private function createEntityRepo(array $items = []): \Doctrine\ORM\EntityRepository
{
$repo = $this->createStub(\Doctrine\ORM\EntityRepository::class);
$repo->method('findAll')->willReturn($items);
return $repo;
}
public function testSyncContactsSuccess(): void
{
$repo = $this->createEntityRepo([$this->createStub(\App\Entity\CustomerContact::class)]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncContacts($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncContactsError(): void
{
$repo = $this->createEntityRepo([]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$meilisearch->method('setupIndexes')->willThrowException(new \RuntimeException('down'));
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncContacts($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncDomainsSuccess(): void
{
$repo = $this->createEntityRepo([$this->createStub(\App\Entity\Domain::class)]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncDomains($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncDomainsError(): void
{
$repo = $this->createEntityRepo([]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$meilisearch->method('setupIndexes')->willThrowException(new \RuntimeException('down'));
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncDomains($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncWebsitesSuccess(): void
{
$repo = $this->createEntityRepo([$this->createStub(\App\Entity\Website::class)]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncWebsites($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncWebsitesError(): void
{
$repo = $this->createEntityRepo([]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$meilisearch->method('setupIndexes')->willThrowException(new \RuntimeException('down'));
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncWebsites($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncDevisSuccess(): void
{
$repo = $this->createEntityRepo([$this->createStub(\App\Entity\Devis::class)]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncDevis($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncDevisError(): void
{
$repo = $this->createEntityRepo([]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$meilisearch->method('setupIndexes')->willThrowException(new \RuntimeException('down'));
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncDevis($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncAdvertsSuccess(): void
{
$repo = $this->createEntityRepo([$this->createStub(\App\Entity\Advert::class)]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncAdverts($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncAdvertsError(): void
{
$repo = $this->createEntityRepo([]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$meilisearch->method('setupIndexes')->willThrowException(new \RuntimeException('down'));
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncAdverts($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncFacturesSuccess(): void
{
$repo = $this->createEntityRepo([$this->createStub(\App\Entity\Facture::class)]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncFactures($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testSyncFacturesError(): void
{
$repo = $this->createEntityRepo([]);
$em = $this->createStub(EntityManagerInterface::class);
$em->method('getRepository')->willReturn($repo);
$meilisearch = $this->createStub(MeilisearchService::class);
$meilisearch->method('setupIndexes')->willThrowException(new \RuntimeException('down'));
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->syncFactures($em, $meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
public function testPurgeIndexesRedirects(): void
{
$meilisearch = $this->createStub(MeilisearchService::class);
$controller = new SyncController();
$controller->setContainer($this->createContainer());
$response = $controller->purgeIndexes($meilisearch);
$this->assertSame(302, $response->getStatusCode());
}
refactor: sécurité Discord webhook, tests 100% coverage, factorisation templates PDF et DNS Sécurité - Discord Webhook : - Suppression de l'URL Discord webhook en dur dans CheckDnsCommand (ligne 34) - Ajout de la variable d'environnement DISCORD_WEBHOOK dans .env (vide par défaut) - Injection via #[Autowire(env: 'DISCORD_WEBHOOK')] dans le constructeur - Vérification que le webhook est configuré avant envoi ('' !== $this->discordWebhook) - Remplacement de l'URL en dur dans discord-notify.yml par ${{ secrets.DISCORD_WEBHOOK }} Factorisation DNS (suppression duplication SonarQube) : - Création de src/Service/DnsInfraHelper.php avec les méthodes partagées : enrichWithCloudflare, enrichLastCheck, loadCloudflareRecords, getActualDnsValue, getMxValues, getFirstTxtValue, getSrvValue, checkMxExists, checkTxtContains, checkDnsRecordExists, getTxtSpfValue - Constantes DOMAINS et EXPECTED_MX centralisées dans DnsInfraHelper - Refactorisation de CheckDnsCommand pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) - Refactorisation de DnsReportController pour utiliser DnsInfraHelper au lieu des méthodes privées dupliquées (enrichWithCloudflare, enrichLastCheck, etc.) Factorisation templates PDF (suppression duplication lignes 6-22) : - Création de templates/pdf/_base.html.twig comme layout commun avec : CSS partagé (banner, container, info-grid, verify-box, hmac, contact-box, data tables), blocs Twig configurables (title, font_size, extra_styles, content, verify_box, hmac_section, footer_contact, signature_box, footer_legal) - Refactorisation de rgpd_access.html.twig : extends _base, accent #4338ca, bloc content avec sessions/events, styles session-meta et no-data - Refactorisation de rgpd_deletion.html.twig : extends _base, accent #dc2626, font 11px, bloc content avec attestation-box et warning - Refactorisation de rgpd_no_data.html.twig : extends _base, accent #fabf04/#111827, font 11px, bloc content avec attestation absence - Refactorisation de admin/logs/pdf.html.twig : extends _base, accent #4338ca, bloc content avec tables utilisateur/requête et HMAC verification box, suppression du bloc signature, footer légal avec Siret/TVA Tests - Couverture 100% (469 tests, 857 assertions, 0 failures) : AnalyticsControllerTest (8 tests) : - testTrackInvalidToken : token incorrect retourne 404 - testTrackEmptyPayload : payload sans clé 'd' retourne 400 - testTrackInvalidEncryptedData : données chiffrées invalides retourne 403 - testTrackNewVisitorCreation : création visiteur avec screen/language/UA, retourne uid+hash - testTrackPageViewWithValidHash : page view avec uid/hash valides retourne 204 - testTrackSetUserWithValidHash : setUser avec uid/hash valides retourne 204 - testTrackWithInvalidHash : hash incorrect retourne 403 - testTrackWithMissingHash : hash absent retourne 403 AttestationControllerTest (8 tests) : - testVerifyNotFound : référence inconnue retourne 200 (template not_found) - testVerifyFound : attestation trouvée retourne 200 (template verify) - testDownloadNotFound : référence inconnue lance NotFoundHttpException - testDownloadNoPdf : attestation sans PDF lance NotFoundHttpException - testDownloadWithPdf : attestation avec PDF signé retourne BinaryFileResponse 200 - testAuditNotFound : référence inconnue lance NotFoundHttpException - testAuditNoCertificate : attestation sans certificat lance NotFoundHttpException - testAuditWithCertificate : attestation avec certificat retourne BinaryFileResponse 200 CspReportControllerTest (13 tests) : - testGetReturns204 : GET /my-csp-report retourne 204 - testReportEmptyPayload : payload vide retourne 400 - testReportInvalidJson : JSON invalide retourne 400 - testReportIgnoredExtension : chrome-extension ignoré, retourne 204 - testReportIgnoredMozExtension : moz-extension ignoré, retourne 204 - testReportIgnoredLocalhost : localhost ignoré, retourne 204 - testReportIgnoredLocalDomain : .local ignoré, retourne 204 - testReportIgnoredWasmEval : wasm-eval ignoré, retourne 204 - testReportIgnoredAboutBlank : about:blank ignoré, retourne 204 - testReportIgnoredNodeModulesInline : node_modules inline ignoré, retourne 204 - testReportRealViolationSendsEmail : violation réelle envoie email, retourne 204 - testReportRealViolationEmailFailure : échec email ne bloque pas, retourne 204 - testReportWithoutCspReportWrapper : payload sans wrapper csp-report fonctionne EmailTrackingControllerTest (10 tests) : - testTrackWithExistingTracking : tracking trouvé, markAsOpened appelé, état 'opened' - testTrackWithNonExistingTracking : tracking absent, retourne image sans erreur - testViewNotFound : messageId inconnu lance NotFoundHttpException - testViewNoHtmlBody : tracking sans htmlBody lance NotFoundHttpException - testViewWithHtmlBody : retourne HTML du tracking - testViewWithAttachments : retourne HTML avec section pièces jointes - testAttachmentNotFoundEmail : email inconnu lance NotFoundHttpException - testAttachmentIndexNotFound : index absent lance NotFoundHttpException - testAttachmentFileNotExists : fichier supprimé lance NotFoundHttpException - testAttachmentSuccess : téléchargement pièce jointe retourne BinaryFileResponse StatsControllerTest (4 tests) : - testIndexCurrentPeriod : période 'current', dates du mois en cours - testIndexCustomPeriod : période 'custom' avec from/to explicites - testIndexMonthsPeriod : période '3', dateFrom = -3 mois - testIndexDefaultPeriod : pas de paramètre, défaut 'current' StatusControllerTest (20 tests) : - testIndexEmpty : catégories vides retourne 200 - testIndexWithServices : catégorie avec service, appel getHistoryForDays/getDailyStatus - testManage : page gestion retourne 200 - testCategoryCreateEmptyName : nom vide redirige avec flash error - testCategoryCreateSuccess : création catégorie avec position redirige avec flash success - testCategoryDelete : suppression catégorie redirige avec flash success - testServiceCreateEmptyName : nom vide redirige avec flash error - testServiceCreateCategoryNotFound : catégorie inexistante redirige avec flash error - testServiceCreateSuccess : création service avec URL redirige avec flash success - testServiceCreateWithExternalType : création service externe avec type http_check - testServiceDelete : suppression service redirige avec flash success - testUpdateValidStatus : statut 'down' avec message, setStatus appelé - testUpdateInvalidStatus : statut invalide redirige avec flash error - testUpdateStatusWithEmptyMessage : statut 'up' sans message (null passé) - testMessageCreateEmptyFields : champs vides redirige avec flash error - testMessageCreateServiceNotFound : service inexistant redirige avec flash error - testMessageCreateSuccessNoUser : message créé sans utilisateur connecté - testMessageCreateSuccessWithUser : message créé avec User injecté via tokenStorage - testMessageResolve : message résolu, isActive=false, resolvedAt non null - testApiDaily : retourne JsonResponse avec données getDailyStatus SyncControllerTest (14 tests) : - testIndexWithMixedPrices : prix avec/sans stripeId, compteurs stripeSynced/stripeNotSynced - testSyncCustomersSuccess : indexation 1 client dans Meilisearch - testSyncCustomersError : exception findAll, flash error - testSyncRevendeursSuccess : indexation 1 revendeur dans Meilisearch - testSyncRevendeursError : exception findAll, flash error - testSyncPricesSuccess : indexation 1 tarif dans Meilisearch - testSyncPricesError : exception findAll, flash error - testSyncStripeWebhooksEmptyUrl : WEBHOOK_BASE_URL vide, flash error - testSyncStripeWebhooksCreatedNew : webhook créé + webhook existant, persist nouveau secret - testSyncStripeWebhooksUpdateExisting : mise à jour secret existant + erreurs Stripe - testSyncStripePricesNoErrors : sync sans erreurs, flash success - testSyncStripePricesWithErrors : sync avec erreurs, flash success + flash errors - testSyncAllSuccess : sync all avec données, flash success - testSyncAllError : exception setupIndexes, flash error ServiceMessageTest (3 tests) : - testConstructorDefaults : valeurs par défaut (info, active, null author/resolvedAt) - testConstructorWithSeverityAndAuthor : severity custom + User author - testResolve : isActive=false, resolvedAt DateTimeImmutable, fluent return StripeWebhookSecretTest (4 tests) : - testConstructorDefaults : type/secret, endpointId null, createdAt DateTimeImmutable - testConstructorWithEndpointId : constructeur avec 3 arguments - testSetSecret : modification du secret - testSetEndpointId : set/unset endpointId (nullable) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 00:42:07 +02:00
}