Commit a23c7028 authored by Stephane Bouvry's avatar Stephane Bouvry
Browse files

Rappel des validateurs en cours (backup)

parent fe7ffead
Loading
Loading
Loading
Loading
Loading
+164 −0
Original line number Diff line number Diff line
<?php
/**
 * Created by PhpStorm.
 * User: bouvry
 * Date: 04/10/19
 * Time: 11:49
 */

namespace Oscar\Command;


use Doctrine\ORM\NoResultException;
use Moment\Moment;
use Oscar\Entity\Authentification;
use Oscar\Entity\LogActivity;
use Oscar\Entity\Person;
use Oscar\Entity\Role;
use Oscar\Entity\WorkPackage;
use Oscar\Entity\WorkPackagePerson;
use Oscar\Service\ConnectorService;
use Oscar\Service\MailingService;
use Oscar\Service\OscarConfigurationService;
use Oscar\Service\OscarMailerService;
use Oscar\Service\OscarUserContext;
use Oscar\Service\PersonService;
use Oscar\Service\TimesheetService;
use Oscar\Utils\DateTimeUtils;
use Oscar\Utils\PeriodInfos;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use UnicaenApp\Service\Mailer\MailerService;
use Zend\Validator\Date;

class OscarTimesheetValidatorrRecallCommand extends OscarAdvancedCommandAbstract
{
    protected static $defaultName = 'timesheets:validator-recall';

    const OPT_FORCE = "force";
    const OPT_VALIDATOR = "validator";
    const OPT_PERIOD = "period";
    const OPT_PROCESSDATE = "processdate";

    const ARG_PERSONID = "personid";

