diff --git a/config/packages/backoffice_menu.yaml b/config/packages/backoffice_menu.yaml index 4e0cc5648..2be36219b 100644 --- a/config/packages/backoffice_menu.yaml +++ b/config/packages/backoffice_menu.yaml @@ -225,6 +225,8 @@ parameters: - admin_speaker_list - admin_speaker_add - admin_speaker_edit + - admin_speaker_pick + - admin_speaker_person admin_event_speakers_management: nom: 'Infos speakers' niveau: 'ROLE_EVENT_READER' diff --git a/config/routing/admin_speaker.yml b/config/routing/admin_speaker.yml index 61830f47f..826c66842 100644 --- a/config/routing/admin_speaker.yml +++ b/config/routing/admin_speaker.yml @@ -25,3 +25,31 @@ admin_speaker_link_gravatar: admin_speaker_register: path: /register defaults: {_controller: AppBundle\Controller\Admin\Speaker\SpeakerRegisterAction} + +admin_speaker_pick: + path: /pick + defaults: {_controller: AppBundle\Controller\Admin\Speaker\SpeakerPickAction} + +admin_speaker_person: + path: /person + defaults: {_controller: AppBundle\Controller\Admin\Speaker\SpeakerPersonAction} + +admin_speaker_person_create: + path: /person/create + methods: [POST] + defaults: {_controller: AppBundle\Controller\Admin\Speaker\SpeakerPersonCreateAction} + +admin_speaker_person_attach: + path: /person/attach + methods: [POST] + defaults: {_controller: AppBundle\Controller\Admin\Speaker\SpeakerPersonAttachAction} + +admin_speaker_person_detach: + path: /person/detach + methods: [POST] + defaults: {_controller: AppBundle\Controller\Admin\Speaker\SpeakerPersonDetachAction} + +admin_speaker_person_merge: + path: /person/merge + methods: [POST] + defaults: {_controller: AppBundle\Controller\Admin\Speaker\SpeakerPersonMergeAction} diff --git a/db/seeds/Conferenciers.php b/db/seeds/Conferenciers.php index 0a9650da2..ef82431a1 100644 --- a/db/seeds/Conferenciers.php +++ b/db/seeds/Conferenciers.php @@ -8,6 +8,7 @@ class Conferenciers extends AbstractSeed { public const ID_CONFERENCIER = 1; + public const ID_CONFERENCIER_ANCIEN = 4; public function run(): void { @@ -72,6 +73,48 @@ public function run(): void 'special_diet_description' => null, 'hotel_nights' => null, ], + // Conférencière d'une édition passée, pas encore inscrite au forum : reprise en back-office et CFP prérempli + [ + 'conferencier_id' => self::ID_CONFERENCIER_ANCIEN, + 'id_forum' => Event::ID_PASSED, + 'genre' => Genre::Femme->value, + 'nom' => 'Ancienne', + 'prenom' => 'Marie', + 'email' => 'marie@example.com', + 'societe' => 'Ancienne Société', + 'ville' => 'Lyon', + 'biographie' => 'Bio Marie', + 'twitter' => '', + 'mastodon' => '', + 'bluesky' => '', + 'user_github' => GithubUsers::ID_GITHUBUSER_ANCIEN, + 'photo' => self::ID_CONFERENCIER_ANCIEN . '.png', + 'will_attend_speakers_diner' => null, + 'has_special_diet' => null, + 'special_diet_description' => null, + 'hotel_nights' => null, + ], + // Fiche historique non rattachée, homonyme de Geoffrey Bachelet : suggestion de rattachement + [ + 'conferencier_id' => 5, + 'id_forum' => Event::ID_PASSED, + 'genre' => null, + 'nom' => 'Bachelet', + 'prenom' => 'Geoffrey', + 'email' => 'geoffrey@example.com', + 'societe' => null, + 'ville' => null, + 'biographie' => 'Ancienne bio', + 'twitter' => null, + 'mastodon' => null, + 'bluesky' => null, + 'user_github' => null, + 'photo' => null, + 'will_attend_speakers_diner' => null, + 'has_special_diet' => null, + 'special_diet_description' => null, + 'hotel_nights' => null, + ], ]; $table = $this->table('afup_conferenciers'); diff --git a/db/seeds/GithubUsers.php b/db/seeds/GithubUsers.php index e9190826e..840840cfd 100644 --- a/db/seeds/GithubUsers.php +++ b/db/seeds/GithubUsers.php @@ -7,6 +7,8 @@ class GithubUsers extends AbstractSeed { public const ID_GITHUBUSER_UBERMUDA = 1; + /** Conférencier d'une édition passée, sans fiche sur le forum courant (voir TestGithubAuthenticator) */ + public const ID_GITHUBUSER_ANCIEN = 4; public function run(): void { @@ -41,6 +43,16 @@ public function run(): void 'avatar_url' => 'https://avatars.githubusercontent.com/u/1090307?v=4', 'afup_crew' => 1, ], + [ + 'id' => self::ID_GITHUBUSER_ANCIEN, + 'github_id' => 77, + 'login' => 'ancien', + 'name' => 'Marie Ancienne', + 'company' => 'AFUP', + 'profile_url' => 'https://github.com/ancien', + 'avatar_url' => 'https://avatars.githubusercontent.com/u/77?v=4', + 'afup_crew' => 0, + ], ]; $table = $this->table('afup_user_github'); diff --git a/db/seeds/SpeakerPersons.php b/db/seeds/SpeakerPersons.php new file mode 100644 index 000000000..c5e613d9d --- /dev/null +++ b/db/seeds/SpeakerPersons.php @@ -0,0 +1,46 @@ + ['slug' => 'geoffrey-bachelet', 'speakers' => [1]], + 2 => ['slug' => 'adrien-gallou', 'speakers' => [2]], + 3 => ['slug' => 'john-doe', 'speakers' => [3]], + 4 => ['slug' => 'marie-ancienne', 'speakers' => [Conferenciers::ID_CONFERENCIER_ANCIEN]], + ]; + + $this->execute('UPDATE afup_conferenciers SET person_id = NULL'); + $this->execute('DELETE FROM afup_speaker_person'); + + $this->table('afup_speaker_person') + ->insert(array_map( + static fn(int $id, array $person): array => ['id' => $id, 'slug' => $person['slug']], + array_keys($persons), + $persons, + )) + ->save(); + + foreach ($persons as $id => $person) { + $this->execute(sprintf( + 'UPDATE afup_conferenciers SET person_id = %d WHERE conferencier_id IN (%s)', + $id, + implode(',', $person['speakers']), + )); + } + } +} diff --git a/sources/AppBundle/CFP/PhotoStorage.php b/sources/AppBundle/CFP/PhotoStorage.php index 232040af5..722a2d0ca 100644 --- a/sources/AppBundle/CFP/PhotoStorage.php +++ b/sources/AppBundle/CFP/PhotoStorage.php @@ -40,19 +40,47 @@ public function store(File $photo, Speaker $speaker): string $fileName = $speaker->getId() . '.' . $photo->guessExtension(); $directory = $this->basePath . '/' . $speaker->getEventId() . '/' . self::DIR_ORIGINAL; $this->createDirectory($directory); - // delete all formats - if ($speaker->getId() !== null) { - foreach (array_keys(self::FORMAT) as $format) { - $files = glob($this->basePath . '/' . $speaker->getEventId() . '/' . $format . '/' . $speaker->getId() . '.*'); - $this->filesystem->remove($files); - } - } + $this->removeAllFormats($speaker); $photo->move($directory, $fileName); return $fileName; } + /** + * Copie la photo originale d'une ligne (autre édition) vers une ligne déjà enregistrée. + * Retourne le nom de fichier de la cible, ou null si la source n'a pas de photo. + */ + public function copyFrom(Speaker $source, Speaker $target): ?string + { + if ($source->getPhoto() === null || $target->getId() === null) { + return null; + } + $sourcePath = $this->getPath($source, self::DIR_ORIGINAL); + if (!is_file($sourcePath)) { + return null; + } + + $fileName = $target->getId() . '.' . pathinfo($sourcePath, PATHINFO_EXTENSION); + $directory = $this->basePath . '/' . $target->getEventId() . '/' . self::DIR_ORIGINAL; + $this->createDirectory($directory); + $this->removeAllFormats($target); + $this->filesystem->copy($sourcePath, $directory . '/' . $fileName, true); + + return $fileName; + } + + private function removeAllFormats(Speaker $speaker): void + { + if ($speaker->getId() === null) { + return; + } + foreach (array_keys(self::FORMAT) as $format) { + $files = glob($this->basePath . '/' . $speaker->getEventId() . '/' . $format . '/' . $speaker->getId() . '.*'); + $this->filesystem->remove($files); + } + } + public function getUrl(Speaker $speaker, $format = null): ?string { if ($format === null) { diff --git a/sources/AppBundle/CFP/SpeakerFactory.php b/sources/AppBundle/CFP/SpeakerFactory.php index 4d465e90e..58b460ce4 100644 --- a/sources/AppBundle/CFP/SpeakerFactory.php +++ b/sources/AppBundle/CFP/SpeakerFactory.php @@ -37,14 +37,31 @@ public function getSpeaker(Event $event): Speaker 'eventId' => $event->getId(), ]); - if ($speaker === null) { - $speaker = new Speaker(); - $speaker - ->setUser($user) - ->setEventId($event->getId()) - ; + if ($speaker !== null) { + return $speaker; } + $personId = null; + if (is_int($user)) { + $personId = $this->speakerRepository->findLatestPersonIdByGithubUser($user); + // La personne a peut-être déjà une ligne pour cet événement, saisie par l'admin sans compte GitHub : + // on la reprend plutôt que de créer un doublon. + $adminSpeaker = $personId !== null ? $this->speakerRepository->findOneByPersonInEventWithoutGithubUser($personId, $event) : null; + if ($adminSpeaker !== null) { + $adminSpeaker->setUser($user); + $this->speakerRepository->save($adminSpeaker); + + return $adminSpeaker; + } + } + + $speaker = new Speaker(); + $speaker + ->setUser($user) + ->setEventId($event->getId()) + ->setPersonId($personId) + ; + return $speaker; } } diff --git a/sources/AppBundle/Controller/Admin/Speaker/SpeakerAddAction.php b/sources/AppBundle/Controller/Admin/Speaker/SpeakerAddAction.php index 380bc141d..f596c2f68 100644 --- a/sources/AppBundle/Controller/Admin/Speaker/SpeakerAddAction.php +++ b/sources/AppBundle/Controller/Admin/Speaker/SpeakerAddAction.php @@ -7,10 +7,12 @@ use AppBundle\AuditLog\Audit; use AppBundle\CFP\PhotoStorage; use AppBundle\Event\Form\SpeakerFormData; +use AppBundle\Event\Form\SpeakerFormDataFactory; use AppBundle\Event\Form\SpeakerType; use AppBundle\Event\Model\Repository\EventRepository; use AppBundle\Event\Model\Repository\SpeakerRepository; use AppBundle\Event\Model\Speaker; +use AppBundle\Event\Speaker\SpeakerPersonLinker; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -24,6 +26,8 @@ public function __construct( private readonly EventRepository $eventRepository, private readonly SpeakerRepository $speakerRepository, private readonly PhotoStorage $photoStorage, + private readonly SpeakerFormDataFactory $speakerFormDataFactory, + private readonly SpeakerPersonLinker $speakerPersonLinker, private readonly Audit $audit, ) {} @@ -31,9 +35,29 @@ public function __invoke(Request $request): Response { $event = $this->eventRepository->get($request->query->get('eventId')); Assert::notNull($event); - $data = new SpeakerFormData(); + + // Reprise d'un conférencier d'une édition passée (?from=) + $source = $request->query->has('from') ? $this->speakerRepository->get($request->query->getInt('from')) : null; + $sourcePhoto = null; + if ($source instanceof Speaker) { + $personId = $this->speakerPersonLinker->findPersonId($source); + $existing = $personId !== null ? $this->speakerPersonLinker->findRowInEvent($personId, $event) : null; + if ($existing instanceof Speaker) { + $this->addFlash('notice', 'Ce conférencier existe déjà pour cet événement'); + + return $this->redirectToRoute('admin_speaker_edit', ['id' => $existing->getId()]); + } + $data = $this->speakerFormDataFactory->fromSpeaker($source); + if ($source->getPhoto() !== null) { + $sourcePhoto = $this->photoStorage->getUrl($source, PhotoStorage::DIR_ORIGINAL); + } + } else { + $data = new SpeakerFormData(); + } + $form = $this->createForm(SpeakerType::class, $data, [ SpeakerType::OPT_USER_GITHUB => true, + SpeakerType::OPT_PHOTO_REQUIRED => null === $sourcePhoto, ]); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { @@ -50,15 +74,30 @@ public function __invoke(Request $request): Response $speaker->setEmail($data->email); $speaker->setUser($data->githubUser !== null ? $data->githubUser->getId() : null); $speaker->setCompany($data->company); + $speaker->setLocality($data->locality); $speaker->setPhoneNumber($data->phoneNumber); $speaker->setReferentPerson($data->referentPerson); + $speaker->setReferentPersonEmail($data->referentPersonEmail); + if ($source instanceof Speaker) { + // La source rejoint la même personne que la nouvelle ligne. + if ($source->getPersonId() === null) { + $this->speakerPersonLinker->ensurePerson($source); + $this->speakerRepository->save($source); + } + $speaker->setPersonId($source->getPersonId()); + } else { + $this->speakerPersonLinker->ensurePerson($speaker); + } $this->speakerRepository->save($speaker); if (null !== $data->photoFile) { - $fileName = $this->photoStorage->store($data->photoFile, $speaker); - $speaker->setPhoto($fileName); + $speaker->setPhoto($this->photoStorage->store($data->photoFile, $speaker)); + $this->speakerRepository->save($speaker); + } elseif ($source instanceof Speaker && null !== $sourcePhoto) { + $speaker->setPhoto($this->photoStorage->copyFrom($source, $speaker)); $this->speakerRepository->save($speaker); } - $this->audit->log('Ajout du conférencier de ' . $speaker->getFirstname() . ' ' . $speaker->getLastname()); + $this->audit->log('Ajout du conférencier de ' . $speaker->getFirstname() . ' ' . $speaker->getLastname() + . ($source instanceof Speaker ? ' (repris de ' . $source->getId() . ')' : '')); $this->addFlash('notice', 'Le conférencier a été ajouté'); @@ -70,6 +109,8 @@ public function __invoke(Request $request): Response return $this->render('admin/speaker/add.html.twig', [ 'event' => $event, 'form' => $form->createView(), + 'source' => $source, + 'sourcePhoto' => $sourcePhoto, ]); } } diff --git a/sources/AppBundle/Controller/Admin/Speaker/SpeakerEditAction.php b/sources/AppBundle/Controller/Admin/Speaker/SpeakerEditAction.php index 715891ed7..6551046c7 100644 --- a/sources/AppBundle/Controller/Admin/Speaker/SpeakerEditAction.php +++ b/sources/AppBundle/Controller/Admin/Speaker/SpeakerEditAction.php @@ -7,12 +7,14 @@ use Afup\Site\Utils\Utils; use AppBundle\AuditLog\Audit; use AppBundle\CFP\PhotoStorage; +use AppBundle\Event\Entity\Repository\SpeakerPersonRepository; use AppBundle\Event\Form\SpeakerFormDataFactory; use AppBundle\Event\Form\SpeakerType; use AppBundle\Event\Model\Repository\EventRepository; use AppBundle\Event\Model\Repository\SpeakerRepository; use AppBundle\Event\Model\Repository\TalkRepository; use AppBundle\Event\Model\Talk; +use AppBundle\Event\Speaker\SpeakerSearchResult; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Webmozart\Assert\Assert; @@ -29,6 +31,7 @@ public function __construct( private readonly EventRepository $eventRepository, private readonly PhotoStorage $photoStorage, private readonly SpeakerFormDataFactory $speakerFormDataFactory, + private readonly SpeakerPersonRepository $speakerPersonRepository, private readonly Audit $audit, ) {} @@ -95,6 +98,9 @@ public function __invoke(Request $request) ]); } + // Recherche d'une personne à laquelle rattacher la ligne (formulaire GET du bloc « Personne ») + $personSearch = $request->query->getString('personQuery'); + return $this->render('admin/speaker/edit.html.twig', [ 'speakerId' => $speaker->getId(), 'eventId' => $event->getId(), @@ -104,6 +110,12 @@ public function __invoke(Request $request) 'talks' => $talks, 'photo' => $photo, 'originalPhoto' => $originalPhoto, + 'person' => $speaker->getPersonId() !== null ? $this->speakerPersonRepository->find($speaker->getPersonId()) : null, + 'personSearch' => $personSearch, + 'personCandidates' => array_values(array_filter( + $this->speakerRepository->searchAcrossEvents($personSearch), + static fn(SpeakerSearchResult $result): bool => $result->personId !== null, + )), ]); } } diff --git a/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonAction.php b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonAction.php new file mode 100644 index 000000000..7fb7d8b3d --- /dev/null +++ b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonAction.php @@ -0,0 +1,55 @@ +speakerPersonRepository->find($request->query->getInt('id')); + if ($person === null) { + throw $this->createNotFoundException('Personne non trouvée'); + } + $search = $request->query->getString('q'); + + $eventTitles = []; + foreach ($this->eventRepository->getAll() as $event) { + if ($event->getId() !== null) { + $eventTitles[$event->getId()] = $event->getTitle(); + } + } + + return $this->render('admin/speaker/person.html.twig', [ + 'person' => $person, + 'speakers' => $this->speakerRepository->findByPerson($person->id), + 'suggestions' => $this->speakerRepository->findLinkSuggestions($person->id), + 'search' => $search, + 'mergeCandidates' => array_values(array_filter( + $this->speakerRepository->searchAcrossEvents($search), + static fn(SpeakerSearchResult $result): bool => $result->personId !== null && $result->personId !== $person->id, + )), + 'eventTitles' => $eventTitles, + ]); + } +} diff --git a/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonAttachAction.php b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonAttachAction.php new file mode 100644 index 000000000..5d3e985db --- /dev/null +++ b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonAttachAction.php @@ -0,0 +1,47 @@ +speakerRepository->get($request->request->getInt('speakerId')); + $person = $this->speakerPersonRepository->find($request->request->getInt('personId')); + if ($speaker === null || $person === null) { + throw $this->createNotFoundException('Speaker ou personne non trouvé'); + } + if (!$this->isCsrfTokenValid('admin_speaker_person', $request->request->getString('_token'))) { + $this->addFlash('error', 'Token invalide'); + + return $this->redirectToRoute('admin_speaker_person', ['id' => $person->id]); + } + + $speaker->setPersonId($person->id); + $this->speakerRepository->save($speaker); + $this->audit->log('Rattachement du conférencier ' . $speaker->getId() . ' à la personne ' . $person->slug); + $this->addFlash('notice', 'Le conférencier a été rattaché à la personne'); + + return $this->redirectToRoute('admin_speaker_person', ['id' => $person->id]); + } +} diff --git a/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonCreateAction.php b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonCreateAction.php new file mode 100644 index 000000000..121379c40 --- /dev/null +++ b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonCreateAction.php @@ -0,0 +1,50 @@ +speakerRepository->get($request->request->getInt('speakerId')); + if ($speaker === null) { + throw $this->createNotFoundException('Speaker non trouvé'); + } + if (!$this->isCsrfTokenValid('admin_speaker_person', $request->request->getString('_token'))) { + $this->addFlash('error', 'Token invalide'); + + return $this->redirectToRoute('admin_speaker_edit', ['id' => $speaker->getId()]); + } + if ($speaker->getPersonId() !== null) { + return $this->redirectToRoute('admin_speaker_person', ['id' => $speaker->getPersonId()]); + } + + $person = $this->speakerPersonLinker->createPerson($speaker->getFirstname() . ' ' . $speaker->getLastname()); + $speaker->setPersonId($person->id); + $this->speakerRepository->save($speaker); + $this->audit->log('Création de la personne ' . $person->slug . ' pour le conférencier ' . $speaker->getId()); + $this->addFlash('notice', 'La personne a été créée'); + + return $this->redirectToRoute('admin_speaker_person', ['id' => $person->id]); + } +} diff --git a/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonDetachAction.php b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonDetachAction.php new file mode 100644 index 000000000..46eac6b70 --- /dev/null +++ b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonDetachAction.php @@ -0,0 +1,48 @@ +speakerRepository->get($request->request->getInt('speakerId')); + if ($speaker === null) { + throw $this->createNotFoundException('Speaker non trouvé'); + } + $personId = $speaker->getPersonId(); + if ($personId === null) { + return $this->redirectToRoute('admin_speaker_edit', ['id' => $speaker->getId()]); + } + if (!$this->isCsrfTokenValid('admin_speaker_person', $request->request->getString('_token'))) { + $this->addFlash('error', 'Token invalide'); + + return $this->redirectToRoute('admin_speaker_person', ['id' => $personId]); + } + + $speaker->setPersonId(null); + $this->speakerRepository->save($speaker); + $this->audit->log('Détachement du conférencier ' . $speaker->getId() . ' de la personne ' . $personId); + $this->addFlash('notice', 'Le conférencier a été détaché de la personne'); + + return $this->redirectToRoute('admin_speaker_person', ['id' => $personId]); + } +} diff --git a/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonMergeAction.php b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonMergeAction.php new file mode 100644 index 000000000..1352578b8 --- /dev/null +++ b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPersonMergeAction.php @@ -0,0 +1,45 @@ +speakerPersonRepository->find($request->request->getInt('id')); + $source = $this->speakerPersonRepository->find($request->request->getInt('sourceId')); + if ($target === null || $source === null) { + throw $this->createNotFoundException('Personne non trouvée'); + } + if (!$this->isCsrfTokenValid('admin_speaker_person', $request->request->getString('_token')) || $target->id === $source->id) { + $this->addFlash('error', 'Fusion impossible'); + + return $this->redirectToRoute('admin_speaker_person', ['id' => $target->id]); + } + + $sourceSlug = $source->slug; + $this->speakerPersonRepository->merge($target, $source); + $this->audit->log('Fusion de la personne ' . $sourceSlug . ' dans ' . $target->slug); + $this->addFlash('notice', 'La personne ' . $sourceSlug . ' a été fusionnée dans ' . $target->slug); + + return $this->redirectToRoute('admin_speaker_person', ['id' => $target->id]); + } +} diff --git a/sources/AppBundle/Controller/Admin/Speaker/SpeakerPickAction.php b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPickAction.php new file mode 100644 index 000000000..9715fdc5c --- /dev/null +++ b/sources/AppBundle/Controller/Admin/Speaker/SpeakerPickAction.php @@ -0,0 +1,38 @@ +eventRepository->get($request->query->get('eventId')); + Assert::notNull($event); + $search = $request->query->getString('q'); + + return $this->render('admin/speaker/pick.html.twig', [ + 'event' => $event, + 'search' => $search, + 'results' => $this->speakerRepository->searchAcrossEvents($search), + ]); + } +} diff --git a/sources/AppBundle/Controller/Event/CFP/SpeakerAction.php b/sources/AppBundle/Controller/Event/CFP/SpeakerAction.php index f49d2398a..f748cd466 100644 --- a/sources/AppBundle/Controller/Event/CFP/SpeakerAction.php +++ b/sources/AppBundle/Controller/Event/CFP/SpeakerAction.php @@ -9,6 +9,8 @@ use AppBundle\Controller\Event\EventActionHelper; use AppBundle\Event\Form\SpeakerType; use AppBundle\Event\Model\Repository\SpeakerRepository; +use AppBundle\Event\Model\Speaker; +use AppBundle\Event\Speaker\SpeakerPersonLinker; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; @@ -25,6 +27,7 @@ public function __construct( private readonly TranslatorInterface $translator, private readonly PhotoStorage $photoStorage, private readonly SidebarRenderer $sidebarRenderer, + private readonly SpeakerPersonLinker $speakerPersonLinker, ) {} public function __invoke(Request $request): Response @@ -38,11 +41,25 @@ public function __invoke(Request $request): Response } $speaker = $this->speakerFactory->getSpeaker($event); + // Profil prérempli depuis la dernière édition (voir SpeakerType) : sa photo, rangée par édition, + // est copiée à l'enregistrement. Le nom provisoire satisfait la validation de Speaker. + $previousSpeaker = null; + $previousPhoto = null; + if ($speaker->getId() === null) { + $previousSpeaker = $this->speakerRepository->getFromLastEventAndUserId($event->getId(), $speaker->getUser()); + if ($previousSpeaker instanceof Speaker && $previousSpeaker->getPhoto() !== null) { + $previousPhoto = $this->photoStorage->getUrl($previousSpeaker, PhotoStorage::DIR_ORIGINAL); + if ($previousPhoto !== null) { + $speaker->setPhoto($previousSpeaker->getPhoto()); + } + } + } $form = $this->createForm(SpeakerType::class, $speaker, [ SpeakerType::OPT_PHOTO_REQUIRED => null === $speaker->getPhoto(), ]); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { + $this->speakerPersonLinker->ensurePerson($speaker); $this->speakerRepository->save($speaker); $file = $speaker->getPhotoFile(); @@ -50,6 +67,9 @@ public function __invoke(Request $request): Response $fileName = $this->photoStorage->store($file, $speaker); $speaker->setPhoto($fileName); $this->speakerRepository->save($speaker); + } elseif ($previousPhoto !== null && $previousSpeaker instanceof Speaker) { + $speaker->setPhoto($this->photoStorage->copyFrom($previousSpeaker, $speaker)); + $this->speakerRepository->save($speaker); } /** @var Session $session */ @@ -65,8 +85,8 @@ public function __invoke(Request $request): Response ]); } - $photo = null; - if (null !== $speaker->getPhoto()) { + $photo = $previousPhoto; + if (null === $photo && null !== $speaker->getPhoto()) { $photo = $this->photoStorage->getUrl($speaker, PhotoStorage::DIR_ORIGINAL); } diff --git a/sources/AppBundle/Event/Entity/Repository/SpeakerPersonRepository.php b/sources/AppBundle/Event/Entity/Repository/SpeakerPersonRepository.php new file mode 100644 index 000000000..9b444da7c --- /dev/null +++ b/sources/AppBundle/Event/Entity/Repository/SpeakerPersonRepository.php @@ -0,0 +1,39 @@ + + */ +class SpeakerPersonRepository extends EntityRepository +{ + public function __construct(ManagerRegistry $registry) + { + parent::__construct($registry, SpeakerPerson::class); + } + + public function slugExists(string $slug): bool + { + return $this->count(['slug' => $slug]) > 0; + } + + /** + * Déplace les lignes conférencier de $source vers $target puis supprime $source (son slug est perdu). + */ + public function merge(SpeakerPerson $target, SpeakerPerson $source): void + { + $this->getEntityManager()->wrapInTransaction(function () use ($target, $source): void { + $this->getEntityManager()->getConnection()->executeStatement( + 'UPDATE afup_conferenciers SET person_id = :target WHERE person_id = :source', + ['target' => $target->id, 'source' => $source->id], + ); + $this->getEntityManager()->remove($source); + }); + } +} diff --git a/sources/AppBundle/Event/Entity/SpeakerPerson.php b/sources/AppBundle/Event/Entity/SpeakerPerson.php new file mode 100644 index 000000000..e97df6104 --- /dev/null +++ b/sources/AppBundle/Event/Entity/SpeakerPerson.php @@ -0,0 +1,32 @@ + true])] + public int $id; + + #[ORM\Column(name: 'created_at')] + public \DateTimeImmutable $createdAt; + + public function __construct( + #[ORM\Column(length: 255, unique: true)] + public string $slug, + ) { + $this->createdAt = new \DateTimeImmutable(); + } +} diff --git a/sources/AppBundle/Event/Form/SpeakerType.php b/sources/AppBundle/Event/Form/SpeakerType.php index 3337ec4d8..1fe680829 100644 --- a/sources/AppBundle/Event/Form/SpeakerType.php +++ b/sources/AppBundle/Event/Form/SpeakerType.php @@ -112,7 +112,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $speaker->setMastodon($previousSpeakerInfos->getMastodon()); $speaker->setLinkedin($previousSpeakerInfos->getLinkedin()); $speaker->setBluesky($previousSpeakerInfos->getBluesky()); - $speaker->setPhoto($previousSpeakerInfos->getPhoto()); + // La photo n'est pas reprise ici : son fichier est rangé par édition, SpeakerAction le copie à l'enregistrement. $formEvent->getForm()->add('isFromPreviousEvent', HiddenType::class, ['mapped' => false]); } diff --git a/sources/AppBundle/Event/Model/Repository/SpeakerRepository.php b/sources/AppBundle/Event/Model/Repository/SpeakerRepository.php index 5a92ad0df..674f6237b 100644 --- a/sources/AppBundle/Event/Model/Repository/SpeakerRepository.php +++ b/sources/AppBundle/Event/Model/Repository/SpeakerRepository.php @@ -8,10 +8,12 @@ use AppBundle\Event\Model\Event; use AppBundle\Event\Model\Speaker; use AppBundle\Event\Model\Talk; +use AppBundle\Event\Speaker\SpeakerSearchResult; use AppBundle\Event\Speaker\MicrophoneType; use AppBundle\Ting\JoinHydrator; use CCMBenchmark\Ting\Driver\Mysqli\Serializer\Boolean; use CCMBenchmark\Ting\Repository\CollectionInterface; +use CCMBenchmark\Ting\Repository\HydratorArray; use CCMBenchmark\Ting\Repository\HydratorSingleObject; use CCMBenchmark\Ting\Repository\Metadata; use CCMBenchmark\Ting\Repository\MetadataInitializer; @@ -120,6 +122,151 @@ public function getFromLastEventAndUserId($eventId, $githubUserId) return $speaker->first(); } + /** + * Personne de la ligne la plus récente rattachée à ce compte GitHub. + */ + public function findLatestPersonIdByGithubUser(int $githubUserId): ?int + { + $query = $this->getPreparedQuery( + 'SELECT c.person_id + FROM afup_conferenciers c + LEFT JOIN afup_forum f ON f.id = c.id_forum + WHERE c.user_github = :userGithub AND c.person_id IS NOT NULL + ORDER BY f.date_debut DESC, c.conferencier_id DESC + LIMIT 1', + )->setParams(['userGithub' => $githubUserId]); + + /** @var array{person_id: string}|null $row */ + $row = $query->query($this->getCollection(new HydratorArray()))->first(); + + return $row === null ? null : (int) $row['person_id']; + } + + public function findOneByPersonInEvent(int $personId, Event $event): ?Speaker + { + return $this->getOneBy(['personId' => $personId, 'eventId' => $event->getId()]); + } + + /** + * Ligne d'une personne dans un événement, saisie sans compte GitHub (par exemple par l'admin). + */ + public function findOneByPersonInEventWithoutGithubUser(int $personId, Event $event): ?Speaker + { + $query = $this->getPreparedQuery( + 'SELECT c.* FROM afup_conferenciers c + WHERE c.person_id = :personId AND c.id_forum = :eventId AND c.user_github IS NULL + ORDER BY c.conferencier_id + LIMIT 1', + )->setParams(['personId' => $personId, 'eventId' => $event->getId()]); + + $speaker = $query->query($this->getCollection(new HydratorSingleObject()))->first(); + + return $speaker instanceof Speaker ? $speaker : null; + } + + /** + * Recherche tous événements confondus : une ligne par personne, plus une ligne par conférencier non rattaché. + * Chaque résultat pointe vers la ligne la plus récente. + * + * @return list + */ + public function searchAcrossEvents(string $search, int $limit = 50): array + { + $search = trim($search); + if ($search === '') { + return []; + } + + $match = "CONCAT_WS(' ', m.prenom, m.nom, m.nom, m.prenom, m.email, m.societe) COLLATE utf8mb4_unicode_ci LIKE :search"; + $query = $this->getPreparedQuery( + "SELECT c.conferencier_id, c.id_forum, c.person_id, c.prenom, c.nom, c.societe, c.email, f.titre, p.slug + FROM afup_conferenciers c + LEFT JOIN afup_forum f ON f.id = c.id_forum + LEFT JOIN afup_speaker_person p ON p.id = c.person_id + WHERE c.conferencier_id IN (SELECT m.conferencier_id FROM afup_conferenciers m WHERE $match) + OR c.person_id IN (SELECT m.person_id FROM afup_conferenciers m WHERE m.person_id IS NOT NULL AND $match) + ORDER BY f.date_debut DESC, c.conferencier_id DESC", + )->setParams(['search' => '%' . $search . '%']); + + $groups = []; + /** @var iterable $rows */ + $rows = $query->query($this->getCollection(new HydratorArray())); + foreach ($rows as $row) { + $key = $row['person_id'] !== null ? 'p' . $row['person_id'] : 's' . $row['conferencier_id']; + if (!isset($groups[$key])) { + $groups[$key] = ['row' => $row, 'events' => []]; + } + $groups[$key]['events'][(int) $row['id_forum']] = true; + } + + $results = []; + foreach (array_slice($groups, 0, $limit) as $group) { + $row = $group['row']; + $results[] = new SpeakerSearchResult( + (int) $row['conferencier_id'], + $row['person_id'] !== null ? (int) $row['person_id'] : null, + $row['slug'], + $row['prenom'], + $row['nom'], + $row['societe'], + $row['email'], + $row['titre'], + count($group['events']), + ); + } + + return $results; + } + + /** + * Lignes d'une personne, de la plus récente à la plus ancienne. + * + * @return list + */ + public function findByPerson(int $personId): array + { + $query = $this->getPreparedQuery( + 'SELECT c.* FROM afup_conferenciers c + LEFT JOIN afup_forum f ON f.id = c.id_forum + WHERE c.person_id = :personId + ORDER BY f.date_debut DESC, c.conferencier_id DESC', + )->setParams(['personId' => $personId]); + + /** @var list $speakers */ + $speakers = iterator_to_array($query->query($this->getCollection(new HydratorSingleObject())), false); + + return $speakers; + } + + /** + * Lignes non rattachées qui ressemblent à la personne : même compte GitHub ou même « prénom nom » + * (comparaison insensible à la casse et aux accents). Le rattachement reste une décision humaine. + * + * @return list + */ + public function findLinkSuggestions(int $personId): array + { + $query = $this->getPreparedQuery( + "SELECT c.* FROM afup_conferenciers c + LEFT JOIN afup_forum f ON f.id = c.id_forum + WHERE c.person_id IS NULL + AND EXISTS ( + SELECT 1 FROM afup_conferenciers p + WHERE p.person_id = :personId + AND ( + p.user_github = c.user_github + OR CONCAT_WS(' ', TRIM(p.prenom), TRIM(p.nom)) COLLATE utf8mb4_unicode_ci = CONCAT_WS(' ', TRIM(c.prenom), TRIM(c.nom)) COLLATE utf8mb4_unicode_ci + ) + ) + ORDER BY f.date_debut DESC, c.conferencier_id DESC", + )->setParams(['personId' => $personId]); + + /** @var list $speakers */ + $speakers = iterator_to_array($query->query($this->getCollection(new HydratorSingleObject())), false); + + return $speakers; + } + /** * Retourne `true` si le speaker avec l'email ($email) a soumis au moins 1 CFP pour l'évènement ($event) passé en paramètre. * @@ -273,6 +420,11 @@ public static function initMetadata(SerializerFactoryInterface $serializerFactor 'fieldName' => 'user', 'type' => 'int', ]) + ->addField([ + 'columnName' => 'person_id', + 'fieldName' => 'personId', + 'type' => 'int', + ]) ->addField([ 'columnName' => 'photo', 'fieldName' => 'photo', diff --git a/sources/AppBundle/Event/Model/Repository/TalkRepository.php b/sources/AppBundle/Event/Model/Repository/TalkRepository.php index 967add9b4..8ca7ebb12 100644 --- a/sources/AppBundle/Event/Model/Repository/TalkRepository.php +++ b/sources/AppBundle/Event/Model/Repository/TalkRepository.php @@ -157,8 +157,9 @@ public function getNewTalksToRate(Event $event, GithubUser $user, $randomSeed, $ AND asvg.id IS NULL AND sessions.session_id NOT IN ( SELECT sessions.session_id FROM afup_sessions sessions - LEFT JOIN afup_conferenciers_sessions cs ON cs.session_id = sessions.session_id - WHERE id_forum = :excluded_event AND cs.conferencier_id = :excluded_user + INNER JOIN afup_conferenciers_sessions cs ON cs.session_id = sessions.session_id + INNER JOIN afup_conferenciers c ON c.conferencier_id = cs.conferencier_id + WHERE sessions.id_forum = :excluded_event AND c.user_github = :excluded_user ) ORDER BY RAND(:randomSeed) LIMIT ' . ((int) $page - 1) * $limit . ', ' . ((int) $limit + 1), diff --git a/sources/AppBundle/Event/Model/Speaker.php b/sources/AppBundle/Event/Model/Speaker.php index ee64e4720..d14959705 100644 --- a/sources/AppBundle/Event/Model/Speaker.php +++ b/sources/AppBundle/Event/Model/Speaker.php @@ -39,6 +39,8 @@ class Speaker implements NotifyPropertyInterface #[Assert\GreaterThan(0)] private $user; + private ?int $personId = null; + private ?Genre $genre = null; /** @@ -166,6 +168,18 @@ public function setUser($user): self return $this; } + public function getPersonId(): ?int + { + return $this->personId; + } + + public function setPersonId(?int $personId): self + { + $this->propertyChanged('personId', $this->personId, $personId); + $this->personId = $personId; + return $this; + } + /** * @return int */ diff --git a/sources/AppBundle/Event/Speaker/SpeakerPersonLinker.php b/sources/AppBundle/Event/Speaker/SpeakerPersonLinker.php new file mode 100644 index 000000000..d60a7723d --- /dev/null +++ b/sources/AppBundle/Event/Speaker/SpeakerPersonLinker.php @@ -0,0 +1,79 @@ +getPersonId() !== null) { + return $speaker->getPersonId(); + } + + $githubUserId = $speaker->getUser(); + + return $githubUserId ? $this->speakerRepository->findLatestPersonIdByGithubUser($githubUserId) : null; + } + + /** + * À appeler avant d'enregistrer une nouvelle ligne : rattache la personne du compte GitHub + * ou, à défaut, en crée une. Ne sauvegarde pas la ligne. + */ + public function ensurePerson(Speaker $speaker): void + { + if ($speaker->getPersonId() !== null) { + return; + } + + $speaker->setPersonId( + $this->findPersonId($speaker) + ?? $this->createPerson($speaker->getFirstname() . ' ' . $speaker->getLastname())->id, + ); + } + + /** + * Le slug vient de « prénom nom », suffixé -2, -3… s'il est déjà pris. Il ne change plus ensuite. + */ + public function createPerson(string $label): SpeakerPerson + { + $base = new Slugify()->slugify($label); + if ($base === '') { + $base = 'conferencier'; + } + + $slug = $base; + for ($suffix = 2; $this->speakerPersonRepository->slugExists($slug); $suffix++) { + $slug = $base . '-' . $suffix; + } + + $person = new SpeakerPerson($slug); + $this->speakerPersonRepository->save($person); + + return $person; + } + + public function findRowInEvent(int $personId, Event $event): ?Speaker + { + return $this->speakerRepository->findOneByPersonInEvent($personId, $event); + } +} diff --git a/sources/AppBundle/Event/Speaker/SpeakerSearchResult.php b/sources/AppBundle/Event/Speaker/SpeakerSearchResult.php new file mode 100644 index 000000000..55e21bdfa --- /dev/null +++ b/sources/AppBundle/Event/Speaker/SpeakerSearchResult.php @@ -0,0 +1,24 @@ + 320372, 'name' => 'agallou', 'login' => 'agallou', + ], 'ancien' => [ + 'id' => 77, + 'name' => 'Marie Ancienne', + 'login' => 'ancien', ]]; } diff --git a/templates/admin/speaker/add.html.twig b/templates/admin/speaker/add.html.twig index 8411db7af..46808ad0d 100644 --- a/templates/admin/speaker/add.html.twig +++ b/templates/admin/speaker/add.html.twig @@ -4,6 +4,12 @@ {% block content %}

Ajouter un conférencier pour le {{ event.title }}

+ {% if source %} +
+ Fiche reprise de {{ source.firstname }} {{ source.lastname }} (conférencier n°{{ source.id }}). + {% if sourcePhoto %}La photo sera copiée si vous n'en envoyez pas d'autre.{% endif %} +
+ {% endif %}

Conférencier

@@ -26,6 +32,14 @@ {{ form_row(form.referent_person_email) }} {{ form_row(form.photoFile) }} {{ form_row(form.github_user) }} + {% if sourcePhoto %} +
+
+
+ Photo reprise +
+
+ {% endif %}
diff --git a/templates/admin/speaker/edit.html.twig b/templates/admin/speaker/edit.html.twig index 7faba66cb..494fdf246 100644 --- a/templates/admin/speaker/edit.html.twig +++ b/templates/admin/speaker/edit.html.twig @@ -53,6 +53,61 @@ {{ form_end(form) }}
+
+

Personne

+
+ {% if person %} +

+ Fiche rattachée à la personne + {{ person.slug }}. +

+ {% else %} +

Cette fiche n'est rattachée à aucune personne.

+
+ + + +
+

Rattacher à la personne…

+
+ +
+
+ + +
+
+ +
+
+
+ {% if personCandidates is not empty %} + + + {% for candidate in personCandidates %} + + + + + + + + {% endfor %} + +
{{ candidate.personSlug }}{{ candidate.lastname }} {{ candidate.firstname }}{{ candidate.lastEventTitle }}{{ candidate.eventCount }} édition(s) +
+ + + + +
+
+ {% elseif personSearch is not empty %} +

Aucune personne trouvée.

+ {% endif %} + {% endif %} +
+

Gravatar (si besoin)

diff --git a/templates/admin/speaker/list.html.twig b/templates/admin/speaker/list.html.twig index bb087504d..074ab5a78 100644 --- a/templates/admin/speaker/list.html.twig +++ b/templates/admin/speaker/list.html.twig @@ -12,6 +12,10 @@ Ajouter
+ + + Reprendre un conférencier + Créer les insciptions conférencier pour le forum diff --git a/templates/admin/speaker/person.html.twig b/templates/admin/speaker/person.html.twig new file mode 100644 index 000000000..36e5f5338 --- /dev/null +++ b/templates/admin/speaker/person.html.twig @@ -0,0 +1,105 @@ +{% extends 'admin/base_with_header.html.twig' %} + +{% set token = csrf_token('admin_speaker_person') %} + +{% macro speaker_row(speaker, eventTitles, action, label, personId, token) %} + + {{ eventTitles[speaker.eventId] ?? speaker.eventId }} + + {{ speaker.lastname }} {{ speaker.firstname }} + + {{ speaker.email }} + {{ speaker.user ?: '' }} + +
+ + + + +
+ + +{% endmacro %} + +{% block content %} +

Personne {{ person.slug }}

+ +
+

Fiches conférencier rattachées

+ {% if speakers is not empty %} + + + + + + {% for speaker in speakers %} + {{ _self.speaker_row(speaker, eventTitles, 'admin_speaker_person_detach', 'Détacher', person.id, token) }} + {% endfor %} + +
ÉditionNom PrénomEmailCompte GitHub 
+ {% else %} +

Aucune fiche rattachée.

+ {% endif %} +
+ +
+

Suggestions

+

Fiches non rattachées avec le même compte GitHub ou le même nom.

+ {% if suggestions is not empty %} + + + + + + {% for speaker in suggestions %} + {{ _self.speaker_row(speaker, eventTitles, 'admin_speaker_person_attach', 'Rattacher', person.id, token) }} + {% endfor %} + +
ÉditionNom PrénomEmailCompte GitHub 
+ {% else %} +

Aucune suggestion.

+ {% endif %} +
+ +
+

Fusionner avec la personne…

+

Les fiches de la personne choisie rejoignent {{ person.slug }}, puis elle est supprimée.

+
+ +
+
+ + +
+
+ +
+
+
+ {% if mergeCandidates is not empty %} + + + {% for candidate in mergeCandidates %} + + + + + + + + {% endfor %} + +
{{ candidate.personSlug }}{{ candidate.lastname }} {{ candidate.firstname }}{{ candidate.lastEventTitle }}{{ candidate.eventCount }} édition(s) +
+ + + + +
+
+ {% elseif search is not empty %} +

Aucune autre personne trouvée.

+ {% endif %} +
+{% endblock %} diff --git a/templates/admin/speaker/pick.html.twig b/templates/admin/speaker/pick.html.twig new file mode 100644 index 000000000..d222ef969 --- /dev/null +++ b/templates/admin/speaker/pick.html.twig @@ -0,0 +1,67 @@ +{% extends 'admin/base_with_header.html.twig' %} + +{% block content %} +

Reprendre un conférencier pour le {{ event.title }}

+ +
+
+ +
+
+ + +
+
+ +
+
+
+ + {% if search is not empty %} + {% if results is not empty %} + + + + + + + + + + + + {% for result in results %} + + + + + + + + {% endfor %} + +
Nom PrénomSociétéDernière éditionÉditions 
+ {{ result.lastname }} {{ result.firstname }} + {% if result.personSlug %} + {{ result.personSlug }} + {% else %} + non rattaché + {% endif %} + {{ result.company }}{{ result.lastEventTitle }}{{ result.eventCount }} + Reprendre +
+ {% else %} +
+
+ + Aucun conférencier trouvé. +
+
+ {% endif %} + {% endif %} +
+{% endblock %} diff --git a/tests/behat/bootstrap/FeatureContext.php b/tests/behat/bootstrap/FeatureContext.php index ada57e0da..db30917c9 100644 --- a/tests/behat/bootstrap/FeatureContext.php +++ b/tests/behat/bootstrap/FeatureContext.php @@ -15,6 +15,8 @@ use Behat\Mink\Element\NodeElement; use Behat\Mink\Exception\ExpectationException; use Behat\MinkExtension\Context\MinkContext; +use Symfony\Component\Filesystem\Filesystem; +use Behat\Step\Given; use Behat\Step\Then; use Behat\Step\When; @@ -74,6 +76,15 @@ public function restoreFollowRedirects(): void } } + /** + * Les photos des conférenciers ne sont pas versionnées : ce step en dépose une, par exemple « 3/originals/4.png ». + */ + #[Given('the speaker photo :file is stored as :path')] + public function storeSpeakerPhoto(string $file, string $path): void + { + new Filesystem()->copy(__DIR__ . '/../files/' . $file, __DIR__ . '/../../../htdocs/uploads/speakers/' . $path, true); + } + #[Then('simulate the Paybox callback')] public function simulateThePayboxCallback(): void { diff --git a/tests/behat/features/Admin/AdminGithubUsers.feature b/tests/behat/features/Admin/AdminGithubUsers.feature index 1b8c98ca1..fd2b852ee 100644 --- a/tests/behat/features/Admin/AdminGithubUsers.feature +++ b/tests/behat/features/Admin/AdminGithubUsers.feature @@ -19,7 +19,7 @@ Feature: Administration - Partie GitHub Users And I should see "Github Users" And I should see "" And I should see "" - Then I should see 4 "table tbody tr" elements + Then I should see 5 "table tbody tr" elements # on vérifie que si on ajoute deux fois le même user, l'ajout est bloqué When I follow "Ajouter" Then I should see "Ajouter un utilisateur GitHub" diff --git a/tests/behat/features/Admin/AdminSpeakers.feature b/tests/behat/features/Admin/AdminSpeakers.feature index 1df803afd..e4414eee7 100644 --- a/tests/behat/features/Admin/AdminSpeakers.feature +++ b/tests/behat/features/Admin/AdminSpeakers.feature @@ -14,7 +14,7 @@ Feature: Administration - Partie Speakers # ajout d'un speaker When I follow "Ajouter" Then I should see "Ajouter un conférencier pour le forum" - Then The "speaker[github_user]" field should only contain the follow values '["","agallou (Adrien Gallou)","ubermuda (Geoffrey Bachelet)","UnLoginGithub (John Doe)"]' + Then The "speaker[github_user]" field should only contain the follow values '["","agallou (Adrien Gallou)","ancien (Marie Ancienne)","ubermuda (Geoffrey Bachelet)","UnLoginGithub (John Doe)"]' When I fill in "speaker[firstname]" with "Damien" When I fill in "speaker[lastname]" with "Segui" When I fill in "speaker[email]" with "damien@gmail.com" @@ -50,3 +50,67 @@ Feature: Administration - Partie Speakers Then I should see "Créer les insciptions conférencier pour le forum" And I should see "Le conférencier a été supprimé" But the ".content table" element should not contain "Seguy Damien" + + @reloadDbWithTestData + Scenario: Reprise d'un conférencier d'une édition passée + Given the speaker photo "avatar1.png" is stored as "3/originals/4.png" + And I am logged in as admin and on the Administration + And I follow "Speakers" + When I follow "Reprendre un conférencier" + Then I should see "Reprendre un conférencier pour le forum" + When I fill in "q" with "ancienne" + And I press "Rechercher" + Then I should see "Un évènement du passé" + And I should see "marie-ancienne" + When I follow the button of tooltip "Reprendre Ancienne Marie" + Then I should see "Ajouter un conférencier pour le forum" + And I should see "Fiche reprise de Marie Ancienne" + And the "speaker[firstname]" field should contain "Marie" + And the "speaker[locality]" field should contain "Lyon" + And The "speaker[github_user]" field should have the following selected value "4" + When I fill in "speaker[referent_person_email]" with "referente@example.com" + And I press "Sauvegarder" + Then I should see "Le conférencier a été ajouté" + And the ".content table" element should contain "Ancienne Marie" + # même personne, champs et photo repris + When I follow the button of tooltip "Modifier la fiche de Ancienne Marie" + Then the "#speaker-person" element should contain "marie-ancienne" + And the "speaker[locality]" field should contain "Lyon" + And the "speaker[referent_person_email]" field should contain "referente@example.com" + And I should see "Voir la photo originale" + # la reprendre une seconde fois mène à la fiche existante + When I am on "/admin/speaker/pick?eventId=1&q=ancienne" + And I follow the button of tooltip "Reprendre Ancienne Marie" + Then I should see "Ce conférencier existe déjà pour cet événement" + And I should see "Modifier un conférencier pour le forum" + + @reloadDbWithTestData + Scenario: Rattacher, détacher et fusionner sur la fiche personne + Given I am logged in as admin and on the Administration + And I follow "Speakers" + When I follow the button of tooltip "Modifier la fiche de Bachelet Geoffrey" + Then the "#speaker-person" element should contain "geoffrey-bachelet" + When I follow "geoffrey-bachelet" + Then I should see "Personne geoffrey-bachelet" + And the "#person-suggestions" element should contain "geoffrey@example.com" + # rattacher la fiche homonyme d'une édition passée + When I press "Rattacher" in the row of "geoffrey@example.com" + Then I should see "Le conférencier a été rattaché à la personne" + And the "#person-speakers" element should contain "geoffrey@example.com" + And I should see "Aucune suggestion." + # la détacher + When I press "Détacher" in the row of "geoffrey@example.com" + Then I should see "Le conférencier a été détaché de la personne" + And the "#person-suggestions" element should contain "geoffrey@example.com" + # lui créer sa propre personne depuis sa fiche, puis fusionner les deux personnes + When I am on "/admin/speaker/edit?id=5" + Then I should see "Cette fiche n'est rattachée à aucune personne." + When I press "Créer la personne" + Then I should see "La personne a été créée" + And I should see "Personne geoffrey-bachelet-2" + When I fill in "q" with "Bachelet" + And I press "Rechercher" + And I press "Fusionner" in the row of "geoffrey-bachelet" + Then I should see "La personne geoffrey-bachelet a été fusionnée dans geoffrey-bachelet-2" + And I should see 2 "#person-speakers tbody tr" elements + And the "#person-speakers" element should contain "foo@bar.baz" diff --git a/tests/behat/features/EventPages/Cfp.feature b/tests/behat/features/EventPages/Cfp.feature index 1b3cffbe3..94f4096a9 100644 --- a/tests/behat/features/EventPages/Cfp.feature +++ b/tests/behat/features/EventPages/Cfp.feature @@ -121,3 +121,30 @@ Feature: Event pages - CFP When I am on "/event/afup-day-lyon/vote" Then I should not see "Une deuxième conf pour voter" Then I should see "Une conf pour voter" + + @reloadDbWithTestData + Scenario: Une conférencière d'une édition passée retrouve son profil prérempli, avec sa photo + Given the speaker photo "avatar1.png" is stored as "3/originals/4.png" + And I am on "/event/forum/cfp" + When I follow "Connect as ancien" + And I follow "Mon profil conférencier" + Then the "speaker[firstname]" field should contain "Marie" + And the "speaker[company]" field should contain "Ancienne Société" + And the response should contain "/uploads/speakers/3/originals/4.png" + When I press "Sauvegarder" + Then I should see "Profil sauvegardé." + And the response should contain "/uploads/speakers/1/originals/" + + @reloadDbWithTestData + Scenario: Le CFP reprend la fiche créée par l'admin pour la même personne, sans doublon + Given I am logged in as admin and on the Administration + And I am on "/admin/speaker/add?eventId=1&from=4" + When I select "" from "speaker[github_user]" + And I press "Sauvegarder" + Then I should see "Le conférencier a été ajouté" + When I am on "/event/forum/cfp" + And I follow "Connect as ancien" + Then I should see "Mon espace conférencier" + And I should not see "Vous n'avez pas encore rempli votre profil conférencier." + When I am on "/admin/speaker/person?id=4" + Then I should see 2 "#person-speakers tbody tr" elements diff --git a/tests/integration/AppBundle/CFP/SpeakerFactoryTest.php b/tests/integration/AppBundle/CFP/SpeakerFactoryTest.php new file mode 100644 index 000000000..a0097e9c3 --- /dev/null +++ b/tests/integration/AppBundle/CFP/SpeakerFactoryTest.php @@ -0,0 +1,83 @@ +connection = self::getContainer()->get(Connection::class); + $this->connection->insert('afup_forum', ['id' => 1, 'titre' => 'Forum 2024', 'date_debut' => '2024-11-01']); + $this->connection->insert('afup_forum', ['id' => 2, 'titre' => 'Forum 2025', 'date_debut' => '2025-11-01']); + $this->connection->insert('afup_speaker_person', ['id' => 1, 'slug' => 'marie-curie']); + // Édition passée, saisie via le CFP avec le compte GitHub 7 + $this->insertSpeaker(10, 1, 7, 1); + $this->logInAsGithubUser(7); + } + + public function testReusesTheRowOfThePersonCreatedByTheAdminWithoutGithubAccount(): void + { + $this->insertSpeaker(20, 2, null, 1); + + $speaker = self::getContainer()->get(SpeakerFactory::class)->getSpeaker($this->event(2)); + + self::assertSame(20, $speaker->getId()); + self::assertSame(7, (int) $this->connection->fetchOne('SELECT user_github FROM afup_conferenciers WHERE conferencier_id = 20'), 'le compte GitHub est rattaché à la ligne admin'); + self::assertSame(2, (int) $this->connection->fetchOne('SELECT COUNT(*) FROM afup_conferenciers'), 'aucune ligne créée'); + } + + public function testCreatesANewRowLinkedToThePersonOfTheGithubAccount(): void + { + $speaker = self::getContainer()->get(SpeakerFactory::class)->getSpeaker($this->event(2)); + + self::assertNull($speaker->getId()); + self::assertSame(7, $speaker->getUser()); + self::assertSame(1, $speaker->getPersonId()); + } + + public function testReturnsTheExistingRowOfTheGithubAccount(): void + { + $this->insertSpeaker(21, 2, 7, null); + $this->insertSpeaker(20, 2, null, 1); + + self::assertSame(21, self::getContainer()->get(SpeakerFactory::class)->getSpeaker($this->event(2))->getId()); + } + + private function logInAsGithubUser(int $id): void + { + $user = new GithubUser(); + $user->setId($id); + self::getContainer()->get(TokenStorageInterface::class)->setToken(new UsernamePasswordToken($user, 'github')); + } + + private function event(int $id): Event + { + return new Event()->setId($id); + } + + private function insertSpeaker(int $id, int $eventId, ?int $githubUserId, ?int $personId): void + { + $this->connection->insert('afup_conferenciers', [ + 'conferencier_id' => $id, + 'id_forum' => $eventId, + 'prenom' => 'Marie', + 'nom' => 'Curie', + 'email' => 'marie@example.com', + 'user_github' => $githubUserId, + 'person_id' => $personId, + ]); + } +} diff --git a/tests/integration/AppBundle/Event/Speaker/SpeakerPersonLinkerTest.php b/tests/integration/AppBundle/Event/Speaker/SpeakerPersonLinkerTest.php new file mode 100644 index 000000000..03965933c --- /dev/null +++ b/tests/integration/AppBundle/Event/Speaker/SpeakerPersonLinkerTest.php @@ -0,0 +1,79 @@ +get(Connection::class); + $connection->insert('afup_forum', ['id' => 1, 'titre' => 'Forum 2020', 'date_debut' => '2020-11-01']); + $connection->insert('afup_forum', ['id' => 2, 'titre' => 'Forum 2024', 'date_debut' => '2024-11-01']); + $connection->insert('afup_speaker_person', ['id' => 1, 'slug' => 'ancienne-personne']); + $connection->insert('afup_speaker_person', ['id' => 2, 'slug' => 'marie-curie']); + $this->insertSpeaker($connection, 10, 1, 7, 1); + $this->insertSpeaker($connection, 11, 2, 7, 2); + + $speaker = $this->buildSpeaker(7); + self::getContainer()->get(SpeakerPersonLinker::class)->ensurePerson($speaker); + + self::assertSame(2, $speaker->getPersonId()); + self::assertSame(2, (int) $connection->fetchOne('SELECT COUNT(*) FROM afup_speaker_person'), 'aucune personne créée'); + } + + public function testEnsurePersonCreatesAPersonWhenTheGithubAccountHasNone(): void + { + $connection = self::getContainer()->get(Connection::class); + + $speaker = $this->buildSpeaker(7); + self::getContainer()->get(SpeakerPersonLinker::class)->ensurePerson($speaker); + + self::assertNotNull($speaker->getPersonId()); + self::assertSame('marie-curie', $connection->fetchOne('SELECT slug FROM afup_speaker_person WHERE id = ?', [$speaker->getPersonId()])); + } + + public function testEnsurePersonSuffixesTheSlugWhenItIsAlreadyTaken(): void + { + $connection = self::getContainer()->get(Connection::class); + $connection->insert('afup_speaker_person', ['slug' => 'marie-curie']); + $connection->insert('afup_speaker_person', ['slug' => 'marie-curie-2']); + + $speaker = $this->buildSpeaker(null); + self::getContainer()->get(SpeakerPersonLinker::class)->ensurePerson($speaker); + + self::assertSame('marie-curie-3', $connection->fetchOne('SELECT slug FROM afup_speaker_person WHERE id = ?', [$speaker->getPersonId()])); + } + + public function testEnsurePersonKeepsAnExistingPerson(): void + { + $speaker = $this->buildSpeaker(7)->setPersonId(42); + self::getContainer()->get(SpeakerPersonLinker::class)->ensurePerson($speaker); + + self::assertSame(42, $speaker->getPersonId()); + } + + private function buildSpeaker(?int $githubUserId): Speaker + { + return new Speaker()->setFirstname('Marie')->setLastname('Curie')->setUser($githubUserId); + } + + private function insertSpeaker(Connection $connection, int $id, int $eventId, ?int $githubUserId, ?int $personId): void + { + $connection->insert('afup_conferenciers', [ + 'conferencier_id' => $id, + 'id_forum' => $eventId, + 'prenom' => 'Marie', + 'nom' => 'Curie', + 'email' => 'marie@example.com', + 'user_github' => $githubUserId, + 'person_id' => $personId, + ]); + } +} diff --git a/tests/integration/AppBundle/Event/Speaker/SpeakerPersonRowsTest.php b/tests/integration/AppBundle/Event/Speaker/SpeakerPersonRowsTest.php new file mode 100644 index 000000000..026cdb05a --- /dev/null +++ b/tests/integration/AppBundle/Event/Speaker/SpeakerPersonRowsTest.php @@ -0,0 +1,105 @@ +connection = self::getContainer()->get(Connection::class); + $this->connection->insert('afup_forum', ['id' => 1, 'titre' => 'Forum 2020', 'date_debut' => '2020-11-01']); + $this->connection->insert('afup_forum', ['id' => 2, 'titre' => 'AFUP Day 2022', 'date_debut' => '2022-05-01']); + $this->connection->insert('afup_forum', ['id' => 3, 'titre' => 'Forum 2024', 'date_debut' => '2024-11-01']); + $this->connection->insert('afup_speaker_person', ['id' => 1, 'slug' => 'helene-martin']); + $this->connection->insert('afup_speaker_person', ['id' => 2, 'slug' => 'helene-martin-2']); + } + + public function testSearchAcrossEventsReturnsOnePersonOrOneUnlinkedRowPointingToTheLatestRow(): void + { + $this->insertSpeaker(10, 1, 'Hélène', 'Martin', 'Acme', 1); + $this->insertSpeaker(11, 3, 'Hélène', 'Martin', 'Nouvelle société', 1); + $this->insertSpeaker(12, 2, 'Helene', 'Martin', 'Autre', null); + $this->insertSpeaker(13, 2, 'Paul', 'Durand', 'Acme', null); + + $results = self::getContainer()->get(SpeakerRepository::class)->searchAcrossEvents('helene'); + + self::assertSame( + [[11, 1, 'helene-martin', 'Nouvelle société', 'Forum 2024', 2], [12, null, null, 'Autre', 'AFUP Day 2022', 1]], + array_map(static fn(SpeakerSearchResult $r): array => [$r->speakerId, $r->personId, $r->personSlug, $r->company, $r->lastEventTitle, $r->eventCount], $results), + 'recherche insensible aux accents, une ligne par personne, la plus récente', + ); + } + + public function testSearchAcrossEventsMatchesCompanyAndEmailAndCountsEveryRowOfAMatchingPerson(): void + { + $this->insertSpeaker(10, 1, 'Hélène', 'Martin', 'Ancienne boîte', 1); + $this->insertSpeaker(11, 3, 'Hélène', 'Martin', 'Acme', 1); + + $results = self::getContainer()->get(SpeakerRepository::class)->searchAcrossEvents('acme'); + + self::assertCount(1, $results); + self::assertSame(2, $results[0]->eventCount); + self::assertCount(1, self::getContainer()->get(SpeakerRepository::class)->searchAcrossEvents('h.martin@example')); + self::assertSame([], self::getContainer()->get(SpeakerRepository::class)->searchAcrossEvents(' ')); + } + + public function testLinkSuggestionsAreUnlinkedRowsWithTheSameGithubAccountOrTheSameName(): void + { + $this->insertSpeaker(10, 1, 'Hélène', 'Martin', null, 1, 7); + $this->insertSpeaker(11, 2, 'HELENE', 'MARTIN', null, null); + $this->insertSpeaker(12, 3, 'H.', 'Martin', null, null, 7); + $this->insertSpeaker(13, 3, 'Paul', 'Martin', null, null); + $this->insertSpeaker(14, 3, 'Hélène', 'Martin', null, 2); + + $suggestions = self::getContainer()->get(SpeakerRepository::class)->findLinkSuggestions(1); + + self::assertSame([12, 11], array_map(static fn($speaker): ?int => $speaker->getId(), $suggestions)); + } + + public function testMergeMovesTheRowsThenDeletesTheMergedPerson(): void + { + $this->insertSpeaker(10, 1, 'Hélène', 'Martin', null, 1); + $this->insertSpeaker(11, 3, 'Hélène', 'Martin', null, 2); + $this->insertSpeaker(12, 2, 'Paul', 'Durand', null, null); + + $repository = self::getContainer()->get(SpeakerPersonRepository::class); + $repository->merge($repository->find(1), $repository->find(2)); + + self::assertSame( + [[10, 1], [11, 1], [12, null]], + array_map( + static fn(array $row): array => [(int) $row['conferencier_id'], $row['person_id'] === null ? null : (int) $row['person_id']], + $this->connection->fetchAllAssociative('SELECT conferencier_id, person_id FROM afup_conferenciers ORDER BY conferencier_id'), + ), + ); + self::assertSame(['helene-martin'], $this->connection->fetchFirstColumn('SELECT slug FROM afup_speaker_person')); + } + + private function insertSpeaker(int $id, int $eventId, string $firstname, string $lastname, ?string $company, ?int $personId, ?int $githubUserId = null): void + { + $this->connection->insert('afup_conferenciers', [ + 'conferencier_id' => $id, + 'id_forum' => $eventId, + 'prenom' => $firstname, + 'nom' => $lastname, + 'email' => 'h.martin@example.com', + 'societe' => $company, + 'person_id' => $personId, + 'user_github' => $githubUserId, + ]); + } +} diff --git a/tests/unit/AppBundle/CFP/PhotoStorageTest.php b/tests/unit/AppBundle/CFP/PhotoStorageTest.php new file mode 100644 index 000000000..f3b092d42 --- /dev/null +++ b/tests/unit/AppBundle/CFP/PhotoStorageTest.php @@ -0,0 +1,54 @@ +basePath = sys_get_temp_dir() . '/' . uniqid('photo-storage-', true); + } + + protected function tearDown(): void + { + new Filesystem()->remove($this->basePath); + } + + public function testCopyFromCopiesTheOriginalPhotoIntoTheFolderOfTheTargetEvent(): void + { + $filesystem = new Filesystem(); + $filesystem->dumpFile($this->basePath . '/3/originals/4.png', 'photo'); + // Ancienne vignette de la cible : elle doit être régénérée depuis la nouvelle photo + $filesystem->dumpFile($this->basePath . '/1/thumbnails/12.jpg', 'old'); + $storage = new PhotoStorage($this->basePath, $this->basePath); + + $fileName = $storage->copyFrom($this->speaker(4, 3, '4.png'), $this->speaker(12, 1, null)); + + self::assertSame('12.png', $fileName); + self::assertSame('photo', file_get_contents($this->basePath . '/1/originals/12.png')); + self::assertFileExists($this->basePath . '/3/originals/4.png', 'la source est conservée'); + self::assertFileDoesNotExist($this->basePath . '/1/thumbnails/12.jpg'); + } + + public function testCopyFromReturnsNullWhenTheSourceHasNoPhotoFile(): void + { + $storage = new PhotoStorage($this->basePath, $this->basePath); + + self::assertNull($storage->copyFrom($this->speaker(4, 3, '4.png'), $this->speaker(12, 1, null))); + self::assertNull($storage->copyFrom($this->speaker(4, 3, null), $this->speaker(12, 1, null))); + } + + private function speaker(int $id, int $eventId, ?string $photo): Speaker + { + return new Speaker()->setId($id)->setEventId($eventId)->setPhoto($photo); + } +}