/**
  * Helper function for generating possessions summary HTML fragment
  *
  * @return string
  * @munt 10 HTML in strings? REALLY? That's what partials are for. Also in-line styles. Seriously. I'm going grey because of this!! - PB
  */
 public function yourPossessions()
 {
     $output = '';
     $pageSession = new Zend_Session_Namespace('tenants_insurance_quote');
     $possession = new Datasource_Insurance_Policy_SpecPossessions($pageSession->PolicyNumber);
     $possessionsData = $possession->listPossessions();
     if (count($possessionsData) > 0) {
         $output .= '<table class="table table-bordered table-condensed table-possessions">';
         $output .= '<thead>';
         $output .= '  <tr>';
         $output .= '    <th>Items you have added to your policy</th>';
         $output .= '    <th colspan="2">Value</th>';
         $output .= '  </tr>';
         $output .= '</thead>';
         $output .= '<tbody>';
         foreach ($possessionsData as $key => $possession) {
             $output .= '  <tr>';
             // Line container with bottom edge
             $output .= "    <td class='description'>{$possession['category']} - Description: {$possession['description']}</td>";
             $output .= "    <td class='price'>&pound;" . number_format(doubleval($possession['value']), 2) . "</td>";
             $output .= "    <td><a id=\"removePossession{$key}\" onclick=\"removePossessionClick('{$key}'); return false;\" class=\"tertiary-colour\" href=\"#\">Remove item</a></td>";
             $output .= "  </tr>";
         }
         $output .= '</tbody>';
         $output .= "</table>";
     }
     return $output;
 }
