Example #1
0
 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();
         }
     }
 }
 /**
  * getMonthlyPrepayments 
  * Takes a contract and determines how many payments have already
  * been made against charges assigned to this contract.  Payments
  * are grouped by calendar month.
  * 
  * @param Contract $contract 
  * @access public
  * @return void
  */
 public function getMonthlyPrepayments(Contract $contract, $contractStartDate = null)
 {
     // Initialize an array of $contract->getDeferralDurationMonths() buckets, indexed by month
     for ($j = 0; $j < $contract->getDeferralDurationMonths(); $j++) {
         $bucketDate = clone $contractStartDate;
         // $bucketDate = clone $contract->getContractStartDate();
         $bucketDate->add(new \DateInterval('P' . $j . 'M'));
         $buckets[$bucketDate->format('Y-m')] = 0;
     }
     // Query journal table to determine how much has already been realized by this contract?
     $conn = $this->getDoctrine()->getConnection();
     $stmt = $conn->prepare('select date_format(j.journal_date, "%m") as dmonth, year(j.journal_date) as dyear, sum(j.credit_amount) as damount from tsk_journal j inner join tsk_contract_charge cc where j.fk_credit_account_id=:credit_account_id AND cc.fk_contract_id=:contract_id and j.fk_charge_id=cc.fk_charge_id group by date_format(j.journal_date, "%m"), year(j.journal_date)');
     $stmt->bindValue(':credit_account_id', 4);
     $stmt->bindValue(':contract_id', $contract->getId());
     $stmt->execute();
     $prepayments = $stmt->fetchAll();
     // Add prepayments to buckets
     foreach ($prepayments as $pp) {
         $buckets[$pp['dyear'] . '-' . $pp['dmonth']] += $pp['damount'];
     }
     // Index bucket array by ints instead of months
     foreach ($buckets as $month => $bucketAmount) {
         $inits[] = $bucketAmount;
     }
     return $inits;
 }
 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);
 }
 /**
  * @Route("/admin/contract/view/{id}", name="tsk_contract_default_view", defaults={"_format" = "html" })
  * @Template()
  */
 public function viewAction(Contract $contract)
 {
     $em = $this->getDoctrine()->getEntityManager();
     $doc = $contract->getLatestContractDoc();
     $paymentTermsJSON = $doc->getPaymentTerms();
     // ld($paymentTermsJSON);
     $paymentTerms = json_decode($paymentTermsJSON['paymentsData']);
     // $paymentTerms = new \StdClass();
     // foreach ($paymentTermsJSON as $k => $v) {
     //     $paymentTerms->$k = $v;
     // }
     $s = new String();
     $installments = $s->stringifyPayments($paymentTerms->payments);
     // Get contract school and school state
     // $school = $doc->getSchool();
     $contractTemplate = $contract->getProgram()->getMembershipType()->getContractTemplate();
     if ($contractTemplate) {
         $template = $contractTemplate->getTemplate();
         $orgId = $this->get('session')->get('tsk_organization_id');
         $orgRepo = $em->getRepository('TSK\\UserBundle\\Entity\\Organization');
         $org = $orgRepo->find($orgId);
         $stringRenderer = $this->get('tsk.twig.string');
         $output = $stringRenderer->render($template, array('contractAmount' => $paymentTerms->principal, 'contractDiscount' => !empty($paymentTerms->discount) ? $paymentTerms->discount : '', 'contractPayments' => $paymentTerms->payments, 'contractNumPayments' => count($paymentTerms->payments), 'schoolLegalName' => $doc->getSchoolLegalName(), 'schoolAddress1' => $doc->getSchoolAddress1(), 'schoolAddress2' => $doc->getSchoolAddress2(), 'schoolCity' => $doc->getSchoolCity(), 'schoolState' => $doc->getSchoolState(), 'schoolPostalCode' => $doc->getSchoolPostalCode(), 'schoolPhone' => $doc->getSchoolPhone(), 'schoolLateGraceDays' => $doc->getSchoolLateGraceDays(), 'schoolLatePaymentCharge' => $doc->getSchoolLatePaymentCharge(), 'programLegalDescription' => $doc->getProgramLegalDescription(), 'org' => $org, 'orgName' => $org->getTitle(), 'abbrOrgName' => $org->getTitle(), 'blackBeltFee' => 495, 'student' => $doc->getStudents(), 'installments' => '$installments'));
         // $xml = $response->getContent();
         $response = new Response();
         $facade = $this->get('ps_pdf.facade');
         $content = $facade->render($output);
         return new Response($content, 200, array('content-type' => 'application/pdf'));
         exit;
     }
     $refundPolicy = $this->generateRefundPolicy($student->getContracts()->count(), $school->getContact()->getState()->getStateName(), $latestContract->getAmount());
     $cancelPolicy = $this->generateCancelPolicy($school->getContact()->getState()->getStateName());
     $format = $this->get('request')->get('_format');
     return $this->render('TSKContractBundle:Default:index.pdf.twig', array('contract' => $latestContract, 'school' => $school, 'orgName' => "Tiger Schulmann's Mixed Martial Arts Center", 'abbrOrgName' => 'TSMMA', 'blackBeltFee' => 495, 'student' => $student, 'refundPolicy' => $refundPolicy, 'cancelPolicy' => $cancelPolicy, 'installments' => $installments));
 }