Commit 161a2d41 authored by Bertrand Gauthier's avatar Bertrand Gauthier
Browse files

Traitement des résultats d'observation de l'import : Amélioration des logs

parent 3ec43d1e
Loading
Loading
Loading
Loading
+21 −5
Changes for module/Application/src/Application/Rule/NotificationDepotVersionCorrigeeAttenduRule.php: 21 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -2,9 +2,12 @@

namespace Application\Rule;

use Application\Constants;
use Application\Entity\Db\These;
use DateInterval;
use DateTime;
use UnicaenApp\Exception\RuntimeException;
use UnicaenApp\Traits\MessageAwareTrait;

/**
 * Règle concernant notification au sujet du dépôt attendu de la version corrigée.
@@ -13,6 +16,8 @@ use DateTime;
 */
class NotificationDepotVersionCorrigeeAttenduRule implements RuleInterface
{
    use MessageAwareTrait;

    const SPEC_INTERVAL_ENTRE_DATE_NOTIF_ET_BUTOIRE = 'P1M'; // 1 mois

    /**
@@ -80,9 +85,11 @@ class NotificationDepotVersionCorrigeeAttenduRule implements RuleInterface
    public function execute()
    {
        $dateButoir = $this->these->getDateButoirDepotVersionCorrigee();

        if ($dateButoir === null) {
            $this->dateProchaineNotif = null;
            $this->estPremiereNotif = $this->dateDerniereNotif === null;
            $this->addMessage("Notification non applicable, il n'y a aucune date butoir.");
            return $this;
        }

@@ -92,6 +99,7 @@ class NotificationDepotVersionCorrigeeAttenduRule implements RuleInterface
        if ($this->dateAujourdhui > $dateButoir) {
            $this->dateProchaineNotif = null;
            $this->estPremiereNotif = $this->dateDerniereNotif === null;
            $this->addMessage("Plus la peine de notifier, la date butoir est dépassée.");
            return $this;
        }

@@ -99,6 +107,7 @@ class NotificationDepotVersionCorrigeeAttenduRule implements RuleInterface
        if ($this->dateDerniereNotif === null) {
            $this->dateProchaineNotif = $this->dateAujourdhui;
            $this->estPremiereNotif = true;
            $this->addMessage("Première notification à faire immédiatement.");
            return $this;
        }

@@ -106,18 +115,20 @@ class NotificationDepotVersionCorrigeeAttenduRule implements RuleInterface

        switch ($this->these->getCorrectionAutorisee()) {
            case These::CORRECTION_MAJEURE:
                if ($dateButoir !== null) {
                $spec = self::SPEC_INTERVAL_ENTRE_DATE_NOTIF_ET_BUTOIRE;
                    $dateProchaineNotif = $dateButoir->sub(new DateInterval($spec)); // Date butoir - interval
                }
                else {
                    $dateProchaineNotif = null;
                try {
                    $interval = new DateInterval($spec);
                } catch (\Exception $e) {
                    throw new RuntimeException("Interval invalide : $spec", null, $e);
                }
                $dateProchaineNotif = $dateButoir->sub($interval); // Date butoir - interval
                break;
            case These::CORRECTION_MINEURE:
                // Une seule notification pour des corrections mineures
                $dateProchaineNotif = null;
                break;
            default:
                // pas possible
                $dateProchaineNotif = null;
                break;
        }
@@ -133,15 +144,18 @@ class NotificationDepotVersionCorrigeeAttenduRule implements RuleInterface
        // La date de prochaine notif est passée: plus de notif.
        if ($dateProchaineNotif < $this->dateAujourdhui) {
            $this->dateProchaineNotif = null;
            $this->addMessage("Plus de notification nécessaire.");
            return $this;
        }
        // La date de prochaine notif égale la date de dernière notif: les notifications sont terminées.
        if ($dateProchaineNotif == $this->dateDerniereNotif) {
            $this->dateProchaineNotif = null;
            $this->addMessage("Les notifications sont terminées.");
            return $this;
        }

        $this->dateProchaineNotif = $dateProchaineNotif;
        $this->addMessage(sprintf("Prochaine notification le %s.", $this->dateProchaineNotif->format(Constants::DATETIME_FORMAT)));

        return $this;
    }
@@ -175,4 +189,6 @@ class NotificationDepotVersionCorrigeeAttenduRule implements RuleInterface

        return $this;
    }


}
 No newline at end of file
+4 −3
Changes for module/Application/src/Application/Service/Notification/NotifierService.php: 4 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -4,18 +4,19 @@ namespace Application\Service\Notification;

use Application\Entity\Db\EcoleDoctorale;
use Application\Entity\Db\Etablissement;
use Application\Entity\Db\Fichier;
use Application\Entity\Db\ImportObservResult;
use Application\Entity\Db\Individu;
use Application\Entity\Db\MailConfirmation;
use Application\Entity\Db\Role;
use Application\Entity\Db\These;
use Application\Entity\Db\UniteRecherche;
use Application\Entity\Db\ValiditeFichier;
use Application\Entity\Db\Variable;
use Application\Notification\CorrectionAttendueUpdatedNotification;
use Application\Notification\ResultatTheseAdmisNotification;
use Application\Notification\ResultatTheseModifieNotification;
use Application\Notification\ValidationDepotTheseCorrigeeNotification;
use Application\Notification\ValidationPageDeCouvertureNotification;
use Application\Notification\ValidationRdvBuNotification;
use Application\Rule\NotificationDepotVersionCorrigeeAttenduRule;
use Application\Service\EcoleDoctorale\EcoleDoctoraleServiceAwareTrait;
@@ -140,7 +141,7 @@ class NotifierService extends \Notification\Service\NotifierService
    /**
     * @param ImportObservResult $record
     * @param These              $these
     * @return ImportObservResult|null
     * @return CorrectionAttendueUpdatedNotification|null
     */
    public function triggerCorrectionAttendue(ImportObservResult $record, These $these)
    {
@@ -171,7 +172,7 @@ class NotifierService extends \Notification\Service\NotifierService

        $this->trigger($notif);

        return $record;
        return $notif;
    }