Esempio n. 2
0
 /**
  * Create possessions subform
  *
  * @return void
  */
 public function init()
 {
     $params = Zend_Registry::get('params');
     $pageSession = new Zend_Session_Namespace('tenants_insurance_quote');
     $possession = new Datasource_Insurance_Policy_SpecPossessions($pageSession->PolicyNumber);
     $maximumReached = $possession->countPossessions() == $possession->maxPossessions;
     if (isset($pageSession->CustomerRefNo)) {
         $customerManager = new Manager_Core_Customer();
         $customer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $pageSession->CustomerRefNo);
         switch ($customer->getTitle('title')) {
             case 'Mr':
             case 'Sir':
                 $this->gender = 'male';
                 break;
             case 'Mrs':
             case 'Ms':
             case 'Miss':
                 $this->gender = 'female';
                 break;
             default:
                 $this->gender = 'unknown';
                 break;
         }
     }
     // Add taking items from house element
     $this->addElement('radio', 'away_from_home', array('label' => 'Would you like to cover your belongings that you take away from the home?', 'required' => true, 'multiOptions' => array('yes' => 'Yes', 'no' => 'No'), 'separator' => '', 'label_placement' => 'prepend', 'validators' => array(array('NotEmpty', true, array('messages' => array('isEmpty' => 'Please select whether you take items away from the home', 'notEmptyInvalid' => 'Please select whether you take items away from the home'))))));
     // Add possessions cover select element
     $this->addElement('select', 'possessions_cover', array('label' => 'Cover level', 'required' => false, 'multiOptions' => array('' => '--- please select ---', '1000' => html_entity_decode('&pound;', ENT_COMPAT, 'UTF-8') . '1000', '2000' => html_entity_decode('&pound;', ENT_COMPAT, 'UTF-8') . '2000', '4000' => html_entity_decode('&pound;', ENT_COMPAT, 'UTF-8') . '4000', '6000' => html_entity_decode('&pound;', ENT_COMPAT, 'UTF-8') . '6000'), 'validators' => array(array('NotEmpty', true, array('messages' => array('isEmpty' => 'Please select a level of cover', 'notEmptyInvalid' => 'Please select a level of cover')))), 'attribs' => array('class' => 'form-control')));
     // Add above x amount element
     $this->addElement('radio', 'above_x', array('label' => 'Would you like to cover any individual items that can be taken out and about that are worth more than &pound;1,000?', 'required' => true, 'multiOptions' => array('yes' => 'Yes', 'no' => 'No'), 'separator' => '', 'label_placement' => 'prepend', 'validators' => array(array('NotEmpty', true, array('messages' => array('isEmpty' => 'Please select if you would like to cover any individual items with a value of more than &pound;1,000', 'notEmptyInvalid' => 'Please select if you would like to cover any individual items with a value of more than &pound;1,000'))))));
     // Add possessions cover select element
     $this->addElement('select', 'possession_categoryId', array('label' => 'Category', 'required' => false, 'multiOptions' => $possession->listCategories(), 'validators' => array(array('NotEmpty', true, array('messages' => array('isEmpty' => 'Please select a category', 'notEmptyInvalid' => 'Please select a category')))), 'attribs' => array('class' => 'form-control')));
     // Add fields for new possession types and values (the visible fields associated with the "Add possession" button)
     $this->addElement('text', 'possession_description', array('required' => false, 'filters' => array('StringTrim'), 'validators' => array(array('NotEmpty', true, array('messages' => array('isEmpty' => 'Please enter a description of the possession', 'notEmptyInvalid' => 'Please enter a description of the possession'))), array('regex', true, array('pattern' => '/^[0-9a-z\\ \\-\\,\\(\\)\\.\']{3,}$/i', 'messages' => 'Possession description must contain at least three alphanumeric characters and only basic punctuation (space, hyphen, comma, round brackets, full stop and single quote)'))), 'attribs' => array('data-validate' => 'validate', 'data-required' => 'required', 'class' => 'form-control')));
     $this->addElement('text', 'possession_value', array('label' => "Item value", 'required' => false, 'validators' => array(array('NotEmpty', true, array('messages' => array('isEmpty' => 'Please enter the value of the possession', 'notEmptyInvalid' => 'Please enter the value of the possession'))), array('GreaterThan', true, array('min' => $params->uw->mv->tenantsp->specPossession, 'messages' => 'Possession value must be above &pound;1,000'))), 'attribs' => array('data-required' => 'required', 'data-validate' => 'validate', 'data-type' => 'currency', 'class' => 'form-control')));
     // Add a filter suitable for currency input - this strips anything non-digit and non-decimal point such as pound
     //   symbols and commas
     $possessionValue = $this->getElement('possession_value');
     $possessionValue->addFilter('callback', function ($v) {
         return preg_replace('/[^\\d\\.]/', '', $v);
     });
     if ($maximumReached) {
         // Disable the possessions entry forms
         $this->possession_description->setAttrib('disabled', 'disabled');
         $this->possession_jewellery->setAttrib('disabled', 'disabled');
         $this->possession_value->setAttrib('disabled', 'disabled');
     }
     // Set custom subform decorator
     $this->setDecorators(array(array('ViewScript', array('viewScript' => 'subforms/possessions.phtml'))));
     // Strip all tags to prevent XSS errors - done iteratively so not to overwrite any existing filters
     foreach ($this->getElements() as $element) {
         $element->addFilter('StripTags');
     }
     $this->setElementDecorators(array(array('ViewHelper', array('escape' => false)), array('Label', array('escape' => false))));
     $view = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');
     $view->headScript()->appendFile('/assets/tenants-insurance-quote/js/possessions.js', 'text/javascript');
 }
 /**
  * Helper function for generating view breakdown HTML fragment
  *
  * @param bool $showAdminFees Optional switch to include admin fees, defaults to false
  *
  * @return string
  */
 public function viewBreakdown($includeAdminFees = true)
 {
     // Get customer ref no and policy number
     $pageSession = new Zend_Session_Namespace('tenants_insurance_quote');
     $this->_customerReferenceNumber = $pageSession->CustomerRefNo;
     $this->_policyNumber = $pageSession->PolicyNumber;
     // Get premium values for quote
     $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
     $premiums = $quoteManager->calculatePremiums();
     $this->view->premiums = $premiums;
     // Get cover amounts
     $this->view->contentsCoverAmount = $quoteManager->getCoverAmount(Manager_Insurance_TenantsContentsPlus_Quote::CONTENTS);
     $this->view->bicyclesCoverAmount = $quoteManager->getCoverAmount(Manager_Insurance_TenantsContentsPlus_Quote::PEDALCYCLES);
     $this->view->specifiedPossessionsCoverAmount = $quoteManager->getCoverAmount(Manager_Insurance_TenantsContentsPlus_Quote::SPECIFIEDPOSSESSIONS);
     $this->view->unspecifiedPossessionsCoverAmount = $quoteManager->getCoverAmount(Manager_Insurance_TenantsContentsPlus_Quote::UNSPECIFIEDPOSSESSIONS);
     // Get any sharer occupation details
     $sharersManager = new Manager_Insurance_TenantsContentsPlus_Sharers();
     $sharerData = $sharersManager->getSharers($this->_policyNumber);
     $this->view->sharer1 = !is_null($sharerData) ? $sharerData->getSharerOccupation(1) : '';
     $this->view->sharer2 = !is_null($sharerData) ? $sharerData->getSharerOccupation(2) : '';
     // Get specified possessions info
     $possession = new Datasource_Insurance_Policy_SpecPossessions($this->_policyNumber);
     $this->view->possessions = $possession->listPossessions();
     // Get bicycle info
     $bike = new Datasource_Insurance_Policy_Cycles($this->_customerReferenceNumber, $this->_policyNumber);
     $this->view->bicycles = $bike->listBikes();
     // Get Current IPT percentage
     $quote = $quoteManager->getQuoteObject();
     $postcode = $quote->propertyPostcode;
     $taxDatasource = new Datasource_Core_Tax();
     $tax = $taxDatasource->getTaxbyTypeAndPostcode('ipt', $postcode);
     $ipt = 1 + $tax['rate'];
     // Get admin fees, if required
     if ($includeAdminFees) {
         $fees = $quoteManager->getFees();
         $this->view->feeMonthly = $fees->tenantspMonthlyFee;
         $this->view->feeAnnual = 0;
         // TODO: parameterise?  Legacy DB and fee object currently don't handle annual fees
     } else {
         $this->view->feeMonthly = 0;
         $this->view->feeAnnual = 0;
     }
     $this->view->includeAdminFees = $includeAdminFees;
     // Return partial view HTML
     return $this->view->partial('partials/view-breakdown.phtml', $this->view);
 }
 /**
  * Helper function to populate the zend form elements with database data
  *
  * @param Zend_Form $pageForm form definition for this step
  * @param int $stepNum current step number
  *
  * @return void
  */
 private function _formStepCommonPopulate($pageForm, $stepNum)
 {
     $pageSession = new Zend_Session_Namespace('tenants_insurance_quote');
     // First of all check that this form should be viewable and the user isn't trying to skip ahead
     $this->view->stepNum = $stepNum;
     $this->view->stepMax = $this->_stepMax;
     // Check to see if the user is trying to skip ahead in the quote
     $tooFarAhead = false;
     if ((!isset($pageSession->completed) || is_null($pageSession->completed)) && $stepNum != 1) {
         $tooFarAhead = true;
         $lastCompleted = 1;
     } elseif ($stepNum > 1) {
         // Check to see if any pages previous to the one the user's trying to get to are incomplete
         $tooFarAhead = false;
         for ($i = 1; $i < $stepNum; $i++) {
             if (!isset($pageSession->completed[$i]) || !$pageSession->completed[$i]) {
                 $tooFarAhead = true;
                 $lastCompleted = $i;
                 break;
                 break;
             }
         }
     }
     if ($tooFarAhead) {
         // Drop user onto page that needs completing
         $this->_helper->redirector->gotoUrl('/tenants/insurance-quote-b/step' . $lastCompleted);
         return false;
     }
     // Now check to see if they need to login (using an existing email address without being logged in)
     if ($stepNum > 1) {
         // Before we do ANYTHING we need to check to see if the email address entered matches a customer record
         // we already have - if it does we need to ask them to login before they proceed.
         $customerReferenceNumber = $pageSession->CustomerRefNo;
         $customerManager = new Manager_Core_Customer();
         $legacyCustomer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $customerReferenceNumber);
         $emailAddress = $legacyCustomer->getEmailAddress();
         $customer = $customerManager->getCustomerByEmailAddress($emailAddress);
         if ($customer) {
             // There is already a customer entry for this email address - so we need to see if they are logged in
             // if not we need to force them to login
             $auth = Zend_Auth::getInstance();
             $auth->setStorage(new Zend_Auth_Storage_Session('homelet_customer'));
             /*if ($auth->hasIdentity()) {
             					$loggedInEmail = $auth->getStorage()->read()->email_address;
             					if ($loggedInEmail != $customer->getEmailAddress()) {
             						// They are logged in but not who they should be to do this quote
             						$this->_helper->redirector->gotoUrl('/account/login?refer=tenants-insurance&step='. $stepNum);
             
             						return false;
             					}
             				} else {
             					// They aren't logged in and need to
             					$this->_helper->redirector->gotoUrl('/account/login?refer=tenants-insurance&step='. $stepNum);
             
             					return false;
             				}*/
         }
     }
     // Echo out some debug info if not in production mode
     Application_Core_Logger::log("Policy Number : " . $this->_policyNumber);
     Application_Core_Logger::log("Customer Ref No : " . $this->_customerReferenceNumber);
     Application_Core_Logger::log("agentSchemeNumber : " . $this->_agentSchemeNumber);
     $formData = array();
     // If step 1 and not in session (so producing a quick quote) - we need to pre-populate
     // a few bits if the customer is already logged into the site
     if ($stepNum == 1 && !isset($pageSession->CustomerRefNo)) {
         $auth = Zend_Auth::getInstance();
         $auth->setStorage(new Zend_Auth_Storage_Session('homelet_customer'));
         if ($auth->hasIdentity()) {
             // Customer is logged in and starting a new quote - so we need to pre-populate the customers details from stored details
             $customerID = $auth->getStorage()->read()->id;
             $customerManager = new Manager_Core_Customer();
             $customer = $customerManager->getCustomer(Model_Core_Customer::IDENTIFIER, $customerID);
             // Get the customer's legacy record too as DoB is only in the old system
             $legacyCustomer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $customerID);
             $formData['title'] = $customer->getTitle();
             $formData['first_name'] = $customer->getFirstName();
             $formData['last_name'] = $customer->getLastName();
             $formData['phone_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE1);
             $formData['mobile_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE2);
             $formData['email_address'] = $customer->getEmailAddress();
             // Fetch DoB from old customer manager
             $formData['date_of_birth_at'] = $legacyCustomer->getDateOfBirth();
             $pageForm->populate($formData);
         }
     }
     // Only populate from DB if we are in session and have a reference number
     if (isset($pageSession->CustomerRefNo)) {
         $customerReferenceNumber = $pageSession->CustomerRefNo;
         $policyNumber = $pageSession->PolicyNumber;
         // Populate $formData with data from model, if available
         switch ($stepNum) {
             case 1:
                 // Personal Details section
                 $customerManager = new Manager_Core_Customer();
                 $customer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $customerReferenceNumber);
                 $titleOptions = TenantsInsuranceQuoteB_Form_Subforms_PersonalDetails::$titles;
                 if (in_array($customer->getTitle(), $titleOptions)) {
                     $formData['title'] = $customer->getTitle();
                 } else {
                     $formData['title'] = "Other";
                     $formData['other_title'] = $customer->getTitle();
                 }
                 $formData['first_name'] = $customer->getFirstName();
                 $formData['last_name'] = $customer->getLastName();
                 $formData['phone_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE1);
                 $formData['mobile_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE2);
                 $formData['email_address'] = $customer->getEmailAddress();
                 $dob = $customer->getDateOfBirthAt();
                 if (null != $dob && '0000-00-00' != $dob) {
                     $formData['date_of_birth_at'] = Application_Core_Utilities::mysqlDateToUk($dob);
                 }
                 // Data Protection section
                 $dpaManager = new Manager_Core_DataProtection();
                 $dpaItems = $dpaManager->getItems($customerReferenceNumber, Model_Core_DataProtection_ItemEntityTypes::INSURANCE);
                 foreach ($dpaItems as $currentItem) {
                     switch ($currentItem->constraintTypeId) {
                         case Model_Core_DataProtection_ItemConstraintTypes::MARKETING_BY_PHONEANDPOST:
                             if ($currentItem->isAllowed) {
                                 $formData['dpa_phone_post'] = 0;
                             } else {
                                 $formData['dpa_phone_post'] = 1;
                             }
                             break;
                         case Model_Core_DataProtection_ItemConstraintTypes::MARKETING_BY_SMSANDEMAIL:
                             if ($currentItem->isAllowed) {
                                 $formData['dpa_sms_email'] = 0;
                                 // For Redmine Ref #8003, "Updated marketing preference questions on online quotes"
                             } else {
                                 $formData['dpa_sms_email'] = 1;
                                 // For Redmine Ref #8003, "Updated marketing preference questions on online quotes"
                             }
                             break;
                         case Model_Core_DataProtection_ItemConstraintTypes::MARKETING_BY_THIRDPARTY:
                             if ($currentItem->isAllowed) {
                                 $formData['dpa_resale'] = 1;
                             } else {
                                 $formData['dpa_resale'] = 0;
                             }
                             break;
                     }
                 }
                 // Contents Insurance section
                 $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
                 // If we've retrieved this quote we need to setup some session variables to match the quote (agent scheme number mostly)
                 $session = new Zend_Session_Namespace('homelet_global');
                 $session->agentSchemeNumber = Manager_Core_Agent::filterAsn($quoteManager->getAgentSchemeNumber());
                 $contentsSI = $quoteManager->getCoverAmount(Manager_Insurance_TenantsContentsPlus_Quote::CONTENTS);
                 // TODO: Remove the hard-coded contents insured splits - should be loaded from DB
                 if ($contentsSI == '5000' || $contentsSI == '7500' || $contentsSI == '10000' || $contentsSI == '15000') {
                     $formData['contents_cover_a'] = $contentsSI;
                 } else {
                     $formData['contents_cover_a'] = '15000+';
                     $formData['contents_cover_b'] = $contentsSI;
                 }
                 // Shares section
                 $sharersManager = new Manager_Insurance_TenantsContentsPlus_Sharers();
                 $existingSharers = $sharersManager->getSharers($policyNumber);
                 $formData['policy_sharers'] = 0;
                 if ($existingSharers) {
                     if ($existingSharers->getSharerOccupation(1) != '') {
                         $formData['policy_sharers'] = 1;
                         $formData['policy_sharer1_occupation'] = $existingSharers->getSharerOccupation(1);
                     }
                     if ($existingSharers->getSharerOccupation(2) != '') {
                         $formData['policy_sharers'] = 2;
                         $formData['policy_sharer2_occupation'] = $existingSharers->getSharerOccupation(2);
                     }
                 }
                 for ($i = 1; $i <= $pageForm->maxSharers; $i++) {
                     $formData["policy_sharer{$i}_occupation"] = $existingSharers->getSharerOccupation($i);
                 }
                 // Decide max number of sharers allowed based on contents insured value
                 $contentsAmount = new Zend_Currency(array('value' => $contentsSI, 'precision' => 0));
                 $sharersAllowed = $sharersManager->getNoOfSharersAllowed($contentsAmount);
                 // Push this into Javascript on the page
                 $this->view->headScript()->appendScript("var sharersAllowed = {$sharersAllowed};");
                 // Initial Disclosure Agreement section
                 // As we have a customer reference number they must have saved step 1 at some point which means
                 // they must have agreed to the IDD section
                 $formData['idd'] = 1;
                 break;
             case 2:
                 // Unspecified Possessions section
                 $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
                 $unspecSI = $quoteManager->getCoverAmount(Manager_Insurance_TenantsContentsPlus_Quote::UNSPECIFIEDPOSSESSIONS);
                 // If step has been completed before we can assume some defaults that we'll over-write later
                 if (isset($pageSession->completed[2]) && $pageSession->completed[2] == true or $quoteManager->getPropertyPostcode() != '') {
                     $formData['away_from_home'] = 'no';
                     $formData['above_x'] = 'no';
                     $formData['bicycle'] = 'no';
                 }
                 // TODO: Re-factor this so that it doesn't use hardcoded pricing breaks anymore
                 if ($unspecSI > 0) {
                     $formData['away_from_home'] = 'yes';
                     $formData['possessions_cover'] = $unspecSI;
                 }
                 //TODO: This should be talking to the quote manager NOT directly to the datasource
                 $possessions = new Datasource_Insurance_Policy_SpecPossessions($pageSession->PolicyNumber);
                 if ($possessions->countPossessions() > 0) {
                     $formData['above_x'] = 'yes';
                 }
                 // Bicycle section
                 //TODO: This should be talking to the quote manager NOT directly to the datasource
                 $bicycle = new Datasource_Insurance_Policy_Cycles($this->_customerReferenceNumber, $this->_policyNumber);
                 if ($bicycle->countBikes() > 0) {
                     $formData['bicycle'] = 'yes';
                 }
                 break;
             case 3:
                 // Insured Address section
                 // Fetch previously stored address
                 $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
                 $addressArray = $quoteManager->getPropertyAddress();
                 if ($addressArray['postcode'] != '') {
                     if (strpos($addressArray['address1'], ',') !== false) {
                         $formData['ins_house_number_name'] = preg_replace('/,.*$/', '', $addressArray['address1']);
                     } else {
                         $formData['ins_house_number_name'] = preg_replace('/ .*$/', '', $addressArray['address1']);
                     }
                     $formData['ins_postcode'] = $addressArray['postcode'];
                     // Look up address again to populate dropdown
                     $postcodeLookup = new Manager_Core_Postcode();
                     $addresses = $postcodeLookup->getPropertiesByPostcode(preg_replace('/[^\\w\\ ]/', '', $formData['ins_postcode']));
                     $addressList = array('' => '--- please select ---');
                     $filterString = is_numeric($formData['ins_house_number_name']) ? $formData['ins_house_number_name'] . ", " : $formData['ins_house_number_name'];
                     foreach ($addresses as $address) {
                         $addressList[$address['id']] = $address['singleLineWithoutPostcode'];
                         if (stripos($address['singleLineWithoutPostcode'], $filterString) === 0) {
                             $addressID = $address['id'];
                         }
                     }
                     // Add some validation
                     $ins_address = $pageForm->getSubForm('subform_insuredaddress')->getElement('ins_address');
                     $ins_address->setMultiOptions($addressList);
                     $validator = new Zend_Validate_InArray(array('haystack' => array_keys($addressList)));
                     $validator->setMessages(array(Zend_Validate_InArray::NOT_IN_ARRAY => 'Insured address does not match with postcode'));
                     $ins_address->addValidator($validator, true);
                     // Set the address to selected
                     $ins_address->setValue($addressID);
                     $addressID = null;
                     // Make sure we don't use this again for the correspondance address!
                     // Upsell Message section
                     $pageSession = new Zend_Session_Namespace('tenants_insurance_quote');
                     $session = new Zend_Session_Namespace('homelet_global');
                     $agentSchemeNumber = $session->agentSchemeNumber;
                 }
                 // Correspondance Address section
                 $customerManager = new Manager_Core_Customer();
                 $customer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $this->_customerReferenceNumber);
                 $addressLine1 = $customer->getAddressLine(Model_Core_Customer::ADDRESSLINE1);
                 $addressPostcode = $customer->getPostCode();
                 if ($addressPostcode != '') {
                     if (strpos($addressLine1, ',') !== false) {
                         $formData['cor_house_number_name'] = preg_replace('/,.*$/', '', $addressLine1);
                     } else {
                         $formData['cor_house_number_name'] = preg_replace('/ .*$/', '', $addressLine1);
                     }
                     $formData['cor_postcode'] = $addressPostcode;
                     // TODO: Surely if this postcode and house number matches the previous one
                     // we can just tick the YES box and hide the correspondance address form??
                     $postcodeLookup = new Manager_Core_Postcode();
                     $addresses = $postcodeLookup->getPropertiesByPostcode(preg_replace('/[^\\w\\ ]/', '', $formData['cor_postcode']));
                     $addressList = array('' => '--- please select ---');
                     $filterString = is_numeric($formData['cor_house_number_name']) ? $formData['cor_house_number_name'] . ", " : $formData['cor_house_number_name'];
                     foreach ($addresses as $address) {
                         $addressList[$address['id']] = $address['singleLineWithoutPostcode'];
                         if (stripos($address['singleLineWithoutPostcode'], $filterString) === 0) {
                             $addressID = $address['id'];
                         }
                     }
                     $cor_address = $pageForm->getSubForm('subform_correspondencedetails')->getElement('cor_address');
                     $cor_address->setMultiOptions($addressList);
                     $validator = new Zend_Validate_InArray(array('haystack' => array_keys($addressList)));
                     $validator->setMessages(array(Zend_Validate_InArray::NOT_IN_ARRAY => 'Insured address does not match with postcode'));
                     $cor_address->addValidator($validator, true);
                     $cor_address->setValue($addressID);
                 }
                 if ($addressPostcode != '' && $addressArray['postcode'] != '') {
                     if ($cor_address->getValue() == $ins_address->getValue()) {
                         $formData['cor_same_address'] = 'yes';
                     } else {
                         $formData['cor_same_address'] = 'no';
                     }
                 }
                 // Letting Agent section
                 // If the agent scheme number is not our default one - load the agent details
                 $params = Zend_Registry::get('params');
                 $agentSchemeNumber = Manager_Core_Agent::filterAsn($quoteManager->getAgentSchemeNumber());
                 // How did you hear about us section
                 $marketQuestion = new Manager_Core_ManagementInformation();
                 $formData['how_hear'] = $marketQuestion->getMarketingAnswers($this->_policyNumber);
                 //Campaign code section
                 $webLeadManager = new Manager_Core_WebLead();
                 $webLeadSummary = $webLeadManager->getSummary($this->_webLeadSummaryId);
                 $formData['campaign_code'] = $webLeadSummary->promotionCode;
                 // Start and end date
                 $startDate = $quoteManager->getStartDate();
                 if ($startDate != '' && $startDate != '0000-00-00') {
                     $formData['policy_start'] = substr($startDate, 8, 2) . '/' . substr($startDate, 5, 2) . '/' . substr($startDate, 0, 4);
                 }
                 break;
             case 4:
                 // Important Information section
                 // If this page has previously passed validation, we know what the answers
                 //   given must have been without hitting the DB (as anything else refers)
                 if (isset($pageSession->completed[$stepNum]) && $pageSession->completed[$stepNum]) {
                     $formData['declaration1'] = 'no';
                     $formData['declaration2'] = 'no';
                     $formData['declaration3'] = 'no';
                     $formData['declaration4'] = 'no';
                     $formData['declaration_confirmation'] = 'yes';
                     // If the step is completed we can also assume they said yes to the declaration agreement
                     $formData['declaration_statement'] = 1;
                 }
                 break;
             case 5:
                 // Not sure if we should really be loading payment methods back in
                 // surely it would be best to just let them choose again
                 break;
             case 'dd':
                 $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
                 $this->view->payMonthly = strtolower($quoteManager->getPayBy()) == 'monthly';
                 break;
         }
         $pageForm->populate($formData);
         // Populate the quick quote box
         $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
         $premiums = $quoteManager->calculatePremiums();
         $fees = $quoteManager->getFees();
         $this->view->premiums = $premiums;
         $this->view->fees = $fees;
     } else {
         // Not in session but there are some defaults we need to set for step 1
         // TODO: Write the javascript better so we don't need to do fudges like this
         $this->view->headScript()->appendScript("var sharersAllowed = 0;");
     }
     return true;
 }
 /**
  * Validate and handle adding and removing possessions via AJAX
  *
  * @return void
  */
 public function possessionAction()
 {
     $output = array();
     $pageSession = new Zend_Session_Namespace('tenants_insurance_quote');
     // TODO: This needs to stop using datasources directly and use the quote manager
     // Add the bikes details to the database
     $possession = new Datasource_Insurance_Policy_SpecPossessions($pageSession->PolicyNumber);
     $ajaxForm = new TenantsInsuranceQuote_Form_Json_Possessions();
     // Ignore 'away_from_home' and 'above_x' fields for AJAX requests
     $ajaxForm->subform_possessions->getElement('away_from_home')->setRequired(false);
     $ajaxForm->subform_possessions->getElement('above_x')->setRequired(false);
     $request = $this->getRequest();
     $postdata = $request->getPost();
     // Filter to mirror the subform element definitions.
     $currencyFilterElements = array('possession_value');
     foreach ($currencyFilterElements as $filterElement) {
         if (isset($postdata[$filterElement])) {
             $postdata[$filterElement] = preg_replace(array('/[^\\d\\.]/'), array(''), $postdata[$filterElement]);
         }
     }
     // Force the elements to be required as this is an add item click - ugly :(
     if (isset($postdata['addPossession']) && $postdata['addPossession'] == 1) {
         $ajaxForm->subform_possessions->getElement('possession_categoryId')->setRequired(true);
         $ajaxForm->subform_possessions->getElement('possession_description')->setRequired(true);
         $ajaxForm->subform_possessions->getElement('possession_value')->setRequired(true);
     }
     $ajaxForm->populate($postdata);
     $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $pageSession->PolicyNumber);
     if ($ajaxForm->isValid($postdata)) {
         // Check if a new possession's details are being added and possessions is below max
         if (isset($postdata['addPossession']) && $postdata['addPossession'] == 1) {
             $cleanData = $ajaxForm->getValues();
             // According to the Zend manual these *should* be the clean values
             $possession->addNew($cleanData['subform_possessions']);
         }
         // Check if an existing possession's details are being removed
         if (isset($postdata['removePossession']) && $postdata['removePossession'] == 1) {
             $possession->remove($postdata['possessionNum']);
         }
         $totalValue = $possession->getTotalValue();
         // Now we need to update the total amounts covered in the quote manager
         $quoteManager->setCoverAmount($totalValue, Manager_Insurance_TenantsContentsPlus_Quote::SPECIFIEDPOSSESSIONS);
     }
     $errorMessages = $ajaxForm->getMessagesFlattened();
     $output['errorJs'] = $errorMessages;
     $output['errorCount'] = count($errorMessages);
     $output['errorHtml'] = $this->view->partial('partials/error-list.phtml', array('errors' => $errorMessages));
     // Tell page if max possessions reached
     $output['disableAdd'] = $possession->countPossessions() == $possession->maxPossessions ? 1 : 0;
     $output['html'] = $this->view->getHelper('yourPossessions')->yourPossessions();
     $premiums = $quoteManager->calculatePremiums();
     $fees = $quoteManager->getFees();
     $output['premiums'] = $premiums;
     $output['fees'] = $fees;
     echo Zend_Json::encode($output);
 }
