protected function processContract($row)
 {
     if ($row) {
         $manager = $this->getContainer()->get('doctrine.orm.entity_manager');
         $contractRepo = $manager->getRepository('TSK\\ContractBundle\\Entity\\Contract');
         $programRepo = $manager->getRepository('TSK\\ProgramBundle\\Entity\\Program');
         $schoolRepo = $manager->getRepository('TSK\\SchoolBundle\\Entity\\School');
         $oldContract = $contractRepo->findOneBy(array('legacyContractId' => $row[0]));
         if (!$oldContract) {
             $contract = new Contract();
             $contract->setOrganization($this->org);
             $contract->setLegacyContractId($row[0]);
             $students = $this->parseStudents($row[1]);
             $today = new \DateTime();
             $contractExpiry = new \DateTime($row[4]);
             $studentStatusRepo = $manager->getRepository('TSK\\StudentBundle\\Entity\\StudentStatus');
             $expiredStatus = $studentStatusRepo->findOneBy(array('name' => 'expired'));
             foreach ($students as $student) {
                 $contract->addStudent($student);
                 // If contract has already expired, then mark student as expired
                 if ($contractExpiry < $today) {
                     $student->setStudentStatus($expiredStatus);
                     $manager->persist($student);
                 }
             }
             $program = $programRepo->findOneBy(array('programName' => $row[2]));
             if (!$program) {
                 throw new \Exception('Invalid program ' . $row[2]);
             }
             $contract->setProgram($program);
             $contract->setContractExpiry(new \DateTime($row[4]));
             $contract->setContractNumTokens($row[5]);
             $contract->setDeferralRate($row[6]);
             $contract->setDeferralDistributionStrategy($row[7]);
             $contract->setContractStartDate(new \DateTime($row[11]));
             $contract->setSchool($this->school);
             $contract->setIsActive(true);
             if ($row[12] < 9999) {
                 $payments = $this->distributeInt($row[10], $row[9]);
                 $paymentTerms = array('paymentFrequency' => 'monthly', 'summary' => $this->generateSummary($payments), 'principal' => $row[10], 'payments' => $payments);
             } else {
                 $paymentTerms = array('paymentFrequency' => 'monthly', 'summary' => 'summary', 'principal' => $row[10], 'payments' => array());
             }
             $contract->setPaymentTerms(array('paymentsData' => json_encode($paymentTerms)));
             $doc = $contract->renderContractVersion();
             $manager->persist($contract);
             $manager->persist($doc);
             $manager->flush();
         }
     }
 }
 public function saveNewStudentRegistration($em, $studentRegistration)
 {
     $contactRepo = $em->getRepository('TSK\\UserBundle\\Entity\\Contact');
     $studentRepo = $em->getRepository('TSK\\StudentBundle\\Entity\\Student');
     // flow finished
     $student = $studentRegistration->getStudent();
     if (!$student) {
         $studentContact = $studentRegistration->getStudentContact();
         // check for dupe student
         if ($dupeStudent = $studentRepo->findOneBy(array('contact' => $studentContact))) {
             $student = $dupeStudent;
             $student->getContact()->addSchool($studentRegistration->getSchool());
         } else {
             // Create student
             // check for dupe contact
             if ($dupeContact = $contactRepo->findDupe($studentContact)) {
                 $studentContact = $dupeContact;
             }
             $studentContact->addSchool($studentRegistration->getSchool());
             $student = new Student();
             $student->setContact($studentContact);
         }
     }
     $studentStatusActive = $em->getRepository('TSK\\StudentBundle\\Entity\\StudentStatus')->findOneBy(array('name' => 'active', 'organization' => $this->getOrg()));
     $student->setStudentStatus($studentStatusActive);
     $student->setIsProspective(false);
     // Create Billee
     $billeeContact = $studentRegistration->getBilleeContact();
     if ($dupeContact = $contactRepo->findDupe($billeeContact)) {
         $billeeContact = $dupeContact;
     }
     $billeeContact->addSchool($studentRegistration->getSchool());
     $student->addBillee($billeeContact);
     // Create Emergency Contact
     $emergencyContact = $studentRegistration->getEmergencyContactContact();
     if ($dupeContact = $contactRepo->findDupe($emergencyContact)) {
         $emergencyContact = $dupeContact;
     }
     $emergencyContact->addSchool($studentRegistration->getSchool());
     $student->addEmergencyContact($emergencyContact);
     $pp = $studentRegistration->getPaymentPlanCustomizedPayments();
     // Hmmm ... after adding Gedmo loggable now I need to stripslashes on json data ...
     $paymentObj = json_decode(stripslashes($pp['paymentsData']));
     // Create contract
     // Soon we will need to select the contract based on membership type
     $contract = new Contract();
     $contract->setIsActive(true);
     $contract->setProgram($studentRegistration->getProgram());
     // $contract->setAmount($paymentObj->principal);
     $contract->setSchool($studentRegistration->getSchool());
     $contract->addStudent($student);
     $contract->setPaymentTerms($studentRegistration->getPaymentPlanCustomizedPayments());
     $contractStartDate = new \DateTime();
     // We may want the ability to set this manually in the future ...
     $contract->setContractStartDate($contractStartDate);
     $programExpiry = new \DateTime();
     $expireDays = $studentRegistration->getProgram()->getDurationDays() + $studentRegistration->getContractBalanceDays();
     $programExpiry->add(new \DateInterval('P' . $expireDays . 'D'));
     $contract->setContractExpiry($programExpiry);
     $contract->setContractNumTokens($studentRegistration->getProgram()->getNumTokens());
     $contract->setRolloverDays($studentRegistration->getContractBalanceDays());
     $contract->setDeferralRate($studentRegistration->getProgramPaymentPlan()->getDeferralRate());
     $contract->setDeferralDurationMonths($studentRegistration->getProgramPaymentPlan()->getDeferralDurationMonths());
     $contract->setDeferralDistributionStrategy($studentRegistration->getProgramPaymentPlan()->getDeferralDistributionStrategy());
     // Add to contract_token table
     $contractToken = new ContractToken();
     $contractToken->setContract($contract);
     $contractToken->setAmount($studentRegistration->getProgram()->getNumTokens());
     // Billee Payment Method
     if (!$studentRegistration->getPayInFull()) {
         $bpm = new BilleePaymentMethod();
         $bpm->setContact($billeeContact);
         $bpm->setPaymentMethod($studentRegistration->getPaymentMethod());
         // $bpm->setCcNum($studentRegistration->getCcNum());
         $bpm->setTransArmorToken($studentRegistration->getTransArmorToken());
         if ($studentRegistration->getCcExpirationDate()) {
             $bpm->setCcExpirationDate($studentRegistration->getCcExpirationDate());
         }
         $bpm->setCvvNumber($studentRegistration->getCvvNumber());
         // $bpm->setRoutingNum($studentRegistration->getRoutingNumber());
         // $bpm->setAccountNum($studentRegistration->getAccountNumber());
     }
     if (!empty($bpm)) {
         $bpmContract = new BilleePaymentMethodContract();
         $bpmContract->setContract($contract);
         $bpmContract->setBilleePaymentMethod($bpm);
         $bpmContract->setPortion(100);
     }
     // Set up charges
     $session = $this->getRequest()->getSession();
     $sessionKey = $this->container->getParameter('tsk_user.session.org_key');
     $org = $this->get('session')->get($sessionKey);
     $tuitionIncomeType = $em->getRepository('TSK\\PaymentBundle\\Entity\\IncomeType')->findOneBy(array('name' => 'tuition', 'organization' => $org));
     // Grab IncFmStudents account
     $incFmStudents = $em->getRepository('TSK\\PaymentBundle\\Entity\\Account')->findOneBy(array('name' => 'Inc Fm Students', 'organization' => $org));
     $deferralAccount = $em->getRepository('TSK\\PaymentBundle\\Entity\\Account')->findOneBy(array('name' => 'Deferred Income', 'organization' => $org));
     if (!empty($paymentObj->payments)) {
         $payments = $paymentObj->payments;
         foreach ($payments as $idx => $payment) {
             $charge = new Charge();
             $charge->setSchool($studentRegistration->getSchool());
             $charge->setAmount($payment);
             $charge->setAccount($incFmStudents);
             $charge->setDeferralAccount($deferralAccount);
             $charge->setIncomeType($tuitionIncomeType);
             // 0 Months, 1 month, 2 months ...
             // TODO:  Make this respond to paymentFrequency
             $du = new DatesUtil();
             $today = new \DateTime();
             $charge->setDueDate($du->getMonthaversary($today->format('Y-m-d'), $idx));
             $em->persist($charge);
             // It feels a little funny doing this here, could be improved ... MJH
             $contract->addCharge($charge);
         }
     }
     $em->persist($student);
     $em->persist($billeeContact);
     $em->persist($emergencyContact);
     $em->persist($contract);
     $em->persist($contractToken);
     if (!empty($bpm)) {
         $em->persist($bpm);
         $em->persist($bpmContract);
     }
     // Set up RPI's
     if (!empty($bpm)) {
         if (!empty($paymentObj->payments)) {
             $payments = $paymentObj->payments;
             foreach ($payments as $idx => $payment) {
                 $rpi = new RecurringPaymentInstruction();
                 $rpi->setAmount($payment);
                 $rpi->setBilleePaymentMethod($bpm);
                 $rpi->setContract($contract);
                 $rpi->setStatus('pending');
                 // 0 Months, 1 month, 2 months ...
                 // TODO:  Make this respond to paymentFrequency
                 $du = new DatesUtil();
                 $today = new \DateTime();
                 $rpiDueDate = $du->getMonthaversary($today->format('Y-m-d'), $idx);
                 $rpi->setRunDate($rpiDueDate);
                 $em->persist($rpi);
             }
         }
     }
     $em->flush();
     // So we actually need to trigger a post registration event
     // We also need to run our discount.post rules engine
     $studentRegistration->setStudent($student);
     $studentRegistration->setContract($contract);
     $studentPostRegistrationEvent = new StudentPostRegistrationEvent($student, $studentRegistration);
     $dispatcher = $this->get('event_dispatcher');
     $dispatcher->dispatch(StudentEvents::STUDENT_REGISTRATION_POST, $studentPostRegistrationEvent);
 }