/**
  * @param Site $site
  * @param LoanOfficer $loanOfficer
  * @return \Doctrine\ORM\QueryBuilder
  */
 public function findAllByLoanOfficerQuery(Site $site, LoanOfficer $loanOfficer)
 {
     $siteIds = $site->getChildSiteIds();
     array_push($siteIds, $site->getId());
     $q = $this->createQueryBuilder('q')->where('q.site IN (:site_ids)')->andWhere('q.deleted = 0')->andWhere('q.loan_officer = :loan_officer')->orderBy('q.created', 'DESC')->setParameter('loan_officer', $loanOfficer->getId())->setParameter('site_ids', $siteIds);
     return $q;
 }
 /**
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  * @throws \Symfony\Component\Form\Exception\AlreadyBoundException
  */
 public function addAction(Request $request)
 {
     $siteRequest = $this->get('sudoux.cms.site');
     $site = $siteRequest->getSite();
     $em = $this->getDoctrine()->getEntityManager();
     $officer = new LoanOfficer();
     $officer->setSite($site);
     $siteType = $site->getSiteType();
     if (isset($siteType)) {
         $siteBranch = $site->getSettings()->getBranch();
         if ($siteType->getKeyName() == 'branch' && isset($siteBranch)) {
             $officer->setBranch($siteBranch);
         }
     }
     $form = $this->createForm(new LoanOfficerType($site), $officer);
     if ($request->getMethod() == 'POST') {
         $form->bind($request);
         if ($form->isValid()) {
             $user = $this->get('security.context')->getToken()->getUser();
             $photoData = $form['officer_photo_file']->getData();
             if (isset($photoData)) {
                 $photo = new File();
                 $photo->setName(sprintf('%s %s', $form['first_name']->getData(), $form['last_name']->getData()));
                 $photo->setUser($user);
                 $photo->setSite($site);
                 $photo->setFile($photoData);
                 $officer->setOfficerPhoto($photo);
             }
             $em->persist($officer);
             $em->flush($officer);
             $request->getSession()->getFlashBag()->add('success', 'Your loan officer has been created.');
             return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_officer'));
         }
     }
     return $this->render('SudouxMortgageBundle:LoanOfficerAdmin:add.html.twig', array('form' => $form->createView(), 'officer' => $officer));
 }
 /**
  * @param LoanOfficer $loanOfficer
  */
 protected function addLoanOfficerUser(LoanOfficer $loanOfficer)
 {
     $loUser = $loanOfficer->getUser();
     $loSite = $loanOfficer->getOfficerSite();
     $loCreateUser = $loanOfficer->getAutoCreateUser();
     if ($loCreateUser && !isset($loUser) && isset($loSite)) {
         $loRole = $this->em->getRepository('SudouxCmsUserBundle:Role')->findOneBy(array('role' => 'ROLE_LOAN_OFFICER'));
         // check if user already exists by email
         $existingUser = $this->em->getRepository('SudouxCmsUserBundle:User')->findOneBy(array('email' => $loanOfficer->getEmail()));
         if (isset($existingUser)) {
             // assign existing user to lo
             $loanOfficer->setUser($existingUser);
             $this->em->persist($loanOfficer);
         } else {
             $user = new User();
             $username = strtolower(substr($loanOfficer->getFirstName(), 0, 1) . $loanOfficer->getLastName());
             $username = str_replace(' ', '', preg_replace("/[^A-Za-z0-9 ]/", '', $username));
             $user->setUsername($this->getLoanOfficerUsername($username));
             $factory = $this->container->get('security.encoder_factory');
             $encoder = $factory->getEncoder($user);
             $password = $encoder->encodePassword($user->generatePassword(), $user->getSalt());
             $user->setPassword($password);
             $user->setEmail($loanOfficer->getEmail());
             $user->setFirstName($loanOfficer->getFirstName());
             $user->setLastName($loanOfficer->getLastName());
             $user->addSite($loanOfficer->getOfficerSite());
             $user->addRole($loRole);
             $user->addToken();
             $user->setTimezone($loanOfficer->getSite()->getTimezone());
             $loanOfficer->setUser($user);
             $this->em->persist($loanOfficer);
             $emailUtil = $this->container->get('sudoux.cms.message.email_util');
             $email = new Email();
             $email->setRecipient($user->getEmail());
             $email->setRecipientName($user->getFullName());
             $email->setSubject($this->container->get('sudoux.cms.site')->getSiteVar('New Website Account', 'loan_officer_user_add_email_subject'));
             $email->setUser($user);
             $email->setSite($loanOfficer->getSite());
             $resetPasswordUrl = sprintf("https://%s%s", $loanOfficer->getOfficerSite()->getPrimaryDomain()->getDomain(), $this->router->generate('sudoux_cms_user_reset_password', array('token' => $user->getToken())));
             // default message
             $message = sprintf('<p>An account has been created for you on your new website. Your username is %s</p>', $user->getUsername());
             $message .= sprintf('<p><a href="%s">Click here</a> to set your password and confirm your account.</p>', $resetPasswordUrl);
             $tokens = array('username' => $user->getUsername(), 'email' => $user->getEmail(), 'reset_password_url' => $resetPasswordUrl, 'first_name' => $user->getFirstName(), 'last_name' => $user->getLastName(), 'website_url' => 'https://' . $loanOfficer->getOfficerSite()->getPrimaryDomain()->getDomain());
             $message = $this->container->get('sudoux.cms.site')->getSiteVar($message, 'loan_officer_user_add_email_message', $tokens);
             $email->setMessage($message);
             $emailUtil->logAndSend($email);
         }
         $this->em->flush($loanOfficer);
     }
 }
 /**
  * @param $csvPath
  * @throws \Exception
  */
 protected function importLoanOfficersFromCsv($csvPath)
 {
     ini_set('auto_detect_line_endings', true);
     $siteId = $this->site->getId();
     $header = array('first_name', 'last_name', 'email', 'los_id', 'nmls_id', 'title', 'phone_office', 'phone_mobile', 'phone_tollfree', 'fax', 'signature', 'bio', 'branch_nmls_id');
     $headerValid = true;
     $batchCount = 10;
     if (file_exists($csvPath)) {
         if (($handle = fopen($csvPath, "r")) !== FALSE) {
             $row = 0;
             while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                 if ($row == 0) {
                     // validate the header
                     for ($i = 0; $i < count($data); $i++) {
                         if ($data[$i] != $header[$i]) {
                             $headerValid = false;
                             break;
                         }
                     }
                     if (!$headerValid) {
                         throw new \Exception('Csv headers are not valid. Correct format is ' . implode(',', $header));
                     }
                 } else {
                     $loanOfficer = new LoanOfficer();
                     $loanOfficer->setFirstName($this->getCsvValue($data[0]));
                     $loanOfficer->setLastName($this->getCsvValue($data[1]));
                     $loanOfficer->setEmail($this->getCsvValue($data[2]));
                     $loanOfficer->setLosId($this->getCsvValue($data[3]));
                     $loanOfficer->setNmlsId($this->getCsvValue($data[4]));
                     $loanOfficer->setTitle($this->getCsvValue($data[5]));
                     $loanOfficer->setPhoneOffice($this->getCsvValue($data[6]));
                     $loanOfficer->setPhoneMobile($this->getCsvValue($data[7]));
                     $loanOfficer->setPhoneTollfree($this->getCsvValue($data[8]));
                     $loanOfficer->setFax($this->getCsvValue($data[9]));
                     $loanOfficer->setSignature($this->getCsvValue($data[10]));
                     $loanOfficer->setBio($this->getCsvValue($data[11]));
                     $loanOfficer->setSite($this->site);
                     $loanOfficer->setAutoCreateUser(false);
                     // this needs to be set after setSite to override default functionality
                     // lookup branch
                     $branchNmlsId = $this->getCsvValue($data[12]);
                     if (!empty($branchNmlsId)) {
                         $branch = $this->em->getRepository('SudouxMortgageBundle:Branch')->findOneBySiteAndNmlsId($this->site, $branchNmlsId);
                         if (isset($branch)) {
                             $loanOfficer->setBranch($branch);
                         }
                     }
                     $this->em->persist($loanOfficer);
                     if ($row % $batchCount == 0) {
                         $this->em->flush();
                         $this->em->clear();
                         $this->site = $this->em->getRepository('SudouxCmsSiteBundle:Site')->find($siteId);
                         $this->output->writeln(sprintf('%s rows processed', $row));
                     }
                 }
                 $row++;
             }
             exit;
             $this->em->flush();
             $this->em->clear();
             $this->output->writeln(sprintf('Processing complete! %s rows processed', $row));
         }
     }
 }