    protected function configure()
    {
        $this
            ->setDescription("Relance ponctuelle d'un déclarant")
            ->addOption(
                self::OPT_PROCESSDATE,
                null,
                InputOption::VALUE_OPTIONAL,
                "Date effective du rappel",
                null
            )
            ->addOption(
                self::OPT_PERIOD,
                null,
                InputOption::VALUE_OPTIONAL,
                "Période (par défaut, période en cours)",
                null
            )
            ->addOption(
                self::OPTION_FORCE,
                null,
                InputOption::VALUE_OPTIONAL,
                "Forcer l'envoi du mail même si ça n'est pas necessaire",
                false
            )
            ->addArgument(
                self::ARG_PERSONID,
                InputArgument::OPTIONAL,
                "ID du déclarant"
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        parent::execute($input, $output);

        // Argument ALL
        $personId = $input->getArgument(self::ARG_PERSONID);

        /// OPTIONS and PARAMETERS
        $processDate = $input->getOption(self::OPT_PROCESSDATE);
        $processDate = new \DateTime($processDate);

        $force = $input->getOption(self::OPTION_FORCE) === null;

        // Période
        $period = $input->getOption(self::OPT_PERIOD);

        $helps = [];

        if (!$period) {
            $period = null;
            $periodText = " (Période non-spécifée)";
            $helps[] = "l'option '--period=<PERIOD>' permet de spécifier la période sous la forme YYYY-MM (ou 'now' pour la période en cours)";
        } else {
            if ($period == 'now') {
                $period = (new \DateTime())->format('Y-m');
            }
            $periodInfos = DateTimeUtils::periodBounds($period);
            $periodlabel = $periodInfos['periodLabel'];
            $periodText = " (Pour la période $periodlabel)";
        }

        if ($personId == null) {
            $this->getIO()->title("Liste des validateurs $periodText");

            $validators = $this->getPersonService()->getPersonsByIds(
                $period == null ?
                    $this->getPersonService()->getValidatorsIds() :
                    $this->getPersonService()->getValidatorsIdsPeriod($period)
            );
            $headers = ['ID', 'Personne', 'Email', "Identifiant"];
            $rows = [];
            foreach ($validators as $validator) {
                $rows[] = [
                    $validator->getId(),
                    $validator->getDisplayName(),
                    $validator->getEmail(),
                    $validator->getLadapLogin()
                ];
            }
            $this->getIO()->table($headers, $rows);
            $this->getIO()->comment("Vous pouvez utiliser l'ID de la personne pour afficher les détails");
        } else {

            $validator = $this->getPersonService()->getPersonById($personId, true);

            if (!$period) {
                $periods = $this->getTimesheetService()->getPeriodsValidator($validator);
                $rows = [];
                foreach ($periods as $period) {
                    $periodInfos = PeriodInfos::getPeriodInfosObj($period);
                    $rows[] = [$periodInfos->getPeriodCode(), $periodInfos->getPeriodLabel()];
                }
                $this->getIO()->title("Périodes pour $validator où des validations sont à faire");
                $headers = ["Code", "Période"];
                $this->getIO()->table($headers, $rows);
                $this->getIO()->comment("Utiliser --period=CODE_PERIOD pour déclencher le rappel");
            } else {
                $this->getIO()->title("Rappel pour $validator $periodText");

            }
        }

        return 1;
    }

    /**
     * @return TimesheetService
     */
    protected function getTimesheetService(): TimesheetService
    {
        return $this->getServicemanager()->get(TimesheetService::class);
    }
}
 No newline at end of file
+93 −1
Original line number Diff line number Diff line
@@ -16,6 +16,7 @@ use Oscar\Connector\IConnectedRepository;
use Oscar\Exception\OscarException;
use Oscar\Import\Data\DataExtractorFullname;
use Oscar\Utils\DateTimeUtils;
use Oscar\Utils\PeriodInfos;

/**
 * Class ProjectGrantRepository
@@ -387,8 +388,73 @@ class PersonRepository extends EntityRepository implements IConnectedRepository
        return $filtersUsed;
    }

    public function getIdsValidatorsProject(bool $hasToValidate = false, int $year = -1, int $month = -1): array
    {
        $qb = $this->getBaseQueryValidator($year, $month)
            ->innerJoin('vp.validatorsPrj', 'p');

        if ($hasToValidate === true) {
            $qb->andWhere('vp.status = :step')
                ->setParameter('step', ValidationPeriod::STATUS_STEP1);
        }

        $ids = $qb->getQuery()->getArrayResult();

        return array_map('current', $ids);
    }

    public function getIdsValidatorsSci(bool $hasToValidate = false, int $year = -1, int $month = -1): array
    {
        $qb = $this->getBaseQueryValidator($year, $month)
            ->innerJoin('vp.validatorsSci', 'p');

        if ($hasToValidate === true) {
            $qb->andWhere('vp.status = :step')
                ->setParameter('step', ValidationPeriod::STATUS_STEP2);
        }

        $ids = $qb->getQuery()->getArrayResult();

        return array_map('current', $ids);
    }

    public function getIdsValidatorsAdm(bool $hasToValidate = false, int $year = -1, int $month = -1): array
    {
        $qb = $this->getBaseQueryValidator($year, $month)
            ->innerJoin('vp.validatorsAdm', 'p');

        if ($hasToValidate === true) {
            $qb->andWhere('vp.status = :step')
                ->setParameter('step', ValidationPeriod::STATUS_STEP3);
        }

        $ids = $qb->getQuery()->getArrayResult();

        return array_map('current', $ids);
    }


    public function getIdsValidators($hasValidating = true, $period = ""): array
    {
        $year = -1;
        $month = -1;
        if ($period != "") {
            $periodInfos = PeriodInfos::getPeriodInfosObj($period);
            $year = $periodInfos->getYear();
            $month = $periodInfos->getMonth();
        }

        $prj = $this->getIdsValidatorsProject($hasValidating, $year, $month);
        $sci = $this->getIdsValidatorsSci($hasValidating, $year, $month);
        $adm = $this->getIdsValidatorsAdm($hasValidating, $year, $month);

        $ids = array_unique(array_merge($sci, $adm, $prj));

        return $ids;
    }

    /**
     * Retourne le liste des déclarants (pour la période si spécifiée).
     * Retourne le liste des person.id des déclarants (pour la période si spécifiée).
     *
     * @param string|null $periodA (période, sous la forme YYYY-MM)
     * @return array
@@ -422,6 +488,32 @@ class PersonRepository extends EntityRepository implements IConnectedRepository
        $results = $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
        return array_map('current', $results);
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Requête de base pour obtenir les PersonID des validateurs identifiés dans les procédures de validation.
     *
     * @param int $year Année ou -1 pour ignorer
     * @param int $month Mois (1=Janvier, 2=février, etc..  ou -1 pour ignorer)
     * @return \Doctrine\ORM\QueryBuilder
     */
    protected function getBaseQueryValidator(int $year = -1, int $month = -1)
    {
        $qb = $this->getEntityManager()->createQueryBuilder('vp')
            ->select('DISTINCT(p.id)')
            ->from(ValidationPeriod::class, 'vp');

        if ($year > -1) {
            $qb->andWhere('vp.year = :year')
                ->setParameter('year', $year);
        }

        if ($month > -1) {
            $qb->andWhere('vp.month = :month')
                ->setParameter('month', $month);
        }
        return $qb;
    }

    public function getObjectByConnectorID($connectorName, $connectorID)
    {
+12 −0
Original line number Diff line number Diff line
@@ -50,6 +50,7 @@ use Oscar\Traits\UseProjectGrantService;
use Oscar\Traits\UseProjectGrantServiceTrait;
use Oscar\Traits\UseServiceContainer;
use Oscar\Traits\UseServiceContainerTrait;
use Oscar\Utils\PeriodInfos;
use Oscar\Utils\UnicaenDoctrinePaginator;
use Symfony\Component\Console\Style\SymfonyStyle;
use UnicaenApp\Mapper\Ldap\People;
@@ -1467,6 +1468,17 @@ class PersonService implements UseOscarConfigurationService, UseEntityManager, U
        return $queryBuilder;
    }

    public function getValidatorsIds()
    {
        return $this->getPersonRepository()->getIdsValidators();
    }

    public function getValidatorsIdsPeriod(string $period)
    {
        $periodInfo = PeriodInfos::getPeriodInfosObj($period);
        return $this->getPersonRepository()->getIdsValidators(true, $periodInfo->getPeriodCode());
    }

    /**
     * @return RecallExceptionRepository
     */
+31 −0
Original line number Diff line number Diff line
@@ -2587,6 +2587,37 @@ class TimesheetService implements UseOscarUserContextService, UseOscarConfigurat
        return $periods;
    }

    public function getPeriodsValidator( Person $validator ) :array
    {
        $qb = $this->getEntityManager()->createQuery(
          "SELECT DISTINCT vp.id, vp.year, vp.month, vp.object, 
                    vp.validationActivityById,
                    vp.validationSciById,
                    vp.validationAdmById
       
           FROM " . ValidationPeriod::class . " vp 
           LEFT JOIN vp.validatorsPrj prj 
           LEFT JOIN vp.validatorsSci sci 
           LEFT JOIN vp.validatorsAdm adm 
           WHERE prj.id = :validator OR sci.id = :validator OR adm.id = :validator
           "
        );

        $r = $qb->setParameter('validator', $validator->getId())->getArrayResult();
        $periods = [];
        foreach ($r as $row) {
            $period = sprintf('%s-%s', $row['year'], ($row['month'] < 10 ? '0':'').$row['month']);
            if( !in_array($period, $periods) ){
                $periods[] = $period;
            }
        }
        var_dump($periods);
        die();


        return [];
    }

    public function getPersonPeriodsTimesheetTotals(Person $declarer)
    {
        return $this->getTimesheetRepository()->getTimesheetTotalByPeriodPerson($declarer->getId());
+67 −7
Original line number Diff line number Diff line
<?php

namespace Oscar\Utils;

use Oscar\Exception\OscarException;
@@ -8,8 +9,11 @@ class PeriodInfos
    private int $month;
    private int $year;

    private string $_label='';
    private string $_label;
    private string $_code;
    private ?int $_totalDays = null;
    private ?\DateTime $_start = null;
    private ?\DateTime $_end = null;

    /**
     * PeriodInfos constructor.
@@ -44,7 +48,7 @@ class PeriodInfos
            $this->month = 12;
            $this->year--;
        }
        $this->_label = '';
        $this->resetCache();
        return $this;
    }

@@ -60,10 +64,21 @@ class PeriodInfos
            $this->month = 1;
            $this->year++;
        }
        $this->_label = '';
        $this->resetCache();
        return $this;
    }

    /**
     * Reset cached datas
     */
    protected function resetCache(): void
    {
        $this->_totalDays = null;
        $this->_start = null;
        $this->_end = null;
        $this->_label = '';
    }

    /**
     * @return int
     */
@@ -72,6 +87,10 @@ class PeriodInfos
        return $this->year;
    }

    /**
     * @return string
     * @throws \Exception
     */
    public function getPeriodLabel(): string
    {
        if (!$this->_label) {
@@ -89,6 +108,11 @@ class PeriodInfos
        return $this->_label;
    }

    /**
     * Retourne le code de la période sous la forme YYYY-MM
     *
     * @return string
     */
    public function getPeriodCode(): string
    {
        return sprintf('%s-%s', $this->getYear(), ($this->getMonth() < 10 ? '0' : '') . $this->getMonth());
@@ -105,6 +129,42 @@ class PeriodInfos
        ];
    }

    /**
     * Retourne le premier jour de la période.
     *
     * @return \DateTime
     * @throws \Exception
     */
    public function getStart(): \DateTime
    {
        if ($this->_start == null) {
            $this->_start = new \DateTime(sprintf('%s-01 00:00:00', $this->getPeriodCode()));
        }
        return $this->_start;
    }

    /**
     * Retourne le dernier jour de la période.
     *
     * @return \DateTime
     * @throws \Exception
     */
    public function getEnd(): \DateTime
    {
        if ($this->_end == null) {
            $this->_end = new \DateTime(sprintf('%s-%s 23:59:59', $this->getPeriodCode(), $this->getTotalDays()));
        }
        return $this->_end;
    }

    public function getTotalDays(): int
    {
        if (!$this->_totalDays) {
            $this->_totalDays = cal_days_in_month(CAL_GREGORIAN, $this->getMonth(), $this->getYear());
        }
        return $this->_totalDays;
    }

    public static function getPeriodInfosObj(string $str): PeriodInfos
    {
        $re = '/([0-9]{4})\-(10|11|12|0?[1-9])$/';
Loading