<?php
namespace Globals\ClaimManagementBundle\Controller\ClaimFlow;
use Globals\ClaimManagementBundle\DependencyInjection\ClaimInsuredChangesHelper;
use Globals\ClaimManagementBundle\DependencyInjection\ClaimOtherPartyChangesHelper;
use Globals\ClaimManagementBundle\DependencyInjection\ClaimPermissionHelper;
use Globals\ClaimManagementBundle\DependencyInjection\ClaimReportFormHelper;
use Globals\ClaimManagementBundle\DependencyInjection\ClaimsInsuredHelper;
use Globals\ClaimManagementBundle\DependencyInjection\ClaimsOtherPartyHelper;
use Globals\ClaimManagementBundle\DependencyInjection\CompareHelpers\ClaimCompareHelper;
use Globals\ClaimManagementBundle\DependencyInjection\CompareHelpers\InsuredCompareHelper;
use Globals\ClaimManagementBundle\DependencyInjection\CompareHelpers\OtherPartyCompareHelper;
use Globals\ClaimManagementBundle\DependencyInjection\ExpensesHelper;
use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\ClaimLimitFormHelper;
use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\CoverageFormHelper;
use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\DeductibleFormHelper;
use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\DisbursementTimeLogFormHelper;
use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\InsuredFormHelper;
use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\InvoiceFormHelper;
use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\OtherPartyFormHelper;
use Globals\ClaimManagementBundle\DependencyInjection\PerilHelper;
use Globals\ClaimManagementBundle\DependencyInjection\PerilTreeHelper;
use Globals\ClaimManagementBundle\Entity\Attribute;
use Globals\ClaimManagementBundle\Entity\Claim;
use Globals\ClaimManagementBundle\Entity\XactClaimReport;
use Globals\ClaimManagementBundle\Entity\ClaimInsuredType;
use Globals\ClaimManagementBundle\Entity\ClaimReport;
use Globals\ClaimManagementBundle\Entity\ClaimResource;
use Globals\ClaimManagementBundle\Entity\ClaimResourcePrevious;
use Globals\ClaimManagementBundle\Entity\ClaimsInsured;
use Globals\ClaimManagementBundle\Entity\ClaimsOtherParty;
use Globals\ClaimManagementBundle\Entity\ClaimStatus;
use Globals\ClaimManagementBundle\Entity\ClaimTeam;
use Globals\ClaimManagementBundle\Entity\Coverage;
use Globals\ClaimManagementBundle\Entity\CoverageReserve;
use Globals\ClaimManagementBundle\Entity\Deductible;
use Globals\ClaimManagementBundle\Entity\DiaryEntry;
use Globals\ClaimManagementBundle\Entity\Insured;
use Globals\ClaimManagementBundle\Entity\PolicyType;
use Globals\ClaimManagementBundle\Form\ClaimMainFragment;
use Globals\ClaimManagementBundle\Form\ClaimMainFragmentCarrier;
use Globals\ClaimManagementBundle\Form\ClaimPolicyFragment;
use Globals\ClaimManagementBundle\Form\ClaimResourceForm;
use Globals\ClaimManagementBundle\Form\DiaryFormType;
use Globals\ClaimManagementBundle\Form\DisbursementTimeLogType;
use Globals\ClaimManagementBundle\Form\InsuredMainFragment;
use Globals\ClaimManagementBundle\Repository\ClaimRepository;
use Globals\ClaimManagementBundle\Service\ClaimNotesProviderService;
use Globals\ClaimManagementBundle\Service\InvoicePreviewService;
use Globals\CoreBundle\Repository\SystemControlMetadataRepository;
use Globals\CoreBundle\Repository\SystemControlRepository;
use Globals\CoreBundle\Services\GoogleGeocoder;
use Globals\CustomerManagementBundle\Entity\Customer;
use Globals\InvoiceManagementBundle\Entity\Disbursement;
use Globals\InvoiceManagementBundle\Entity\Invoice;
use Globals\ResourceManagementBundle\Entity\Resource;
use Doctrine\ORM\EntityManager;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Globals\ResourceManagementBundle\DependencyInjection\SortOrderHelper;
use Globals\ResourceManagementBundle\Service\PaginatorSQL;
use Globals\ResourceManagementBundle\Service\SLogger;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Intl\NumberFormatter\NumberFormatter;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Globals\ClaimManagementBundle\Entity\DocumentLibrary;
use Symfony\Component\Validator\Constraints\DateTime;
use Globals\ClaimManagementBundle\Entity\ClaimLimit;
use Globals\CompanyManagementBundle\Entity\Company;
use Globals\ClaimManagementBundle\Event\ChangeTeamEvent;
use Globals\CompanyManagementBundle\Entity\TpaCustomer;
/**
* @Route("/claims/fragments")
*/
class ClaimController extends Controller
{
# maximum amount of perils on a claim
const MAX_PERILS_ON_CLAIM = 3;
/**
* @Route("/main/{id}", defaults={"id" = "none"})
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function mainFragmentAction(Claim $claim, Request $request)
{
/** @var EntityManager $em */
$em = $this->getDoctrine()->getManager();
// $systemParamService = $this->container->get('fact.service');
// $response = $systemParamService->createClaim($claim,'faa2cda0-e5ae-40b8-a1cf-1f84affe0e32');
// dd($response);
// die;
# load up all the property types
$PropertyTypeRepo = $em->getRepository("ClaimManagementBundle:PropertyType");
$PropertyTypes = $PropertyTypeRepo->findBy([],['propertyType'=>'ASC']);
$CwopReasons = $em->getRepository("ClaimManagementBundle:CwopReason")->findAll();
$SettlementTypes = $em->getRepository("ClaimManagementBundle:SettlementType")->findAll();
$companyId = 1;
if (!empty($claim->getCustomer())) {
$ClaimCustomer = $claim->getCustomer();
if ($ClaimCustomer->getSubCompany()) {
$companyId = $ClaimCustomer->getSubCompany()->getId();
}
}
$company = $em->getRepository("CompanyManagementBundle:Company")->find($companyId);
$curr_claim_no = $claim->getClaimNumber();
$slog = new SLogger();
if ($claim) {
$tokenStorage = $this->container->get("security.token_storage");
$User = $tokenStorage->getToken()->getUser();
if (!$User) {
throw new AccessDeniedException('You do not have access to this page.');
}
// Check if the user is a TLG user
if ($User->getIsTlg()) {
// For TLG users, we only want to show claims where the company ID is 19
if (!empty($claim->getCustomer())) {
$ClaimCustomer = $claim->getCustomer();
if ($ClaimCustomer->getSubCompany() && $ClaimCustomer->getSubCompany()->getId() != 19) {
// If the claim's company is not 19, throw access denied exception
throw new AccessDeniedException('You do not have access to this claim.');
}
} else {
// If there's no customer associated with the claim, deny access as well
throw new AccessDeniedException('You do not have access to this claim.');
}
} else {
// For non-TLG users, keep the existing logic
if (!empty($claim->getCustomer())) {
$ClaimCustomer = $claim->getCustomer();
if ($ClaimCustomer->getSubCompany()) {
$companyId = $ClaimCustomer->getSubCompany()->getId();
}
}
}
// if ICM
### ICM ###
$slog = new SLogger();
$slog->log('In ICM');
$this->denyAccessUnlessGranted("view_claim", $claim);
$claimStatus = $em->getRepository("ClaimManagementBundle:ClaimStatus")->find($claim->getStatus());
# 1) Create a Form for the Claim. It will be a PARTIAL form
$form = $this->createForm(ClaimMainFragment::class, $claim, array('status' => $claim->getStatus(), 'roles' => $User->getRoles()));
$customer = $claim->getCustomer();
$customerTmp = $claim->getCustomer();
$isTpaCustomer=false;
if(!empty($customer) && $customer->isTpaUi()){
$isTpaCustomer=true;
}
#get id of the all the TPA customer
$tpacust='';
$TpaCustomerObj=$em->getRepository("CustomerManagementBundle:Customer")->findBy(array('tpaUi'=>1));
if(!empty($TpaCustomerObj)){
foreach($TpaCustomerObj as $objkey=>$customer){
$tpacust .=$customer->getId().',';
}
$tpacust=rtrim($tpacust,',');
}
$ReopenDate = $claim->getDateReopened();
$PropertyStatusRepo = $em->getRepository("ClaimManagementBundle:PropertyStatus");
# 2) Create a Form for the Insured. It too, will be a PARTIAL form
//$insuredForm = $this->createForm(InsuredMainFragment::class, $claim->getInsured());
// --------------------------------------------------------------------------------
// CLAIM FLOW CRUD SUBMISSION
/*
* If the form was submitted, we'll catch it here and return a better output (JSON)
* We'll need to come up with a good convention for doing this, otherwise the Controller
* might end up fat. For now, we approach it here.
*
*/
# Create Form Builder Object for "Create Certificate"
$em = $this->container->get("doctrine.orm.entity_manager");
if($claim->getAssignmentId()) {
$this->_updateDatesFromSymbility($claim);
}
//dd(new \DateTime($InsuredContactedUserDate));
// dd($symData);
$formFactory = $this->container->get("form.factory");
$insuredFormHelper = new InsuredFormHelper($em, $formFactory, false);
// EXISTING CLAIM CHECK
$conn = $em->getConnection();
$claim_exists = $conn->prepare("SELECT id FROM claim WHERE claim_number = ?");
$insuredForm = $insuredFormHelper->getAddForm();
if ($request->getMethod() === "POST") {
//dd($request->request);
$ResourceInTeam=[];
$OldTeam='';
if(!empty($claim->getClaimTeam())) {
$OldTeam = $claim->getClaimTeam()->getName();
}
$NewTeam='';
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$response = [
'error' => false, 'data' => []
];
# Grab the serialized submission data
$claimFormSubmission = $request->request->get('claim_main_fragment');
$insuredFormSubmission = $request->request->get('insured_main_fragment');
$claimExtraFields = $request->request->get('claim_extra_fields');
$tpaSubmission = $request->request->get('claim_tpa_fragment');
$claim_rep_id = $request->request->get('claim_rep');
$claimNumber = $request->request->get('claim_number');
$AutoclaimFields = $request->request->get('auto_claim_main_fragment');
$settlement = $claimFormSubmission['settlement'];
if (!empty($claimFormSubmission['reopenSettlementType']))
$settlement = $claimFormSubmission['reopenSettlementType'];
# Added 08/2018 -- Capturing COUNTY, CUSTOMER
$form_request = $request->request->get('form');
$County = false;
if(!empty($form_request) && isset($form_request['claim_main_fragment_lossCounty']))
{
$county_id = intval($form_request['claim_main_fragment_lossCounty']);
if ($county_id) {
$County = $em->getRepository("ResourceManagementBundle:Counties")->find(intval($county_id));
}
}
# Added 08/2018 -- Checking to see if COUNTY is required (per tpa_ui)
/*$county_pass = true;
if($claim->getCustomer()->isTpaUi() && !$County)
{
$county_pass = false;
}*/
$site_inspected = ($request->request->has("site_inspected")) ? intval($request->request->get("site_inspected")) : 0;
# Added TPA pass 09/2018 -- Checking to see if we submitted a UMR
$tpa_pass = true;
$is_tpa_cust = false;
$umrValue = false;
$propertyTypeInbound = false;
if( isset($tpaSubmission) && isset($tpaSubmission['umr']) )
{
$is_tpa_cust = true;
# check if we submitted an UMR no.
if( $tpaSubmission['umr'] && $tpaSubmission['umr'] != "" )
{
$umrValue = $tpaSubmission['umr'];
}else{
$tpa_pass = false;
}
# check if we submitted a property type (id, in this case)
if( $tpaSubmission['property_type'] && intval($tpaSubmission['property_type']) > 0 )
{
$propertyTypeInbound = $PropertyTypeRepo->find( intval($tpaSubmission['property_type']) );
}else{
$tpa_pass = false;
}
}
# Submit the actual forms
$form->submit($claimFormSubmission);
//dd($form->getErrors());
//$insuredForm->submit($insuredFormSubmission);
# If the first form was ok, SUBMIT the insured form. Otherwise, archive the errors.
if ($form->isValid() && $tpa_pass) {
// Save and persist the new data
/** @var Claim $newClaim */
$newClaim = $form->getData();
//$newClaim->setSiteInspected($site_inspected); //setSiteInspected is removed
# Added 08/2018 -- SET the county
if($County && !empty($County))
{
$newClaim->setLossCounty( $County );
}
//update LossLatitude and LossLongitude start
//$address = $claimFormSubmission['lossStreet'];
//$city = $claimFormSubmission['lossCity'];
//$stateId = intval($claimFormSubmission['lossState']);
//$lossState = $em->getRepository("ResourceManagementBundle:State")->find($stateId);
// $state = $lossState->getStateName();
// $zip = $claimFormSubmission['lossZip'];
//$googleApiCall = $this->container->get("google.geocoder");
//$latitudeLongitudeData = $googleApiCall->getLatLongFromAddress($address, $city, $state, $zip);
//$newClaim->setLossLatitude($latitudeLongitudeData['lat']);
//$newClaim->setLossLongitude($latitudeLongitudeData['lng']);
//update LossLatitude and LossLongitude end here
# Added 09/2018 -- SET the tpa info
if($is_tpa_cust && $umrValue && $propertyTypeInbound)
{
$newClaim->setUmr( $umrValue );
$newClaim->setPropertyType( $propertyTypeInbound );
}
if ($claim_rep_id) {
$ClaimRep = $em->getRepository("ResourceManagementBundle:Resource")->find($claim_rep_id);
if ($ClaimRep) {
$newClaim->setClaimRep($ClaimRep);
}
}
$arrSettlemenTypeForCWOP = array(1,4,5,6);
if (!empty($ReopenDate)) {
if (empty($settlement) || (!empty($settlement) && in_array($settlement,$arrSettlemenTypeForCWOP) === false )) {
$newClaim->setReopenCwopRsn(null);
$newClaim->setReopenDenialDescriptionLine('');
}
if (!empty($settlement)) {
$objSettlementType = $em->getRepository("ClaimManagementBundle:SettlementType")->find($settlement);
$newClaim->setReopenSettlementType($objSettlementType);
}
} else{
if (empty($settlement) || (!empty($settlement) && in_array($settlement,$arrSettlemenTypeForCWOP) === false)) {
$newClaim->setCwopReason(null);
$newClaim->setDenialDescriptionLine('');
}
}
if ($claimNumber) {
// CHECK FOR DUPES
$claim_exists->execute([$claimNumber]);
//Check if Claim Number is different from the current claim Number
//If yesm then check if count is more than 0, if yes, then give error.
if($claimNumber != $curr_claim_no && ($claim_exists->rowCount() > 0)){
$response['error'] = true;
$response['data']['errors'][] = [
'id' => 'claimNumber',
'text' => "You cannot have a duplicate Claim number"
];
}else{
$newClaim->setClaimNumber($claimNumber);
}
}
# Don't change customer on XACT or Symbility claims
/*if ($claim->getTransactionId()) {
if ($claim->failsChangeCustomerValidation($customer,$claimFormSubmission)) {
$response['error'] = true;
$response['data']['errors'][] = [
'id' => 'claim_main_fragment_customer',
'text' => 'You cannot change the customer of this claim'
];
}
} else {*/
# dont throw error but throw alert message for user
if ($claim->failsChangeCustomerValidation($customerTmp,$claimFormSubmission)) {
$response['alert'] = [
'title' => "Internal Rep Removed",
'content' => "Customer has been changed, removing internal rep"
];
$newClaim->removeClaimRep();
}
//}
/**
* Add resources to the claim team if needed
*/
$claimResources = $claim->getResources();
if (isset($claimFormSubmission['claimTeam'])) {
$claimTeam = $em->getRepository('ClaimManagementBundle:ClaimTeam')->find($claimFormSubmission['claimTeam']);
if ($claimTeam) {
$NewTeam=$claimTeam->getName();
$claimTeamManager = $this->get('claimteam.manager');
foreach ($claimResources as $claimResource) {
$adjuster = $claimResource->getResource();
# Assign the resource to the team if he is not on the team
$clamTeamResources = $em->getRepository("ClaimManagementBundle:ClaimTeamResource")
->findBy(['claimTeam' => $claimTeam, 'resource' => $adjuster]);
if (empty($clamTeamResources)) {
$claimTeamManager->addResourceToClaimTeam($adjuster, $claimTeam);
}
$OldAdjuster = $em->find("ResourceManagementBundle:Resource", intval($adjuster->getId()));
$ResourceInTeam[]=$OldAdjuster;
}
//if ($claim->getClaimTeam() != $claimFormSubmission['claimTeam']) {
if($claim->getIsClaimCategory() ==1) {
if ($claim->getClaimTeam()->getId() != intval($claimFormSubmission['claimTeam'])) {
# First to Call Un-assigned event
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(new ChangeTeamEvent($claim, $ResourceInTeam, $OldTeam, false), ChangeTeamEvent::NAME);
#second to call assign event
$dispatcher->dispatch(new ChangeTeamEvent($claim, $ResourceInTeam, $NewTeam, true), ChangeTeamEvent::NAME);
}
}
}
}
$customer_report_to_id = $request->request->get('customer_reporting');
if($customer_report_to_id){
$newClaim->setReportToId($customer_report_to_id);
}else{
$newClaim->setReportToId(0);
}
if (!empty($claimFormSubmission['policy'] ?? "")) {
$policyType = $em->getRepository(PolicyType::class)
->findOneBy(['id' => $claimFormSubmission['policy']]);
if ($policyType instanceof PolicyType) {
$newClaim->setPolicyType($policyType->getName());
}
}
if(isset($claimFormSubmission['customerCatCode'])) {
$newClaim->setCustomerCatCode($claimFormSubmission['customerCatCode']);
}else{
$newClaim->setCustomerCatCode(null);
}
if(isset($claimFormSubmission['liabilityType'])) {
$newClaim->setLiabilityType($claimFormSubmission['liabilityType']);
}else{
$newClaim->setLiabilityType(0);
}
if(isset($claimFormSubmission['recoveriesType'])) {
$newClaim->setRecoveriesType($claimFormSubmission['recoveriesType']);
}else{
$newClaim->setRecoveriesType(0);
}
if(isset($claimExtraFields['subPerilId']) && !empty($claimExtraFields['subPerilId'])) {
$subPeril = $em->getRepository("ClaimManagementBundle:Peril")->find(intval($claimExtraFields['subPerilId']));
$newClaim->setSubPeril($subPeril);
}else{
$newClaim->setSubPeril(null);
}
if(isset($claimExtraFields['propertyDamageType']) && !empty($claimExtraFields['propertyDamageType']) ) {
$newClaim->setPropertyDamageType($claimExtraFields['propertyDamageType']);
}else{
$newClaim->setPropertyDamageType(null);
}
if(isset($AutoclaimFields['treaty_number'])) {
$newClaim->setTreatyNumber($AutoclaimFields['treaty_number']);
}else{
$newClaim->setTreatyNumber(null);
}
if(isset($AutoclaimFields['sub_treaty_number'])) {
$newClaim->setSubTreatyNumber($AutoclaimFields['sub_treaty_number']);
}else{
$newClaim->setSubTreatyNumber(null);
}
if ($response['error'] === false) {
$em->persist($newClaim);
$em->flush();
}
if ($newClaim->getPlanId()) {
$PlanId = $em->getRepository("ClaimManagementBundle:PlanID")->find($newClaim->getPlanId()->getId());
$PlanId->setWasUsedOnClaim(true);
$em->persist($PlanId);
$em->flush();
}
# for Update Auto claim
$AutoClaim = $em->getRepository("ClaimManagementBundle:AutoClaim")->findOneBy(['claim'=>$newClaim]);
if(!empty($AutoClaim)){
$AutoClaim->setIssueDate(new \DateTime($claimFormSubmission['policyStartDate']));
$AutoClaim->setEffDate(new \DateTime($AutoclaimFields['eff_date']));
$AutoClaim->setExpiryDate(new \DateTime($claimFormSubmission['policyEndDate']));
$AutoClaim->setYear($AutoclaimFields['year']);
$AutoClaim->setMake($AutoclaimFields['make']);
$AutoClaim->setModel($AutoclaimFields['model']);
$AutoClaim->setMileage($AutoclaimFields['mileage']);
$AutoClaim->setVinId($AutoclaimFields['vin_id']);
if(!empty($claimExtraFields['compType'])) {
$compType = $em->getRepository("CompanyManagementBundle:CompType")->find(intval($claimExtraFields['compType']));
$AutoClaim->setCompType($compType);
}else{
$AutoClaim->setCompType(null);
}
if(!empty($claimExtraFields['compCode'])) {
$compCode = $em->getRepository("CompanyManagementBundle:CompCode")->find(intval($claimExtraFields['compCode']));
$AutoClaim->setCompCode($compCode);
}else{
$AutoClaim->setCompCode(null);
}
$AutoClaim->setUpdatedAt(new \DateTime());
//dd($AutoClaim);
$em->persist($AutoClaim);
$em->flush();
}
# for Update Auto claim
return new JsonResponse($response);
} else {
/*/
foreach ($form as $formField) {
$response['error'] = true;
$errorString = (string)$formField->getErrors();
if ($errorString != "") {
$response['data']['errors'][] = [
'id' => $form->getName() . "_" . $formField->getName(),
'text' => $errorString
];
}
}
return new JsonResponse($response);
//*/
$newClaim = $form->getData();
$data = array();
$errors2 = array();
$alert = array();
# Get Validation Error Messages
$errors = $this->get("validator")->validate($newClaim);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $form->getName() . "_" . $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
/*if(!$county_pass)
{
$data['errors'][] = [
'id' => 'claim_main_fragment_lossCounty',
'text' => 'This customer requires you to have a loss county'
];
}*/
if(!$tpa_pass)
{
if(!$umrValue){
$data['errors'][] = [
'id' => 'claim_tpa_fragment_umr',
'text' => 'This customer requires a UMR number'
];
}
if(!$propertyTypeInbound){
$data['errors'][] = [
'id' => 'claim_tpa_fragment_property_type',
'text' => 'Please select a Property Type'
];
}
}
# Return JSON Errors Object
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
// --------------------------------------------------------------------------------
$claim_switch_action = "";
$session = new Session();
if ($session->has("claim_switch_action")) {
$claim_switch_action = $session->get("claim_switch_action");
$session->remove("claim_switch_action");
}
#get the peril type and sub peril type information
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$em = $this->container->get("doctrine.orm.entity_manager");
$rootPeril = null;
$rootPerilId = 0;
if ($claim->getPeril()) {
//$rootPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getPeril()->getId());
//$rootPerilId = $rootPeril->getId();
$rootPeril = $claim->getPeril();
$rootPerilId = $claim->getPeril()->getId();
}
$RootPerils = $em->getRepository("ClaimManagementBundle:Peril")->getRootPerils();
$subPeril = null;
$subPerilId = 0;
if ($claim->getSubPeril()) {
//$subPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getSubPeril()->getId());
//$subPerilId = $subPeril->getId();
$subPeril = $claim->getSubPeril();
$subPerilId = $claim->getSubPeril()->getId();
}
$ChildrenPerils = array();
if ($rootPeril !== null) {
$ChildrenPerils = $em->getRepository("ClaimManagementBundle:Peril")->getPerilChildren($rootPerilId);
}
$PropertyStatuses = $PropertyStatusRepo->findAll();
$claimRep = $claim->getClaimRep();
$sql = "SELECT r.id, r.first_name, r.last_name
FROM resource r
INNER JOIN customer_resource cr ON r.id = cr.resource_id
WHERE r.is_active = :is_active
AND cr.customer_id = :cust_id
ORDER BY r.first_name";
$dataParams = array();
$dataParams['is_active'] = 1;
$dataParams['cust_id'] = 0;
if ($claim->getCustomer()) {
$dataParams['cust_id'] = $claim->getCustomer()->getId();
}
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute($dataParams);
$claimRepResources = $stmt->fetchAll( \PDO::FETCH_ASSOC );
$reportToId = $claim->getReportToId();
$sql = "SELECT *
FROM customer_reporting
WHERE is_active = :is_active
AND customer_id = :cust_id
ORDER BY id= :report_to_id desc, first_name asc";
$dataParams = array();
$dataParams['is_active'] = 1;
$dataParams['cust_id'] = 0;
$dataParams['report_to_id'] = $reportToId;
if ($claim->getCustomer()) {
$dataParams['cust_id'] = $claim->getCustomer()->getId();
}
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute($dataParams);
$customerReporting = $stmt->fetchAll( \PDO::FETCH_ASSOC );
$dateOpened = $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
$dateClosed = $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
if($dateClosed < $dateOpened){
$dateClosed = new \DateTime('now');
}
$difference = date_diff($dateOpened,$dateClosed);
$difference = (array)$difference;
$daysOpen = array();
$daysOpen['days'] = $difference['days'];
$daysOpen['h'] = $difference['h'];
$daysOpen['m'] = $difference['m'];
$systemParamService = $this->container->get('core.system_parameter_control');
$swbc_payments = false;
$swbc_payments = $systemParamService->isEnabledControl('SWBC_payment_letter');
# 3) If this wasn't a form submission, we render the screen
$systemAdminUsers = $systemParamService->getAccessArray('Invoicing_access');
$bShowInvoiceAccessTab = false;
$user = $this->get('security.token_storage')->getToken()->getUser();
if (!empty($systemAdminUsers) && in_array($user->getId(),$systemAdminUsers)) {
$bShowInvoiceAccessTab = true;
}
$bShowSymbilityRefUrl = false;
$bShowRefUrl = false;
$session = new Session();
if ($claim->getStatus()>=10) {
$bShowRefUrl = true;
#check for Symbility Refer Url
if ($claim->getAssignmentId()) {
$bShowSymbilityRefUrl = true;
$bReferSymbilityUrl=$systemParamService->getParameterValue('symbilityLiveReferUrl','url_token');
$session->set("claimSymbilityUrl", $bReferSymbilityUrl);
}
# End of the check
}
# check if the External Resource Widget is allowed to show for TPA Customer
$TpaCustomer = $this->getDoctrine()->getRepository("CompanyManagementBundle:TpaCustomer")->findOneBy(['customerId'=>$claim->getCustomer()->getId()]);
$isTpaCustomerAllowed=false;
if(!empty($TpaCustomer)){
$isTpaCustomerAllowed=true;
}
# load up all the sub loss types
$sql = "SELECT *
FROM perils p
WHERE p.peril_id is null OR p.peril_id <> 0
ORDER BY p.description";
$dataParams = array();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute($dataParams);
$ChildrenPerils = $stmt->fetchAll( \PDO::FETCH_ASSOC );
$SubPerilIdArray =[];
if(!empty($ChildrenPerils)){
foreach ($ChildrenPerils as $ky=>$childrenPeril){
$SubPerilIdArray[$childrenPeril['id']]=$childrenPeril['description'];
}
}
# load up all the sub damage types
$propertyDamageTypes = $em->getRepository("ClaimManagementBundle:PropertyDamageType")->findAll();
$CompType = $em->getRepository("CompanyManagementBundle:CompType")->getActiveCompType();
$CompCode = $em->getRepository("CompanyManagementBundle:CompCode")->getActiveCompCode();
//dd($claim->getLiabilityType());
//dd($SubPerilIdArray);
// check if the logged-in user have access to order the hover report
$hoverReportUsers = $systemParamService->getAccessArray('hover_report_order');
$hoverReportApprovers = $systemParamService->getAccessArray('hover_report_approvers');
$showHoverReport = $isReportApprover = false;
$hoverReportDetails = [];
if ((!empty($hoverReportApprovers) && in_array($user->getId(), $hoverReportApprovers)) ||
(!empty($hoverReportUsers) && in_array($user->getId(), $hoverReportUsers))) {
$showHoverReport = true;
// get hover report details
$hoverReportDetails = $em->getRepository("ClaimManagementBundle:ClaimHoverReport")->findOneBy(['claimId' => $claim->getId()]);
if (!empty($hoverReportApprovers) && in_array($user->getId(), $hoverReportApprovers)) {
$isReportApprover = true;
}
if (empty($hoverReportDetails) && !in_array($user->getId(), $hoverReportUsers)) {
$showHoverReport = false;
}
}
return $this->render('ClaimManagementBundle:ClaimFlowScreen/Fragments:main-fragment.html.twig', [
'active' => 'main',
'claim' => $claim,
'claimStatus' => $claimStatus,
'form' => $form->createView(),
'claim_switch_action' => $claim_switch_action,
'insured_form' => $insuredForm,
"rootPerilId" => $rootPerilId,
"rootPeril" => $rootPeril,
"SubPerilId" => $subPerilId,
"subPeril" => $subPeril,
"RootPerils" => $RootPerils,
"ChildrenPerils" => $ChildrenPerils,
'PropertyTypes' => $PropertyTypes,
'PropertyStatuses' => $PropertyStatuses,
'claimRep' => $claimRep,
'customerReporting' => $customerReporting,
'resources' => $claimRepResources,
"company" => $company,
"daysOpen" => $daysOpen,
"CwopReasons" => $CwopReasons,
"swbc_payments" => $swbc_payments,
"SettlementTypes" => $SettlementTypes,
'bShowInvoiceAccessTab' => $bShowInvoiceAccessTab,
"isTpaCustomer" => $isTpaCustomer,
'tPACustomer' => $tpacust,
"ShowRefUrl" =>$bShowRefUrl,
"isTpaCustomerAllowed" => $isTpaCustomerAllowed,
"SubPerilIdArray" => $SubPerilIdArray,
"propertyDamageTypes" => $propertyDamageTypes,
'comptypeArray' => $CompType,
'compcodeArray' => $CompCode,
'bShowSymbilityRefUrl' => $bShowSymbilityRefUrl,
'isReportApprover' => $isReportApprover,
'showHoverReport' => $showHoverReport,
'hoverReportDetails' => $hoverReportDetails
]);
} else {
throw new NotFoundHttpException('Could not find this claim!');
}
}
public function _updateDatesFromSymbility($claim){
$em = $this->container->get("doctrine.orm.entity_manager");
$InsuredContactedUserDate = '';
$InspectionAppointmentDate = '';
$InspectionPerformedUserDate = '';
$EstimateReadyForReviewDate = '';
$symService = $this->get('integration.symbility.outbound');
$claimData = $symService->getClaim($claim);
$symData = json_decode(json_encode($claimData), true);
if(!empty($symData['claim']['ClaimAssignments']['ClaimAssignment'])){
foreach($symData['claim']['ClaimAssignments']['ClaimAssignment'] as $key=>$value){
if(!empty($value['InsuredContactedUserDate'])){
$InsuredContactedUserDate = $value['InsuredContactedUserDate'];
}
if(!empty($value['InspectionAppointmentDate'])){
$InspectionAppointmentDate = $value['InspectionAppointmentDate'];
}
if(!empty($value['InspectionPerformedUserDate'])){
$InspectionPerformedUserDate = $value['InspectionPerformedUserDate'];
}
if(!empty($value['EstimateReadyForReviewDate'])){
$EstimateReadyForReviewDate = $value['EstimateReadyForReviewDate'];
}
}
}
if(!empty($InsuredContactedUserDate) && $claim->getDateContacted()==''){
$claim->setDateContacted(new \DateTime($InsuredContactedUserDate));
$em->persist($claim);
$em->flush();
}
if(!empty($InspectionAppointmentDate) && $claim->getPlannedInspectionDate()==''){
$claim->setPlannedInspectionDate(new \DateTime($InspectionAppointmentDate));
$em->persist($claim);
$em->flush();
}
if(!empty($InspectionPerformedUserDate) && $claim->getDateInspected()==''){
$claim->setDateInspected(new \DateTime($InspectionPerformedUserDate));
$em->persist($claim);
$em->flush();
}
if(!empty($EstimateReadyForReviewDate) && $claim->getDateReviewReady()==''){
$claim->setDateReviewReady(new \DateTime($EstimateReadyForReviewDate));
$em->persist($claim);
$em->flush();
}
}
/**
* @Route("/create/{id}", defaults={"id" = null})
*/
public function createclaimAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
// IF we're a Carrier acct
$claimStatus = 5;
$isCarrier='N';
/*
* 01/24/2020
*
* TBCA - We want to make sure that the feature is enabled before actually doing
* any of the row work.
*
*/
$parentClaim = false;
$form = $this->createForm(ClaimMainFragmentCarrier::class, new Claim());
# Load Extra Field Values
$insuredFirstName = "";
$insuredLastName = "";
$SubPeril = null;
$countyId = 0;
$county = "";
$LossCounty = null;
if ($request->getMethod() === "POST") {
# Request in Extra Fields
$insuredFirstName = $request->request->get("insured_first_name");
$insuredLastName = $request->request->get("insured_last_name");
$sub_peril = ($request->request->has("sub_peril")) ? intval($request->request->get("sub_peril")) : 0;
$county_id = intval($request->request->get("county_id"));
$claim_rep_id = intval($request->request->get("claim_rep"));
# Grab the serialized submission data
$claimFormSubmission = $request->request->get('claim_main_fragment_carrier');
$claimNumber = $claimFormSubmission['claimNumber'];
$lossZip = $claimFormSubmission['lossZip'];
$lossDate = $claimFormSubmission['lossDate'];
$get_peril_id = $claimFormSubmission['peril'];
# Submit the actual forms
$form->submit($claimFormSubmission);
# If the first form was ok, SUBMIT the insured form. Otherwise, archive the errors.
if ($form->isValid()) {
/** @var Claim $newClaim */
$newClaim = $form->getData();
if (!$lossDate || $lossDate == "") {
$response['error'] = true;
$response['data'] = array();
$response['data']['errors'] = array();
$response['data']['errors'][] = [
'id' => "claim_main_fragment_carrier_lossDate",
'text' => "ERROR: This value should not be blank."
];
return new JsonResponse($response);
}
if (!$lossZip) {
$response['error'] = true;
$response['data'] = array();
$response['data']['errors'] = array();
$response['data']['errors'][] = [
'id' => "claim_main_fragment_carrier_lossZip",
'text' => "ERROR: This value should not be blank."
];
} else if (strlen($lossZip) != 5) {
$response['error'] = true;
$response['data'] = array();
$response['data']['errors'] = array();
$response['data']['errors'][] = [
'id' => "claim_main_fragment_carrier_lossZip",
'text' => "ERROR: This value should be a valid zip code."
];
}
# Validate Peril
if (!$get_peril_id) {
$response['error'] = true;
$response['data'] = array();
$response['data']['errors'] = array();
$response['data']['errors'][] = [
'id' => "claim_main_fragment_carrier_peril",
'text' => "ERROR: This value should not be blank."
];
$response['error'] = true;
return new JsonResponse($response);
}
$claimNumber = $newClaim->getClaimNumber();
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->findOneBy([
"claimNumber" => $claimNumber
]);
if ($Claim) {
$response['error'] = true;
$response['data'] = array();
$response['data']['errors'] = array();
$response['data']['errors'][] = [
'id' => "claim_main_fragment_carrier_claimNumber",
'text' => "ERROR: Claim Number already exists."
];
$response['error'] = true;
return new JsonResponse($response);
}
if ($get_peril_id) {
$Peril = $em->getRepository("ClaimManagementBundle:Peril")->find($get_peril_id);
if ($Peril) {
$newClaim->setPeril($Peril);
}
}
if ($sub_peril) {
$SubPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($sub_peril);
if ($SubPeril) {
$newClaim->setSubPeril($SubPeril);
}
}
if ($county_id) {
$County = $em->getRepository("ResourceManagementBundle:Counties")->find($county_id);
if ($County) {
$newClaim->setLossCounty($County);
}
}
if ($claim_rep_id) {
$ClaimRep = $em->getRepository("ResourceManagementBundle:Resource")->find($claim_rep_id);
if ($ClaimRep) {
$newClaim->setClaimRep($ClaimRep);
}
}
$ClaimService = $this->container->get("claim.service");
$claimId = $ClaimService->saveNewClaim($newClaim, $insuredFirstName, $insuredLastName);
$response = [
'error' => false, 'data' => ["claim_id" => $claimId]
];
return new JsonResponse($response);
} else {
# Validate Insured Name
$response['error'] = true;
$response['data'] = array();
$response['data']['errors'] = array();
if (!$insuredFirstName || !$insuredLastName) {
if (!$insuredFirstName) {
$response['data']['errors'][] = [
'id' => "insured_first_name",
'text' => "ERROR: This value should not be blank."
];
}
if (!$insuredLastName) {
$response['data']['errors'][] = [
'id' => "insured_last_name",
'text' => "ERROR: This value should not be blank."
];
}
}
if (!$get_peril_id) {
$response['data']['errors'][] = [
'id' => "claim_main_fragment_carrier_peril",
'text' => "ERROR: This value should not be blank."
];
}
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->findOneBy([
"claimNumber" => $claimNumber
]);
if ($Claim) {
$response['data']['errors'][] = [
'id' => "claim_main_fragment_carrier_claimNumber",
'text' => "ERROR: Claim Number already exists."
];
}
foreach ($form as $formField) {
$response['error'] = true;
$errorString = (string)$formField->getErrors(true, false);
if ($errorString != "") {
$response['data']['errors'][] = [
'id' => $form->getName() . "_" . $formField->getName(),
'text' => $errorString
];
}
}
return new JsonResponse($response);
}
}
// --------------------------------------------------------------------------------
$claim_switch_action = "";
$session = new Session();
if ($session->has("claim_switch_action")) {
$claim_switch_action = $session->get("claim_switch_action");
$session->remove("claim_switch_action");
}
$coassign = $this->get('core.coassignment');
# 3) If this wasn't a form submission, we render the screen
return $this->render('ClaimManagementBundle:ClaimFlowScreen/Fragments:new-claim-carrier.html.twig', [
'active' => 'main',
'claimStatus' => 5,
'form' => $form->createView(),
'claim_switch_action' => $claim_switch_action,
"insuredFirstName" => $insuredFirstName,
"insuredLastName" => $insuredLastName,
"SubPeril" => $SubPeril,
"countyId" => $countyId,
"county" => $county,
"ommitMenu" => true,
"parent_claim_number" => $parentClaim,
"isCarrier" => $isCarrier,
"next_index" => ((($parentClaim === false) || empty($parentClaim)) ? 0 : $coassign->assignSubTaskId($parentClaim))
]);
}
/**
* Action to update session that allows you to override
* isCarrier Parameter from Environment. If you pass isCarrier 0,
* you can view the ICM version of the Claim Details Tabs
*
* @Route("/switch_claims_carrier/{isCarrier}")
*/
public function switchClaimTabsIsCarrier($isCarrier)
{
$session = new Session();
if ($isCarrier) {
$session->remove("ForceICM");
} else {
$session->set("ForceICM", 1);
}
return new JsonResponse([
"error" => false
]);
}
/**
* Used by Main Claim Tab on Carrier to
* get counties from state_id param
*
* @Route("/search_county")
* @Method({"POST"})
*/
public function getCountiesByState(Request $request)
{
$em = $this->getDoctrine();
$term = $request->request->get("term");
$state_id = intval($request->request->get("state_id"));
$dataParams = array();
$sql = "SELECT c.id, county, s.id as state_id, s.stateCode
FROM counties c
LEFT JOIN state s
ON c.stateId = s.id
WHERE 1 = 1 ";
if ($term) {
$sql .= "AND county LIKE :term ";
$dataParams['term'] = $term . '%';
}
if ($state_id > 0) {
$sql .= "AND c.stateId = :state_id ";
$dataParams['state_id'] = $state_id;
}
$sql .= "GROUP BY county, stateCode
ORDER BY county, stateCode DESC";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute($dataParams);
$Counties = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return new JsonResponse([
"error" => false,
"data" => $Counties
]);
}
/**
* Use by Main Claim Tab on Carrier to
* identify the state and county when zip
* code is entered
*
* @Route("/search_zip")
* @Method({"POST"})
*/
public function searchZipCodesAjax(Request $request)
{
$em = $this->getDoctrine();
$term = $request->request->get("term");
$dataParams = array();
$sql = "SELECT z.state_id, c.id as county_id, c.county, z.zip
FROM zip_codes z
INNER JOIN counties c
ON z.county_id = c.id
WHERE z.zip = :term
LIMIT 1 ";
$Zip = array();
$dataParams['term'] = $term;
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute($dataParams);
$Zips = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($Zips) > 0) {
$Zip = $Zips[0];
}
return new JsonResponse([
"error" => false,
"data" => $Zip
]);
}
/**
* @Route("/main/coverages/{id}")
*/
public function showClaimCoveragesAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
$InsuredTypes = $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->findAll();
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/coverages-widget.html.twig", [
"claim" => $claim,
"insuredTypes" => $InsuredTypes
]);
}
/**
* @Route("/main/coverages_data/{id}")
*/
public function getCoveragesDatatablesData(Claim $claim)
{
/** @var EntityManager $em */
$em = $this->getDoctrine();
/** @var \PDO $conn */
$conn = $em->getConnection();
# Start by opening a new Coverages array
$Coverages = [];
# Prepared statements we need
// $fetch_coverages = $conn->prepare("SELECT c.id, c.amount, ct.coverage_type as name FROM coverage c LEFT JOIN coverage_type ct ON ct.id = c.coverage_type_id WHERE c.claim_id = ?");
$fetch_coverages = $conn->prepare("SELECT id, amount, name, reserve FROM coverage WHERE claim_id = ?");
$fetch_coverages->execute([$claim->getId()]);
//$fetch_reserve = $conn->prepare("SELECT amount FROM coverage_reserve WHERE coverage_id = ? ORDER BY date_modified DESC LIMIT 1");
# Go through each result and add to Coverages
while($cov = $fetch_coverages->fetch(\PDO::FETCH_ASSOC))
{
# Get the reserve for this
/*$fetch_reserve->execute([$cov['id']]);
$reserve = $fetch_reserve->fetch(\PDO::FETCH_ASSOC);*/
$Coverages[] = [
'id' => $cov['id'],
'name' => $cov['name'],
'amount' => $cov['amount'],
'reserve' => $cov['reserve']
];
}
return new JsonResponse([
"recordsTotal" => count($Coverages),
"recordsFiltered" => count($Coverages),
"data" => $Coverages,
]);
}
/**
* @Route("/main/deductibles_data/{id}")
*/
public function getDeductiblesDatatablesData(Claim $claim)
{
$em = $this->getDoctrine();
$sql = "SELECT d.id,d.claim_id,d.deductible_name_id,d.amount, dn.name as deductibleName
FROM deductible d
INNER JOIN deductible_name dn
ON d.deductible_name_id = dn.id
WHERE d.claim_id = :claim_id ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"claim_id" => $claim->getId()
]);
$Deductibles = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return new JsonResponse([
"recordsTotal" => count($Deductibles),
"recordsFiltered" => count($Deductibles),
"data" => $Deductibles,
]);
}
/**
* @Route("/main/limits/{id}")
*/
public function showClaimLimitsAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/claim-limits-widget.html.twig", [
"claim" => $claim
]);
}
/**
* @Route("/main/deductibles/{id}")
*/
public function showClaimDeductiblesAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/deductibles-widget.html.twig", [
"claim" => $claim
]);
}
/**
* @Route("/main/insureds/{id}")
*/
public function showClaimInsuredAction(Claim $claim)
{
$em = $this->container->get("doctrine.orm.entity_manager");
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$InsuredTypes = $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->findAll();
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/insured-widget.html.twig", [
"claim" => $claim,
"insuredTypes" => $InsuredTypes
]);
}
/**
* @Route("/main/other-parties/{id}")
*/
public function showClaimOtherPartiesAction(Claim $claim)
{
$em = $this->container->get("doctrine.orm.entity_manager");
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$otherPartyTypes = $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->findAll();
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/other-parties-widget.html.twig", [
"claim" => $claim,
"insuredTypes" => $otherPartyTypes
]);
}
/**
* @Route("/main/resources/{id}")
*/
public function showClaimResourcesAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$em = $this->container->get("doctrine.orm.entity_manager");
$assignmentService = $this->get('claim.assignment');
$alertMessageDateExpiryArray = $assignmentService->validLicense($claim);
$alertMessageDateExpiry = $alertMessageDateExpiryArray['alertMessageDateExpiry'];
$licenseDataArray = $alertMessageDateExpiryArray['licenseDataArray'];
$adjusterRepo = $em->getRepository("ResourceManagementBundle:Resource");
$claimTeamRepo = $em->getRepository("ClaimManagementBundle:ClaimTeam");
//$adjusters = $adjusterRepo->findBy(['resourceType'=>array(2,3,4)]);
$claimTeams = $claimTeamRepo->findBy(['enabled'=>true]);
$resourceTypes = $em->getRepository("ResourceManagementBundle:ResourceType")->findAll();
$assignmentParties = $em->getRepository("AssignmentBundle:AssignmentParty")->findAll();
/*$sql = "SELECT count(id) as resource_count
FROM claim_resource cr
WHERE cr.claim_id = :claim_id";*/
$sql = "SELECT count(id) as resource_count
FROM assignments cr
WHERE cr.claim_id = :claim_id
AND IFNULL(cr.next_assignment_id,0) = 0
AND cr.is_current_assignment = 1 ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"claim_id"=>$claim->getId()
]);
$resourceCountResults = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$resourceCount = 0;
foreach ($resourceCountResults as $resourceCountRow){
$resourceCount = $resourceCountRow['resource_count'];
}
# check if the External Resource Widget is allowed to show for TPA Customer
$TpaCustomer = $this->getDoctrine()->getRepository("CompanyManagementBundle:TpaCustomer")->findOneBy(['customerId'=>$claim->getCustomer()->getId()]);
$isTpaCustomerAllowed=false;
if(!empty($TpaCustomer)){
$isTpaCustomerAllowed=true;
}
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/resources-widget.html.twig", [
"claim" => $claim,
'resourceTypes' => $resourceTypes,
'assignmentParties' => $assignmentParties,
'teams' => $claimTeams,
'resourceCount' => $resourceCount,
'licenseDataArray' => $licenseDataArray,
'alertMessageDateExpiry' =>$alertMessageDateExpiry,
'isTpaCustomerAllowed' =>$isTpaCustomerAllowed
]);
}
/**
* @Route("/main/coverage/add/{id}")
*/
public function addClaimCoverageAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$formFactory = $this->container->get("form.factory");
$CoverageFormHelper = new CoverageFormHelper($em, $formFactory, false);
$form = $CoverageFormHelper->getAddForm();
# 1) Create a Form for the Claim. It will be a PARTIAL form
//$form = $this->createForm(ClaimPolicyFragment::class, $claim);
$CoverageTypes = $em->getRepository("ClaimManagementBundle:CoverageType")->findBy([], ['coverageType' => 'ASC']);
$dateOpened = $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
$dateClosed = $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
if($dateClosed < $dateOpened){
$dateClosed = new \DateTime('now');
}
$difference = date_diff($dateOpened,$dateClosed);
$difference = (array)$difference;
$daysOpen = array();
$daysOpen['days'] = $difference['days'];
$daysOpen['h'] = $difference['h'];
$daysOpen['m'] = $difference['m'];
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-coverage-modal.html.twig", [
'CoverageTypes' => $CoverageTypes,
'claim' => $claim,
'coverageForm' => $form->createView(),
"daysOpen" => $daysOpen
]);
}
/**
* @Route("/main/coverage/edit/{id}")
*/
public function editClaimCoverageAction(Coverage $coverage)
{
# Make sure valid claim object was passed
if ($coverage === null) {
throw $this->createNotFoundException("Coverage does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
# 1) Create a Form for the Claim. It will be a PARTIAL form
$claim = $coverage->getClaim();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$coverageName = $coverage->getName();
//$coverageForm = $this->createForm(ClaimPolicyFragment::class, $claim);
$CoverageTypes = $em->getRepository("ClaimManagementBundle:CoverageType")->findAll();
$formFactory = $this->container->get("form.factory");
$CoverageFormHelper = new CoverageFormHelper($em, $formFactory, false);
$form = $CoverageFormHelper->getEditForm($coverage);
$dateOpened = $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
$dateClosed = $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
if($dateClosed < $dateOpened){
$dateClosed = new \DateTime('now');
}
$difference = date_diff($dateOpened,$dateClosed);
$difference = (array)$difference;
$daysOpen = array();
$daysOpen['days'] = $difference['days'];
$daysOpen['h'] = $difference['h'];
$daysOpen['m'] = $difference['m'];
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-coverage-modal.html.twig", [
'CoverageTypes' => $CoverageTypes,
'coverage' => $coverage,
'claim' => $claim,
'coverageForm' => $form->createView(),
'coverageName' => $coverageName,
"daysOpen" => $daysOpen
]);
}
/**
* @Route("/main/coverage/delete/{id}")
*/
public function deleteClaimCoverageAction(Request $request,$id)
{
$em = $this->container->get("doctrine.orm.entity_manager");
$ClaimCoverage = $em->getRepository("ClaimManagementBundle:Coverage")->find($id);
$claim = $ClaimCoverage->getClaim();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
if($ClaimCoverage){
$em->remove($ClaimCoverage);
$em->flush();
}
# Return JSON Errors Object
$retVal = array(
"result" => "success",
"error_msgs" => "",
"error" => false,
"data" => "Claim Coverage Deleted Sucessfully"
);
return new JsonResponse($retVal);
}
/**
* @Route("/main/claim_limit/add/{id}")
*/
public function addClaimLimitAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$formFactory = $this->container->get("form.factory");
$ClaimLimitFormHelper = new ClaimLimitFormHelper($em, $formFactory, false);
$form = $ClaimLimitFormHelper->getAddForm();
$dateOpened = $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
$dateClosed = $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
if($dateClosed < $dateOpened){
$dateClosed = new \DateTime('now');
}
$difference = date_diff($dateOpened,$dateClosed);
$difference = (array)$difference;
$daysOpen = array();
$daysOpen['days'] = $difference['days'];
$daysOpen['h'] = $difference['h'];
$daysOpen['m'] = $difference['m'];
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-claim-limit-modal.html.twig", [
'claim' => $claim,
'claimLimitForm' => $form->createView(),
"daysOpen" => $daysOpen
]);
}
/**
* @Route("/main/deductible/add/{id}")
*/
public function addClaimDeductibleAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$formFactory = $this->container->get("form.factory");
$DeductibleFormHelper = new DeductibleFormHelper($em, $formFactory, false);
$form = $DeductibleFormHelper->getAddForm();
$dateOpened = $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
$dateClosed = $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
if($dateClosed < $dateOpened){
$dateClosed = new \DateTime('now');
}
$difference = date_diff($dateOpened,$dateClosed);
$difference = (array)$difference;
$daysOpen = array();
$daysOpen['days'] = $difference['days'];
$daysOpen['h'] = $difference['h'];
$daysOpen['m'] = $difference['m'];
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-deductible-modal.html.twig", [
'claim' => $claim,
'deductibleForm' => $form->createView(),
"daysOpen" => $daysOpen
]);
}
/**
* @Route("/main/claim_limit/edit/{id}")
*/
public function editClaimLimitAction(ClaimLimit $claimLimit)
{
# Make sure valid claim object was passed
if ($claimLimit === null) {
throw $this->createNotFoundException("Claim Limit does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$claim = $claimLimit->getClaim();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$ClaimLimitFormHelper = new ClaimLimitFormHelper($em, $formFactory, false);
$form = $ClaimLimitFormHelper->getEditForm($claimLimit);
$dateOpened = $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
$dateClosed = $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
if($dateClosed < $dateOpened){
$dateClosed = new \DateTime('now');
}
$difference = date_diff($dateOpened,$dateClosed);
$difference = (array)$difference;
$daysOpen = array();
$daysOpen['days'] = $difference['days'];
$daysOpen['h'] = $difference['h'];
$daysOpen['m'] = $difference['m'];
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-claim-limit-modal.html.twig", [
'claim' => $claim,
'claimLimit' => $claimLimit,
'claimLimitForm' => $form->createView(),
"daysOpen" => $daysOpen
]);
}
/**
* @Route("/main/deductible/edit/{id}")
*/
public function editClaimDeductibleAction(Deductible $deductible)
{
# Make sure valid claim object was passed
if ($deductible === null) {
throw $this->createNotFoundException("Deductible does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$claim = $deductible->getClaim();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$DeductibleFormHelper = new DeductibleFormHelper($em, $formFactory, false);
$form = $DeductibleFormHelper->getEditForm($deductible);
$dateOpened = $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
$dateClosed = $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
if($dateClosed < $dateOpened){
$dateClosed = new \DateTime('now');
}
$difference = date_diff($dateOpened,$dateClosed);
$difference = (array)$difference;
$daysOpen = array();
$daysOpen['days'] = $difference['days'];
$daysOpen['h'] = $difference['h'];
$daysOpen['m'] = $difference['m'];
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-deductible-modal.html.twig", [
'claim' => $claim,
'deductible' => $deductible,
'deductibleForm' => $form->createView(),
"daysOpen" => $daysOpen
]);
}
/**
* @Route("/main/claim_limit/delete/{id}")
*/
public function deleteClaimLimitAction(Request $request, $id)
{
$em = $this->container->get("doctrine.orm.entity_manager");
$ClaimLimit = $em->getRepository("ClaimManagementBundle:ClaimLimit")->find($id);
$claim = $ClaimLimit->getClaim();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
if($ClaimLimit){
$em->remove($ClaimLimit);
$em->flush();
}
# Return JSON Errors Object
$retVal = array(
"result" => "success",
"error_msgs" => "",
"error" => false,
"data" => "Claim Limit sucessfully removed"
);
return new JsonResponse($retVal);
}
/**
* @Route("/main/deductible/delete/{id}")
*/
public function deleteClaimDeductibleAction(Request $request,$id)
{
$em = $this->container->get("doctrine.orm.entity_manager");
$ClaimDeductible = $em->getRepository("ClaimManagementBundle:Deductible")->find($id);
$claim = $ClaimDeductible->getClaim();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
if($ClaimDeductible){
$em->remove($ClaimDeductible);
$em->flush();
}
# Return JSON Errors Object
$retVal = array(
"result" => "success",
"error_msgs" => "",
"error" => false,
"data" => "Claim Coverage Deductible Sucessfully"
);
return new JsonResponse($retVal);
}
/**
* @Route("/main/resource/add/{id}")
* @deprecated
*/
public function addClaimResourceAction(Claim $claim, Request $request)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
$resourceId = intval($request->request->get("res_id"));
$Resource = array();
$claimResource = array();
if($resourceId <> 0){
$Resource = $em->getRepository("ResourceManagementBundle:Resource")->find($resourceId);
$claimResource = $em->getRepository("ClaimManagementBundle:ClaimResource")->findOneBy(
["resource" => $Resource, "claim" => $claim]
);
}
$teams = $em->getRepository("ClaimManagementBundle:ClaimTeam")->findBy(['enabled'=>true]);
$resourceTypes = $em->getRepository("ResourceManagementBundle:ResourceType")->findAll();
$assignmentParties = $em->getRepository("AssignmentBundle:AssignmentParty")->findAll();
$hasAdjusters = $em->getRepository("ClaimManagementBundle:ClaimResource")->getAdjustersByClaim($claim);
$adjusterRepo = $em->getRepository("ResourceManagementBundle:Resource");
$claimTeamRepo = $em->getRepository("ClaimManagementBundle:ClaimTeam");
$claimTeams = $claimTeamRepo->findBy(['enabled'=>true]);
if (count($hasAdjusters) > 0)
$hasAdjusters = true;
else
$hasAdjusters = false;
$claimTeamId = $claimTeamName = '';
$claimTeamObj = $claim->getClaimTeam();
if(!empty($claimTeamObj)){
$claimTeamId = $claim->getClaimTeam()->getId();
$claimTeamName = $claim->getClaimTeam()->getName();
}
//return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/share-resource-modal.html.twig", [
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/share-multple-resource-modal.html.twig", [
'claim' => $claim,
'teams' => $teams,
"hasAdjusters" => $hasAdjusters,
'resourceTypes' => $resourceTypes,
'assignmentParties' => $assignmentParties,
'resourceId'=>$resourceId,
"Resource" => $Resource,
"claimResource" => $claimResource,
"claimTeamId" => $claimTeamId,
"claimTeamName" => $claimTeamName
]);
}
/**
* @Route("/main/resource/change_team_cust/{id}")
*/
public function changeTeamCustomer(Claim $claim, Request $request)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
# entities needed for form
$teams = $em->getRepository("ClaimManagementBundle:ClaimTeam")->findBy(['enabled'=>true], ['name' => 'ASC']);
$customers = $em->getRepository("CustomerManagementBundle:Customer")->findBy([], ['companyName' => 'ASC']);
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/change-team-customer-modal.html.twig", [
'claim' => $claim,
'customers' => $customers,
'teams' => $teams
]);
}
/**
* @Route("/main/resource/reassign/{id}")
* @deprecated
*/
public function reassignClaimResourceAction(Claim $claim, Request $request)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
$resourceId = intval($request->request->get("res_id"));
$Resource = array();
$claimResources = array();
$claimResources = $em->getRepository("ClaimManagementBundle:ClaimResource")->findBy(
[ "claim" => $claim]
);
if($claim->getClaimTeam()){
$teams = $em->getRepository("ClaimManagementBundle:ClaimTeam")->find($claim->getClaimTeam()->getId());
}else{
$teams = $em->getRepository("ClaimManagementBundle:ClaimTeam")->findAll();
}
$resourceTypes = $em->getRepository("ResourceManagementBundle:ResourceType")->findAll();
$assignmentParties = $em->getRepository("AssignmentBundle:AssignmentParty")->findAll();
$hasAdjusters = $em->getRepository("ClaimManagementBundle:ClaimResource")->getAdjustersByClaim($claim);
//$claimTeamRepo = $em->getRepository("ClaimManagementBundle:ClaimTeam");
if (count($hasAdjusters) > 0)
$hasAdjusters = true;
else
$hasAdjusters = false;
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/reassign-resource-modal.html.twig", [
'claim' => $claim,
'teams' => $teams,
"hasAdjusters" => $hasAdjusters,
'resourceTypes' => $resourceTypes,
'assignmentParties' => $assignmentParties,
'resourceId'=>$resourceId,
"Resource" => $Resource,
"claimResources" => $claimResources
]);
}
/**
* @Route("/main/other-parties/add/{id}")
*/
public function addClaimOtherPartiesAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
# Get Other Parties Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$otherPartyFormHelper = new OtherPartyFormHelper($em, $formFactory, true);
$otherPartyForm = $otherPartyFormHelper->getAddForm();
$otherPartyTypes = $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->findAll();
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-other-party-modal.html.twig", [
"claim" => $claim,
'other_party_form' => $otherPartyForm->createView(),
"otherPartyTypes" => $otherPartyTypes
]);
}
/**
* @Route("/main/insureds/add/{id}")
*/
public function addClaimInsuredAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
# Get Insured Form Instance from Form Helper (will use without form tags)
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$InsuredFormHelper = new InsuredFormHelper($em, $formFactory, true);
$insuredForm = $InsuredFormHelper->getAddForm();
$InsuredTypes = $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->findAll();
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-insured-modal.html.twig", [
"claim" => $claim,
'insured_form' => $insuredForm->createView(),
"insuredTypes" => $InsuredTypes
]);
}
/**
* @Route("/main/insureds/update/{claimId}/{claimInsuredId}")
*/
public function updateClaimInsuredAction($claimId, $claimInsuredId)
{
$em = $this->getDoctrine()->getManager();
$claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$claimInsured = $em->getRepository("ClaimManagementBundle:ClaimsInsured")->find($claimInsuredId);
# Get Insured Form Instance from Form Helper (will use without form tags)
$formFactory = $this->container->get("form.factory");
$InsuredFormHelper = new InsuredFormHelper($em, $formFactory, true);
$insuredForm = $InsuredFormHelper->getEditForm($claimInsured->getInsured());
$InsuredTypes = $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->findAll();
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-insured-modal.html.twig", [
"claim" => $claim,
'insured_form' => $insuredForm->createView(),
"insuredTypes" => $InsuredTypes,
"claimInsuredId" => $claimInsuredId,
"claimInsured" => $claimInsured //added to save minor dob
]);
}
/**
* Modular Route that allows user to add/modify perils on claim,
* by calling twig render function
*
* @Route("/main/perils/{id}")
*/
public function showClaimPerilsAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$em = $this->container->get("doctrine.orm.entity_manager");
$rootPeril = null;
$rootPerilId = 0;
if ($claim->getPeril()) {
// $rootPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getPeril()->getId());
// $rootPerilId = $rootPeril->getId();
$rootPeril = $claim->getPeril();
$rootPerilId =$claim->getPeril()->getId();
}
$RootPerils = $em->getRepository("ClaimManagementBundle:Peril")->getRootPerils();
$subPeril = null;
$subPerilId = 0;
if ($claim->getSubPeril()) {
//$subPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getSubPeril()->getId());
//$subPerilId = $subPeril->getId();
$subPeril = $claim->getSubPeril();
$subPerilId =$claim->getSubPeril()->getId();
}
$ChildrenPerils = array();
if ($rootPeril !== null) {
$ChildrenPerils = $em->getRepository("ClaimManagementBundle:Peril")->getPerilChildren($rootPerilId);
}
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/perils-widget.html.twig", [
"claim" => $claim,
"rootPerilId" => $rootPerilId,
"rootPeril" => $rootPeril,
"SubPerilId" => $subPerilId,
"subPeril" => $subPeril,
"RootPerils" => $RootPerils,
"ChildrenPerils" => $ChildrenPerils,
]);
}
/**
* Action to show Modal "Edit Perils" box,
* to edit perils on claim
*
* @Route("/main/edit_peril/{id}")
*/
public function showEditClaimPerilsAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$em = $this->container->get("doctrine.orm.entity_manager");
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$rootPeril = null;
$rootPerilId = 0;
if ($claim->getPeril()) {
// $rootPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getPeril()->getId());
//$rootPerilId = $rootPeril->getId();
$rootPeril = $claim->getPeril();
$rootPerilId =$claim->getPeril()->getId();
}
$RootPerils = $em->getRepository("ClaimManagementBundle:Peril")->getRootPerils();
$subPeril = null;
$subPerilId = 0;
if ($claim->getSubPeril()) {
//$subPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getSubPeril()->getId());
//$subPerilId = $subPeril->getId();
$subPeril = $claim->getSubPeril();
$subPerilId =$claim->getSubPeril()->getId();
}
$ChildrenPerils = array();
if ($rootPeril !== null) {
$ChildrenPerils = $em->getRepository("ClaimManagementBundle:Peril")->getPerilChildren($rootPerilId);
}
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit_perils_modal.html.twig", [
"claim" => $claim,
"rootPerilId" => $rootPerilId,
"rootPeril" => $rootPeril,
"SubPerilId" => $subPerilId,
"subPeril" => $subPeril,
"RootPerils" => $RootPerils,
"ChildrenPerils" => $ChildrenPerils,
]);
}
/**
* Action to save Edit Perils Action, coming
* from Edit Perils Modal Box
*
* @Route("/main/save_edit_peril/{id}")
* @Method(methods={"POST"})
*/
public function saveEditPerilsAction(Claim $claim, Request $request)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$em = $this->container->get("doctrine.orm.entity_manager");
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$peril = $request->request->get("peril");
if (intval($peril) == 0) {
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "primary_loss_dropdown",
'text' => "You did not select a Loss Type."
];
return new JsonResponse($response);
}
# Save the Perils to the Claim using the Peril Helper Class
$ClaimNote = $this->container->get("claim.note_provider");
$perilHelper = new PerilHelper($em, $ClaimNote, $request);
$perilHelper->saveClaimPerils($claim->getId());
$response['error'] = false;
$response['data'] = [];
return new JsonResponse($response);
}
/**
* Called by Perils Module Twig Route to request children peril
* of a Peril
*
* @Route("/main/sub_perils/{parentPerilId}")
*/
public function getSubPerilsAction($parentPerilId)
{
$em = $this->container->get("doctrine.orm.entity_manager");
$SubPerils = $em->getRepository("ClaimManagementBundle:Peril")->getPerilChildren($parentPerilId);
if (count($SubPerils) > 0) {
$getSubPerils = array();
foreach ($SubPerils as $getPeril) {
$eachPeril = [
"id" => $getPeril->getId(),
"description" => $getPeril->getDescription()
];
$getSubPerils[] = $eachPeril;
}
return new JsonResponse([
"error" => false,
"data" => $getSubPerils
]);
} else {
return new JsonResponse([
"error" => true,
"data" => [],
"errors" => [
"No Sub Perils exist for this Parent Peril."
]
]);
}
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/perils-widget.html.twig", [
"SubPerils" => $SubPerils
]);
}
/**
* @Route("/main/insureds/search/{id}")
*/
public function getClaimInsuredDataAjaxAction(Request $request, Claim $claim)
{
## Use PaginatorService to return paginated results to DataTables Ajax Request
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$em = $this->container->get("doctrine.orm.entity_manager");
$claimId = $claim->getId();
# Array of columns that will be sorted
$columnsArr = array(
"insuredName",
"insuredEmail",
"insured_type",
"is_primary",
"stateCode"
);
# Build Query and PDO Parameters that will be passed to PaginatorService class
$dataParams = array();
$sql = "SELECT
ci.id, CONCAT(i.first_name, ' ', i.last_name) AS insuredName,i.email as insuredEmail, i.address, ci.is_primary, cit.insured_type, i.city, s.stateCode, i.zip_code
FROM claims_insured ci
INNER JOIN insured i
ON ci.insured_id = i.id
INNER JOIN claim_insured_types cit
ON ci.claim_insured_type_id = cit.id
LEFT JOIN state s
ON i.state_id = s.id
WHERE 1 = 1 ";
# Search By Claim ID
if ($claimId > 0) {
$sql .= "AND ci.claim_id = :claimId ";
$dataParams['claimId'] = $claimId;
}
# build keyword filter, which is requested by datatables ajax when someone types into keyword field
//$keyword_filter = "AND (s.stateCode like :keyword OR CONCAT(si.first_name, ' ', si.last_name) LIKE :keyword OR i.city like :keyword OR i.address like :keyword OR i.zip_code LIKE :keyword) ";
# call PaginatorService
$paginator = $this->container->get("resource.paginator_service");
$retVal = $paginator->getPaginationResults($request, $sql, $dataParams, "ci.id ASC", $columnsArr, "search_keyword", "", "keyword", "");
return new JsonResponse($retVal);
}
/**
* Load Claims Insured Record
*
* @Route("/main/claims_insureds/{id}")
*/
public function loadClaimInsured(ClaimsInsured $ClaimInsured)
{
$em = $this->getDoctrine();
if ($ClaimInsured === null) {
$this->createNotFoundException("Claims Insured record does not exist");
}
$Insured = $ClaimInsured->getInsured();
if ($Insured === null) {
$this->createNotFoundException("Insured entity does not exist on Claims Insured");
}
# Return loaded ClaimsInsured Entity as Json
/*/
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$insured_object = $serializer->serialize($Insured, 'json');
//*/
$sql = "SELECT * FROM insured WHERE id = :id ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"id"=>$ClaimInsured->getClaim()->getId()
]);
$insuredResults = $stmt->fetchAll(\PDO::FETCH_ASSOC);
echo "<pre>";print_r($insuredResults);die;
if (count($insuredResults) > 0){
$insured = $insuredResults[0];
}
$claimInsuredType = $ClaimInsured->getClaimInsuredType();
$insuredTypeId = $claimInsuredType->getId();
$minor_bday = "";
if ($ClaimInsured->getMinorBday()) {
$minor_bday = $ClaimInsured->getMinorBday()->format("Y-m-d");
}
$insuredTypes = $em->getRepository('ClaimManagementBundle:ClaimInsuredType')->findAll();
$retVal = [
"insured" => $insured,
"minor_bday" => $minor_bday,
"isPrimary" => ($ClaimInsured->getIsPrimary() === true) ? "1" : "0",
"insuredTypeId" => $insuredTypeId
];
return new JsonResponse($retVal);
}
/**
* @Route("/main/insured/save_add/{id}")
*/
public function saveClaimInsuredAction(Request $request, Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$em = $this->container->get("doctrine.orm.entity_manager");
$user = $this->getUser();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$minorInvolved = ($request->request->get('minorInvolved') == "1") ? true : false; //Added to save minor dob
$minor_dob = $request->request->get('minor_dob');//Added to save minor dob
# Check CSRF Token
$submittedToken = $request->request->get("_csrf_token");
if (!($user instanceof Resource)) { // if invalid user
# Send back error
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "";
$nextError['text'] = "You do not have permission to submit this form.";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => array(),
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$InsuredFormHelper = new InsuredFormHelper($em, $formFactory, true);
$insuredForm = $InsuredFormHelper->getAddForm();
$formSubmission = $request->request->get('form');
# Manually submit form
$insuredForm->submit($formSubmission);
# Get Form Fields
$insuredTypeId = $request->request->get("insuredType");
$isPrimary = intval($request->request->get("isPrimary"));
$HasPrimary = $em->getRepository("ClaimManagementBundle:ClaimsInsured")->findOneBy([
"claim" => $claim,
"isPrimary" => true
]);
if (!$HasPrimary) {
$isPrimary = 1;
}
$claimInsuredType = $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->find($insuredTypeId);
$Insured = $insuredForm->getData();
# Validate Entity set from Request
$errors = $this->get("validator")->validate($Insured);
//added code to save county
if(!empty($formSubmission["county"])) {
$county = $em->getRepository("ResourceManagementBundle:Counties")->findOneById($formSubmission["county"]);
if(!empty($county)) {
$Insured->setCounty($county);
}
}
$data = array();
$errors2 = array();
if (count($errors) == 0) { // if form is valid
//Added to save minor dob
if ($minorInvolved == 1) {
if ($minor_dob == "") {
$retVal = array();
$retVal['error'] = true;
$retVal['data'] = array();
$errorsArr = [
"id" => "minor_dob",
"text" => "Minor Date of Birth is required."
];
$retVal['data']['errors'][] = $errorsArr;
return new JsonResponse($retVal);
}
}
# Persist Document
$em->persist($Insured);
# Create ClaimsInsured Record
$ClaimsInsureds = new ClaimsInsured();
$ClaimsInsureds->setClaim($claim);
$ClaimsInsureds->setInsured($Insured);
//Added to save minor dob
$ClaimsInsureds->setMinorInvolved($minorInvolved);
if ($minorInvolved === true) {
$ClaimsInsureds->setMinorDOB(new \DateTime($minor_dob));
}
# Set Insured Type
if ($claimInsuredType) {
$ClaimsInsureds->setClaimInsuredType($claimInsuredType);
}
$em->persist($ClaimsInsureds);
# Persist to DB
$em->flush();
$claimInsured = $claim->getClaimsInsureds();
if (count($claimInsured) == 1) {
$isPrimary = true;
}
if ($isPrimary === true) { // if need to set to primary
# Use Claim Insured Helper to set this claimInsured record to primary, and all others on claim to isPrimary = false
$claimsInsuredHelper = new ClaimsInsuredHelper($em);
$claimsInsuredHelper->makeClaimInsuredPrimary($ClaimsInsureds, $claim);
}
# Log adding Claim Insured using Monolog
$logger = $this->get('monolog.logger.claims_log');
$logger->info('Claim Insured Created - Claim Insured ID: ' . $ClaimsInsureds->getId() . ", for Insured ID: " . $Insured->getId() . ", on Claim ID: " . $claim->getId());
$comment = 'Claim Insured Created - Claim Insured ID: ' . $ClaimsInsureds->getId() . ", for Insured ID: " . $Insured->getId() . ", on Claim ID: " . $claim->getId();
$userNoteLog = $this->container->get("app.resource_note_logger");
$user = $this->container->get("security.token_storage")->getToken()->getUser();
$resource = $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
$userNoteLog->logNote($comment, $resource,10,$claim);
/**
* @date 8/11/2017
*
* Added a Claim Note here to denote that an INSURED (CLAIMANT) was added to our Claim here.
*
*/
$ClaimNotes = $this->get('claim.note_provider');
//Status note = 65 Claimant
$ClaimNotes->addClaimNote( $ClaimsInsureds->getClaim(), "Claimant added to claim! First name: ".$ClaimsInsureds->getInsured()->getFirstName(), false, 65);
$retVal = array(
"status" => "success",
"error_msgs" => []
);
return new JsonResponse($retVal);
} else { // if form not valid
# Send back errors to client
$data = array();
$errors2 = array();
$errors = $this->get("validator")->validate($Insured);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
/**
* @Route("/main/team_cust/save/{id}")
*/
public function saveTeamCustChanges(Claim $claim, Request $request)
{
$em = $this->getDoctrine()->getManager();
$claimTeamManager = $this->get('claimteam.manager');
$formSubmission = $request->request->get('teamCustForm');
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$customer = $claim->getCustomer();
$customerSubmitted = $formSubmission['customer'];
$claimTeamSubmitted = $formSubmission['claimTeam'];
$response = [];
$ResourceInTeam=[];
$OldTeam='';
$NewTeam='';
/**
* Change Customer Validations
*/
# Don't change customer on XACT or Symbility claims
/*if ($claim->getTransactionId()) {
if ($claim->failsChangeCustomerValidation($customer, $formSubmission)) {
$response['error'] = "You can not change the customer of this claim!";
}
} else {*/
# dont throw error but throw alert message for user
if ($customer->getId() != $customerSubmitted) {
$response['alert'] = [
'title' => "Internal Rep Removed",
'content' => "Customer has been changed, removing internal rep"
];
$newCustomer = $em->getRepository('CustomerManagementBundle:Customer')->find($customerSubmitted);
$claim->removeClaimRep();
$claim->setCustomer($newCustomer);
$em->persist($claim);
$em->flush();
}
//}
# Save Claim Team
if ($claim->getClaimTeam() != $claimTeamSubmitted) {
$newClaimTeam = $em->getRepository('ClaimManagementBundle:ClaimTeam')->find($claimTeamSubmitted);
$NewTeam=$newClaimTeam->getName();
// added for error handling null
if ($claim->getClaimTeam() === null) {
}else{
$OldTeam=$claim->getClaimTeam()->getName();
}
// added for error handling null
$claim->setClaimTeam($newClaimTeam);
$em->persist($claim);
$em->flush();
}
/**
* Change ClaimTeam Validations
*/
$claimResources = $claim->getResources();
$claimTeam = $em->getRepository('ClaimManagementBundle:ClaimTeam')->find($claimTeamSubmitted);
# loop through our resources on the claim
foreach($claimResources as $claimResource) {
$adjuster = $claimResource->getResource();
# Assign the resource to the team if he is not on the team
$clamTeamResources = $em->getRepository("ClaimManagementBundle:ClaimTeamResource")
->findBy(['claimTeam' => $claimTeam,'resource' => $adjuster]);
if(empty($clamTeamResources)){
$claimTeamManager->addResourceToClaimTeam($adjuster,$claimTeam);
}
$OldAdjuster = $em->find("ResourceManagementBundle:Resource", intval($adjuster->getId()));
$ResourceInTeam[]=$OldAdjuster;
}
if ($claim->getClaimTeam() != $claimTeamSubmitted) {
# First to Call Un-assigned event
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(new ChangeTeamEvent($claim, $ResourceInTeam,$OldTeam,false), ChangeTeamEvent::NAME);
#second to call assign event
$dispatcher->dispatch(new ChangeTeamEvent($claim, $ResourceInTeam,$NewTeam,true), ChangeTeamEvent::NAME);
}
return new JsonResponse($response);
}
/**
* @Route("/main/insured/save_update/{claimId}/{claimInsuredId}")
*/
public function saveUpdateClaimInsuredAction(Request $request, $claimId, $claimInsuredId)
{
$em = $this->container->get("doctrine.orm.entity_manager");
$claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
$ClaimsInsureds = $em->getRepository("ClaimManagementBundle:ClaimsInsured")->find($claimInsuredId);
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$minorInvolved = ($request->request->get('minorInvolved') == "1") ? true : false; //Added to save minor dob
$minor_dob = $request->request->get('minor_dob');//Added to save minor dob
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Make sure valid Claims Insured Record exists
if ($ClaimsInsureds === null) {
throw $this->createNotFoundException("Claims Insured Record does not exist");
}
# Make sure Insured Record exists
$Insured = $ClaimsInsureds->getInsured();
if ($Insured === null) {
throw $this->createNotFoundException("Claim does not have insured record");
}
# Check CSRF Token
$submittedToken = $request->request->get("_csrf_token");
// if (!$this->isCsrfTokenValid('edit_claim_insured', $submittedToken)) { // if invalid csrf token
if (!($this->getUser() instanceof Resource)) {
# Send back error
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "";
$nextError['text'] = "You do not have permission to submit this form.";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => array(),
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$InsuredFormHelper = new InsuredFormHelper($em, $formFactory, true);
$insuredForm = $InsuredFormHelper->getEditForm($Insured);
# Get Form Fields
$formSubmission = $request->request->get('form');
# Manually submit form
$insuredForm->submit($formSubmission);
$insuredTypeId = $request->request->get("insuredType");
$isPrimary = intval($request->request->get("isPrimary"));
$claimInsuredType = $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->find($insuredTypeId);
$Insured = $insuredForm->getData();
$Insured2 = $Insured;
## Code checks if changes were made to Insured Object ##
# Get Current Resource on DB
$insured_compare = new InsuredCompareHelper($em);
$insured_compare->setCurInsured($Insured2);
$ClaimInsured = $em->getRepository("ClaimManagementBundle:ClaimsInsured")->loadByClaimAndInsured($claim, $Insured);
if ($claimInsuredType) {
$ClaimInsured->setClaimInsuredType($claimInsuredType);
}
###
# Deal with setting Claim Insured Type, Minor Birthday, verifying if these fields have changed on this update
# Do some checking to check if Claim Insured Type Changed
//*/
$claimInsuredChanged = false;
$insuredTypeChanged = false;
$ClaimInsuredHelper = new ClaimInsuredChangesHelper($em);
$changedInsuredType = $ClaimInsuredHelper->insuredTypeDidChange($claim, $Insured, $claimInsuredType);
$claimInsuredChanged = $ClaimInsuredHelper->minorBDayDidChange($ClaimsInsureds, $minor_dob); //Added to save the minor involved and minor dob change
if ($changedInsuredType != "") {
$insuredTypeChanged = true;
}
//added code to save county
if(!empty($formSubmission["county"])) {
$county = $em->getRepository("ResourceManagementBundle:Counties")->findOneById($formSubmission["county"]);
if(!empty($county)) {
$Insured->setCounty($county);
}
}
#
###
# Set Claim Insured Type
# Validate Entity set from Request
$errors = $this->get("validator")->validate($Insured);
$data = array();
$errors2 = array();
if (count($errors) == 0) { // if form is valid
//Added to save the minor involved and minor dob change
if ($minorInvolved == 1) {
if ($minor_dob == "") {
$retVal = array();
$retVal['error'] = true;
$retVal['data'] = array();
$errorsArr = [
"id" => "minor_dob",
"text" => "Minor Date of Birth is required."
];
$retVal['data']['errors'][] = $errorsArr;
return new JsonResponse($retVal);
}
$ClaimInsured->setMinorInvolved($minorInvolved);
$ClaimInsured->setMinorDOB(new \DateTime($minor_dob));
}
else{
$ClaimInsured->setMinorInvolved($minorInvolved);
$ClaimInsured->setMinorDOB(null);
}
# Compare 2 objects to see if there were any changes made
$insured_compare->setNewInsured($Insured);
$hasChanges = $insured_compare->compareObjects();
# Persist Document
$em->persist($Insured);
$em->persist($ClaimInsured);
$em->flush();
if ($hasChanges || $claimInsuredChanged) { // check if whether Insured Entity or Claim Insured Entity was changed
$getChanges = array();
if ($hasChanges) {
$changeLog = $insured_compare->changeLog;
$getChanges2 = array_merge($getChanges, $changeLog);
} else {
$getChanges2 = $getChanges;
}
$ClaimNote = $this->container->get("claim.note_provider");
$ClaimNote->addClaimNote($claim, "Claim Insured was updated. " . implode(" ", $getChanges2), false, 52);
}
if ($isPrimary === 1) { // if set to primary
# Use Claim Insured Helper to set this claimInsured record to primary, and all others on claim to isPrimary = false
$claimsInsuredHelper = new ClaimsInsuredHelper($em);
$claimsInsuredHelper->makeClaimInsuredPrimary($ClaimInsured, $claim);
}
# Log updating Claim Insured using Monolog
$logger = $this->get('monolog.logger.claims_log');
$logger->info("Claim Insured Updated - Insured ID: " . $Insured->getId() . ", with ClaimInsuredID: " . $ClaimInsured->getId() . ", on Claim ID: " . $claim->getId());
$comment = 'Claim Insured Updated - Claim Insured ID: ' . $Insured->getId() . ", with ClaimInsuredID: " . $ClaimInsured->getId() . ", on Claim ID: " . $claim->getId();
$userNoteLog = $this->container->get("app.resource_note_logger");
$user = $this->container->get("security.token_storage")->getToken()->getUser();
$resource = $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
$userNoteLog->logNote($comment, $resource,10,$claim);
$ClaimNotes = $this->get('claim.note_provider');
$ClaimNotes->addClaimNote( $ClaimsInsureds->getClaim(), "Insured edited! First name: ". $Insured->getFirstName() , false, 52);
$retVal = array(
"status" => "success",
"error_msgs" => []
);
return new JsonResponse($retVal);
} else { // if form not valid
# Send back errors to client
$data = array();
$errors2 = array();
$errors = $this->get("validator")->validate($Insured);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
/**
* @Route("/main/insured/delete")
* @Method(methods={"POST"})
*/
public function deleteClaimInsuredAction(Request $request)
{
$em = $this->container->get("doctrine.orm.entity_manager");
# Request ID to delete
$id = intval($request->request->get("id"));
# Delete Certificate
$ClaimsInsured = $em->getRepository("ClaimManagementBundle:ClaimsInsured")->find($id);
if ($ClaimsInsured->getIsPrimary()) {
$retVal = [
'error' => true,
'error_msgs' => ["You cannot remove the Primary Insured."]
];
return new JsonResponse($retVal);
}
# Get claim, claim insured objects while they exist
$insured = $ClaimsInsured->getInsured();
$insuredId = $insured->getId();
$claim = $ClaimsInsured->getClaim();
$claimId = $claim->getId();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$em->remove($ClaimsInsured->getInsured());
$em->remove($ClaimsInsured);
$em->flush();
# Get all claim insureds after removing one of them
$claimInsured = $claim->getClaimsInsureds();
if (count($claimInsured) == 1) { // if there is only one insured on the claim
# Make that insured primary
$getClaimInsured = $claimInsured[0];
$claimsInsuredHelper = new ClaimsInsuredHelper($em);
$claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
$claimsInsuredHelper->makeClaimInsuredPrimary($getClaimInsured, $claim);
}
# Log deleting Claim Insured using Monolog
$logger = $this->get('monolog.logger.claims_log');
$logger->info("Claim Insured Deleted - Insured ID: " . $insuredId . ", with ClaimInsuredID: " . $id . ", on Claim ID: " . $claimId);
$comment = "Claim Insured Deleted - Insured ID: " . $insuredId . ", with ClaimInsuredID: " . $id . ", on Claim ID: " . $claimId;
$userNoteLog = $this->container->get("app.resource_note_logger");
$user = $this->container->get("security.token_storage")->getToken()->getUser();
$resource = $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
$userNoteLog->logNote($comment, $resource,10,$claim);
/*$retVal = array(
"status" => "success",
"error_msgs" => []
);*/
$retVal = [
'error' => false,
'error_msgs' => []
];
return new JsonResponse($retVal);
}
/**
* @Route("/main/resource/save_add/{id}")
*/
public function saveClaimResourceAction(Request $request, $id)
{
// entity manager
$em = $this->container->get("doctrine.orm.entity_manager");
// Default response
$response = [
'error' => false
];
return new JsonResponse($response);
}
/**
* @Route("/main/claim_limit/save_add/{id}")
*/
public function saveClaimLimitAction(Request $request, $id)
{
// entity manager
$em = $this->container->get("doctrine.orm.entity_manager");
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->find($id);
if ($Claim === null) {
return new NotFoundHttpException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $Claim);
// Default response
$response = [
'error' => false
];
$formFactory = $this->container->get("form.factory");
$ClaimLimitFormHelper = new ClaimLimitFormHelper($em, $formFactory, false);
$form = $ClaimLimitFormHelper->getAddForm();
# Handle request
$form->handleRequest($request);
$ClaimLimit = $form->getData();
if ($form->isValid()) { // if form is valid
//test for duplicate
$sql = "SELECT COUNT(*) as claim_count
FROM claim_limit
WHERE claim_id = :claim_id
AND claim_limit_type_id =:claim_limit_type_id";
$claimLimitType = $ClaimLimit->getClaimLimitType();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"claim_limit_type_id" => $claimLimitType->getId(),
'claim_id' => $Claim->getId()
]);
$claim_count = $stmt->fetchAll( \PDO::FETCH_ASSOC );
if( $claim_count[0]['claim_count'] > 0 ){
$retVal = array(
"error" => true,
'msg' => 'Claim limit "'.$claimLimitType->getName().'"" has already been set'
);
return new JsonResponse($retVal);
}
$ClaimLimit->setClaim($Claim);
$em->persist($ClaimLimit);
$em->flush();
# Return JSON Errors Object
$retVal = array(
"error" => false
);
return new JsonResponse($retVal);
}else{
$data = array();
$errors2 = array();
# Get Validation Error Messages
$errors = $this->get("validator")->validate($ClaimLimit);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
# Return JSON Errors Object
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
return new JsonResponse($response);
}
/**
* @Route("/main/deductible/save_add/{id}")
*/
public function saveClaimDeductibleAction(Request $request, $id)
{
// entity manager
$em = $this->container->get("doctrine.orm.entity_manager");
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->find($id);
if ($Claim === null) {
return new NotFoundHttpException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $Claim);
// Default response
$response = [
'error' => false
];
$formFactory = $this->container->get("form.factory");
$DeductibleFormHelper = new DeductibleFormHelper($em, $formFactory, false);
$form = $DeductibleFormHelper->getAddForm();
# Handle request
$form->handleRequest($request);
$Deductible = $form->getData();
if ($form->isValid()) { // if form is valid
$Deductible->setClaim($Claim);
$deductibleName = $Deductible->getDeductibleName();
//test for duplicate
$sql = "SELECT COUNT(*) as deductible_count
FROM deductible
WHERE claim_id = :claim_id
AND deductible_name_id = :deductible_name_id";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"deductible_name_id" => $deductibleName->getId(),
'claim_id' => $Claim->getId()
]);
$deductible_count = $stmt->fetchAll( \PDO::FETCH_ASSOC );
if( $deductible_count[0]['deductible_count'] > 0 ){
$retVal = array(
"error" => true,
'msg' => 'Claim limit "'.$deductibleName->getName().'"" has already been set'
);
return new JsonResponse($retVal);
}
$em->persist($Deductible);
$em->flush();
# Return JSON Errors Object
$retVal = array(
"error" => false,
);
return new JsonResponse($retVal);
}else{
$data = array();
$errors2 = array();
# Get Validation Error Messages
$errors = $this->get("validator")->validate($Deductible);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
# Return JSON Errors Object
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
return new JsonResponse($response);
}
/**
* @Route("/main/claim_limit/save_edit/{id}")
*/
public function saveEditClaimLimitAction(Request $request, $id)
{
// entity manager
$em = $this->container->get("doctrine.orm.entity_manager");
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->find($id);
if ($Claim === null) {
return new NotFoundHttpException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $Claim);
// Default response
$response = [
'error' => false
];
$claim_limit_id = $request->request->get("claim_limit_id");
$ClaimLimit = $em->getRepository("ClaimManagementBundle:ClaimLimit")->find($claim_limit_id);
$formFactory = $this->container->get("form.factory");
$ClaimLimitFormHelper = new ClaimLimitFormHelper($em, $formFactory, false);
$form = $ClaimLimitFormHelper->getEditForm($ClaimLimit);
# Handle request
$form->handleRequest($request);
/** @var ClaimLimit $ClaimLimit */
$ClaimLimit = $form->getData();
if ($form->isValid()) { // if form is valid
$ClaimLimit->setClaim($Claim);
$em->persist($ClaimLimit);
$em->flush();
# Return JSON Errors Object
$retVal = array(
"error" => false,
);
return new JsonResponse($retVal);
}else{
$data = array();
$errors2 = array();
# Get Validation Error Messages
$errors = $this->get("validator")->validate($ClaimLimit);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
# Return JSON Errors Object
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
return new JsonResponse($response);
}
/**
* @Route("/main/deductible/save_edit/{id}")
*/
public function saveEditClaimDeductibleAction(Request $request, $id)
{
// entity manager
$em = $this->container->get("doctrine.orm.entity_manager");
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->find($id);
if ($Claim === null) {
return new NotFoundHttpException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $Claim);
// Default response
$response = [
'error' => false
];
$deductible_id = $request->request->get("deductible_id");
$Deductible = $em->getRepository("ClaimManagementBundle:Deductible")->find($deductible_id);
$formFactory = $this->container->get("form.factory");
$DeductibleFormHelper = new DeductibleFormHelper($em, $formFactory, false);
$form = $DeductibleFormHelper->getEditForm($Deductible);
# Handle request
$form->handleRequest($request);
$Deductible = $form->getData();
if ($form->isValid()) { // if form is valid
$Deductible->setClaim($Claim);
$em->persist($Deductible);
$em->flush();
# Return JSON Errors Object
$retVal = array(
"error" => false,
);
return new JsonResponse($retVal);
}else{
$data = array();
$errors2 = array();
# Get Validation Error Messages
$errors = $this->get("validator")->validate($Deductible);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
# Return JSON Errors Object
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
return new JsonResponse($response);
}
/**
* @Route("/main/coverage/save_add/{id}")
*/
public function saveClaimCoverageAction(Request $request, $id)
{
// entity manager
$em = $this->container->get("doctrine.orm.entity_manager");
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->find($id);
if ($Claim === null) {
return new NotFoundHttpException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $Claim);
// Default response
$response = [
'error' => false
];
$coverageType = $em->getRepository("ClaimManagementBundle:CoverageType")->find($request->request->get("coverage_type"));
$formFactory = $this->container->get("form.factory");
$CoverageFormHelper = new CoverageFormHelper($em, $formFactory, false);
$form = $CoverageFormHelper->getAddForm();
# Figure out the current user
$current_user = $this->get('security.token_storage')->getToken()->getUser();
# Handle request
$form->handleRequest($request);
$Coverage = $form->getData();
$Coverage->setClaim($Claim);
if ($coverageType) {
$Coverage->setCoverageType($coverageType);
$Coverage->setName($coverageType->getCoverageType());
}
$Coverage->setDateChanged( date_create() );
// Create the new Reserve here
$covReserve = new CoverageReserve();
$covReserve->setAmount($Coverage->getReserve());
$covReserve->setCoverage($Coverage);
$covReserve->setDateModified( new \DateTime() );
$covReserve->setReason($Coverage->getReasonChanged());
$covReserve->setResource($current_user);
$em->persist($covReserve);
$errors = $this->get("validator")->validate($Coverage);
if (count($errors) == 0) {
$em->persist($Coverage);
$em->flush();
# Return JSON Errors Object
$retVal = array(
"error" => false,
);
return new JsonResponse($retVal);
} else {
$data = array();
$errors2 = array();
# Get Validation Error Messages
$errors = $this->get("validator")->validate($Coverage);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
# Return JSON Errors Object
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
/**
* @Route("/main/coverage/save_edit/{id}")
*/
public function saveEditClaimCoverageAction(Request $request, $id)
{
// entity manager
$em = $this->container->get("doctrine.orm.entity_manager");
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->find($id);
if ($Claim === null) {
return new NotFoundHttpException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $Claim);
// Default response
$response = [
'error' => false
];
$coverageType = $request->request->get("coverage_type");
$coverageId = $request->request->get("coverage_id");
/** @var Coverage $Coverage */
$Coverage = $em->getRepository("ClaimManagementBundle:Coverage")->find($coverageId);
$origVal = $Coverage->getReserve();
# Figure out the current user
$current_user = $this->get('security.token_storage')->getToken()->getUser();
$formFactory = $this->container->get("form.factory");
$CoverageFormHelper = new CoverageFormHelper($em, $formFactory, false);
$form = $CoverageFormHelper->getEditForm($Coverage);
# Handle request
$form->handleRequest($request);
$Coverage = $form->getData();
$Coverage->setName($coverageType);
$Coverage->setClaim($Claim);
$errors = $this->get("validator")->validate($Coverage);
if (count($errors) == 0) {
// Add the user doing it, and the current date (but only if.. hmm.. the change was different?)
if(floatval($Coverage->getReserve()) !== $origVal)
{
$Coverage->setDateChanged( new \DateTime() );
$Coverage->setUserChanged( $current_user );
}
// Create the new Reserve here
$covReserve = new CoverageReserve();
$covReserve->setAmount($Coverage->getReserve());
$covReserve->setCoverage($Coverage);
$covReserve->setDateModified( new \DateTime() );
$covReserve->setReason($Coverage->getReasonChanged());
$covReserve->setResource($current_user);
$em->persist($Coverage);
$em->persist($covReserve);
$em->flush();
# Return JSON Errors Object
$retVal = array(
"error" => false,
);
return new JsonResponse($retVal);
}else{
$data = array();
$errors2 = array();
# Get Validation Error Messages
$errors = $this->get("validator")->validate($Coverage);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
# Return JSON Errors Object
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
/**
* @Route("/unassign/{claimId}")
* @deprecated
*/
public function unassignClaim( $claimId )
{
$assignmentService = $this->get('claim.assignment');
// Set default response mesage
$response = [
'error' => false,
'message' => 'Claim Successfully Unassigned'
];
$em = $this->getDoctrine()->getManager();
# Check Permissions
// $this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$sql = "UPDATE claim SET status_id = 5, claim_team_id = NULL, full_file_assignment = 0, loss_notes = '', updated_at = NOW() WHERE id = :claimId";
$stmt = $em->getConnection()->prepare($sql);
if( !( $stmt->execute([
"claimId" => $claimId
])) ){
$response = [
'error' => TRUE,
'message' => 'Unable to remove claim team'
];
return new JsonResponse($response);
}
# Remove all adjusters
$claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
$assignmentService->removePrevAdjuster($claim);
# 2020 MARCH -- NOTES FOR SUB TASKS
$cns = $this->get('claim.note_provider');
if ($claim->getParentTask() && $claim->getSubTaskIndex()) {
$cns->addClaimNote($claim->getParentTask(), "A sub-task was unassigned: Sub task ID " . $claim->getSubTaskIndex());
}
return new JsonResponse($response);
}
/**
* @Route("/main/resource/delete")
* @deprecated
*/
public function deleteClaimResourceAction(Request $request)
{
$em = $this->container->get("doctrine.orm.entity_manager");
// $diaryEntry = $this->getDoctrine()->getRepository('ClaimManagementBundle:DiaryEntry')->find($diary_id);
// $diaryEntry->setStatus(1);
# Request ID to delete
$resource_id = intval($request->request->get("res_id"));
$claim_id = intval($request->request->get("claim_id"));
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claim_id);
$Resource = $em->getRepository("ResourceManagementBundle:Resource")->find($resource_id);
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $Claim);
# Delete Claim Resource
/** @var ClaimResource $ClaimResource */
$ClaimResource = $em->getRepository("ClaimManagementBundle:ClaimResource")->findOneBy([
'claim' => $Claim,
'resource' => $Resource,
]);
if( (is_countable($ClaimResource) && count($ClaimResource) == 0) || !is_object($ClaimResource)){
$retVal = [
'error' => true,
'error_msgs' => ['No resource Found!']
];
return new JsonResponse($retVal);
}
# Create a new entry in claim_resource_previous table
$claimResourcesPrev = $em->getRepository("ClaimManagementBundle:ClaimResourcePrevious")->findBy([
'claim' => $Claim,
'resource' => $Resource,
]);
if(count($claimResourcesPrev)>0){
foreach ($claimResourcesPrev as $claimResourcePrevious){
$claimResourcePrevious->setClaim($Claim);
$claimResourcePrevious->setResource($Resource);
$em->persist($claimResourcePrevious);
$em->flush();
}
}else {
$claimResourcePrevious = new ClaimResourcePrevious();
$claimResourcePrevious->setClaim($Claim);
$claimResourcePrevious->setIsPrimary($ClaimResource->getIsPrimaryAdjuster());
$claimResourcePrevious->setResource($Resource);
$em->persist($claimResourcePrevious);
$em->flush();
}
# remove resource from claim
/** @var ClaimNotesProviderService $noteService */
$noteService = $this->get('claim.note_provider');
$format = "%s was removed from the Claim";
$noteService->addClaimNote($Claim, (sprintf($format, $ClaimResource->getResource()->getFullName())), true, 52);
$em->remove($ClaimResource);
$em->flush();
/*
* Check diary objects and set them to Complete for the resource removed
*/
$sql = "select id from diary_entry where resource_id = :resource_id and claim_id = :claim_id ";
$dataParams['resource_id'] = $resource_id;
$dataParams['claim_id'] = $claim_id;
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute($dataParams);
$diaryObjectsIds = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if ($diaryObjectsIds){
foreach ($diaryObjectsIds as $getID) {
//echo $getID['id'];
$diaryEntry = $this->getDoctrine()->getRepository('ClaimManagementBundle:DiaryEntry')->find($getID['id']);
$diaryEntry->setStatus(1);
$em = $this->getDoctrine()->getManager();
$em->persist($diaryEntry);
$em->flush();
}
}
# Get all claim resources
# after removing one of them
$claimResources = $em->getRepository("ClaimManagementBundle:ClaimResource")->findBy([
'claim' => $Claim,
]);
if (count($claimResources) > 0) {
//check if any primary adjuster exists
$isPrimaryExists = false;
foreach ($claimResources as $claimResource) {
if ($claimResource->getIsPrimaryAdjuster() ) {
$isPrimaryExists = true;
}
}
//if not make one as primary adjuster
if(!$isPrimaryExists){
$claimResource = $claimResources[0];
$claimResource->setIsPrimaryAdjuster(true);
$em->persist($claimResource);
}
$em->flush();
}else{
$Claim->setStatus(5);
$Claim->setClaimTeam(null);
$em->persist($Claim);
$em->flush();
}
$retVal = [
'error' => false,
'error_msgs' => []
];
return new JsonResponse($retVal);
}
/**
* @Route("/main/resource/validate")
*/
public function validateResourcesOnTeam(Request $request)
{
$em = $this->getDoctrine()->getManager();
# Request ID to delete
$claimId = intval($request->request->get("claim_id"));
$teamId = intval($request->request->get("team_id"));
$Claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
$Team = $em->getRepository("ClaimManagementBundle:ClaimTeam")->find($teamId);
$claimResources = $Claim->getResources();
$json_response = [
'error' => false,
'errors' => [],
'data' => []
];
foreach($claimResources as $claimResource) {
$Adjuster = $claimResource->getResource();
$claimTeamResource = $em->getRepository("ClaimManagementBundle:ClaimTeamResource")->findBy(['claimTeam' => $Team, 'resource' => $Adjuster]);
if (empty($claimTeamResource)) {
$json_response['error'] = true;
$json_response['errors'][] = "{$Adjuster->getFullName()} does not belong to the team {$Team->getName()} ! ";
}
}
return new JsonResponse($json_response);
}
public function slugify($text)
{
$delimiter = "_";
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
return strtolower(preg_replace('/[^A-Za-z0-9-]+/', $delimiter, $text));
}
/**
* @Route("/main/other-party/save_add/{id}")
*/
public function saveClaimOtherPartyAction(Request $request, Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$user = $this->getUser();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$minorInvolved = ($request->request->get('minorInvolved') == "1") ? true : false; //Added to save minor dob
$minor_dob = $request->request->get('minor_dob');//Added to save minor dob
# Check CSRF Token
$submittedToken = $request->request->get("_csrf_token");
if (!($user instanceof Resource)) { // if invalid user
# Send back error
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "";
$nextError['text'] = "You do not have permission to submit this form.";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => array(),
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$otherPartyFormHelper = new OtherPartyFormHelper($em, $formFactory, true);
$otherPartyForm = $otherPartyFormHelper->getAddForm();
$formSubmission = $request->request->get('form');
# Manually submit form
$otherPartyForm->submit($formSubmission);
# Get Form Fields
$otherPartyTypeId = $request->request->get("otherPartyType");
$isPrimary = intval($request->request->get("isPrimary"));
$HasPrimary = $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->findOneBy([
"claim" => $claim,
"isPrimary" => true
]);
if (!$HasPrimary) {
$isPrimary = 1;
}
$claimOtherPartyType = $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->find($otherPartyTypeId);
$otherParty = $otherPartyForm->getData();
# Validate Entity set from Request
$errors = $this->get("validator")->validate($otherParty);
//added code to save county
if(!empty($formSubmission["county"])) {
$county = $em->getRepository("ResourceManagementBundle:Counties")->findOneById($formSubmission["county"]);
if(!empty($county)) {
$otherParty->setCounty($county);
}
}
$data = array();
$errors2 = array();
if (count($errors) == 0) { // if form is valid
//Added to save minor dob
if ($minorInvolved == 1) {
if ($minor_dob == "") {
$retVal = array();
$retVal['error'] = true;
$retVal['data'] = array();
$errorsArr = [
"id" => "minor_dob",
"text" => "Minor Date of Birth is required."
];
$retVal['data']['errors'][] = $errorsArr;
return new JsonResponse($retVal);
}
}
# Persist Document
$em->persist($otherParty);
# Create ClaimOtherParty Record
$claimOtherParty = new ClaimsOtherParty();
$claimOtherParty->setClaim($claim);
$claimOtherParty->setOtherParty($otherParty);
//Added to save minor dob
$claimOtherParty->setMinorInvolved($minorInvolved);
if ($minorInvolved === true) {
$claimOtherParty->setMinorDOB(new \DateTime($minor_dob));
}
# Set Other Party Type
if ($claimOtherPartyType) {
$claimOtherParty->setClaimOtherPartyType($claimOtherPartyType);
}
$em->persist($claimOtherParty);
# Persist to DB
$em->flush();
$claimOtherParties = $claim->getOtherPartyOther();
if (count($claimOtherParties) == 1) {
$isPrimary = true;
}
if ($isPrimary === true) { // if need to set to primary
# Use Claim Other Party Helper to set this claimInsured record to primary, and all others on claim to isPrimary = false
$claimsOtherPartyHelper = new ClaimsOtherPartyHelper($em);
$claimsOtherPartyHelper->makeClaimOtherPartyPrimary($claimOtherParty, $claim);
}
# Log adding Claim Insured using Monolog
$logger = $this->get('monolog.logger.claims_log');
$logger->info('Claim Other Party added - Claim Other Party ID: ' . $claimOtherParty->getId() . ", for Other Party ID: " . $otherParty->getId() . ", on Claim ID: " . $claim->getId());
$comment = 'Claim Other Party added - Claim Other Party ID: ' . $claimOtherParty->getId() . ", for Other Party ID: " . $otherParty->getId() . ", on Claim ID: " . $claim->getId();
$userNoteLog = $this->container->get("app.resource_note_logger");
$user = $this->container->get("security.token_storage")->getToken()->getUser();
$resource = $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
$userNoteLog->logNote($comment, $resource,10,$claim);
/**
* @date 8/11/2017
*
* Added a Claim Note here to denote that an INSURED (CLAIMANT) was added to our Claim here.
*
*/
$ClaimNotes = $this->get('claim.note_provider');
//Status note = 65 Claimant
$ClaimNotes->addClaimNote( $claimOtherParty->getClaim(), "Other Party added to claim! First name: ".$claimOtherParty->getOtherParty()->getFirstName(), false, 65);
$retVal = array(
"status" => "success",
"error_msgs" => []
);
return new JsonResponse($retVal);
} else { // if form not valid
# Send back errors to client
$data = array();
$errors2 = array();
$errors = $this->get("validator")->validate($otherParty);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
/**
* @Route("/main/other-parties/search/{id}")
*/
public function getClaimOtherPartiesDataAjaxAction(Request $request, Claim $claim)
{
## Use PaginatorService to return paginated results to DataTables Ajax Request
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$em = $this->container->get("doctrine.orm.entity_manager");
$claimId = $claim->getId();
# Array of columns that will be sorted
$columnsArr = array(
"insuredName",
"other_party_type",
"is_primary",
"stateCode"
);
# Build Query and PDO Parameters that will be passed to PaginatorService class
$dataParams = array();
$sql = "SELECT
cop.id, CONCAT(op.first_name, ' ', op.last_name) AS insuredName, op.address, cop.is_primary, copt.other_party_type, op.city, s.stateCode, op.zip_code
FROM claims_other_party cop
INNER JOIN other_party op
ON cop.other_party_id = op.id
INNER JOIN claim_other_party_type copt
ON cop.claim_other_party_type_id = copt.id
LEFT JOIN state s
ON op.state_id = s.id
WHERE 1 = 1 ";
# Search By Claim ID
if ($claimId > 0) {
$sql .= "AND cop.claim_id = :claimId ";
$dataParams['claimId'] = $claimId;
}
# build keyword filter, which is requested by datatables ajax when someone types into keyword field
//$keyword_filter = "AND (s.stateCode like :keyword OR CONCAT(si.first_name, ' ', si.last_name) LIKE :keyword OR i.city like :keyword OR i.address like :keyword OR i.zip_code LIKE :keyword) ";
# call PaginatorService
$paginator = $this->container->get("resource.paginator_service");
$retVal = $paginator->getPaginationResults($request, $sql, $dataParams, "cop.id ASC", $columnsArr, "search_keyword", "", "keyword", "");
return new JsonResponse($retVal);
}
/**
* @Route("/main/other-party/update/{claimId}/{claimOtherPartyId}")
*/
public function updateClaimOtherPartyAction($claimId, $claimOtherPartyId)
{
$em = $this->getDoctrine()->getManager();
$claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$claimOtherParty = $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->find($claimOtherPartyId);
# Get Insured Form Instance from Form Helper (will use without form tags)
$formFactory = $this->container->get("form.factory");
$otherPartyFormHelper = new OtherPartyFormHelper($em, $formFactory, true);
$otherPartyForm = $otherPartyFormHelper->getEditForm($claimOtherParty->getOtherParty());
$otherPartyTypes = $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->findAll();
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-other-party-modal.html.twig", [
"claim" => $claim,
'other_party_form' => $otherPartyForm->createView(),
"otherPartyTypes" => $otherPartyTypes,
"claimOtherPartyId" => $claimOtherPartyId,
"claimOtherParty" => $claimOtherParty //added to save minor dob
]);
}
/**
* @Route("/main/other-party/save_update/{claimId}/{claimOtherPartyId}")
*/
public function saveUpdateClaimOtherPartyAction(Request $request, $claimId, $claimOtherPartyId)
{
$em = $this->container->get("doctrine.orm.entity_manager");
$claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
$claimsOtherParty = $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->find($claimOtherPartyId);
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$minorInvolved = ($request->request->get('minorInvolved') == "1") ? true : false; //Added to save minor dob
$minor_dob = $request->request->get('minor_dob');//Added to save minor dob
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Make sure valid Claims Insured Record exists
if ($claimsOtherParty === null) {
throw $this->createNotFoundException("Claims Other Party Record does not exist");
}
# Make sure Insured Record exists
$otherParty = $claimsOtherParty->getOtherParty();
if ($otherParty === null) {
throw $this->createNotFoundException("Claim does not have other party record");
}
# Check CSRF Token
$submittedToken = $request->request->get("_csrf_token");
// if (!$this->isCsrfTokenValid('edit_claim_insured', $submittedToken)) { // if invalid csrf token
if (!($this->getUser() instanceof Resource)) {
# Send back error
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "";
$nextError['text'] = "You do not have permission to submit this form.";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => array(),
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$otherPartyFormHelper = new OtherPartyFormHelper($em, $formFactory, true);
$otherPartyForm = $otherPartyFormHelper->getEditForm($otherParty);
# Get Form Fields
$formSubmission = $request->request->get('form');
# Manually submit form
$otherPartyForm->submit($formSubmission);
$otherPartyTypeId = $request->request->get("otherPartyType");
$isPrimary = intval($request->request->get("isPrimary"));
$claimOtherPartyType = $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->find($otherPartyTypeId);
$otherParty = $otherPartyForm->getData();
$otherParty2 = $otherParty;
## Code checks if changes were made to Insured Object ##
# Get Current Resource on DB
$otherPartyCompare = new OtherPartyCompareHelper($em);
$otherPartyCompare->setCurOtherParty($otherParty2);
$claimOtherParty = $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->loadByClaimAndOtherParty($claim, $otherParty);
if ($claimOtherPartyType) {
$claimOtherParty->setClaimOtherPartyType($claimOtherPartyType);
}
###
# Deal with setting Claim Insured Type, Minor Birthday, verifying if these fields have changed on this update
# Do some checking to check if Claim Insured Type Changed
//*/
$claimOtherPartyChanged = false;
$otherPartyTypeChanged = false;
$claimOtherPartyChangesHelper = new ClaimOtherPartyChangesHelper($em);
$changedOtherPartyType = $claimOtherPartyChangesHelper->otherPartyTypeDidChange($claim, $otherParty, $claimOtherPartyType);
$claimOtherPartyChanged = $claimOtherPartyChangesHelper->minorBDayDidChange($claimsOtherParty, $minor_dob); //Added to save the minor involved and minor dob change
if ($changedOtherPartyType != "") {
$otherPartyTypeChanged = true;
}
//added code to save county
if(!empty($formSubmission["county"])) {
$county = $em->getRepository("ResourceManagementBundle:Counties")->findOneById($formSubmission["county"]);
if(!empty($county)) {
$otherParty->setCounty($county);
}
}
#
###
# Set Claim Insured Type
# Validate Entity set from Request
$errors = $this->get("validator")->validate($otherParty);
$data = array();
$errors2 = array();
if (count($errors) == 0) { // if form is valid
//Added to save the minor involved and minor dob change
if ($minorInvolved == 1) {
if ($minor_dob == "") {
$retVal = array();
$retVal['error'] = true;
$retVal['data'] = array();
$errorsArr = [
"id" => "minor_dob",
"text" => "Minor Date of Birth is required."
];
$retVal['data']['errors'][] = $errorsArr;
return new JsonResponse($retVal);
}
$claimOtherParty->setMinorInvolved($minorInvolved);
$claimOtherParty->setMinorDOB(new \DateTime($minor_dob));
}
else{
$claimOtherParty->setMinorInvolved($minorInvolved);
$claimOtherParty->setMinorDOB(null);
}
# Compare 2 objects to see if there were any changes made
$otherPartyCompare->setNewOtherParty($otherParty);
$hasChanges = $otherPartyCompare->compareObjects();
# Persist Document
$em->persist($otherParty);
$em->persist($claimOtherParty);
$em->flush();
if ($hasChanges || $claimOtherPartyChanged) { // check if whether Insured Entity or Claim Insured Entity was changed
$getChanges = array();
if ($hasChanges) {
$changeLog = $otherPartyCompare->changeLog;
$getChanges2 = array_merge($getChanges, $changeLog);
} else {
$getChanges2 = $getChanges;
}
$ClaimNote = $this->container->get("claim.note_provider");
$ClaimNote->addClaimNote($claim, "Claim Other Party was updated. " . implode(" ", $getChanges2), false, 52);
}
if ($isPrimary === 1) { // if set to primary
# Use Claim Insured Helper to set this claimInsured record to primary, and all others on claim to isPrimary = false
$claimsOtherPartyHelper = new ClaimsOtherPartyHelper($em);
$claimsOtherPartyHelper->makeClaimOtherPartyPrimary($claimOtherParty, $claim);
}
# Log updating Claim Insured using Monolog
$logger = $this->get('monolog.logger.claims_log');
$logger->info("Claim Other party Updated - Other party ID: " . $otherParty->getId() . ", with ClaimOtherPartyID: " . $claimOtherParty->getId() . ", on Claim ID: " . $claim->getId());
$comment = "Claim Other party Updated - Other party ID: " . $otherParty->getId() . ", with ClaimOtherPartyID: " . $claimOtherParty->getId() . ", on Claim ID: " . $claim->getId();
$userNoteLog = $this->container->get("app.resource_note_logger");
$user = $this->container->get("security.token_storage")->getToken()->getUser();
$resource = $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
$userNoteLog->logNote($comment, $resource,10,$claim);
$ClaimNotes = $this->get('claim.note_provider');
$ClaimNotes->addClaimNote( $claimsOtherParty->getClaim(), "Other Party edited! First name: ". $otherParty->getFirstName() , false, 52);
$retVal = array(
"status" => "success",
"error_msgs" => []
);
return new JsonResponse($retVal);
} else { // if form not valid
# Send back errors to client
$data = array();
$errors2 = array();
$errors = $this->get("validator")->validate($otherParty);
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
/**
* @Route("/main/other-party/delete")
* @Method(methods={"POST"})
*/
public function deleteClaimOtherPartyAction(Request $request)
{
$em = $this->container->get("doctrine.orm.entity_manager");
# Request ID to delete
$id = intval($request->request->get("id"));
# Delete ClaimOtherParty
$claimOtherParty = $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->find($id);
if ($claimOtherParty->getIsPrimary()) {
$retVal = [
'error' => true,
'error_msgs' => ["You cannot remove the Primary Other party."]
];
return new JsonResponse($retVal);
}
# Get claim, claim insured objects while they exist
$otherParty = $claimOtherParty->getOtherParty();
$otherPartyId = $otherParty->getId();
/**
* @var $claim Claim
*/
$claim = $claimOtherParty->getClaim();
$claimId = $claim->getId();
# Check Permissions
$this->denyAccessUnlessGranted("edit_claim_tab", $claim);
$em->remove($claimOtherParty->getOtherParty());
$em->remove($claimOtherParty);
$em->flush();
# Get all claim other parties after removing one of them
$claimOtherParties = $claim->getClaimsOtherParties();
if (count($claimOtherParties) == 1) { // if there is only one insured on the claim
# Make that other party primary
$getClaimOtherParty = $claimOtherParties[0];
$claimsInsuredHelper = new ClaimsOtherPartyHelper($em);
$claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
$claimsInsuredHelper->makeClaimOtherPartyPrimary($getClaimOtherParty, $claim);
}
# Log deleting Claim Other Parties using Monolog
$logger = $this->get('monolog.logger.claims_log');
$logger->info("Claim Other Party Deleted - Other party ID: " . $otherPartyId . ", with ClaimOtherPartyID: " . $id . ", on Claim ID: " . $claimId);
$comment = "Claim Other Party Deleted - Other party ID: " . $otherPartyId . ", with ClaimOtherPartyID: " . $id . ", on Claim ID: " . $claimId;
$userNoteLog = $this->container->get("app.resource_note_logger");
$user = $this->container->get("security.token_storage")->getToken()->getUser();
$resource = $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
$userNoteLog->logNote($comment, $resource,10,$claim);
$retVal = [
'error' => false,
'error_msgs' => []
];
return new JsonResponse($retVal);
}
/**
* @Route("/street-view-iframe/{id}", defaults={"id" = "none"})
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function streetViewWidgetIframeAction(Claim $claim, Request $request)
{
$data = [
"apiKey" => "",
"lat" => 15,
"lng" => 15
];
$metaData = $this->container->get('core.system_parameter_control')->getSystemControlMetaData(
SystemControlRepository::GOOGLE_MAP_API
);
if (is_array($metaData)) {
$apiKey = $metaData[SystemControlMetadataRepository::META_GOOGLE_MAP_API_KEY] ?? "";
if (!empty($apiKey)) {
$data['apiKey'] = $apiKey;
$latLong = GoogleGeocoder::getLatLongFromLossAddress(
$apiKey,
$claim->getLossStreet(),
$claim->getLossCity(),
$claim->getLossState(),
$claim->getLossZip()
);
$data['lat'] = $latLong['lat'];
$data['lng'] = $latLong['lng'];
}
}
return $this->render('ClaimManagementBundle:ClaimFlowScreen/Fragments/widgets:street-view-widget-iframe.html.twig', [
'data' => $data
]);
}
/**
* @Route("/street-view-iframe-preload/{id}", defaults={"id" = "none"})
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function streetViewWidgetIframePreloadAction(Claim $claim, Request $request)
{
return $this->render('ClaimManagementBundle:ClaimFlowScreen/Fragments/widgets:street-view-widget-iframe-preload.html.twig', [
'loadIframe' => ($claim instanceof Claim),
'claim' => $claim
]);
}
/**
* @Route("/media-proxy/{id}", defaults={"id" = "none"}, name="claim_media_proxy")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function claimMediaProxyAction(Claim $claim, Request $request)
{
$response = new Response();
$url = $this->get('claim.media')->googleStreetViewUrl($claim);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$content = curl_exec($ch);
curl_close ($ch);
if ($content === false) {
$content = file_get_contents($this->get('kernel')->getProjectDir()."/web/img/location-not-found.jpg");
}
$filename = sprintf("%s.jpg", $claim->getId());
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', 'image/jpg' );
$response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '";');
$response->headers->set('Content-length', strlen($content));
$response->sendHeaders();
$response->setContent($content);
return $response;
}
/**
* @Route("/main/externalclaimresources/{id}")
*/
public function externalclaimresourcesAction(Claim $claim)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$em = $this->container->get("doctrine.orm.entity_manager");
$assignmentService = $this->get('claim.assignment');
$alertMessageDateExpiryArray = $assignmentService->validLicenseExternal($claim);
$alertMessageDateExpiry = $alertMessageDateExpiryArray['alertMessageDateExpiry'];
$licenseDataArray = $alertMessageDateExpiryArray['licenseDataArray'];
$adjusterRepo = $em->getRepository("ResourceManagementBundle:Resource");
$claimTeamRepo = $em->getRepository("ClaimManagementBundle:ClaimTeam");
//$adjusters = $adjusterRepo->findBy(['resourceType'=>array(2,3,4)]);
$claimTeams = $claimTeamRepo->findBy(['enabled'=>true]);
$resourceTypes = $em->getRepository("ResourceManagementBundle:ResourceType")->findAll();
$assignmentParties = $em->getRepository("AssignmentBundle:AssignmentParty")->findAll();
/*$sql = "SELECT count(id) as resource_count
FROM claim_resource cr
WHERE cr.claim_id = :claim_id";*/
$sql = "SELECT count(id) as resource_count
FROM assignments_external cr
WHERE cr.claim_id = :claim_id
AND IFNULL(cr.next_assignment_id,0) = 0
AND cr.is_current_assignment = 1 ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"claim_id"=>$claim->getId()
]);
$resourceCountResults = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$resourceCount = 0;
foreach ($resourceCountResults as $resourceCountRow){
$resourceCount = $resourceCountRow['resource_count'];
}
return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/resources-external-widget.html.twig", [
"claim" => $claim,
'resourceTypes' => $resourceTypes,
'assignmentParties' => $assignmentParties,
'teams' => $claimTeams,
'resourceCount' => $resourceCount,
'licenseDataArray' => $licenseDataArray,
'alertMessageDateExpiry' =>$alertMessageDateExpiry
]);
}
/**
* @Route("/main/resource/verify_claim_api/{id}")
*/
public function verifyClaimApi(Claim $claim, Request $request)
{
# Make sure valid claim object was passed
if ($claim === null) {
throw $this->createNotFoundException("Claim does not exist");
}
$session = new Session();
$systemParamService = $this->container->get('core.system_parameter_control');
if ($session->has("claimPublishedID")) {
$session_claim_no = $session->get("claimPublishedNo");
if($session_claim_no !== $claim->getClaimNumber()){
$bReferUrl=$systemParamService->getParameterValue('api_publisher','api_publisher_host');
$apiPublisherService = $this->container->get('core.api_publisher_service');
$apiResponseValues=$apiPublisherService->publishRetrieveClaimApi($claim->getId(), 'GET', 'json');
$session->set("claimPublishedID", 0);
if(!empty($apiResponseValues)){
$session->set("claimPublishedID", $apiResponseValues);
$session->set("claimPublishedUrl", $bReferUrl);
$session->set("claimPublishedNo", $claim->getId());
$retVal = [
'error' => false,
'claimPublishedID' => $apiResponseValues,
'claimPublishedUrl' => $bReferUrl,
'claimPublishedNo' => $claim->getId()
];
return new JsonResponse($retVal);
}else{
$retVal = [
'error' => true
];
return new JsonResponse($retVal);
}
}else{
$retVal = [
'error' => false,
'claimPublishedID' => $session->get("claimPublishedID"),
'claimPublishedUrl' => $session->get("claimPublishedUrl"),
'claimPublishedNo' => $claim->getId()
];
return new JsonResponse($retVal);
}
}else{
$bReferUrl=$systemParamService->getParameterValue('api_publisher','api_publisher_host');
$apiPublisherService = $this->container->get('core.api_publisher_service');
$apiResponseValues=$apiPublisherService->publishRetrieveClaimApi($claim->getId(), 'GET', 'json');
$session->set("claimPublishedID", 0);
if(!empty($apiResponseValues)){
$session->set("claimPublishedID", $apiResponseValues);
$session->set("claimPublishedUrl", $bReferUrl);
$session->set("claimPublishedNo", $claim->getId());
$retVal = [
'error' => false,
'claimPublishedID' => $apiResponseValues,
'claimPublishedUrl' => $bReferUrl,
'claimPublishedNo' => $claim->getId()
];
return new JsonResponse($retVal);
}else{
$retVal = [
'error' => true
];
return new JsonResponse($retVal);
}
}
}
}