    /**
+53 −28
Changes for module/Import/src/Import/Service/ImportObservResult/ImportObservResultService.php: 53 added lines, 28 removed lines.
Original line number Diff line number Diff line
@@ -80,13 +80,13 @@ class ImportObservResultService extends BaseService
     */
    public function handleImportObservResultsForResultatAdmis()
    {
        $this->logger->info(
            "# Traitement des résultats d'import : " .
            "notifications au sujet des thèses dont le résultat est passé à \"admis\"");

        $records = $this->repository->fetchImportObservResultsForResultatAdmis();
        if (! count($records)) {
            $this->logger->info("Aucun résultat d'import à traiter.");
            return;
        }

        $this->logger->info(sprintf("%d résultat(s) d'import trouvé.", count($records)));
        $this->logger->info(sprintf("%d résultat(s) d'import trouvé(s) à traiter.", count($records)));

        // Mise en forme des données pour le template du mail
        $data = $this->prepareDataForResultatAdmis($records);
@@ -97,29 +97,22 @@ class ImportObservResultService extends BaseService
            return;
        }

        // Notification :
        // - du BDD concernant l'évolution des résultats de thèses.
        // - des doctorants dont le résultat de la thèse est passé à Admis.
        $notif = $this->notifierService->triggerBdDUpdateResultat($data);
        $this->logger->info(sprintf("Notification envoyée à %s.",
            implode(", ", $notif->getTo())
        ));
        // Notification des doctorants dont le résultat de la thèse est passé à Admis.
        $notifs = $this->notifierService->triggerDoctorantResultatAdmis($data);
        $this->logger->info(sprintf("Notification envoyée à %s.",
            implode(", ", array_map(function (Notification $notif) { return implode(", ", $notif->getTo()); }, $notifs))
        ));
        $this->logAboutNotifications($notifs);
        // Notification du BDD concernant l'évolution des résultats de thèses.
        $notif = $this->notifierService->triggerBdDUpdateResultat($data);
        $this->logAboutNotifications([$notif]);

        // Enregistrement de la date de notification sur chaque résultat d'observation
        // Enregistrement de la date de dernière notification
        foreach ($records as $record) {
            $record->setDateNotif(new \DateTime());
            $record->setDateNotif($notif->getSendDate());
        }
        try {
            $this->getEntityManager()->flush($records);
        } catch (OptimisticLockException $e) {
            throw new RuntimeException("Enregistrement des ImportObservResult impossible", null, $e);
        }

