/** * * @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(); }
public function getLRLastNoticeDate($lrCreated) { $lastContactDate = clone $lrCreated; date_add($lastContactDate, date_interval_create_from_date_string('5 days')); $weekendDays = Utils::countWeekendDays($lrCreated->getTimeStamp(), $lastContactDate->getTimeStamp()); date_add($lastContactDate, date_interval_create_from_date_string($weekendDays . ' days')); return $lastContactDate->format('Y-m-d'); }
/** * 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(); }
/** * 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; }
/** * To add/edit job position in OPIT-HRM * * @Route("/secured/job/show/{id}", name="OpitOpitHrmHiringBundle_job_position_show", defaults={"id" = "new"}, requirements={ "id" = "new|\d+"}) * @Secure(roles="ROLE_TEAM_MANAGER") * @Method({"GET", "POST"}) * @Template() * @throws AccessDeniedException */ public function showJobPositionAction(Request $request) { $entityManager = $this->getDoctrine()->getManager(); $jobPositionId = $request->attributes->get('id'); $isNewJobPosition = 'new' === $jobPositionId; $securityContext = $this->container->get('security.context'); $isTeamManager = $securityContext->isGranted('ROLE_TEAM_MANAGER'); $currentUser = $securityContext->getToken()->getUser(); $isEditable = true; $errors = array(); $externalApplicationFormUrl = ''; if (!$isTeamManager) { throw new AccessDeniedException('Access denied for job position.'); } if ($isNewJobPosition) { $jobPosition = new JobPosition(); } else { $entityManager->getFilters()->disable('softdeleteable'); $jobPosition = $entityManager->getRepository('OpitOpitHrmHiringBundle:JobPosition')->find($jobPositionId); if (null === $jobPosition) { throw $this->createNotFoundException('Missing job position.'); } $isEditable = $securityContext->isGranted('ROLE_ADMIN') || $currentUser->getId() === $jobPosition->getCreatedUser()->getId(); // Only show job position external url when job position is active if (true === $jobPosition->getIsActive()) { $externalApplicationFormUrl = $this->generateUrl('OpitOpitHrmHiringBundle_job_application', array('token' => $jobPosition->getExternalToken()), true); } } $form = $this->createForm(new JobPositionType($isNewJobPosition), $jobPosition, array('em' => $entityManager)); if ($request->isMethod("POST")) { if (!$isEditable) { throw new AccessDeniedException('Job position can not be modified.'); } $form->handleRequest($request); if ($form->isValid()) { $entityManager->persist($jobPosition); $entityManager->flush(); if ($isNewJobPosition) { $this->sendJpMessages($jobPosition); } return $this->redirect($this->generateUrl('OpitOpitHrmHiringBundle_job_position_list')); } else { $errors = Utils::getErrorMessages($form); } } return $this->render('OpitOpitHrmHiringBundle:JobPosition:showJobPosition.html.twig', array('form' => $form->createView(), 'isNewJobPosition' => $isNewJobPosition, 'isEditable' => $isEditable, 'errors' => $errors, 'externalApplicationFormUrl' => $externalApplicationFormUrl)); }
/** * 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; }
/** * 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; }
/** * Format the amount * * @param integer $amount * @param integer $decimals * @param string $decPoint * @param string $thousandSep * @param string $currency * @return int */ public function formatAmount($amount, $decimals, $decPoint, $thousandSep, $currency) { return Utils::getformattedAmount($amount, $decimals, $decPoint, $thousandSep, $currency); }
/** * Get the leave days and leave ids. * * @param integer $year year * @param integer $month month * @return array of leave data */ private function getLeaveData($year, $month) { $em = $this->getDoctrine()->getManager(); $leaveData['leaveDays'] = array(); $leaveData['leaveIds'] = array(); // Get the leave requests $leaveRequests = $em->getRepository('OpitOpitHrmLeaveBundle:LeaveRequest')->findApprovedLeaveRequestsByDates(date($year . '-' . $month . '-01'), date($year . '-' . $month . '-31')); // Fetch leaves for every leave day. foreach ($leaveRequests as $leaveRequest) { foreach ($leaveRequest->getLeaves() as $leave) { // Fetch leave ids to the serialization. $leaveData['leaveIds'][$leaveRequest->getId()][] = $leave->getId(); $days = Utils::diffDays($leave->getStartDate(), $leave->getEndDate()); // Fetch leave days by employee id and category name foreach ($days as $day) { $leaveData['leaveDays'][$day->format('Y-m-d')][$leaveRequest->getEmployee()->getId()] = $leave->getCategory()->getName(); } } } return $leaveData; }
/** * Method to create job application from outside of application * * @Route("/job/application/{token}", name="OpitOpitHrmHiringBundle_job_application", requirements={ "token" }) * @Template() * @throws AccessDeniedException */ public function externalJobApplicationAction(Request $request) { $entityManager = $this->getDoctrine()->getManager(); $errors = array(); $token = $request->attributes->get('token'); $jobPosition = $entityManager->getRepository('OpitOpitHrmHiringBundle:JobPosition')->findOneByExternalToken($token); if (null === $jobPosition || false === $jobPosition->getIsActive()) { throw new AccessDeniedException('Job position (' . $jobPosition->getJobTitle() . ') is no longer active.'); } $applicant = new Applicant(); $applicant->setJobPosition($jobPosition); $applicant->setApplicationDate(new \DateTime()); $form = $this->createForm(new ExternalApplicantType(), $applicant, array('em' => $entityManager)); if ($request->isMethod('POST')) { $form->handleRequest($request); if ($form->isValid()) { // If new applicant is being added // check if applicant has already been added to jp with same email or phone number. // Check after form is valid to make sure all data is present. if ($entityManager->getRepository('OpitOpitHrmHiringBundle:Applicant')->findByEmailPhoneNumber($applicant) > 0) { $form->addError(new FormError('Email or phone number has been already registered for this job position.')); $errors = Utils::getErrorMessages($form); } else { $entityManager->persist($applicant); $entityManager->flush(); // Send email to applicant $this->get('opit.manager.external_application_email_manager')->sendExternalApplicantMail($jobPosition, $applicant); // Add created status to applicant and send email about it $status = $this->get('opit.manager.applicant_status_manager')->addStatus($applicant, Status::CREATED, null); // Send a notification about new applicant $this->get('opit.manager.applicant_notification_manager')->addNewApplicantNotification($applicant, $status); return $this->render('OpitOpitHrmHiringBundle:Default:externalApplicationSuccessful.html.twig', array('jobPosition' => $jobPosition)); } } else { $errors = Utils::getErrorMessages($form); } } return $this->render('OpitOpitHrmHiringBundle:Default:externalApplication.html.twig', array('jobPosition' => $jobPosition, 'errors' => $errors, 'form' => $form->createView())); }
/** * @Route("/secured/admin/teams/show/{id}", name="OpitOpitHrmUserBundle_admin_teams_show", requirements={ "id" = "new|\d+"}, defaults={"id" = "new"}) * @Secure(roles="ROLE_SYSTEM_ADMIN") * @Method({"POST", "GET"}) * @Template() */ public function teamShowAction(Request $request) { $entityManager = $this->getDoctrine()->getManager(); $teamId = $request->attributes->get('id'); $employees = new ArrayCollection(); if ('new' === $teamId) { $team = new Team(); } else { $team = $entityManager->getRepository('OpitOpitHrmUserBundle:Team')->find($teamId); } foreach ($team->getEmployees() as $employee) { $employees->add($employee); } $form = $this->createForm(new TeamType(), $team, array('em' => $entityManager)); if ($request->isMethod('POST')) { $form->handleRequest($request); if ($form->isValid()) { // Remove teams from employee foreach ($employees as $employee) { if (false === $team->getEmployees()->contains($employee)) { $employee->removeTeam($team); } } // Add teams to employees foreach ($team->getEmployees() as $employee) { if (false === $employee->getTeams()->contains($team)) { $employee->addTeam($team); } } $entityManager->persist($team); $entityManager->flush(); return $this->render('OpitOpitHrmUserBundle:Admin:_teamsList.html.twig', $this->getAllTeams()); } else { $statusCode = 500; $errors = Utils::getErrorMessages($form); $result['errorMessage'] = $errors; return new JsonResponse(array($result), $statusCode); } } return $this->render('OpitOpitHrmUserBundle:Admin:showTeam.html.twig', array('form' => $form->createView())); }
/** * Method to create single leave request (own or single employee selected) * * @param \Opit\OpitHrm\LeaveBundle\Entity\LeaveRequest $leaveRequest * @param \Doctrine\ORM\EntityManagerInterface $entityManager * @param type $data * @param type $leftToAvail * @return string|null */ protected function createSingleLR(LeaveRequest $leaveRequest, EntityManagerInterface $entityManager, $data, $leftToAvail, $employee, $isOwn, $children) { $leaveRequestService = $this->get('opit.model.leave_request'); $securityContext = $this->container->get('security.context'); $leaveRequest->setEmployee($employee); $totalLeaveDaysCount = 0; $pastLeaveCount = 0; foreach ($leaveRequest->getLeaves() as $leave) { $countLeaveDays = $leaveRequestService->countLeaveDays($leave->getStartDate(), $leave->getEndDate()); // Validate leave category if (null === $leave->getCategory()) { return 'Category can not be empty.'; } // Check if leave is not to be substracted from entitlement $excludedCategoryIds = Utils::arrayValueRecursive('id', $entityManager->getRepository('OpitOpitHrmLeaveBundle:LeaveCategory')->findNotCountedAsLeaveIds()); if (!in_array($leave->getCategory()->getId(), $excludedCategoryIds)) { $totalLeaveDaysCount += $countLeaveDays; } if ($totalLeaveDaysCount > $leftToAvail) { return 'Employee has no more days left to avail.'; } else { if ($leave->getStartDate() < new \DateTime()) { $pastLeaveCount++; } $leave->setNumberOfDays($countLeaveDays); $entityManager->persist($leave); $leaveRequestService->removeChildNodes($leaveRequest, $children); } } $entityManager->persist($leaveRequest); $status = $data['approvedStatus']; // Check if user is setting LR for himself if ($securityContext->getToken()->getUser()->getEmployee()->getId() === $employee->getId() && $isOwn) { // If LR has leaves only in the past set status to approved else set // status to created $status = $pastLeaveCount === count($leaveRequest->getLeaves()) ? $data['approvedStatus'] : $data['createdStatus']; } $this->setLRStatusSendNotificationEmail($leaveRequest, $leaveRequest->getEmployee(), $status, $leaveRequestService); return null; }
public function testGetformattedAmount() { $decimals = 2; $decPoint = ','; $thousandSep = ' '; $result = Utils::getformattedAmount(10050, $decimals, $decPoint, $thousandSep, 'HUF'); $this->assertEquals('10 050', $result, 'Utils::getformattedAmount The amount format does not match.'); $result2 = Utils::getformattedAmount(10050, $decimals, $decPoint, $thousandSep, 'EUR'); $this->assertEquals('10 050,00', $result2, 'Utils::getformattedAmount The amount format does not match.'); }
/** * 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(); }
/** * * @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(); }
/** * @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); } } }
/** * @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))); }
/** * Builds the base query for user search * * @param string $chunk part of the employee name or email * @param mixed $role String or array of role names * @return object */ protected function getFindUserBaseQueryBuilder($chunk, $role) { $role = Utils::arrayValuesToUpper($role); $q = $this->createQueryBuilder('u')->leftJoin('u.employee', 'e')->innerJoin('u.groups', 'g')->where('e.employeeName LIKE :employeeName')->orWhere('u.email LIKE :email')->andWhere('g.role IN (:role)')->setParameter('employeeName', "%{$chunk}%")->setParameter('email', "%{$chunk}%")->setParameter('role', $role); return $q; }
/** * Count the number of leave days * * @param DateTime $startDate * @param DateTime $endDate * @return integer */ public function countLeaveDays($startDate, $endDate) { $start = $startDate->getTimestamp(); $end = $endDate->getTimestamp(); $administrativeLeavesCount = 0; $administrativeLeaves = $this->entityManager->getRepository('OpitOpitHrmLeaveBundle:LeaveDate')->getAdminLeavesInDateRange($startDate, $endDate); // Count administrative leaves foreach ($administrativeLeaves as $date) { if ($date['holidayDate']->format('D') != 'Sat' && $date['holidayDate']->format('D') != 'Sun') { $administrativeLeavesCount++; } } // Count administrative working days $administrativeWorkingDays = $this->entityManager->getRepository('OpitOpitHrmLeaveBundle:LeaveDate')->countLWDBWDateRange($startDate, $endDate, true); // Count total days $totalDays = $endDate->diff($startDate)->format("%a") + 1; // Count total weekend days $totalWeekendDays = Utils::countWeekendDays($start, $end); // Count total leave days $totalLeaveDays = $totalDays - $totalWeekendDays - $administrativeLeavesCount + $administrativeWorkingDays; return $totalLeaveDays; }
/** * Change the password of an exist user. * * @Route("/secured/user/update/password/{id}", name="OpitOpitHrmUserBundle_user_update_password", requirements={"id" = "\d+"}) * @Secure(roles="ROLE_USER") * @Method({"POST"}) * @Template() */ public function updatePasswordAction() { $result = array('response' => 'error'); $request = $this->getRequest(); $statusCode = 200; $user = $this->getUserObject($request->attributes->get('id')); $form = $this->createForm(new ChangePasswordType(), $user); if ($request->isMethod("POST")) { $form->handleRequest($request); if ($form->isValid()) { $this->setUserPassword($user); $result['response'] = 'success'; } else { $statusCode = 500; $errors = Utils::getErrorMessages($form); $result['errorMessage'] = $errors; } } return new JsonResponse(array($result), $statusCode); }
/** * Exports team employee leaves in iCalendar format * * @Route("/secured/calendar/team/leaves/export", name="OpitOpitHrmLeaveBundle_calendar_team_leaves_export") * @Method({"POST"}) * @Secure(roles="ROLE_USER") * @Template() */ public function exportTeamEmployeeLeavesAction(Request $request) { $entityManager = $this->getDoctrine()->getManager(); $securityContext = $this->container->get('security.context'); $employee = $securityContext->getToken()->getUser()->getEmployee(); $statusManager = $this->get('opit.manager.leave_status_manager'); $teamsEmployees = $this->getTeamsEmployees($employee, $request->request->get('team')); // get all approved leave requests employees are in $leaveRequests = $entityManager->getRepository('OpitOpitHrmLeaveBundle:LeaveRequest')->findEmployeesLeaveRequests($teamsEmployees, $request->request->get('start'), $request->request->get('end'), Status::APPROVED); $iCal = new ICal\ICalendar(); // loop through all leave requests foreach ($leaveRequests as $leaveRequest) { // loop through all leave request leaves $employee = $leaveRequest->getEmployee(); $currentStatus = $statusManager->getCurrentStatusMetaData($leaveRequest); foreach ($leaveRequest->getLeaves() as $leave) { $iCalEvent = new ICal\ICalendarEvent(); $iCalEvent->setDtStamp($currentStatus->getCreated()); $iCalEvent->setSummary(ucwords($employee->getEmployeeName()) . ' - ' . $leave->getCategory()->getName()); $iCalEvent->setDtStart($leave->getStartDate()); $iCalEvent->setDtEnd($leave->getEndDate()); $iCalEvent->addCategory($leave->getCategory()->getName()); $iCal->addEvent($iCalEvent); } } $iCalContent = $iCal->render(); $filename = Utils::sanitizeString($this->container->getParameter('application_name') . '-' . $request->request->get('title')) . '.ics'; $response = new Response(); $response->headers->set('Cache-Control', 'private'); $response->headers->set('Content-type', 'text/calendar'); $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '";'); $response->headers->set('Content-Transfer-Encoding', 'binary'); $response->headers->set('Content-length', strlen(utf8_decode($iCalContent))); $response->sendHeaders(); $response->setContent($iCalContent); return $response; }
/** * Renders a transportation type form * * @Route("/travel/admin/transportation_type/show/{id}", name="OpitOpitHrmTravelBundle_admin_transportationtype_show", requirements={ "id" = "new|\d+"}, defaults={"id" = "new"}) * @Method({"GET", "POST"}) * @Secure(roles="ROLE_SYSTEM_ADMIN") * @Template() */ public function showTransportationTypeAction(Request $request, $id) { $entityManager = $this->getDoctrine()->getManager(); $result = array('response' => 'success'); $statusCode = 200; if ('new' === $id) { $transportationType = new TransportationType(); } else { $transportationType = $entityManager->getRepository('OpitOpitHrmTravelBundle:TransportationType')->find($id); } $form = $this->createForm(new TransportationTypeForm(), $transportationType); // Handle post data and persist if ($request->isMethod('POST')) { $form->handleRequest($request); if ($form->isValid()) { $entityManager->persist($transportationType); $entityManager->flush(); } else { $statusCode = 500; $result['response'] = 'error'; $result['errorMessage'] = Utils::getErrorMessages($form); } return new JsonResponse(array($result), $statusCode); } return array('form' => $form->createView()); }
/** * Method to fetch per diem values from database * * @Route("/secured/expense/perdiemvalues", name="OpitOpitHrmTravelBundle_expense_perdiemvalues") * @Template() * @Method({"POST"}) */ public function fetchPerDiemValuesAction() { // Get the currency format options. $currencyConfig = $this->container->getParameter('currency_config'); $currencyFormat = $currencyConfig['currency_format']; $entityManager = $this->getDoctrine()->getManager(); $perDiemAmounts = $entityManager->getRepository('OpitOpitHrmTravelBundle:TEPerDiem')->findAll(); $values = array(); foreach ($perDiemAmounts as $value) { $values[$value->getHours()] = Utils::getformattedAmount($value->getAmount(), $currencyFormat['decimals'], $currencyFormat['dec_point'], $currencyFormat['thousands_sep'], 'EUR'); } return new JsonResponse($values); }
/** * To add/edit applicant in OPIT-HRM * * @Route("/secured/applicant/show/{id}", name="OpitOpitHrmHiringBundle_applicant_show", defaults={"id" = "new"}, requirements={ "id" = "new|\d+"}) * @Secure(roles="ROLE_TEAM_MANAGER") * @Method({"GET", "POST"}) * @Template() * @throws AccessDeniedException */ public function showApplicantAction(Request $request) { $entityManager = $this->getDoctrine()->getManager(); $applicantId = $request->attributes->get('id'); $jobPositionId = $request->query->get('jobPositionId'); $isNewApplicant = 'new' === $applicantId; $securityContext = $this->container->get('security.context'); $isTeamManager = $securityContext->isGranted('ROLE_TEAM_MANAGER'); $statusManager = $this->get('opit.manager.applicant_status_manager'); $entityManager->getFilters()->disable('softdeleteable'); $currentUser = $securityContext->getToken()->getUser(); $isEditable = true; $isStatusLocked = false; $errors = array(); $nextStates = array(); $applicantCV = ''; if (!$isTeamManager) { throw new AccessDeniedException('Access denied for applicant.'); } if ($isNewApplicant) { $applicant = new Applicant(); // If the job position id exists fetch the job position entity and adding to the applicant. // The calling was from the job position list page. if (null !== $jobPositionId) { $jobPosition = $entityManager->getRepository('OpitOpitHrmHiringBundle:JobPosition')->find($jobPositionId); $applicant->setJobPosition($jobPosition); } } else { $applicant = $entityManager->getRepository('OpitOpitHrmHiringBundle:Applicant')->find($applicantId); $applicantCV = $applicant->getCv(); $isEditable = ($securityContext->isGranted('ROLE_ADMIN') || $applicant->getCreatedUser() && $applicant->getCreatedUser()->getId() === $currentUser->getId()) && null === $applicant->getJobPosition()->getDeletedAt(); if (null === $applicant) { throw $this->createNotFoundException('Missing applicant.'); } } $currentStatus = $statusManager->getCurrentStatusMetaData($applicant); if (null === $currentStatus) { $currentStatus = $entityManager->getRepository('OpitOpitHrmStatusBundle:Status')->find(Status::CREATED); $isStatusLocked = true; } else { $currentStatus = $statusManager->getCurrentStatus($applicant); $nextStates = $statusManager->getNextStates($currentStatus); $isStatusFinalized = Status::HIRED === $currentStatus->getId() || Status::REJECTED === $currentStatus->getId(); $isEditable = $isStatusFinalized ? false : $isEditable; $isStatusLocked = $isStatusFinalized ? true : $isStatusLocked; } $form = $this->createForm(new ApplicantType($isNewApplicant), $applicant, array('em' => $entityManager)); if ($request->isMethod('POST')) { if (!$isEditable) { throw new AccessDeniedException('Applicant can not be modified.'); } $form->handleRequest($request); if ($form->isValid()) { // If new applicant is being added // check if applicant has already been added to jp with same email or phone number. // Check after for is valid to make sure data is present. if ($isNewApplicant && $entityManager->getRepository('OpitOpitHrmHiringBundle:Applicant')->findByEmailPhoneNumber($applicant) > 0) { $form->addError(new FormError('Email or phone number has been already registered for this job position.')); $errors = Utils::getErrorMessages($form); } else { $entityManager->persist($applicant); $entityManager->flush(); if ($isNewApplicant) { $statusManager->addStatus($applicant, Status::CREATED, null); } return $this->redirect($this->generateUrl(null !== $jobPositionId ? 'OpitOpitHrmHiringBundle_job_position_list' : 'OpitOpitHrmHiringBundle_applicant_list')); } } else { $errors = Utils::getErrorMessages($form); } } return $this->render('OpitOpitHrmHiringBundle:Applicant:showApplicant.html.twig', array('form' => $form->createView(), 'isNewApplicant' => $isNewApplicant, 'isEditable' => $isEditable, 'errors' => $errors, 'isStatusLocked' => $isStatusLocked, 'nextStates' => $nextStates, 'currentStatus' => $currentStatus, 'applicantId' => $applicantId, 'applicantCV' => $applicantCV, 'jobPositionId' => $jobPositionId)); }
/** * To save leave setting * * @Route("/secured/admin/save/leavesetting", name="OpitOpitHrmLeaveBundle_admin_save_leave_setting") * @Secure(roles="ROLE_SYSTEM_ADMIN") * @Method({"POST"}) * @Template() */ public function saveLeaveSettingAction() { $request = $this->getRequest(); $data = $request->request->all(); $em = $this->getDoctrine()->getManager(); $result['response'] = 'success'; $status = null; //If it was a post if ($request->isMethod('POST')) { $leaveSettingList = $em->getRepository('OpitOpitHrmLeaveBundle:LeaveSetting')->findAll(); $ids = Utils::arrayValueRecursive('id', $data); // Remove leave settings foreach ($leaveSettingList as $hs) { if (!in_array($hs->getId(), $ids)) { // delete $leaveSetting = $this->getLeaveSetting($hs->getId(), false); $em->remove($leaveSetting); $em->flush(); } } if (!empty($data)) { // Save leave settings foreach ($data['leaveSetting'] as $d) { // save $leaveSetting = $this->getLeaveSetting($d['id'], false); $result = $this->setLeaveSettingData($leaveSetting, $d); if (500 === $result['status']) { $status = $result['status']; break; } } } } return new JsonResponse(array('code' => $status, $result)); }