/**
  * @test
  */
 public function criteria_is_not_satisfied_when_reference_has_adverse_credit()
 {
     $reference = new ReferencingApplication();
     $reference->setHasCCJ(true);
     $rrpReference = new RentRecoveryPlusReference();
     $rrpReference->setParent($reference);
     $this->assertFalse($this->criteria->isSatisfiedBy($rrpReference));
 }
 /**
  * @test
  */
 public function displays_reference_number_after_transformation()
 {
     $transformer = new ReferenceNumberToReferenceObjectTransformer($this->mockDecisionDetailsRetriever, $this->mockSessionHolder, $this->mockRentRecoveryPlusReference);
     $parentReference = new ReferencingApplication();
     $parentReference->setReferenceNumber('HLT999');
     $transformedObject = new RentRecoveryPlusReference();
     $transformedObject->setParent($parentReference);
     $this->assertEquals('HLT999', $transformer->transform($transformedObject));
 }
 /**
  * @test
  */
 public function constraint_is_applied_when_reference_has_expired()
 {
     // The ReferencingApplication object will store the date in milliseconds, so mulitply by 1000 when setting.
     $expiredDate = strtotime('-61 days', time());
     $reference = new ReferencingApplication();
     $reference->setFirstCompletionAt($expiredDate * 1000);
     $mockSessionHolder = $this->getMockBuilder('RRP\\Utility\\SessionReferenceHolder')->disableOriginalConstructor()->setMethods(array('getReferenceFromSession'))->getMock();
     $mockSessionHolder->expects($this->once())->method('getReferenceFromSession')->with('123', '456')->willReturn($reference);
     $constraint = new ReferenceExpiryConstraint($mockSessionHolder);
     $this->assertFalse($constraint->verify('123', array('current_asn' => '456')));
 }
 /**
  * @return array
  */
 public function getIncompleteReferences()
 {
     $incompleteStatuses = array('incomplete' => ApplicationStatuses::INCOMPLETE, 'in_progress' => ApplicationStatuses::IN_PROGRESS, 'awaiting_application_details' => ApplicationStatuses::AWAITING_APPLICATION_DETAILS, 'cancelled' => ApplicationStatuses::CANCELLED, 'declined' => ApplicationStatuses::DECLINED, 'awaiting_agent_review' => ApplicationStatuses::AWAITING_AGENT_REVIEW);
     $references = array();
     foreach ($incompleteStatuses as $key => $incompleteStatus) {
         $reference = new ReferencingApplication();
         $reference->setStatus($incompleteStatus);
         $rrpReference = new RentRecoveryPlusReference();
         $rrpReference->setParent($reference);
         $references[$key] = $rrpReference;
     }
     return array(array($references['incomplete']), array($references['in_progress']), array($references['awaiting_application_details']), array($references['cancelled']), array($references['declined']), array($references['awaiting_agent_review']));
 }
 /**
  * @return array
  */
 public function getUnemployedReferences()
 {
     $unemployedStatuses = array('unemployed' => EmploymentStatuses::UNEMPLOYED, 'independent' => EmploymentStatuses::INDEPENDENT_MEANS, 'contract' => EmploymentStatuses::ON_CONTRACT, 'retired' => EmploymentStatuses::RETIRED, 'student' => EmploymentStatuses::STUDENT, 'self-employed' => EmploymentStatuses::SELF_EMPLOYED);
     $references = array();
     foreach ($unemployedStatuses as $key => $unemployedStatus) {
         $reference = new ReferencingApplication();
         $reference->setEmploymentStatus($unemployedStatus);
         $rrpReference = new RentRecoveryPlusReference();
         $rrpReference->setParent($reference);
         $references[$key] = $rrpReference;
     }
     return array(array($references['unemployed']), array($references['independent']), array($references['contract']), array($references['retired']), array($references['student']), array($references['self-employed']));
 }
 /**
  * Calculate and return number of days between now and the date the reference was completed.
  *
  * @param ReferencingApplication $reference
  * @return int
  */
 private function calculateDaysSinceCompletion(ReferencingApplication $reference)
 {
     // Millisecond timestamp of the date completed.
     $dateCompletedMilliseconds = $reference->getFirstCompletionAt();
     // Milliseconds to seconds, then into DateTime.
     $dateCompletedTimestamp = $dateCompletedMilliseconds / 1000;
     $dateCompleted = new \DateTime();
     $dateCompleted->setTimestamp($dateCompletedTimestamp);
     // Now DateTime.
     $now = new \DateTime();
     $now->setTimestamp(time());
     // Return the difference between the two.
     return $dateCompleted->diff($now)->days;
 }
 /**
  * Put the Reference into the session.
  *
  * @param ReferencingApplication $reference
  * @param $currentAsn
  */
 public function putReferenceInSession(ReferencingApplication $reference, $currentAsn)
 {
     $sessionKey = sprintf('%s.%s', $currentAsn, self::SESSION_KEY_PREFIX);
     // If session already contains an array of references, add to it, otherwise start with an empty array
     $references = array();
     if (false !== $this->session->{$sessionKey}) {
         // Get the current array of references previously added on this form.
         $references = unserialize($this->session->{$sessionKey});
     }
     // Add this new reference to the array, serialize the array up, put it back into the session.
     $key = $reference->getReferenceNumber();
     $references[$key] = $reference;
     $this->session->{$sessionKey} = serialize($references);
 }
 /**
  * Upload missing files to upstream service
  *
  * @param $clientDocuments
  * @param callable $fileDetailCallback
  * @throws DocumentUploader\Exception\InvalidDetailType
  */
 private function addMissing($clientDocuments, Closure $fileDetailCallback)
 {
     //        $upstreamDocuments = $this->clientContext->getDocuments(array(
     //            'referencingApplicationUuId' => $this->application->getReferencingApplicationUuId(),
     //        ));
     // Look for documents in the upload that aren't in IRIS
     // These should be added to IRIS.
     /** @var FormInterface $clientDocument */
     foreach ($clientDocuments as $clientDocument) {
         // Get the uploaded file
         /** @var UploadedFile $uploadedFile */
         $uploadedFileData = $clientDocument->getData();
         $uploadedFile = $uploadedFileData['fileItem'];
         if ($uploadedFile) {
             //                if (!$this->matchUpstreamDocument($uploadedFile->getClientOriginalName(), $upstreamDocuments)) {
             // File not found in IRIS, add the file
             $fileDetail = array();
             if (null !== $fileDetailCallback) {
                 $fileDetailResponse = $fileDetailCallback(array('uploadedFile' => $uploadedFile, 'application' => $this->application));
                 if (null !== $fileDetailResponse && !is_array($fileDetailResponse)) {
                     // Invalid response
                     throw new InvalidDetailType(sprintf('Response of type %s is invalid. Expected null or array.', get_class($fileDetailResponse)));
                 }
                 $fileDetail = $fileDetailResponse;
             }
             $fileName = !empty($fileDetail['uploadedFile']) && is_string($fileDetail['uploadedFile']) ? $fileDetail['uploadedFile'] : $uploadedFile->getClientOriginalName();
             $fileName = rtrim($fileName, $uploadedFile->getClientOriginalExtension());
             $fileName = $this->getSlugifier()->slugify($fileName, '_') . '.' . strtolower($uploadedFile->getClientOriginalExtension());
             $description = !empty($fileDetail['description']) && is_string($fileDetail['description']) ? $fileDetail['description'] : '';
             $this->clientContext->uploadDocument(array('referencingApplicationUuId' => $this->application->getReferencingApplicationUuId(), 'fileName' => $fileName, 'description' => $description, 'file' => $uploadedFile->getPathname(), 'categoryId' => DocumentCategoryOptions::MISCELLANEOUS));
             //                }
         }
     }
 }
 /**
  * Get incomplete references.
  *
  * @return array
  */
 public function getIncompleteReferences()
 {
     $cancelled = new ReferencingApplication();
     $cancelled->setStatus(ApplicationStatuses::CANCELLED);
     $declined = new ReferencingApplication();
     $declined->setStatus(ApplicationStatuses::DECLINED);
     $incomplete = new ReferencingApplication();
     $incomplete->setStatus(ApplicationStatuses::INCOMPLETE);
     $inProgress = new ReferencingApplication();
     $inProgress->setStatus(ApplicationStatuses::IN_PROGRESS);
     $awaitingAgent = new ReferencingApplication();
     $awaitingAgent->setStatus(ApplicationStatuses::AWAITING_AGENT_REVIEW);
     $awaitingDetails = new ReferencingApplication();
     $awaitingDetails->setStatus(ApplicationStatuses::AWAITING_APPLICATION_DETAILS);
     return array(array($cancelled), array($declined), array($incomplete), array($inProgress), array($awaitingAgent), array($awaitingDetails));
 }
 /**
  * @test
  */
 public function an_unacceptable_reference_logs_its_failure_reasons()
 {
     $this->reference->setProductId(ProductIds::INSIGHT)->setStatus(ApplicationStatuses::INCOMPLETE)->setHasCCJ(true)->setEmploymentStatus(EmploymentStatuses::UNEMPLOYED);
     $this->mockCreditReference->expects($this->any())->method('getScore')->willReturn(CreditScoreCriteriaLimits::MINIMUM_INSIGHT_CREDIT_SCORE - 1);
     // The reference has 4 reasons to fail acceptance.
     $this->insightCriteria->isSatisfiedBy($this->mockRrpReference);
     // 4 failing criteria tests should result in 4 logged failure messages.
     $this->assertEquals(4, count($this->insightCriteria->getNotSatisfiedText()));
 }
 /**
  * Handles the persistence of a note (persist & update)
  *
  * @param array $formStepData
  * @param \Barbondev\IRISSDK\IndividualApplication\ReferencingApplication\Model\ReferencingApplication $application
  * @return void
  */
 public function handleNotePersistence(array $formStepData, ReferencingApplication $application)
 {
     $additionalInfoNote = $this->getAdditionalInformationHolderFromProgressiveStore();
     if (!$additionalInfoNote instanceof AdditionalInformationHolder) {
         $additionalInfoNote = new AdditionalInformationHolder();
         $this->progressiveStore->addPrototype($additionalInfoNote);
     }
     $additionalInfoMessage = '';
     if (isset($formStepData['step']['additionalInfo'])) {
         $additionalInfoMessage = $formStepData['step']['additionalInfo'];
     }
     if ($additionalInfoMessage) {
         if ($additionalInfoNote->getNoteId()) {
             // If we have an existing additional info message, update
             $this->client->updateReferencingApplicationNote(array('applicationUuId' => $application->getReferencingApplicationUuId(), 'noteId' => $additionalInfoNote->getNoteId(), 'note' => $additionalInfoMessage));
             $additionalInfoNote->setMessage($additionalInfoMessage);
         } else {
             // If we don't have an existing additional info message, create
             $note = $this->client->createReferencingApplicationNote(array('applicationUuId' => $application->getReferencingApplicationUuId(), 'note' => $additionalInfoMessage));
             $additionalInfoNote->setNoteId($note->getNoteId())->setMessage($additionalInfoMessage);
         }
     }
 }
 /**
  * @test
  */
 public function criteria_is_not_satisfied_when_credit_score_is_unsatisfactory_for_insight()
 {
     $this->reference->setProductId(ProductIds::INSIGHT);
     $this->creditReference->setScore(CreditScoreCriteriaLimits::MINIMUM_INSIGHT_CREDIT_SCORE - 1);
     $this->assertFalse($this->criteria->isSatisfiedBy($this->rrpReference));
 }
 /**
  * Index action
  *
  * @return void
  */
 public function indexAction()
 {
     if ($this->getSymfonyRequest()->query->has('uuid')) {
         $applicationUuId = $this->getSymfonyRequest()->query->get('uuid', null);
         // Get referencing case. Needed for the summary page
         $applicant = $this->getIrisAgentContext()->getReferencingApplicationClient()->getReferencingApplication(array('referencingApplicationUuId' => $applicationUuId));
         $case = $this->getIrisAgentContext()->getReferencingCaseClient()->getReferencingCase(array('referencingCaseUuId' => $applicant->getReferencingCaseUuId()));
         $referencingApplication = new ReferencingApplication();
         $referencingApplication->setProductId($applicant->getProductId())->setPolicyLength($applicant->getPolicyLength());
         $this->getAgentGuarantorProgressiveStore()->setApplicantUuId($applicationUuId)->clearPrototypes()->addPrototype($case)->addPrototype($referencingApplication)->storePrototypes();
     }
     $form = $this->getFormFactory()->create(new RootStepType(new ProductType($this->getAgentGuarantorProgressiveStore())), $this->getAgentGuarantorProgressiveStore()->fetch(self::MODEL_APPLICATION_CLASS), array('removeBack' => true, 'stepTypeOptions' => array('userLabel' => 'Guarantor')));
     // Don't need productId for guarantors
     $form->get('step')->remove('productId')->remove('update');
     if ($this->getSymfonyRequest()->isMethod('POST')) {
         $form->submit($this->getSymfonyRequest());
         $this->getFormFlow()->setForm($form);
         if ($form->isValid()) {
             $object = null;
             try {
                 $object = $this->getAgentGuarantorProgressiveStore()->store($form->getData());
             } catch (ValidationException $e) {
                 $this->getFormValidationErrorBinder()->bind($form, $e);
                 $this->renderTwigView('/iris-add-guarantor/generic-step.html.twig', array('bodyTitle' => 'Guarantor Details', 'form' => $form->createView()));
                 return;
             }
             // If we're completing by email
             if (CompletionMethodsOptions::COMPLETE_BY_EMAIL == $object->getCompletionMethod()) {
                 /** @var \Barbondev\IRISSDK\IndividualApplication\ReferencingCase\Model\ReferencingCase $case */
                 $case = $this->getAgentGuarantorProgressiveStore()->getPrototypeByClass(self::MODEL_CASE_CLASS);
                 /** @var \Barbondev\IRISSDK\IndividualApplication\ReferencingApplication\Model\ReferencingApplication $case */
                 $application = $this->getAgentGuarantorProgressiveStore()->getPrototypeByClass(self::MODEL_APPLICATION_CLASS);
                 // Submit application
                 $submitSuccess = $this->getContainer()->get('iris.referencing.application.submission.application_submitter')->submit($application->getReferencingApplicationUuId(), '/iris-referencing/submission-error?errorCode={error_code}');
                 // Was the submission a success?
                 if ($submitSuccess) {
                     // Do we need to collect another tenant?
                     $difference = $this->getContainer()->get('iris.referencing.application.application_counter')->getApplicantCountDifference($application->getReferencingApplicationUuId(), $case->getNumberOfTenants());
                     // Check the difference
                     if ($difference > 0) {
                         // Clear and add existing prototypes
                         $this->getAgentGuarantorProgressiveStore()->clearPrototypes()->initialisePrototypes()->storePrototypes();
                         // Yes, we need to collect another tenant, redirect
                         $this->_helper->redirector->gotoUrlAndExit(sprintf('/iris-add-tenant?uuid=%s&difference=%d&numberOfTenants=%d', $case->getReferencingCaseUuId(), $difference, $case->getNumberOfTenants()));
                     }
                     // Redirect to success
                     $this->_helper->redirector->gotoUrlAndExit('/iris-add-guarantor/email-to-guarantor-success');
                 } else {
                     // Something went wrong
                     $this->_helper->redirector->gotoUrlAndExit(sprintf('/iris-referencing/failed-to-submit-application?uuid=%s', $application->getReferencingApplicationUuId()));
                 }
             }
             if ($object) {
                 if ($form->get('next')->isClicked()) {
                     $this->_helper->redirector->gotoUrlAndExit($this->getFormFlow()->getNextUrl());
                 }
             }
         }
     }
     $this->renderTwigView('/iris-add-guarantor/generic-step.html.twig', array('bodyTitle' => 'Guarantor Details', 'form' => $form->createView()));
 }
 /**
  * Return combinations containing invalid insight, invalid enhance and valid optimum references.
  *
  * @return array
  */
 public function getInvalidInsightInvalidEnhanceValidOptimumCombinations()
 {
     $insightProduct = new Product();
     $insightProduct->setName('Insight');
     $insight = new ReferencingApplication();
     $insight->setProduct($insightProduct);
     $insight->setProductId(ProductIds::INSIGHT);
     $insight->setRentShare(0);
     $enhanceProduct = new Product();
     $enhanceProduct->setName('Enhance');
     $enhance = new ReferencingApplication();
     $enhance->setProduct($enhanceProduct);
     $enhance->setProductId(ProductIds::ENHANCE);
     $enhance->setRentShare(0);
     $optimumProduct = new Product();
     $optimumProduct->setName('Optimum');
     $optimum = new ReferencingApplication();
     $optimum->setProduct($optimumProduct);
     $optimum->setProductId(ProductIds::OPTIMUM);
     $optimum->setRentShare(1);
     return array(array(array($insight, $optimum)), array(array($enhance, $optimum)), array(array($insight, $enhance, $optimum)));
 }
 /**
  * {@inheritdoc}
  */
 public static function fromCommand(OperationCommand $command)
 {
     $uriSegments = $command->getRequest()->getUrl(true)->getPathSegments();
     $referencingCaseUuId = end($uriSegments);
     if (!is_string($referencingCaseUuId) || 36 != strlen($referencingCaseUuId)) {
         $referencingCaseUuId = null;
     }
     $data = $command->getResponse()->json();
     $address = isset($data['address']) ? self::hydrateModelProperties(new Address(), $data['address']) : null;
     $prospectiveLandlordAddress = isset($data['prospectiveLandlord']['address']) ? self::hydrateModelProperties(new Address(), $data['prospectiveLandlord']['address']) : null;
     $prospectiveLandlord = isset($data['prospectiveLandlord']) ? self::hydrateModelProperties(new ProspectiveLandlord(), $data['prospectiveLandlord'], array(), array('address' => $prospectiveLandlordAddress)) : null;
     $applications = array();
     if (isset($data['applications']) && is_array($data['applications'])) {
         foreach ($data['applications'] as $key => $object) {
             $application = ReferencingApplication::hydrate($object);
             $applications[$key] = $application;
         }
     }
     return self::hydrateModelProperties(new self(), $data, array('caseId' => 'referencingCaseUuId', 'tenancyTerm' => 'tenancyTermInMonths'), array('caseId' => $referencingCaseUuId, 'address' => $address, 'prospectiveLandlord' => $prospectiveLandlord, 'applications' => $applications));
 }
 /**
  * Get DecisionDetails object from IRIS.
  *
  * @param ReferencingApplication $reference
  * @return \Barbondev\IRISSDK\IndividualApplication\ReferencingApplication\Model\ReferencingDecisionDetails
  */
 public function getDecisionDetails(ReferencingApplication $reference)
 {
     return $this->clientRegistry->getAgentContext()->getReferencingApplicationClient()->getReferencingDecisionDetails(array('referencingApplicationUuId' => $reference->getReferencingApplicationUuId()));
 }