Esempio n. 6
0
 /**
  * Implements abstract method from superclass - refer to superclass for description.
  */
 public function getReferralReasons($policyNumber)
 {
     $referralReasons = array();
     $params = Zend_Registry::get('params');
     $quote = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $policyNumber);
     if ($quote->getPolicyName() == 'tenantsp') {
         //Test 1: If the cover is greater than the threshold, then refer.
         $contentsAmount = $quote->getPolicyOptionAmountCovered('contentstp');
         $contentsThreshold = new Zend_Currency(array('value' => $params->uw->rt->tenantsp->contents, 'precision' => 0));
         if ($contentsAmount >= $contentsThreshold) {
             $referralReasons[] = $params->uw->rr->tenantsp->cover;
         }
         //Test 2: If claim values are greater than 1000 then refer.
         if (empty($this->_previousClaimsModel)) {
             $this->_previousClaimsModel = new Datasource_Insurance_PreviousClaims();
         }
         $previousClaimsArray = $this->_previousClaimsModel->getPreviousClaims($quote->getRefno());
         if (!empty($previousClaimsArray)) {
             //Tenant has one or more claims. Add the totals together to see if they exceed
             //the threshold.
             $claimsTotal = new Zend_Currency(array('value' => 0, 'precision' => 2));
             foreach ($previousClaimsArray as $previousClaim) {
                 $claimsTotal->add($previousClaim->getClaimValue());
             }
             //Test against the previous claims threshold
             $claimsThreshold = new Zend_Currency(array('value' => $params->uw->rt->tenantsp->claimsThreshold, 'precision' => 2));
             if ($claimsTotal->isMore($claimsThreshold)) {
                 $referralReasons[] = $params->uw->rr->tenantsp->previousClaims;
             }
         }
         //Test 3: Answering the underwriting questions.
         $answersManager = new Manager_Insurance_Answers();
         $answersArray = $answersManager->getUnderwritingAnswers($policyNumber);
         if (empty($answersArray)) {
             //You can't process for referral if no underwriting answers have first been provided.
             throw new Zend_Exception(get_class() . __FUNCTION__ . ": no underwriting answers provided.");
         }
         foreach ($answersArray as $currentAnswer) {
             //Identify if the current answer is one that should be checked.
             if (in_array($currentAnswer->getQuestionNumber(), $params->uw->rt->tenantsp->checkAnswer->toArray())) {
                 $answer = $currentAnswer->getAnswer();
                 if ($answer == Model_Insurance_Answer::YES) {
                     $referralReasons[] = $params->uw->rr->tenantsp->answer;
                 }
             }
         }
         //Test 4: pedal cycles over 1500
         $pedalCyclesModel = new Datasource_Insurance_Policy_Cycles($quote->getRefno(), $policyNumber);
         $pedalCyclesArray = $pedalCyclesModel->listBikes();
         if (!empty($pedalCyclesArray)) {
             $pedalCycleThreshold = new Zend_Currency(array('value' => $params->uw->rt->tenantsp->pedalCycle, 'precision' => 2));
             foreach ($pedalCyclesArray as $currentPedalCycle) {
                 //Compare the pedal cycle values in Zend_Currency format for simplity.
                 $currentCycleValue = new Zend_Currency(array('value' => $currentPedalCycle['value'], 'precision' => 2));
                 if ($currentCycleValue->isMore($pedalCycleThreshold)) {
                     $referralReasons[] = $params->uw->rr->tenantsp->pedalCycle;
                 }
             }
         }
         //Test 5: specified possessions greater than threshold
         $specPossessionsModel = new Datasource_Insurance_Policy_SpecPossessions($policyNumber);
         $specPossessionsArray = $specPossessionsModel->listPossessions();
         if (!empty($specPossessionsArray)) {
             //Wrap the threshold parameter in a Zend_Currency object for easier comparisons.
             $specPossessionThreshold = new Zend_Currency(array('value' => $params->uw->rt->tenantsp->specPossession, 'precision' => 2));
             //Cycle through each specpossession...
             foreach ($specPossessionsArray as $currentSpecPossession) {
                 //Wrap the current specpossession value in a Zend_Currency for easier comparision.
                 $currentSpecPossessionValue = new Zend_Currency(array('value' => $currentSpecPossession['value'], 'precision' => 2));
                 //Determine if the threshold is exceeded:
                 if ($currentSpecPossessionValue->isMore($specPossessionThreshold)) {
                     $referralReasons[] = $params->uw->rr->tenantsp->specPossession;
                 }
             }
         }
     } else {
         throw new Zend_Exception("Invalid product.");
     }
     return $referralReasons;
 }