        $this->logger->info("Enregistrement de la date de notification sur chaque résultat d'observation effectué.");
    }

    /**
@@ -138,15 +131,16 @@ class ImportObservResultService extends BaseService

        // Fetch thèses concernées
        $qb = $this->theseService->getRepository()->createQueryBuilder('t');
        $qb
            ->where($qb->expr()->in('t.sourceCode', $sourceCodes))
            ->andWhere('1 = pasHistorise(t)');
        /** @var These[] $theses */
        $theses = $qb->getQuery()->getResult();
        $qb->where($qb->expr()->in('t.sourceCode', $sourceCodes));
        $theses = $qb->getQuery()->getResult(); /** @var These[] $theses */

        // Mise en forme des données pour le template du mail
        $data = [];
        foreach ($theses as $index => $these) {
            if (! $these->estNonHistorise()) {
                $this->logger->info(sprintf("La thèse '%s' est écartée car elle est historisée.", $these->getSourceCode()));
                continue;
            }
            $data[] = [
                'these'  => $these,
                'detail' => $details[$index],
@@ -162,6 +156,10 @@ class ImportObservResultService extends BaseService
     */
    public function handleImportObservResultsForCorrectionMineure()
    {
        $this->logger->info(
            "# Traitement des résultats d'import : " .
            "notifications au sujet des thèses pour lesquelles le témoin \"correction autorisée\" est passé à \"mineure\"");

        $records = $this->repository->fetchImportObservResultsForCorrectionMineure();

        $this->_handleImportObservResultsForCorrection($records);
@@ -173,6 +171,10 @@ class ImportObservResultService extends BaseService
     */
    public function handleImportObservResultsForCorrectionMajeure()
    {
        $this->logger->info(
            "# Traitement des résultats d'import : " .
            "notifications au sujet des thèses pour lesquelles le témoin \"correction autorisée\" est passé à \"majeure\"");

        $records = $this->repository->fetchImportObservResultsForCorrectionMajeure();

        $this->_handleImportObservResultsForCorrection($records);
@@ -187,24 +189,35 @@ class ImportObservResultService extends BaseService
    private function _handleImportObservResultsForCorrection(array $records)
    {
        if (! count($records)) {
            $this->logger->info("Aucun résultat d'import à traiter.");
            return;
        }

        $this->logger->info(sprintf("%d résultat(s) d'import trouvé(s).", count($records)));

        $recordsToFlush = [];

        foreach ($records as $record) {
            /** @var These $these */
            $these = $this->theseService->getRepository()->findOneBy(['sourceCode' => $record->getSourceCode()]);
            if (! $these->estNonHistorise()) {
                $this->logger->info(sprintf("La thèse '%s' est écartée car elle est historisée.", $these->getSourceCode()));
                continue;
            }

            $these->setCorrectionAutorisee($record->getImportObserv()->getToValue()); // anticipation nécessaire !

            // notification
            $result = $this->notifierService->triggerCorrectionAttendue($record, $these);
            if ($result === null) {
            $notif = $this->notifierService->triggerCorrectionAttendue($record, $these);
            if ($notif === null) {
                $this->logger->info(sprintf("D'après les règles métiers, aucune notif n'est nécessaire pour la thèse '%s'.", $these->getSourceCode()));
                continue; // si le service de notif renvoie null, aucune notif n'était nécessaire, on passe au suivant
            }

            // Enregistrement de la date de notification
            $record->setDateNotif(new \DateTime());
            $this->logAboutNotifications([$notif]);

            // Enregistrement de la date de dernière notification
            $record->setDateNotif($notif->getSendDate());

            $recordsToFlush[] = $record;
        }
@@ -215,4 +228,16 @@ class ImportObservResultService extends BaseService
            throw new RuntimeException("Enregistrement des ImportObservResult impossible", null, $e);
        }
    }

    /**
     * @param Notification[] $notifs
     */
    private function logAboutNotifications(array $notifs)
    {
        foreach ($notifs as $notif) {
            $this->logger->info(
                sprintf('Notification "%s" envoyée : %s.', $notif->getSubject(), implode(", ", $notif->getTo()), $notifs)
            );
        }
    }
}
+28 −0
Changes for module/Notification/src/Notification/Notification.php: 28 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -62,6 +62,11 @@ class Notification
     */
    protected $infoMessages = [];

    /**
     * @var \DateTime
     */
    protected $sendDate;

    /**
     * Notification constructor.
     *
@@ -322,4 +327,27 @@ class Notification
    {
        return $this->infoMessages;
    }

    /**
     * Renseigne la date d'envoi éventuelle de cette notification.
     *
     * @param \DateTime $sendDate
     * @return self
     */
    public function setSendDate(\DateTime $sendDate)
    {
        $this->sendDate = $sendDate;

        return $this;
    }

    /**
     * Retourne la date d'envoi éventuelle de cette notification.
     *
     * @return \DateTime
     */
    public function getSendDate()
    {
        return $this->sendDate;
    }
}
 No newline at end of file
+20 −1
Changes for module/Notification/src/Notification/Service/NotifierService.php: 20 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -7,6 +7,7 @@ use Notification\MessageContainer;
use Notification\Notification;
use Notification\NotificationRenderer;
use UnicaenApp\Service\Mailer\MailerServiceAwareTrait;
use Zend\Mail\Message;

/**
 * Service d'envoi de notification par mail.
@@ -94,7 +95,25 @@ class NotifierService
    {
        $mail = $this->createMailForNotification($notification);

        $this->mailerService->send($mail);
        $message = $this->mailerService->send($mail);

        $sendDate = $this->extractDateFromMessage($message) ?: new \DateTime();
        $notification->setSendDate($sendDate);
    }

    /**
     * @param Message $message
     * @return \DateTime|null
     */
    private function extractDateFromMessage(Message $message)
    {
        if ($message->getHeaders()->has('Date')) {
            $messageDate = $message->getHeaders()->get('Date')->getFieldValue();

            return date_create_from_format($messageDate, 'r');
        }

        return null;
    }

    /**