/** * * @param \Opit\OpitHrm\LeaveBundle\Entity\LeaveRequest $resource * @param boolean $toGeneralManager * @param \Opit\OpitHrm\StatusBundle\Entity\Status $status */ public function addNewLeaveNotification(LeaveRequest $resource, $toGeneralManager, Status $status) { // get last status name from resource $resourceStatus = strtolower($status->getName()); $message = ''; $notification = new LRNotification(); $notification->setLeaveRequest($resource); $receiver = $resource->getGeneralManager(); $message .= 'leave request '; call_user_func(array($notification, 'set' . Utils::getClassBasename($resource)), $resource); if (strpos('approved', $resourceStatus) !== false || strpos('rejected', $resourceStatus) !== false) { $message .= ' has been ' . $resourceStatus . '.'; $message = ucfirst($message); } else { $message = 'Status of ' . $message; $message .= 'changed to ' . $resourceStatus . '.'; } if (false === $toGeneralManager) { $receiver = $this->entityManager->getRepository('OpitOpitHrmUserBundle:User')->findOneByEmployee($resource->getEmployee()); } $notification->setMessage($message); $notification->setReceiver($receiver); $notification->setDateTime(new \DateTime('now')); $notification = $this->setNotificationStatus($notification); $this->entityManager->persist($notification); $this->entityManager->flush(); }
/** * Method to add a notification * * @param TravelRequest/TravelExpense $resource * @param integer $toGeneralManager */ public function addNewTravelNotification($resource, $toGeneralManager, $status) { // get last status name from resource $resourceStatus = strtolower($status->getName()); $message = ''; if ($resource instanceof TravelRequest) { $notification = new TRNotification(); $notification->setTravelRequest($resource); $receiver = $resource->getGeneralManager(); $message .= 'travel request (' . $resource->getTravelRequestId() . ') '; } elseif ($resource instanceof TravelExpense) { $notification = new TENotification(); $notification->setTravelExpense($resource); $receiver = $resource->getTravelRequest()->getGeneralManager(); $message .= 'travel expense '; } call_user_func(array($notification, 'set' . Utils::getClassBasename($resource)), $resource); if (strpos('approved', $resourceStatus) !== false || strpos('rejected', $resourceStatus) !== false) { $message .= ' has been ' . $resourceStatus . '.'; $message = ucfirst($message); } else { $message = 'Status of ' . $message; $message .= 'changed to ' . $resourceStatus . '.'; } if (false === $toGeneralManager) { $receiver = $resource->getUser(); } $notification->setMessage($message); $notification->setReceiver($receiver); $notification->setDateTime(new \DateTime('now')); $notification = $this->setNotificationStatus($notification); $this->entityManager->persist($notification); $this->entityManager->flush(); }
/** * Get the travel resource's state by the resource id and status id. * * @param \Opit\OpitHrm\TravelBundle\Entity\TravelExpense|\Opit\OpitHrm\TravelBundle\Entity\TravelRequest $resource * @param integer $statusId * @return null|\Opit\OpitHrm\TravelBundle\Entity\TravelExpense|\Opit\OpitHrm\TravelBundle\Entity\TravelRequest */ public function getTravelStateByStatusId($resource, $statusId) { if (null === $resource) { return null; } $className = Utils::getClassBasename($resource); $status = $this->entityManager->getRepository('OpitOpitHrmTravelBundle:States' . $className . 's')->findStatusByStatusId($resource->getId(), $statusId); return $status; }
/** * Composes and send an email based on a status change * * @param Status $status * @param mixed $resource */ public function prepareEmail(Status $status, $resource) { $applicationName = $this->options['applicationName']; // get template name by converting entity name first letter to lower $className = Utils::getClassBasename($resource); // lowercase first character of string $template = lcfirst($className); $statusName = $status->getName(); $statusId = $status->getId(); // split class name at uppercase letters $subjectType = preg_split('/(?=[A-Z])/', $className); // decide if resource is request or expense, if is expense get its request $travelRequest = $resource instanceof TravelExpense ? $resource->getTravelRequest() : $resource; $generalManager = $travelRequest->getGeneralManager(); // call method located in travel expense service $estimatedCosts = $this->getTRCosts($travelRequest); // create string for email travel type e.g.(Travel expense, Travel request) $subjectTravelType = $subjectType[1] . ' ' . strtolower($subjectType[2]); $stateChangeLinks = array(); if (Status::FOR_APPROVAL === $statusId) { $travelToken = $this->setTravelToken($resource->getId()); // Exclude current status from next states to prepare the email $nextStates = $this->statusManager->getNextStates($status); unset($nextStates[$statusId]); foreach ($nextStates as $key => $value) { // Generate links that can be used to change the status of the travel request $stateChangeLinks[] = $this->router->generate('OpitOpitHrmTravelBundle_change_status', array('gmId' => $generalManager->getId(), 'travelType' => $resource::getType(), 'status' => $key, 'token' => $travelToken), true); } $recipient = $generalManager->getEmail(); $templateVariables = array('nextStates' => $nextStates, 'stateChangeLinks' => $stateChangeLinks); } else { $recipient = $travelRequest->getUser()->getEmail(); $templateVariables = array('currentState' => $statusName, 'url' => $this->router->generate('OpitOpitHrmUserBundle_security_login', array(), true)); switch ($statusId) { case Status::APPROVED: $templateVariables['isApproved'] = true; break; case Status::REVISE: $templateVariables['isRevised'] = true; break; case Status::REJECTED: $templateVariables['isRejected'] = true; break; case Status::CREATED: $templateVariables['isCreated'] = true; break; } } // set estimated in HUF and EUR for template $templateVariables['estimatedCostsEUR'] = ceil($estimatedCosts['EUR']); $templateVariables['estimatedCostsHUF'] = ceil($estimatedCosts['HUF']); $templateVariables[$template] = $resource; $this->mailer->setRecipient($recipient); $this->mailer->setSubject('[' . ($applicationName !== null && $applicationName != 'OPIT-HRM' ? $applicationName : 'OPIT-HRM') . '] - ' . $subjectTravelType . ' status changed - ' . $statusName . ' (' . $travelRequest->getTravelRequestId() . ')'); $this->mailer->setBodyByTemplate('OpitOpitHrmTravelBundle:Mail:' . $template . '.html.twig', $templateVariables); $this->mailer->sendMail(); }
/** * Validate the option fields. * * @param mixed $options the option fields which will be validated. * @throws MissingMandatoryParametersException * * @return mixed|boolean with the $options array or false if there was invalid arguments. */ private function validateOptions($options) { // If the startDate is not setted or it is empty then throw exception if (!isset($options['startDate']) || empty($options['startDate'])) { $this->logger->error(sprintf('[|%s] Start date is missing in the argument list.', Utils::getClassBasename($this))); throw new MissingMandatoryParametersException('The "startDate" parameter is missing in the argument list!'); } elseif ($options['startDate'] > date('Y-m-d')) { // If the start date is future then return with empty array $this->logger->alert(sprintf('[|%s] Start date is a future date in the argument list.', Utils::getClassBasename($this))); return false; } elseif (!Utils::validateDate($options['startDate'], 'Y-m-d')) { $this->logger->alert(sprintf('[|%s] The start option is in invalid date format.', Utils::getClassBasename($this))); return false; } // If the endDate is not setted or it is empty then set today if (!isset($options['endDate']) || empty($options['endDate'])) { $options['endDate'] = date('Y-m-d'); } elseif (!Utils::validateDate($options['endDate'], 'Y-m-d')) { $this->logger->alert(sprintf('[|%s] The end option is in invalid date format.', Utils::getClassBasename($this))); return false; } // If the currencyNames is not set in the options array or it is empty, it is gotten the currencies from the DB if (!isset($options['currencyNames']) || empty($options['currencyNames'])) { $options['currencyNames'] = implode(',', $this->em->getRepository('OpitOpitHrmCurrencyRateBundle:Currency')->getAllCurrencyCodes()); } elseif (!Utils::validateCurrencyCodesString($options['currencyNames'])) { $this->logger->alert(sprintf('[|%s] The currency option is in invalid format.', Utils::getClassBasename($this))); return false; } else { $options['currencyNames'] = strtoupper($options['currencyNames']); } return $options; }
/** * @internal */ public function removeChildNodes(TravelExpense $travelExpense, $children) { foreach ($children as $child) { $className = Utils::getClassBasename($child); $getter = null; switch ($className) { case 'TEUserPaidExpense': $getter = 'getUserPaidExpenses'; break; case 'TECompanyPaidExpense': $getter = 'getCompanyPaidExpenses'; break; case 'TEAdvancesReceived': $getter = 'getAdvancesReceived'; break; } if (null !== $getter && false === $travelExpense->{$getter}()->contains($child)) { $child->setTravelExpense(); $this->entityManager->remove($child); } } }
/** * * @param \Opit\OpitHrm\StatusBundle\Entity\Status $status * @param array $nextStates * @param \Opit\OpitHrm\LeaveBundle\Entity\LeaveRequest $leaveRequest * @param type $requiredStatus */ protected function prepareEmail(Status $status, array $nextStates, $leaveRequest) { $applicationName = $this->options['applicationName']; // get template name by converting entity name first letter to lower $className = Utils::getClassBasename($leaveRequest); $statusName = $status->getName(); $statusId = $status->getId(); // split class name at uppercase letters $subjectType = preg_split('/(?=[A-Z])/', $className); $generalManager = $leaveRequest->getGeneralManager(); // create string for email travel type e.g.(Travel expense, Travel request) $subjectTravelType = $subjectType[1] . ' ' . strtolower($subjectType[2]); $stateChangeLinks = array(); // Check if leave request status is for approval and send email to gm, if not send to employee if (Status::FOR_APPROVAL === $statusId) { $leaveToken = $this->setLeaveToken($leaveRequest->getId()); foreach ($nextStates as $key => $value) { // Generate links that can be used to change the status of the travel request $stateChangeLinks[] = $this->router->generate('OpitOpitHrmLeaveBundle_change_status', array('gmId' => $generalManager->getId(), 'status' => $key, 'token' => $leaveToken), true); } $recipient = $generalManager->getEmail(); $templateVariables = array('nextStates' => $nextStates, 'stateChangeLinks' => $stateChangeLinks); } else { $employee = $leaveRequest->getEmployee(); $user = $this->entityManager->getRepository('OpitOpitHrmUserBundle:User')->findByEmployee($employee); $recipient = $user[0]->getEmail(); $templateVariables = array('url' => $this->router->generate('OpitOpitHrmUserBundle_security_login', array(), true)); switch ($statusId) { case Status::APPROVED: $templateVariables['isApproved'] = true; break; case Status::REVISE: $templateVariables['isRevised'] = true; break; case Status::REJECTED: $templateVariables['isRejected'] = true; break; case Status::CREATED: $templateVariables['isCreated'] = true; break; } } $templateVariables['currentState'] = $statusName; $templateVariables['employee'] = $leaveRequest->getEmployee(); $templateVariables['leaveRequest'] = $leaveRequest; $this->mailer->setRecipient($recipient); $this->mailer->setSubject('[' . ($applicationName !== null && $applicationName != 'OPIT-HRM' ? $applicationName : 'OPIT-HRM') . '] - ' . $subjectTravelType . ' status changed - ' . $statusName . ' (' . $leaveRequest->getLeaveRequestId() . ')'); $this->mailer->setBodyByTemplate('OpitOpitHrmLeaveBundle:Mail:leaveRequest.html.twig', $templateVariables); $this->mailer->sendMail(); }
/** * Validate the command input options * Validate the dates and currency codes, if these are not valid then return with false. * * @param mixin $inputOptions * @param Logger $this->logger * @param Symfony\Component\Console\Output\OutputInterface $output * @return boolean|mixin return false if the command options are not valid else return with options */ protected function validateCommandOptions($inputOptions, $output) { $options = array(); $this->logger = $this->getContainer()->get('logger'); if ($inputOptions['start']) { if (!Utils::validateDate($inputOptions['start'], 'Y-m-d')) { $output->writeln('<error>The start date is invalid:</error> ' . $inputOptions['start'] . '. <comment>Correct format:</comment> 2014-01-20'); $this->logger->alert(sprintf('[|%s] The start option is in invalid date format.', Utils::getClassBasename($this))); exit(0); } $options['startDate'] = $inputOptions['start']; } else { // If the start option is missing and the it wasn't marked as a required options. if (!(isset($this->isNotRequiredOptions['start']) && true === $this->isNotRequiredOptions['start'])) { $output->writeln('<error>The start date is misssing</error>.' . 'Please use the <comment>--start</comment> option'); $this->logger->error(sprintf('[|%s] The start option is missing.', Utils::getClassBasename($this))); exit(0); } } if ($inputOptions['end']) { if (!Utils::validateDate($inputOptions['end'], 'Y-m-d')) { $output->writeln('<error>The end date is invalid:</error> ' . $inputOptions['end'] . '. <comment>Correct format:</comment> 2014-01-20'); $this->logger->alert(sprintf('[|%s] The end option is in invalid date format.', Utils::getClassBasename($this))); exit(0); } $options['endDate'] = $inputOptions['end']; } if ($inputOptions['currency']) { if (!Utils::validateCurrencyCodesString($inputOptions['currency'])) { $output->writeln('<error>The currency codes are invalid:</error> ' . $inputOptions['currency'] . '. <comment>Correct format:</comment> EUR,USD'); $this->logger->alert(sprintf('[|%s] The currency option is in invalid format.', Utils::getClassBasename($this))); exit(0); } $options['currencyNames'] = strtoupper($inputOptions['currency']); } return $options; }
/** * @internal */ public function saveExchangeRates($force = false, array $currencyRates = array()) { $this->logger->info(sprintf('[|%s] Rates sync is started.', Utils::getClassBasename($this))); if (!empty($currencyRates)) { $this->currencyRates = $currencyRates; } if (!empty($this->currencyRates)) { try { // Iterate the currencies foreach ($this->currencyRates as $currencyCode => $dates) { $lastDateObj = new \DateTime(key($dates)); $lastRateValue = current($dates); // Iterate the date and rate foreach ($dates as $date => $value) { $dateObj = new \DateTime($date); // Persist rates for date differences between current and last date (weekend) $interval = date_diff($lastDateObj, $dateObj); $this->setMissingRatesAndPersist($lastDateObj, $interval->format('%d') - 1, $currencyCode, $lastRateValue, $force); // Persist the current rate $rate = $this->createOrUpdateRate($currencyCode, $value, $dateObj, $force); if (null !== $rate) { $this->em->persist($rate); } $lastDateObj = clone $dateObj; $lastRateValue = $value; } // Insert difference of last MNB date and tomorrow using last MNB rate $tomorrow = new \DateTime('tomorrow'); $difference = $tomorrow->diff($lastDateObj); $this->setMissingRatesAndPersist($lastDateObj, $difference->format('%d'), $currencyCode, $value, $force); } $this->em->flush(); $this->logger->info(sprintf('[|%s] Rates synced successfully.', Utils::getClassBasename($this))); } catch (Exception $exc) { $this->logger->error(sprintf('[|%s] Rates synced FAILED! Error message: ' . $exc->getTraceAsString(), Utils::getClassBasename($this))); } return true; } else { $this->logger->alert(sprintf('[|%s] The currency rates array is empty.', Utils::getClassBasename($this))); return false; } $this->logger->info(sprintf('[|%s] Rates sync is ended.', Utils::getClassBasename($this))); }
/** * testing getClassBasename method. */ public function testGetClassBasename() { $utils = new Utils(); $result = Utils::getClassBasename($utils); $this->assertEquals('Utils', $result, 'Getting class\'s name.'); }
/** * Enforce status persistence * * @param integer $statusId * @param $resource * @param User $user */ public function forceStatus($statusId, $resource, $user = null) { $pieces = preg_split('/(?=[A-Z])/', $this->request->attributes->get('_template')->get('bundle')); $bundleName = $pieces[4] . '' . $pieces[5]; $status = $this->entityManager->getRepository('OpitOpitHrmStatusBundle:Status')->find($statusId); $instanceS = new \ReflectionClass('Opit\\OpitHrm\\' . $bundleName . '\\Entity\\States' . Utils::getClassBasename($resource) . 's'); $createdStatus = $instanceS->newInstanceArgs(array($status, $resource)); if (null !== $user) { $createdStatus->setCreatedUser($user); $createdStatus->setUpdatedUser($user); } $createdStatus->setStatus($status); $this->entityManager->persist($createdStatus); $this->entityManager->flush(); }