Advertisement
Guest User

Untitled

a guest
Aug 26th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 28.41 KB | None | 0 0
  1. <?php
  2.  
  3. namespace LDMR\MigrationBundle\Cron;
  4.  
  5. use Doctrine\Common\Collections\ArrayCollection;
  6. use Doctrine\ORM\EntityManager;
  7. use LDMR\EmployeeBundle\Entity\Employee;
  8. use LDMR\FormBundle\Entity\FormAnswer;
  9. use LDMR\FormBundle\Entity\FormQuestion;
  10. use LDMR\FormBundle\Repository\FormQuestionRepository;
  11. use LDMR\FormBundle\Repository\LuluFormAnswerRepository;
  12. use LDMR\FormBundle\Repository\LuluFormRepository;
  13. use LDMR\FormBundle\Service\FormPdf;
  14. use \RuntimeException;
  15. use LDMR\CommonBundle\Utils\Tools;
  16. use LDMR\EmployeeBundle\Repository\EmployeeRepository;
  17. use LDMR\FormBundle\Entity\Form;
  18. use LDMR\LuluBundle\Entity\Lulu;
  19. use LDMR\LuluBundle\Repository\AccompanimentTypeRepository;
  20. use LDMR\LuluBundle\Repository\LuluRepository;
  21. use LDMR\MigrationBundle\Entity\CronLog;
  22. use LDMR\MigrationBundle\Repository\CronItemLogRepository;
  23. use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter as Normalizer;
  24. use Symfony\Component\Translation\DataCollectorTranslator as Translator;
  25. use LDMR\LuluBundle\Entity\FollowUpAppointment;
  26. use LDMR\MigrationBundle\Entity\CronItemLog;
  27. use Doctrine\ORM\NonUniqueResultException;
  28. use \Exception;
  29. use \DateTime;
  30.  
  31. /**
  32.  * Class AbstractItem
  33.  *
  34.  * @package LDMR\MigrationBundle\Cron
  35.  */
  36. abstract class AbstractItem
  37. {
  38.     /** @var EntityManager  **/
  39.     public $em;
  40.  
  41.     /** @var array  **/
  42.     public static $itemColumns = [];
  43.  
  44.     /** @var array  **/
  45.     public $association;
  46.  
  47.     /** @var Translator  **/
  48.     public $translator;
  49.  
  50.     /** @var Normalizer  **/
  51.     public $normalizer;
  52.  
  53.     /** @var CronItemLogRepository */
  54.     public $cronItemLogRepo;
  55.  
  56.     /** @var LuluRepository */
  57.     public $luluRepo;
  58.  
  59.     /** @var EmployeeRepository */
  60.     public $employeeRepo;
  61.  
  62.     /** @var AccompanimentTypeRepository */
  63.     public $accompanimentTypeRepo;
  64.  
  65.     /** @var FormQuestionRepository **/
  66.     protected $questionRepo;
  67.  
  68.     /** @var LuluFormRepository **/
  69.     protected $luluFormRepo;
  70.  
  71.     /** @var LuluFormAnswerRepository **/
  72.     protected $luluFormAnswerRepo;
  73.  
  74.     /** @var FormPdf **/
  75.     protected $formPdf;
  76.  
  77.     public function __construct(EntityManager $em, Translator $translator, FormPdf $formPdf)
  78.     {
  79.         $this->em                    = $em;
  80.         $this->translator            = $translator;
  81.         $this->normalizer            = new Normalizer();
  82.         $this->formPdf               = $formPdf;
  83.  
  84.         $this->accompanimentTypeRepo = $this->em->getRepository('LDMRLuluBundle:AccompanimentType');
  85.         $this->employeeRepo          = $this->em->getRepository('LDMREmployeeBundle:Employee');
  86.         $this->luluRepo              = $this->em->getRepository('LDMRLuluBundle:Lulu');
  87.         $this->cronItemLogRepo       = $this->em->getRepository('LDMRMigrationBundle:CronItemLog');
  88.         $this->questionRepo          = $this->em->getRepository('LDMRFormBundle:FormQuestion');
  89.         $this->luluFormRepo          = $this->em->getRepository('LDMRFormBundle:LuluForm');
  90.         $this->luluFormAnswerRepo    = $this->em->getRepository('LDMRFormBundle:LuluFormAnswer');
  91.  
  92.         $this->association = [
  93.             'marital_status' => [
  94.                 $this->getTranslation('field.marital_status.single')               => 'single',
  95.                 $this->getTranslation('field.marital_status.married')              => 'married',
  96.                 $this->getTranslation('field.marital_status.concubinage')          => 'concubinage',
  97.                 $this->getTranslation('field.marital_status.widower')              => 'widower',
  98.                 $this->getTranslation('field.marital_status.divorced')             => 'divorced',
  99.                 $this->getTranslation('field.marital_status.single-parent-family') => 'single-parent-family'
  100.             ],
  101.             'other_revenue_sources' => [
  102.                 $this->getTranslation('field.other_revenue_sources.employed')      => 'employed',
  103.                 $this->getTranslation('field.other_revenue_sources.self-employed') => 'self-employed',
  104.                 $this->getTranslation('field.other_revenue_sources.interim')       => 'interim',
  105.                 $this->getTranslation('field.other_revenue_sources.intermittent')  => 'intermittent',
  106.                 $this->getTranslation('field.other_revenue_sources.casual-work')   => 'casual-work'
  107.             ],
  108.             'availability' => [
  109.                 $this->getTranslation('field.availability.part-time')  => 'part-time',
  110.                 $this->getTranslation('field.availability.full-time')  => 'full-time',
  111.                 $this->getTranslation('field.availability.evening-we') => 'evening-we',
  112.                 $this->getTranslation('field.availability.promptly')   => 'promptly',
  113.                 $this->getTranslation('field.availability.seasonal')   => 'seasonal'
  114.             ],
  115.             'main_activity' => [
  116.                 $this->getTranslation('field.main_activity.works')        => 'works',
  117.                 $this->getTranslation('field.main_activity.helping-hand') => 'helping-hand',
  118.                 $this->getTranslation('field.main_activity.cleaning')     => 'cleaning',
  119.                 $this->getTranslation('field.main_activity.handyman')     => 'handyman',
  120.                 $this->getTranslation('field.main_activity.geek')         => 'geek',
  121.                 $this->getTranslation('field.main_activity.henchman')     => 'henchman'
  122.             ],
  123.             'allowances' => [
  124.                 $this->getTranslation('field.allowances.are')                  => 'are',
  125.                 $this->getTranslation('field.allowances.ass')                  => 'ass',
  126.                 $this->getTranslation('field.allowances.apl')                  => 'apl',
  127.                 $this->getTranslation('field.allowances.rsa')                  => 'rsa',
  128.                 $this->getTranslation('field.allowances.aah')                  => 'aah',
  129.                 $this->getTranslation('field.allowances.activity_bonus')       => 'activity_bonus',
  130.                 $this->getTranslation('field.allowances.housing_assist_paris') => 'housing_assist_paris',
  131.                 $this->getTranslation('field.allowances.aeh')                  => 'aeh',
  132.                 $this->getTranslation('field.allowances.other')                => 'other'
  133.             ],
  134.             'main_motivation' => [
  135.                 'finding-new-clients',
  136.                 'using-skills',
  137.                 'getting-to-know-neighbors',
  138.                 'support-project',
  139.                 'supplement-income',
  140.                 'new-adventure',
  141.                 'other'
  142.             ],
  143.             'family_circle' => [
  144.                 $this->getTranslation('field.family_circle.not-isolated') => 'not-isolated',
  145.                 $this->getTranslation('field.family_circle.isolated')     => 'isolated'
  146.             ],
  147.             'refugee_status' => [
  148.                 'oui'      => 'yes',
  149.                 'non'      => 'no',
  150.                 'en cours' => 'ongoing'
  151.             ],
  152.             'eligible' => [
  153.                 $this->getTranslation('field.sourcing.sourcing_pole_employ') => 'sourcing_pole_employ',
  154.                 $this->getTranslation('field.sourcing.sourcing_paris')       => 'sourcing_paris'
  155.             ],
  156.             'followup_type' => [
  157.                 'admin'      => FollowUpAppointment::TYPE_ADMIN,
  158.                 'activation' => FollowUpAppointment::TYPE_ACTIVATION,
  159.                 'sortie'     => FollowUpAppointment::TYPE_OUT,
  160.                 'litige'     => FollowUpAppointment::TYPE_DISPUTE,
  161.                 'commission' => FollowUpAppointment::TYPE_COMMISSION,
  162.                 'formation'  => FollowUpAppointment::TYPE_FORMATION,
  163.                 'default'    => FollowUpAppointment::TYPE_FOLLOW_UP
  164.             ],
  165.             'skills' => [
  166.                 'ménage'       => $this->getTranslation('field.accompaniment_type.menage'),
  167.                 'brico'        => $this->getTranslation('field.accompaniment_type.bricolage'),
  168.                 'gros bras'    => $this->getTranslation('field.accompaniment_type.gros_bras'),
  169.                 'langue'       => $this->getTranslation('field.accompaniment_type.langue_francaise'),
  170.                 'français'     => $this->getTranslation('field.accompaniment_type.langue_francaise'),
  171.                 'informatique' => $this->getTranslation('field.accompaniment_type.informatique'),
  172.                 'geek'         => $this->getTranslation('field.accompaniment_type.informatique'),
  173.                 'commerc'      => $this->getTranslation('field.accompaniment_type.relation_commerciale'),
  174.                 'admin'        => $this->getTranslation('field.accompaniment_type.gestion_administrative_auto_entreprise'),
  175.                 'gestion'      => $this->getTranslation('field.accompaniment_type.gestion_administrative_auto_entreprise'),
  176.                 'entreprise'   => $this->getTranslation('field.accompaniment_type.gestion_administrative_auto_entreprise'),
  177.                 'santé'        => $this->getTranslation('field.accompaniment_type.sante_handicap'),
  178.                 'handi'        => $this->getTranslation('field.accompaniment_type.sante_handicap'),
  179.                 'logement'     => $this->getTranslation('field.accompaniment_type.logement'),
  180.                 'endettement'  => $this->getTranslation('field.accompaniment_type.endettement'),
  181.                 'travaux'      => $this->getTranslation('field.accompaniment_type.petits_travaux'),
  182.             ],
  183.             'study_level' => [
  184.                 $this->getTranslation('field.study_level.less-college') => 'less-college',
  185.                 $this->getTranslation('field.study_level.college')      => 'college',
  186.                 $this->getTranslation('field.study_level.cap')          => 'cap',
  187.                 $this->getTranslation('field.study_level.bac')          => 'bac',
  188.                 $this->getTranslation('field.study_level.bac+2')        => 'bac+2',
  189.                 $this->getTranslation('field.study_level.bac+3')        => 'bac+3',
  190.                 $this->getTranslation('field.study_level.bac+5')        => 'bac+5'
  191.             ]
  192.         ];
  193.     }
  194.  
  195.     /**
  196.      * set sourcing for lulu
  197.      *
  198.      * @param Lulu   $lulu
  199.      * @param string $sourcing
  200.      *
  201.      * @return void
  202.      */
  203.     protected function setSourcing(Lulu $lulu, string $sourcing)
  204.     {
  205.         if ('' !== $sourcing) {
  206.             $sourcing = explode(', ', $sourcing);
  207.             foreach ($sourcing as $source) {
  208.                 if (isset($this->association['eligible'][$source])) {
  209.                     $method = 'set' . ucfirst($this->normalizer->denormalize($this->association['eligible'][$source]));
  210.                     if (method_exists($lulu, $method)) {
  211.                         $lulu->$method(1);
  212.                     }
  213.                 }
  214.             }
  215.         }
  216.     }
  217.  
  218.     /**
  219.      * get translation
  220.      *
  221.      * @param string $translation translation key
  222.      * @param string $prefix      translation prefix
  223.      * @param string $domain      domain
  224.      *
  225.      * @return string
  226.      */
  227.     protected function getTranslation(string $translation, $prefix = 'luluv2', $domain = 'luluV2')
  228.     {
  229.         return $this->translator->trans($prefix .'.'. $translation, [], $domain);
  230.     }
  231.  
  232.     /**
  233.      * handle logs with retry
  234.      *
  235.      * @param array             $params
  236.      * @param CronItemLog|false $retry
  237.      *
  238.      * @throws Exception
  239.      *
  240.      * @return void
  241.      */
  242.     protected function handleLog(array $params, $retry = false)
  243.     {
  244.         if (false !== $retry) {
  245.             $params['message'] = ('' === $params['message']) ? 'update successfull' : $params['message'];
  246.             $this->cronItemLogRepo->updateItem($retry, $params['status'], $retry->getMessage() ."\r\r". $params['message']);
  247.         }
  248.         else {
  249.             $this->cronItemLogRepo->newItem($params['identifierName'], $params['identifierValue'], $params['cronLog'], $params['status'], $this->luluRepo->getClassName(), $params['message']);
  250.         }
  251.     }
  252.  
  253.     /**
  254.      * associate referent to lulu, and create followup
  255.      *
  256.      * @param Lulu   $lulu
  257.      * @param string $referentEmail
  258.      * @param string $comment
  259.      * @param string $date
  260.      * @param string $time
  261.      * @param string $duration
  262.      * @param string $type
  263.      * @param string $category
  264.      *
  265.      * @return bool
  266.      *
  267.      * @throws Exception
  268.      */
  269.     protected function setAppointment(Lulu $lulu, string $referentEmail, string $comment, string $date, string $time, string $duration, string $type, string $category)
  270.     {
  271.         $employee = $this->setReferent($referentEmail, $lulu);
  272.  
  273.         try {
  274.             $date     = $this->getSanitizedDate($date, $time);
  275.             $duration = $this->getSanitizedDuration($duration);
  276.         }
  277.         catch (RuntimeException $e) {
  278.             throw new Exception($e->getMessage().$lulu->getId());
  279.         }
  280.  
  281.         $followupAppointment = new FollowUpAppointment($lulu);
  282.         $followupAppointment->setComment($comment);
  283.         $followupAppointment->setType($type);
  284.         $followupAppointment->setCategory($category);
  285.         $followupAppointment->setDuration($duration);
  286.         $followupAppointment->setDate($date);
  287.         $followupAppointment->setFormer($employee->getUser());
  288.         $followupAppointment->setStatus(FollowUpAppointment::STATUS_PRESENT);
  289.         $followupAppointment->setCreated(new DateTime());
  290.         $followupAppointment->setUpdated(new DateTime());
  291.  
  292.         $this->em->persist($followupAppointment);
  293.         return true;
  294.     }
  295.  
  296.     /**
  297.      * @param string $duration
  298.      *
  299.      * @return int
  300.      *
  301.      * @throws RuntimeException
  302.      */
  303.     protected function getSanitizedDuration(string $duration)
  304.     {
  305.         if ($duration !== '') {
  306.             list($hours, $minutes, $seconds) = explode(':', $duration);
  307.             return (int)$hours * 60 + (int)$minutes;
  308.         }
  309.  
  310.         throw new RuntimeException('duration "'. $duration .'" is not valid for lulu ');
  311.     }
  312.  
  313.     /**
  314.      * @param string $date
  315.      * @param string $time
  316.      *
  317.      * @return DateTime
  318.      *
  319.      * @throws Exception
  320.      * @throws RuntimeException
  321.      */
  322.     protected function getSanitizedDate(string $date, string $time = '')
  323.     {
  324.         if ($date !== '') {
  325.             $time = ($time == '') ? '00:00:00' : $time;
  326.             list($day, $month, $year) = explode('/', $date);
  327.             $day = (strlen($day) == 2) ? $day : '0' . $day;
  328.             $month = (strlen($month) == 2) ? $month : '0' . $month;
  329.  
  330.             if (checkdate($month, $day, $year)) {
  331.                 return new DateTime(implode('-', [$year, $month, $day]) . ' ' . $time);
  332.             }
  333.  
  334.             throw new RuntimeException('date "' .$date. '" is not valid for lulu ');
  335.         }
  336.  
  337.         throw new RuntimeException('date "' .$date. '" is not valid for lulu ');
  338.     }
  339.  
  340.     /**
  341.      * @param string $referentEmail
  342.      * @param Lulu   $lulu
  343.      *
  344.      * @return Employee
  345.      *
  346.      * @throws NonUniqueResultException
  347.      * @throws Exception
  348.      */
  349.     protected function setReferent(string $referentEmail, Lulu $lulu)
  350.     {
  351.         try {
  352.             $employee = $this->getReferent($referentEmail);
  353.         }
  354.         catch(RuntimeException $e) {
  355.             throw new Exception($e->getMessage().$lulu->getId());
  356.         }
  357.  
  358.         if (!$lulu->getReferent()) {
  359.             $lulu->setReferent($this->getReferent($referentEmail));
  360.         }
  361.  
  362.         return $employee;
  363.     }
  364.  
  365.     /**
  366.      * @param string $referentEmail
  367.      *
  368.      * @return Employee
  369.      *
  370.      * @throws NonUniqueResultException
  371.      * @throws RuntimeException
  372.      */
  373.     protected function getReferent(string $referentEmail)
  374.     {
  375.         if ($referentEmail != '') {
  376.             if (!$employee = $this->employeeRepo->getOneByCriteria(['userEmail' => $referentEmail])) {
  377.                 throw new RuntimeException('referent "' .$referentEmail. '" not found for lulu ');
  378.             }
  379.         }
  380.         else {
  381.             throw new RuntimeException('referent is not set for lulu ');
  382.         }
  383.  
  384.         return $employee;
  385.     }
  386.  
  387.     /**
  388.      * associate accompanimentType to lulu
  389.      *
  390.      * @param Lulu   $lulu
  391.      * @param string $type
  392.      *
  393.      * @return void
  394.      *
  395.      * @throws Exception
  396.      */
  397.     protected function addAccompanimentType(Lulu $lulu, string $type)
  398.     {
  399.         if ($accompanimentType = $this->accompanimentTypeRepo->getOneByCriteria(['label' => $type])) {
  400.             $lulu->addAccompanimentType($accompanimentType);
  401.         }
  402.     }
  403.  
  404.     /**
  405.      * try to retrieve user from csv info
  406.      *
  407.      * @param int|null    $luluId
  408.      * @param string|null $email
  409.      * @param string|null $firstName
  410.      * @param string|null $lastName
  411.      *
  412.      * @return Lulu|null
  413.      *
  414.      * @throws Exception
  415.      */
  416.     protected function getLulu($luluId = null, $email = null, $firstName = null, $lastName = null)
  417.     {
  418.         if (null !== $luluId && $luluId > 0) {
  419.             /** @var Lulu $lulu **/
  420.             if ($lulu = $this->luluRepo->find($luluId)) {
  421.                 return $lulu;
  422.             }
  423.         }
  424.  
  425.         if (null !== $email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
  426.             if ($lulu = $this->luluRepo->getOneByCriteria(['userByEmail' => $email])) {
  427.                 return $lulu;
  428.             }
  429.         }
  430.  
  431.         if (null !== $firstName && null !== $lastName) {
  432.             $slug = Tools::slug($firstName . ' ' . $lastName);
  433.             if ($lulu = $this->luluRepo->getOneByCriteria(['userByName' => $slug])) {
  434.                 return $lulu;
  435.             }
  436.         }
  437.  
  438.         return null;
  439.     }
  440.  
  441.     /**
  442.      * @param array $data
  443.      * @param Lulu  $lulu
  444.      *
  445.      * @return void
  446.      */
  447.     abstract protected function setData(array $data, Lulu $lulu);
  448.  
  449.     /**
  450.      * @param array $data
  451.      * @param Lulu  $lulu
  452.      * @param Form  $form
  453.      *
  454.      * @return void|boolean
  455.      *
  456.      * @throws NonUniqueResultException
  457.      * @throws Exception
  458.      */
  459.     protected function fillLuluFormAnswers(array $data, Lulu $lulu, Form $form)
  460.     {
  461.         $className     = get_class($this);
  462.  
  463.         if (!$luluForm = $this->luluFormRepo->findOneObjectBy(['form' => $form, 'lulu' => $lulu])) {
  464.             $referentEmail = self::getField('Email du (de la) chargé(e) d\'accompagnement', $className, $data);
  465.  
  466.             try {
  467.                 $appointmentDate     = $this->getSanitizedDate(self::getField('Date de l\'entretien', $className, $data));
  468.                 $appointmentDuration = $this->getSanitizedDuration(self::getField('Durée de l\'entretien', $className, $data));
  469.             }
  470.             catch (RuntimeException $e) {
  471.                 throw new Exception($e->getMessage() . $lulu->getId());
  472.             }
  473.  
  474.             $luluForm     = $this->luluFormRepo->createLuluForm($form, $lulu, $this->getReferent($referentEmail), $appointmentDate, $appointmentDuration);
  475.             $formQuestion = $this->questionRepo->getOrderedQuestionFromFormUniqueId($form->getUniqueId(), ['answers']);
  476.  
  477.             foreach ($formQuestion as $question) {
  478.                 $formAnswers = $question->getAnswers();
  479.  
  480.                 $answers = $this->getLuluAnswer($question, $data, $formAnswers, $lulu);
  481.                 $comment = $this->getLuluCommentAnswer($question, $data);
  482.  
  483.                 if (!empty($answers)) {
  484.                     foreach ($answers as $answer) {
  485.                         $value        = $answer['answerValue'];
  486.                         $commentValue = $comment;
  487.                         $this->luluFormAnswerRepo->createLuluFormAnswer($luluForm, $question, $answer['answer'], $value, $commentValue);
  488.                     }
  489.                 }
  490.             }
  491.         }
  492.     }
  493.  
  494.     /**
  495.      * @param FormQuestion                 $question
  496.      * @param array                        $data
  497.      * @param ArrayCollection|FormAnswer[] $formAnswers
  498.      * @param Lulu                         $lulu
  499.      *
  500.      * @return array
  501.      *
  502.      * @throws Exception
  503.      */
  504.     protected function getLuluAnswer(FormQuestion $question, array $data, $formAnswers, Lulu $lulu)
  505.     {
  506.         $className  = get_class($this);
  507.         $luluAnswer = self::getField($question->getLabel(), $className, $data);
  508.  
  509.         if ($question->isRequired() && '' === $luluAnswer) {
  510.             throw new Exception('Question "' .$question->getLabel(). '" is required');
  511.         }
  512.  
  513.         $response = [];
  514.  
  515.         if (FormQuestion::TYPE_TEXT === $question->getType()) {
  516.             $answer = $formAnswers->first();
  517.             $response[] = [
  518.                 'answer'      => $answer,
  519.                 'answerValue' => $luluAnswer
  520.             ];
  521.         }
  522.         else {
  523.             switch ($question->getType()) {
  524.                 case FormQuestion::TYPE_RADIO:
  525.                     $hasOpenValue = false;
  526.                     $answerId     = null;
  527.                     foreach ($formAnswers as $answer) {
  528.                         $value = ($question->isWeighted()) ? $answer->getWeight() .' - '. $answer->getValue() : $answer->getValue();
  529.  
  530.                         if (FormAnswer::TYPE_OPEN === $answer->getType()) {
  531.                             $hasOpenValue = $answer;
  532.                         }
  533.  
  534.                         if ($value == $luluAnswer) {
  535.                             $answerId = $answer->getId();
  536.                             $response[] = [
  537.                                 'answer'      => $answer,
  538.                                 'answerValue' => null
  539.                             ];
  540.                         }
  541.                     }
  542.  
  543.                     if (null === $answerId && $hasOpenValue) {
  544.                         $response[] = [
  545.                             'answer'      => $hasOpenValue,
  546.                             'answerValue' => $luluAnswer
  547.                         ];
  548.                     }
  549.                     else if ($question->isRequired() && empty($response)) {
  550.                         throw new Exception('Question "' .$question->getLabel(). '"  has no appropriate answer "' .$luluAnswer. '" for lulu (' .$lulu->getId(). ')');
  551.                     }
  552.                 break;
  553.  
  554.                 case FormQuestion::TYPE_CHECKBOX:
  555.                     $luluAnswer   = explode(', ', $luluAnswer);
  556.                     $hasOpenValue = false;
  557.                     foreach ($formAnswers as $answer) {
  558.                         $value = ($question->isWeighted()) ? $answer->getWeight() . ' - ' . $answer->getValue() : $answer->getValue();
  559.  
  560.                         if (FormAnswer::TYPE_OPEN === $answer->getType()) {
  561.                             $hasOpenValue = $answer;
  562.                         }
  563.  
  564.                         foreach ($luluAnswer as $key => $luluPartialAnswer) {
  565.                             if ($value == $luluPartialAnswer) {
  566.                                 $response[] = [
  567.                                     'answer'      => $answer,
  568.                                     'answerValue' => null
  569.                                 ];
  570.  
  571.                                 unset($luluAnswer[$key]);
  572.                             }
  573.                         }
  574.  
  575.                         if (!empty($luluAnswer) && $hasOpenValue) {
  576.                             $response[] = [
  577.                                 'answer'      => $hasOpenValue,
  578.                                 'answerValue' => implode(', ', $luluAnswer)
  579.                             ];
  580.                         }
  581.                         elseif ($question->isRequired() && empty($response)) {
  582.                             throw new Exception('Question "' .$question->getLabel(). '"  has no appropriate answer "' .implode(', ', $luluAnswer). '" for lulu (' .$lulu->getId(). ')');
  583.                         }
  584.                     }
  585.                 break;
  586.             }
  587.         }
  588.  
  589.         return $response;
  590.     }
  591.  
  592.     /**
  593.      * @param FormQuestion $question
  594.      * @param array        $data
  595.      *
  596.      * @return string|null
  597.      */
  598.     protected function getLuluCommentAnswer(FormQuestion $question, array $data)
  599.     {
  600.         if (null === $question->getCommentLabel()) {
  601.             return null;
  602.         }
  603.  
  604.         $className  = get_class($this);
  605.         $luluAnswer = self::getField($question->getCommentLabel(), $className, $data);
  606.         $luluAnswer = ('' !== $luluAnswer) ? $luluAnswer : null;
  607.  
  608.         return $luluAnswer;
  609.     }
  610.  
  611.     /**
  612.      * handle pro appointment
  613.      *
  614.      * @param CronLog           $cronLog
  615.      * @param array             $data data
  616.      * @param CronItemLog|false $retry is retry mode
  617.      * @param Form|null         $form  form
  618.      *
  619.      * @return bool success
  620.      *
  621.      * @throws Exception
  622.      */
  623.     public function handleRow(CronLog $cronLog, $data, $retry = false, $form = null)
  624.     {
  625.         $className = get_class($this);
  626.  
  627.         $luluId    = self::getField('ID (V1)', $className, $data);
  628.         $email     = self::getField('Email',   $className, $data);
  629.         $firstName = self::getField('Prénom',  $className, $data);
  630.         $lastName  = self::getField('Nom',     $className, $data);
  631.  
  632.         if ($lulu = $this->getLulu($luluId, $email, $firstName, $lastName)) {
  633.             $this->em->getConnection()->beginTransaction();
  634.  
  635.             try {
  636.                 $this->setData($data, $lulu);
  637.  
  638.                 if (null !== $form) {
  639.                     $this->fillLuluFormAnswers($data, $lulu, $form);
  640.                     $this->formPdf->generateFormPdf($lulu, $form);
  641.                 }
  642.             }
  643.             catch (Exception $e) {
  644.                 $this->em->getConnection()->rollBack();
  645.                 $this->handleLog(['status' => CronItemLog::STATUS_ERROR, 'message' => $e->getMessage(), 'identifierName' => 'id', 'identifierValue' => $lulu->getId(), 'cronLog' => $cronLog], $retry);
  646.  
  647.                 return false;
  648.             }
  649.  
  650.             $this->em->flush();
  651.             $this->em->getConnection()->commit();
  652.             $this->handleLog(['status' => CronItemLog::STATUS_SUCCESS, 'message' => '', 'identifierName' => 'id', 'identifierValue' => $lulu->getId(), 'cronLog' => $cronLog], $retry);
  653.             return true;
  654.         }
  655.         else {
  656.             $this->handleLog(['status' => CronItemLog::STATUS_ERROR, 'message' => 'user not found', 'identifierName' => 'email|firstname|lastname', 'identifierValue' => $email . '|' . $firstName . '|' . $lastName, 'cronLog' => $cronLog], $retry);
  657.             return false;
  658.         }
  659.     }
  660.  
  661.     /**
  662.      * get field value from item description and data
  663.      *
  664.      * @param string $label
  665.      * @param string $className data
  666.      * @param array  $data is retry mode
  667.      *
  668.      * @return string
  669.      */
  670.     public static function getField(string $label, string $className, array $data)
  671.     {
  672.         /** @var AbstractItem $className */
  673.         if (isset($data[array_search($label, array_column($className::$itemColumns, 'csv'))])) {
  674.             return trim($data[array_search($label, array_column($className::$itemColumns, 'csv'))]);
  675.         }
  676.  
  677.         return '';
  678.     }
  679.  
  680.     /**
  681.      * find row
  682.      *
  683.      * @param array       $values csv values
  684.      * @param CronItemLog $itemLog item log
  685.      * @param string      $cronType
  686.      *
  687.      * @return array
  688.      */
  689.     public static function findRow(array $values, CronItemLog $itemLog, string $cronType)
  690.     {
  691.         $identifierName  = $itemLog->getIdentifierName();
  692.         $identifierValue = $itemLog->getIdentifierValue();
  693.  
  694.         $normalizer      = new Normalizer();
  695.         /** @var AbstractItem $className **/
  696.         $className       = __NAMESPACE__ .'\\'. ucfirst($normalizer->denormalize($cronType)).'Item';
  697.  
  698.         $identifiers = explode('|', $identifierName);
  699.         if (in_array('id', $identifiers)) {
  700.             return $values[array_search($identifierValue, array_column($values, array_search('ID (V1)', array_column($className::$itemColumns, 'csv'))))];
  701.         }
  702.         else {
  703.             list($email, $firstName, $lastName) = explode('|', $identifierValue);
  704.  
  705.             if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  706.                 return $values[array_search($email, array_column($values, array_search('Email', array_column($className::$itemColumns, 'csv'))))];
  707.             }
  708.             // dont know if its good or not maybe just check email
  709.             else {
  710.                 $returnValue = $values[array_search($lastName, array_column($values, array_search('Nom', array_column($className::$itemColumns, 'csv'))))];
  711.  
  712.                 if ($className::getField('Prénom', $className, $returnValue) == $firstName) {
  713.                     return $returnValue;
  714.                 }
  715.  
  716.                 return [];
  717.             }
  718.         }
  719.     }
  720. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement