Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace LDMR\MigrationBundle\Cron;
- use Doctrine\Common\Collections\ArrayCollection;
- use Doctrine\ORM\EntityManager;
- use LDMR\EmployeeBundle\Entity\Employee;
- use LDMR\FormBundle\Entity\FormAnswer;
- use LDMR\FormBundle\Entity\FormQuestion;
- use LDMR\FormBundle\Repository\FormQuestionRepository;
- use LDMR\FormBundle\Repository\LuluFormAnswerRepository;
- use LDMR\FormBundle\Repository\LuluFormRepository;
- use LDMR\FormBundle\Service\FormPdf;
- use \RuntimeException;
- use LDMR\CommonBundle\Utils\Tools;
- use LDMR\EmployeeBundle\Repository\EmployeeRepository;
- use LDMR\FormBundle\Entity\Form;
- use LDMR\LuluBundle\Entity\Lulu;
- use LDMR\LuluBundle\Repository\AccompanimentTypeRepository;
- use LDMR\LuluBundle\Repository\LuluRepository;
- use LDMR\MigrationBundle\Entity\CronLog;
- use LDMR\MigrationBundle\Repository\CronItemLogRepository;
- use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter as Normalizer;
- use Symfony\Component\Translation\DataCollectorTranslator as Translator;
- use LDMR\LuluBundle\Entity\FollowUpAppointment;
- use LDMR\MigrationBundle\Entity\CronItemLog;
- use Doctrine\ORM\NonUniqueResultException;
- use \Exception;
- use \DateTime;
- /**
- * Class AbstractItem
- *
- * @package LDMR\MigrationBundle\Cron
- */
- abstract class AbstractItem
- {
- /** @var EntityManager **/
- public $em;
- /** @var array **/
- public static $itemColumns = [];
- /** @var array **/
- public $association;
- /** @var Translator **/
- public $translator;
- /** @var Normalizer **/
- public $normalizer;
- /** @var CronItemLogRepository */
- public $cronItemLogRepo;
- /** @var LuluRepository */
- public $luluRepo;
- /** @var EmployeeRepository */
- public $employeeRepo;
- /** @var AccompanimentTypeRepository */
- public $accompanimentTypeRepo;
- /** @var FormQuestionRepository **/
- protected $questionRepo;
- /** @var LuluFormRepository **/
- protected $luluFormRepo;
- /** @var LuluFormAnswerRepository **/
- protected $luluFormAnswerRepo;
- /** @var FormPdf **/
- protected $formPdf;
- public function __construct(EntityManager $em, Translator $translator, FormPdf $formPdf)
- {
- $this->em = $em;
- $this->translator = $translator;
- $this->normalizer = new Normalizer();
- $this->formPdf = $formPdf;
- $this->accompanimentTypeRepo = $this->em->getRepository('LDMRLuluBundle:AccompanimentType');
- $this->employeeRepo = $this->em->getRepository('LDMREmployeeBundle:Employee');
- $this->luluRepo = $this->em->getRepository('LDMRLuluBundle:Lulu');
- $this->cronItemLogRepo = $this->em->getRepository('LDMRMigrationBundle:CronItemLog');
- $this->questionRepo = $this->em->getRepository('LDMRFormBundle:FormQuestion');
- $this->luluFormRepo = $this->em->getRepository('LDMRFormBundle:LuluForm');
- $this->luluFormAnswerRepo = $this->em->getRepository('LDMRFormBundle:LuluFormAnswer');
- $this->association = [
- 'marital_status' => [
- $this->getTranslation('field.marital_status.single') => 'single',
- $this->getTranslation('field.marital_status.married') => 'married',
- $this->getTranslation('field.marital_status.concubinage') => 'concubinage',
- $this->getTranslation('field.marital_status.widower') => 'widower',
- $this->getTranslation('field.marital_status.divorced') => 'divorced',
- $this->getTranslation('field.marital_status.single-parent-family') => 'single-parent-family'
- ],
- 'other_revenue_sources' => [
- $this->getTranslation('field.other_revenue_sources.employed') => 'employed',
- $this->getTranslation('field.other_revenue_sources.self-employed') => 'self-employed',
- $this->getTranslation('field.other_revenue_sources.interim') => 'interim',
- $this->getTranslation('field.other_revenue_sources.intermittent') => 'intermittent',
- $this->getTranslation('field.other_revenue_sources.casual-work') => 'casual-work'
- ],
- 'availability' => [
- $this->getTranslation('field.availability.part-time') => 'part-time',
- $this->getTranslation('field.availability.full-time') => 'full-time',
- $this->getTranslation('field.availability.evening-we') => 'evening-we',
- $this->getTranslation('field.availability.promptly') => 'promptly',
- $this->getTranslation('field.availability.seasonal') => 'seasonal'
- ],
- 'main_activity' => [
- $this->getTranslation('field.main_activity.works') => 'works',
- $this->getTranslation('field.main_activity.helping-hand') => 'helping-hand',
- $this->getTranslation('field.main_activity.cleaning') => 'cleaning',
- $this->getTranslation('field.main_activity.handyman') => 'handyman',
- $this->getTranslation('field.main_activity.geek') => 'geek',
- $this->getTranslation('field.main_activity.henchman') => 'henchman'
- ],
- 'allowances' => [
- $this->getTranslation('field.allowances.are') => 'are',
- $this->getTranslation('field.allowances.ass') => 'ass',
- $this->getTranslation('field.allowances.apl') => 'apl',
- $this->getTranslation('field.allowances.rsa') => 'rsa',
- $this->getTranslation('field.allowances.aah') => 'aah',
- $this->getTranslation('field.allowances.activity_bonus') => 'activity_bonus',
- $this->getTranslation('field.allowances.housing_assist_paris') => 'housing_assist_paris',
- $this->getTranslation('field.allowances.aeh') => 'aeh',
- $this->getTranslation('field.allowances.other') => 'other'
- ],
- 'main_motivation' => [
- 'finding-new-clients',
- 'using-skills',
- 'getting-to-know-neighbors',
- 'support-project',
- 'supplement-income',
- 'new-adventure',
- 'other'
- ],
- 'family_circle' => [
- $this->getTranslation('field.family_circle.not-isolated') => 'not-isolated',
- $this->getTranslation('field.family_circle.isolated') => 'isolated'
- ],
- 'refugee_status' => [
- 'oui' => 'yes',
- 'non' => 'no',
- 'en cours' => 'ongoing'
- ],
- 'eligible' => [
- $this->getTranslation('field.sourcing.sourcing_pole_employ') => 'sourcing_pole_employ',
- $this->getTranslation('field.sourcing.sourcing_paris') => 'sourcing_paris'
- ],
- 'followup_type' => [
- 'admin' => FollowUpAppointment::TYPE_ADMIN,
- 'activation' => FollowUpAppointment::TYPE_ACTIVATION,
- 'sortie' => FollowUpAppointment::TYPE_OUT,
- 'litige' => FollowUpAppointment::TYPE_DISPUTE,
- 'commission' => FollowUpAppointment::TYPE_COMMISSION,
- 'formation' => FollowUpAppointment::TYPE_FORMATION,
- 'default' => FollowUpAppointment::TYPE_FOLLOW_UP
- ],
- 'skills' => [
- 'ménage' => $this->getTranslation('field.accompaniment_type.menage'),
- 'brico' => $this->getTranslation('field.accompaniment_type.bricolage'),
- 'gros bras' => $this->getTranslation('field.accompaniment_type.gros_bras'),
- 'langue' => $this->getTranslation('field.accompaniment_type.langue_francaise'),
- 'français' => $this->getTranslation('field.accompaniment_type.langue_francaise'),
- 'informatique' => $this->getTranslation('field.accompaniment_type.informatique'),
- 'geek' => $this->getTranslation('field.accompaniment_type.informatique'),
- 'commerc' => $this->getTranslation('field.accompaniment_type.relation_commerciale'),
- 'admin' => $this->getTranslation('field.accompaniment_type.gestion_administrative_auto_entreprise'),
- 'gestion' => $this->getTranslation('field.accompaniment_type.gestion_administrative_auto_entreprise'),
- 'entreprise' => $this->getTranslation('field.accompaniment_type.gestion_administrative_auto_entreprise'),
- 'santé' => $this->getTranslation('field.accompaniment_type.sante_handicap'),
- 'handi' => $this->getTranslation('field.accompaniment_type.sante_handicap'),
- 'logement' => $this->getTranslation('field.accompaniment_type.logement'),
- 'endettement' => $this->getTranslation('field.accompaniment_type.endettement'),
- 'travaux' => $this->getTranslation('field.accompaniment_type.petits_travaux'),
- ],
- 'study_level' => [
- $this->getTranslation('field.study_level.less-college') => 'less-college',
- $this->getTranslation('field.study_level.college') => 'college',
- $this->getTranslation('field.study_level.cap') => 'cap',
- $this->getTranslation('field.study_level.bac') => 'bac',
- $this->getTranslation('field.study_level.bac+2') => 'bac+2',
- $this->getTranslation('field.study_level.bac+3') => 'bac+3',
- $this->getTranslation('field.study_level.bac+5') => 'bac+5'
- ]
- ];
- }
- /**
- * set sourcing for lulu
- *
- * @param Lulu $lulu
- * @param string $sourcing
- *
- * @return void
- */
- protected function setSourcing(Lulu $lulu, string $sourcing)
- {
- if ('' !== $sourcing) {
- $sourcing = explode(', ', $sourcing);
- foreach ($sourcing as $source) {
- if (isset($this->association['eligible'][$source])) {
- $method = 'set' . ucfirst($this->normalizer->denormalize($this->association['eligible'][$source]));
- if (method_exists($lulu, $method)) {
- $lulu->$method(1);
- }
- }
- }
- }
- }
- /**
- * get translation
- *
- * @param string $translation translation key
- * @param string $prefix translation prefix
- * @param string $domain domain
- *
- * @return string
- */
- protected function getTranslation(string $translation, $prefix = 'luluv2', $domain = 'luluV2')
- {
- return $this->translator->trans($prefix .'.'. $translation, [], $domain);
- }
- /**
- * handle logs with retry
- *
- * @param array $params
- * @param CronItemLog|false $retry
- *
- * @throws Exception
- *
- * @return void
- */
- protected function handleLog(array $params, $retry = false)
- {
- if (false !== $retry) {
- $params['message'] = ('' === $params['message']) ? 'update successfull' : $params['message'];
- $this->cronItemLogRepo->updateItem($retry, $params['status'], $retry->getMessage() ."\r\r". $params['message']);
- }
- else {
- $this->cronItemLogRepo->newItem($params['identifierName'], $params['identifierValue'], $params['cronLog'], $params['status'], $this->luluRepo->getClassName(), $params['message']);
- }
- }
- /**
- * associate referent to lulu, and create followup
- *
- * @param Lulu $lulu
- * @param string $referentEmail
- * @param string $comment
- * @param string $date
- * @param string $time
- * @param string $duration
- * @param string $type
- * @param string $category
- *
- * @return bool
- *
- * @throws Exception
- */
- protected function setAppointment(Lulu $lulu, string $referentEmail, string $comment, string $date, string $time, string $duration, string $type, string $category)
- {
- $employee = $this->setReferent($referentEmail, $lulu);
- try {
- $date = $this->getSanitizedDate($date, $time);
- $duration = $this->getSanitizedDuration($duration);
- }
- catch (RuntimeException $e) {
- throw new Exception($e->getMessage().$lulu->getId());
- }
- $followupAppointment = new FollowUpAppointment($lulu);
- $followupAppointment->setComment($comment);
- $followupAppointment->setType($type);
- $followupAppointment->setCategory($category);
- $followupAppointment->setDuration($duration);
- $followupAppointment->setDate($date);
- $followupAppointment->setFormer($employee->getUser());
- $followupAppointment->setStatus(FollowUpAppointment::STATUS_PRESENT);
- $followupAppointment->setCreated(new DateTime());
- $followupAppointment->setUpdated(new DateTime());
- $this->em->persist($followupAppointment);
- return true;
- }
- /**
- * @param string $duration
- *
- * @return int
- *
- * @throws RuntimeException
- */
- protected function getSanitizedDuration(string $duration)
- {
- if ($duration !== '') {
- list($hours, $minutes, $seconds) = explode(':', $duration);
- return (int)$hours * 60 + (int)$minutes;
- }
- throw new RuntimeException('duration "'. $duration .'" is not valid for lulu ');
- }
- /**
- * @param string $date
- * @param string $time
- *
- * @return DateTime
- *
- * @throws Exception
- * @throws RuntimeException
- */
- protected function getSanitizedDate(string $date, string $time = '')
- {
- if ($date !== '') {
- $time = ($time == '') ? '00:00:00' : $time;
- list($day, $month, $year) = explode('/', $date);
- $day = (strlen($day) == 2) ? $day : '0' . $day;
- $month = (strlen($month) == 2) ? $month : '0' . $month;
- if (checkdate($month, $day, $year)) {
- return new DateTime(implode('-', [$year, $month, $day]) . ' ' . $time);
- }
- throw new RuntimeException('date "' .$date. '" is not valid for lulu ');
- }
- throw new RuntimeException('date "' .$date. '" is not valid for lulu ');
- }
- /**
- * @param string $referentEmail
- * @param Lulu $lulu
- *
- * @return Employee
- *
- * @throws NonUniqueResultException
- * @throws Exception
- */
- protected function setReferent(string $referentEmail, Lulu $lulu)
- {
- try {
- $employee = $this->getReferent($referentEmail);
- }
- catch(RuntimeException $e) {
- throw new Exception($e->getMessage().$lulu->getId());
- }
- if (!$lulu->getReferent()) {
- $lulu->setReferent($this->getReferent($referentEmail));
- }
- return $employee;
- }
- /**
- * @param string $referentEmail
- *
- * @return Employee
- *
- * @throws NonUniqueResultException
- * @throws RuntimeException
- */
- protected function getReferent(string $referentEmail)
- {
- if ($referentEmail != '') {
- if (!$employee = $this->employeeRepo->getOneByCriteria(['userEmail' => $referentEmail])) {
- throw new RuntimeException('referent "' .$referentEmail. '" not found for lulu ');
- }
- }
- else {
- throw new RuntimeException('referent is not set for lulu ');
- }
- return $employee;
- }
- /**
- * associate accompanimentType to lulu
- *
- * @param Lulu $lulu
- * @param string $type
- *
- * @return void
- *
- * @throws Exception
- */
- protected function addAccompanimentType(Lulu $lulu, string $type)
- {
- if ($accompanimentType = $this->accompanimentTypeRepo->getOneByCriteria(['label' => $type])) {
- $lulu->addAccompanimentType($accompanimentType);
- }
- }
- /**
- * try to retrieve user from csv info
- *
- * @param int|null $luluId
- * @param string|null $email
- * @param string|null $firstName
- * @param string|null $lastName
- *
- * @return Lulu|null
- *
- * @throws Exception
- */
- protected function getLulu($luluId = null, $email = null, $firstName = null, $lastName = null)
- {
- if (null !== $luluId && $luluId > 0) {
- /** @var Lulu $lulu **/
- if ($lulu = $this->luluRepo->find($luluId)) {
- return $lulu;
- }
- }
- if (null !== $email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
- if ($lulu = $this->luluRepo->getOneByCriteria(['userByEmail' => $email])) {
- return $lulu;
- }
- }
- if (null !== $firstName && null !== $lastName) {
- $slug = Tools::slug($firstName . ' ' . $lastName);
- if ($lulu = $this->luluRepo->getOneByCriteria(['userByName' => $slug])) {
- return $lulu;
- }
- }
- return null;
- }
- /**
- * @param array $data
- * @param Lulu $lulu
- *
- * @return void
- */
- abstract protected function setData(array $data, Lulu $lulu);
- /**
- * @param array $data
- * @param Lulu $lulu
- * @param Form $form
- *
- * @return void|boolean
- *
- * @throws NonUniqueResultException
- * @throws Exception
- */
- protected function fillLuluFormAnswers(array $data, Lulu $lulu, Form $form)
- {
- $className = get_class($this);
- if (!$luluForm = $this->luluFormRepo->findOneObjectBy(['form' => $form, 'lulu' => $lulu])) {
- $referentEmail = self::getField('Email du (de la) chargé(e) d\'accompagnement', $className, $data);
- try {
- $appointmentDate = $this->getSanitizedDate(self::getField('Date de l\'entretien', $className, $data));
- $appointmentDuration = $this->getSanitizedDuration(self::getField('Durée de l\'entretien', $className, $data));
- }
- catch (RuntimeException $e) {
- throw new Exception($e->getMessage() . $lulu->getId());
- }
- $luluForm = $this->luluFormRepo->createLuluForm($form, $lulu, $this->getReferent($referentEmail), $appointmentDate, $appointmentDuration);
- $formQuestion = $this->questionRepo->getOrderedQuestionFromFormUniqueId($form->getUniqueId(), ['answers']);
- foreach ($formQuestion as $question) {
- $formAnswers = $question->getAnswers();
- $answers = $this->getLuluAnswer($question, $data, $formAnswers, $lulu);
- $comment = $this->getLuluCommentAnswer($question, $data);
- if (!empty($answers)) {
- foreach ($answers as $answer) {
- $value = $answer['answerValue'];
- $commentValue = $comment;
- $this->luluFormAnswerRepo->createLuluFormAnswer($luluForm, $question, $answer['answer'], $value, $commentValue);
- }
- }
- }
- }
- }
- /**
- * @param FormQuestion $question
- * @param array $data
- * @param ArrayCollection|FormAnswer[] $formAnswers
- * @param Lulu $lulu
- *
- * @return array
- *
- * @throws Exception
- */
- protected function getLuluAnswer(FormQuestion $question, array $data, $formAnswers, Lulu $lulu)
- {
- $className = get_class($this);
- $luluAnswer = self::getField($question->getLabel(), $className, $data);
- if ($question->isRequired() && '' === $luluAnswer) {
- throw new Exception('Question "' .$question->getLabel(). '" is required');
- }
- $response = [];
- if (FormQuestion::TYPE_TEXT === $question->getType()) {
- $answer = $formAnswers->first();
- $response[] = [
- 'answer' => $answer,
- 'answerValue' => $luluAnswer
- ];
- }
- else {
- switch ($question->getType()) {
- case FormQuestion::TYPE_RADIO:
- $hasOpenValue = false;
- $answerId = null;
- foreach ($formAnswers as $answer) {
- $value = ($question->isWeighted()) ? $answer->getWeight() .' - '. $answer->getValue() : $answer->getValue();
- if (FormAnswer::TYPE_OPEN === $answer->getType()) {
- $hasOpenValue = $answer;
- }
- if ($value == $luluAnswer) {
- $answerId = $answer->getId();
- $response[] = [
- 'answer' => $answer,
- 'answerValue' => null
- ];
- }
- }
- if (null === $answerId && $hasOpenValue) {
- $response[] = [
- 'answer' => $hasOpenValue,
- 'answerValue' => $luluAnswer
- ];
- }
- else if ($question->isRequired() && empty($response)) {
- throw new Exception('Question "' .$question->getLabel(). '" has no appropriate answer "' .$luluAnswer. '" for lulu (' .$lulu->getId(). ')');
- }
- break;
- case FormQuestion::TYPE_CHECKBOX:
- $luluAnswer = explode(', ', $luluAnswer);
- $hasOpenValue = false;
- foreach ($formAnswers as $answer) {
- $value = ($question->isWeighted()) ? $answer->getWeight() . ' - ' . $answer->getValue() : $answer->getValue();
- if (FormAnswer::TYPE_OPEN === $answer->getType()) {
- $hasOpenValue = $answer;
- }
- foreach ($luluAnswer as $key => $luluPartialAnswer) {
- if ($value == $luluPartialAnswer) {
- $response[] = [
- 'answer' => $answer,
- 'answerValue' => null
- ];
- unset($luluAnswer[$key]);
- }
- }
- if (!empty($luluAnswer) && $hasOpenValue) {
- $response[] = [
- 'answer' => $hasOpenValue,
- 'answerValue' => implode(', ', $luluAnswer)
- ];
- }
- elseif ($question->isRequired() && empty($response)) {
- throw new Exception('Question "' .$question->getLabel(). '" has no appropriate answer "' .implode(', ', $luluAnswer). '" for lulu (' .$lulu->getId(). ')');
- }
- }
- break;
- }
- }
- return $response;
- }
- /**
- * @param FormQuestion $question
- * @param array $data
- *
- * @return string|null
- */
- protected function getLuluCommentAnswer(FormQuestion $question, array $data)
- {
- if (null === $question->getCommentLabel()) {
- return null;
- }
- $className = get_class($this);
- $luluAnswer = self::getField($question->getCommentLabel(), $className, $data);
- $luluAnswer = ('' !== $luluAnswer) ? $luluAnswer : null;
- return $luluAnswer;
- }
- /**
- * handle pro appointment
- *
- * @param CronLog $cronLog
- * @param array $data data
- * @param CronItemLog|false $retry is retry mode
- * @param Form|null $form form
- *
- * @return bool success
- *
- * @throws Exception
- */
- public function handleRow(CronLog $cronLog, $data, $retry = false, $form = null)
- {
- $className = get_class($this);
- $luluId = self::getField('ID (V1)', $className, $data);
- $email = self::getField('Email', $className, $data);
- $firstName = self::getField('Prénom', $className, $data);
- $lastName = self::getField('Nom', $className, $data);
- if ($lulu = $this->getLulu($luluId, $email, $firstName, $lastName)) {
- $this->em->getConnection()->beginTransaction();
- try {
- $this->setData($data, $lulu);
- if (null !== $form) {
- $this->fillLuluFormAnswers($data, $lulu, $form);
- $this->formPdf->generateFormPdf($lulu, $form);
- }
- }
- catch (Exception $e) {
- $this->em->getConnection()->rollBack();
- $this->handleLog(['status' => CronItemLog::STATUS_ERROR, 'message' => $e->getMessage(), 'identifierName' => 'id', 'identifierValue' => $lulu->getId(), 'cronLog' => $cronLog], $retry);
- return false;
- }
- $this->em->flush();
- $this->em->getConnection()->commit();
- $this->handleLog(['status' => CronItemLog::STATUS_SUCCESS, 'message' => '', 'identifierName' => 'id', 'identifierValue' => $lulu->getId(), 'cronLog' => $cronLog], $retry);
- return true;
- }
- else {
- $this->handleLog(['status' => CronItemLog::STATUS_ERROR, 'message' => 'user not found', 'identifierName' => 'email|firstname|lastname', 'identifierValue' => $email . '|' . $firstName . '|' . $lastName, 'cronLog' => $cronLog], $retry);
- return false;
- }
- }
- /**
- * get field value from item description and data
- *
- * @param string $label
- * @param string $className data
- * @param array $data is retry mode
- *
- * @return string
- */
- public static function getField(string $label, string $className, array $data)
- {
- /** @var AbstractItem $className */
- if (isset($data[array_search($label, array_column($className::$itemColumns, 'csv'))])) {
- return trim($data[array_search($label, array_column($className::$itemColumns, 'csv'))]);
- }
- return '';
- }
- /**
- * find row
- *
- * @param array $values csv values
- * @param CronItemLog $itemLog item log
- * @param string $cronType
- *
- * @return array
- */
- public static function findRow(array $values, CronItemLog $itemLog, string $cronType)
- {
- $identifierName = $itemLog->getIdentifierName();
- $identifierValue = $itemLog->getIdentifierValue();
- $normalizer = new Normalizer();
- /** @var AbstractItem $className **/
- $className = __NAMESPACE__ .'\\'. ucfirst($normalizer->denormalize($cronType)).'Item';
- $identifiers = explode('|', $identifierName);
- if (in_array('id', $identifiers)) {
- return $values[array_search($identifierValue, array_column($values, array_search('ID (V1)', array_column($className::$itemColumns, 'csv'))))];
- }
- else {
- list($email, $firstName, $lastName) = explode('|', $identifierValue);
- if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
- return $values[array_search($email, array_column($values, array_search('Email', array_column($className::$itemColumns, 'csv'))))];
- }
- // dont know if its good or not maybe just check email
- else {
- $returnValue = $values[array_search($lastName, array_column($values, array_search('Nom', array_column($className::$itemColumns, 'csv'))))];
- if ($className::getField('Prénom', $className, $returnValue) == $firstName) {
- return $returnValue;
- }
- return [];
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement