src/Globals/ClaimManagementBundle/Controller/ClaimFlow/ClaimController.php line 1101

Open in your IDE?
  1. <?php
  2. namespace Globals\ClaimManagementBundle\Controller\ClaimFlow;
  3. use Globals\ClaimManagementBundle\DependencyInjection\ClaimInsuredChangesHelper;
  4. use Globals\ClaimManagementBundle\DependencyInjection\ClaimOtherPartyChangesHelper;
  5. use Globals\ClaimManagementBundle\DependencyInjection\ClaimPermissionHelper;
  6. use Globals\ClaimManagementBundle\DependencyInjection\ClaimReportFormHelper;
  7. use Globals\ClaimManagementBundle\DependencyInjection\ClaimsInsuredHelper;
  8. use Globals\ClaimManagementBundle\DependencyInjection\ClaimsOtherPartyHelper;
  9. use Globals\ClaimManagementBundle\DependencyInjection\CompareHelpers\ClaimCompareHelper;
  10. use Globals\ClaimManagementBundle\DependencyInjection\CompareHelpers\InsuredCompareHelper;
  11. use Globals\ClaimManagementBundle\DependencyInjection\CompareHelpers\OtherPartyCompareHelper;
  12. use Globals\ClaimManagementBundle\DependencyInjection\ExpensesHelper;
  13. use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\ClaimLimitFormHelper;
  14. use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\CoverageFormHelper;
  15. use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\DeductibleFormHelper;
  16. use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\DisbursementTimeLogFormHelper;
  17. use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\InsuredFormHelper;
  18. use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\InvoiceFormHelper;
  19. use Globals\ClaimManagementBundle\DependencyInjection\FormHelpers\OtherPartyFormHelper;
  20. use Globals\ClaimManagementBundle\DependencyInjection\PerilHelper;
  21. use Globals\ClaimManagementBundle\DependencyInjection\PerilTreeHelper;
  22. use Globals\ClaimManagementBundle\Entity\Attribute;
  23. use Globals\ClaimManagementBundle\Entity\Claim;
  24. use Globals\ClaimManagementBundle\Entity\XactClaimReport;
  25. use Globals\ClaimManagementBundle\Entity\ClaimInsuredType;
  26. use Globals\ClaimManagementBundle\Entity\ClaimReport;
  27. use Globals\ClaimManagementBundle\Entity\ClaimResource;
  28. use Globals\ClaimManagementBundle\Entity\ClaimResourcePrevious;
  29. use Globals\ClaimManagementBundle\Entity\ClaimsInsured;
  30. use Globals\ClaimManagementBundle\Entity\ClaimsOtherParty;
  31. use Globals\ClaimManagementBundle\Entity\ClaimStatus;
  32. use Globals\ClaimManagementBundle\Entity\ClaimTeam;
  33. use Globals\ClaimManagementBundle\Entity\Coverage;
  34. use Globals\ClaimManagementBundle\Entity\CoverageReserve;
  35. use Globals\ClaimManagementBundle\Entity\Deductible;
  36. use Globals\ClaimManagementBundle\Entity\DiaryEntry;
  37. use Globals\ClaimManagementBundle\Entity\Insured;
  38. use Globals\ClaimManagementBundle\Entity\PolicyType;
  39. use Globals\ClaimManagementBundle\Form\ClaimMainFragment;
  40. use Globals\ClaimManagementBundle\Form\ClaimMainFragmentCarrier;
  41. use Globals\ClaimManagementBundle\Form\ClaimPolicyFragment;
  42. use Globals\ClaimManagementBundle\Form\ClaimResourceForm;
  43. use Globals\ClaimManagementBundle\Form\DiaryFormType;
  44. use Globals\ClaimManagementBundle\Form\DisbursementTimeLogType;
  45. use Globals\ClaimManagementBundle\Form\InsuredMainFragment;
  46. use Globals\ClaimManagementBundle\Repository\ClaimRepository;
  47. use Globals\ClaimManagementBundle\Service\ClaimNotesProviderService;
  48. use Globals\ClaimManagementBundle\Service\InvoicePreviewService;
  49. use Globals\CoreBundle\Repository\SystemControlMetadataRepository;
  50. use Globals\CoreBundle\Repository\SystemControlRepository;
  51. use Globals\CoreBundle\Services\GoogleGeocoder;
  52. use Globals\CustomerManagementBundle\Entity\Customer;
  53. use Globals\InvoiceManagementBundle\Entity\Disbursement;
  54. use Globals\InvoiceManagementBundle\Entity\Invoice;
  55. use Globals\ResourceManagementBundle\Entity\Resource;
  56. use Doctrine\ORM\EntityManager;
  57. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  58. use Globals\ResourceManagementBundle\DependencyInjection\SortOrderHelper;
  59. use Globals\ResourceManagementBundle\Service\PaginatorSQL;
  60. use Globals\ResourceManagementBundle\Service\SLogger;
  61. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  62. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  63. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  64. use Symfony\Component\HttpFoundation\JsonResponse;
  65. use Symfony\Component\HttpFoundation\Request;
  66. use Symfony\Component\HttpFoundation\Response;
  67. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  68. use Symfony\Component\HttpFoundation\Session\Session;
  69. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  70. use Symfony\Component\Intl\NumberFormatter\NumberFormatter;
  71. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  72. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  73. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  74. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  75. use Symfony\Component\Serializer\Serializer;
  76. use Globals\ClaimManagementBundle\Entity\DocumentLibrary;
  77. use Symfony\Component\Validator\Constraints\DateTime;
  78. use Globals\ClaimManagementBundle\Entity\ClaimLimit;
  79. use Globals\CompanyManagementBundle\Entity\Company;
  80. use Globals\ClaimManagementBundle\Event\ChangeTeamEvent;
  81. use Globals\CompanyManagementBundle\Entity\TpaCustomer;
  82. /**
  83.  * @Route("/claims/fragments")
  84.  */
  85. class ClaimController extends Controller
  86. {
  87.     # maximum amount of perils on a claim
  88.     const MAX_PERILS_ON_CLAIM 3;
  89.     /**
  90.      * @Route("/main/{id}", defaults={"id" = "none"})
  91.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  92.      */
  93.     public function mainFragmentAction(Claim $claimRequest $request)
  94.     {
  95.         /** @var EntityManager $em */
  96.         $em $this->getDoctrine()->getManager();
  97.        // $systemParamService = $this->container->get('fact.service');
  98.        //  $response =  $systemParamService->createClaim($claim,'faa2cda0-e5ae-40b8-a1cf-1f84affe0e32');
  99.        // dd($response);
  100.        // die;
  101.         # load up all the property types
  102.         $PropertyTypeRepo $em->getRepository("ClaimManagementBundle:PropertyType");
  103.         $PropertyTypes $PropertyTypeRepo->findBy([],['propertyType'=>'ASC']);
  104.         $CwopReasons $em->getRepository("ClaimManagementBundle:CwopReason")->findAll();
  105.         $SettlementTypes $em->getRepository("ClaimManagementBundle:SettlementType")->findAll();
  106.         $companyId 1;
  107.         if (!empty($claim->getCustomer())) { 
  108.             $ClaimCustomer $claim->getCustomer();
  109.             if ($ClaimCustomer->getSubCompany()) {
  110.                 $companyId $ClaimCustomer->getSubCompany()->getId();
  111.             }
  112.         }
  113.         $company $em->getRepository("CompanyManagementBundle:Company")->find($companyId);
  114.         $curr_claim_no $claim->getClaimNumber();
  115.         $slog = new SLogger();
  116.         if ($claim) {
  117.             $tokenStorage $this->container->get("security.token_storage");
  118.             $User $tokenStorage->getToken()->getUser();
  119.             if (!$User) {
  120.                 throw new AccessDeniedException('You do not have access to this page.');
  121.             }
  122.               // if ICM
  123.                 ### ICM ###
  124.                 $slog = new SLogger();
  125.                 $slog->log('In ICM');
  126.                 $this->denyAccessUnlessGranted("view_claim"$claim);
  127.                 $claimStatus $em->getRepository("ClaimManagementBundle:ClaimStatus")->find($claim->getStatus());
  128.                 # 1) Create a Form for the Claim. It will be a PARTIAL form
  129.                 $form $this->createForm(ClaimMainFragment::class, $claim, array('status' => $claim->getStatus(), 'roles' => $User->getRoles()));
  130.                 $customer $claim->getCustomer();
  131.                 $customerTmp $claim->getCustomer();
  132.                 $isTpaCustomer=false;
  133.                 if(!empty($customer) && $customer->isTpaUi()){
  134.                     $isTpaCustomer=true;
  135.                 }
  136.                 #get id of the all the TPA customer
  137.                 $tpacust='';
  138.                 $TpaCustomerObj=$em->getRepository("CustomerManagementBundle:Customer")->findBy(array('tpaUi'=>1));
  139.                 if(!empty($TpaCustomerObj)){
  140.                     foreach($TpaCustomerObj as $objkey=>$customer){
  141.                         $tpacust .=$customer->getId().',';
  142.                     }
  143.                     $tpacust=rtrim($tpacust,',');
  144.                 }
  145.                 $ReopenDate $claim->getDateReopened();
  146.                 $PropertyStatusRepo $em->getRepository("ClaimManagementBundle:PropertyStatus");
  147.                 # 2) Create a Form for the Insured. It too, will be a PARTIAL form
  148.                 //$insuredForm = $this->createForm(InsuredMainFragment::class, $claim->getInsured());
  149.                 // --------------------------------------------------------------------------------
  150.                 // CLAIM FLOW CRUD SUBMISSION
  151.                 /*
  152.                  * If the form was submitted, we'll catch it here and return a better output (JSON)
  153.                  * We'll need to come up with a good convention for doing this, otherwise the Controller
  154.                  * might end up fat. For now, we approach it here.
  155.                  *
  156.                  */
  157.                 # Create Form Builder Object for "Create Certificate"
  158.                 $em $this->container->get("doctrine.orm.entity_manager");
  159.                 $formFactory $this->container->get("form.factory");
  160.                 $insuredFormHelper = new InsuredFormHelper($em$formFactoryfalse);
  161.                 // EXISTING CLAIM CHECK
  162.                 $conn $em->getConnection();
  163.                 $claim_exists $conn->prepare("SELECT id FROM claim WHERE claim_number = ?");
  164.                 $insuredForm $insuredFormHelper->getAddForm();
  165.                 if ($request->getMethod() === "POST") {
  166.                    //dd($request->request);
  167.                     $ResourceInTeam=[];
  168.                     $OldTeam='';
  169.                     if(!empty($claim->getClaimTeam())) {
  170.                         $OldTeam $claim->getClaimTeam()->getName();
  171.                     }
  172.                     $NewTeam='';
  173.                     $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  174.                     $response = [
  175.                         'error' => false'data' => []
  176.                     ];
  177.                     # Grab the serialized submission data
  178.                     $claimFormSubmission $request->request->get('claim_main_fragment');
  179.                     $insuredFormSubmission $request->request->get('insured_main_fragment');
  180.                     $claimExtraFields $request->request->get('claim_extra_fields');
  181.                     $tpaSubmission $request->request->get('claim_tpa_fragment');
  182.                     $claim_rep_id $request->request->get('claim_rep');
  183.                     $claimNumber $request->request->get('claim_number');
  184.                     $AutoclaimFields $request->request->get('auto_claim_main_fragment');
  185.                     $settlement  $claimFormSubmission['settlement'];
  186.                     if (!empty($claimFormSubmission['reopenSettlementType']))
  187.                         $settlement  $claimFormSubmission['reopenSettlementType'];
  188.                     # Added 08/2018 -- Capturing COUNTY, CUSTOMER
  189.                     $form_request $request->request->get('form');
  190.                     $County false;
  191.                     if(!empty($form_request) && isset($form_request['claim_main_fragment_lossCounty']))
  192.                     {
  193.                         $county_id intval($form_request['claim_main_fragment_lossCounty']);
  194.                         if ($county_id) {
  195.                             $County $em->getRepository("ResourceManagementBundle:Counties")->find(intval($county_id));
  196.                         }
  197.                     }
  198.                     # Added 08/2018 -- Checking to see if COUNTY is required (per tpa_ui)
  199.                     /*$county_pass = true;
  200.                     if($claim->getCustomer()->isTpaUi() && !$County)
  201.                     {
  202.                         $county_pass = false;
  203.                     }*/
  204.                     $site_inspected = ($request->request->has("site_inspected")) ? intval($request->request->get("site_inspected")) : 0;
  205.                     # Added TPA pass 09/2018 -- Checking to see if we submitted a UMR
  206.                     $tpa_pass true;
  207.                     $is_tpa_cust false;
  208.                     $umrValue false;
  209.                     $propertyTypeInbound false;
  210.                     if( isset($tpaSubmission) && isset($tpaSubmission['umr']) )
  211.                     {
  212.                         $is_tpa_cust true;
  213.                         # check if we submitted an UMR no.
  214.                         if( $tpaSubmission['umr'] && $tpaSubmission['umr'] != "" )
  215.                         {
  216.                             $umrValue $tpaSubmission['umr'];
  217.                         }else{
  218.                             $tpa_pass false;
  219.                         }
  220.                         # check if we submitted a property type (id, in this case)
  221.                         if( $tpaSubmission['property_type'] && intval($tpaSubmission['property_type']) > )
  222.                         {
  223.                             $propertyTypeInbound $PropertyTypeRepo->findintval($tpaSubmission['property_type']) );
  224.                         }else{
  225.                             $tpa_pass false;
  226.                         }
  227.                     }
  228.                     # Submit the actual forms
  229.                     $form->submit($claimFormSubmission);
  230.                     //dd($form->getErrors());
  231.                     //$insuredForm->submit($insuredFormSubmission);
  232.                     # If the first form was ok, SUBMIT the insured form. Otherwise, archive the errors.
  233.                     if ($form->isValid()  && $tpa_pass) {
  234.                         // Save and persist the new data
  235.                         /** @var Claim $newClaim */
  236.                         $newClaim $form->getData();
  237.                         //$newClaim->setSiteInspected($site_inspected); //setSiteInspected is removed
  238.                         # Added 08/2018 -- SET the county
  239.                         if($County && !empty($County))
  240.                         {
  241.                             $newClaim->setLossCounty$County );
  242.                         }
  243.                         //update  LossLatitude and LossLongitude start
  244.                         //$address = $claimFormSubmission['lossStreet'];
  245.                         //$city = $claimFormSubmission['lossCity'];
  246.                         //$stateId = intval($claimFormSubmission['lossState']);
  247.                         //$lossState = $em->getRepository("ResourceManagementBundle:State")->find($stateId);
  248.                        // $state = $lossState->getStateName();
  249.                        // $zip = $claimFormSubmission['lossZip'];
  250.                         //$googleApiCall = $this->container->get("google.geocoder");
  251.                         //$latitudeLongitudeData =  $googleApiCall->getLatLongFromAddress($address, $city, $state, $zip);
  252.                         //$newClaim->setLossLatitude($latitudeLongitudeData['lat']);
  253.                         //$newClaim->setLossLongitude($latitudeLongitudeData['lng']);
  254.                         //update  LossLatitude and LossLongitude end here
  255.                         # Added 09/2018 -- SET the tpa info
  256.                         if($is_tpa_cust && $umrValue && $propertyTypeInbound)
  257.                         {
  258.                             $newClaim->setUmr$umrValue );
  259.                             $newClaim->setPropertyType$propertyTypeInbound );
  260.                         }
  261.                         if ($claim_rep_id) {
  262.                             $ClaimRep $em->getRepository("ResourceManagementBundle:Resource")->find($claim_rep_id);
  263.                             if ($ClaimRep) {
  264.                                 $newClaim->setClaimRep($ClaimRep);
  265.                             }
  266.                         }
  267.                         $arrSettlemenTypeForCWOP = array(1,4,5,6);
  268.                         if (!empty($ReopenDate)) {
  269.                            if (empty($settlement) || (!empty($settlement) && in_array($settlement,$arrSettlemenTypeForCWOP) === false )) {
  270.                                $newClaim->setReopenCwopRsn(null);
  271.                                $newClaim->setReopenDenialDescriptionLine('');
  272.                            }
  273.                            if (!empty($settlement)) {
  274.                               $objSettlementType $em->getRepository("ClaimManagementBundle:SettlementType")->find($settlement);
  275.                               $newClaim->setReopenSettlementType($objSettlementType);
  276.                            }
  277.                         } else{
  278.                            if (empty($settlement) || (!empty($settlement) && in_array($settlement,$arrSettlemenTypeForCWOP) === false)) {
  279.                                $newClaim->setCwopReason(null);
  280.                                $newClaim->setDenialDescriptionLine('');
  281.                            }
  282.                         }
  283.                         if ($claimNumber) {
  284.                             // CHECK FOR DUPES
  285.                             $claim_exists->execute([$claimNumber]);
  286.                             //Check if Claim Number is different from the current claim Number
  287.                             //If yesm then check if count is more than 0, if yes, then give error.
  288.                             if($claimNumber != $curr_claim_no && ($claim_exists->rowCount() > 0)){
  289.                                 $response['error'] = true;
  290.                                 $response['data']['errors'][] = [
  291.                                     'id' => 'claimNumber',
  292.                                     'text' => "You cannot have a duplicate Claim number"
  293.                                 ];
  294.                             }else{
  295.                                 $newClaim->setClaimNumber($claimNumber);
  296.                             }
  297.                         }
  298.                         # Don't change customer on XACT or Symbility claims
  299.                         /*if ($claim->getTransactionId()) {
  300.                             if ($claim->failsChangeCustomerValidation($customer,$claimFormSubmission)) {
  301.                                 $response['error'] = true;
  302.                                 $response['data']['errors'][] = [
  303.                                     'id' => 'claim_main_fragment_customer',
  304.                                     'text' => 'You cannot change the customer of this claim'
  305.                                 ];
  306.                             }
  307.                         } else {*/
  308.                             # dont throw error but throw alert message for user
  309.                             if ($claim->failsChangeCustomerValidation($customerTmp,$claimFormSubmission)) {
  310.                                 $response['alert'] = [
  311.                                     'title' => "Internal Rep Removed",
  312.                                     'content' => "Customer has been changed, removing internal rep"
  313.                                 ];
  314.                                 $newClaim->removeClaimRep();
  315.                             }
  316.                         //}
  317.                         /**
  318.                          * Add resources to the claim team if needed
  319.                          */
  320.                         $claimResources $claim->getResources();
  321.                         if (isset($claimFormSubmission['claimTeam'])) {
  322.                             $claimTeam $em->getRepository('ClaimManagementBundle:ClaimTeam')->find($claimFormSubmission['claimTeam']);
  323.                             if ($claimTeam) {
  324.                                 $NewTeam=$claimTeam->getName();
  325.                                 $claimTeamManager $this->get('claimteam.manager');
  326.                                 foreach ($claimResources as $claimResource) {
  327.                                     $adjuster $claimResource->getResource();
  328.                                     # Assign the resource to the team if he is not on the team
  329.                                     $clamTeamResources $em->getRepository("ClaimManagementBundle:ClaimTeamResource")
  330.                                         ->findBy(['claimTeam' => $claimTeam'resource' => $adjuster]);
  331.                                     if (empty($clamTeamResources)) {
  332.                                         $claimTeamManager->addResourceToClaimTeam($adjuster$claimTeam);
  333.                                     }
  334.                                     $OldAdjuster $em->find("ResourceManagementBundle:Resource"intval($adjuster->getId()));
  335.                                     $ResourceInTeam[]=$OldAdjuster;
  336.                                 }
  337.                                 //if ($claim->getClaimTeam() != $claimFormSubmission['claimTeam']) {
  338.                                 if($claim->getIsClaimCategory() ==1) {
  339.                                     if ($claim->getClaimTeam()->getId() != intval($claimFormSubmission['claimTeam'])) {
  340.                                         # First to Call Un-assigned event
  341.                                         $dispatcher $this->get('event_dispatcher');
  342.                                         $dispatcher->dispatch(new ChangeTeamEvent($claim$ResourceInTeam$OldTeamfalse), ChangeTeamEvent::NAME);
  343.                                         #second to call assign event
  344.                                         $dispatcher->dispatch(new ChangeTeamEvent($claim$ResourceInTeam$NewTeamtrue), ChangeTeamEvent::NAME);
  345.                                     }
  346.                                 }
  347.                             }
  348.                         }
  349.                         if (!empty($claimFormSubmission['policy'] ?? "")) {
  350.                             $policyType $em->getRepository(PolicyType::class)
  351.                                 ->findOneBy(['id' => $claimFormSubmission['policy']]);
  352.                             if ($policyType instanceof PolicyType) {
  353.                                 $newClaim->setPolicyType($policyType->getName());
  354.                             }
  355.                         }
  356.                         if(isset($claimFormSubmission['customerCatCode'])) {
  357.                             $newClaim->setCustomerCatCode($claimFormSubmission['customerCatCode']);
  358.                         }else{
  359.                             $newClaim->setCustomerCatCode(null);
  360.                         }
  361.                         if(isset($claimFormSubmission['liabilityType'])) {
  362.                             $newClaim->setLiabilityType($claimFormSubmission['liabilityType']);
  363.                         }else{
  364.                             $newClaim->setLiabilityType(0);
  365.                         }
  366.                         if(isset($claimFormSubmission['recoveriesType'])) {
  367.                             $newClaim->setRecoveriesType($claimFormSubmission['recoveriesType']);
  368.                         }else{
  369.                             $newClaim->setRecoveriesType(0);
  370.                         }
  371.                         if(isset($claimExtraFields['subPerilId']) && !empty($claimExtraFields['subPerilId'])) {
  372.                             $subPeril $em->getRepository("ClaimManagementBundle:Peril")->find(intval($claimExtraFields['subPerilId']));
  373.                             $newClaim->setSubPeril($subPeril);
  374.                         }else{
  375.                             $newClaim->setSubPeril(null);
  376.                         }
  377.                         if(isset($claimExtraFields['propertyDamageType']) && !empty($claimExtraFields['propertyDamageType']) ) {
  378.                             $newClaim->setPropertyDamageType($claimExtraFields['propertyDamageType']);
  379.                         }else{
  380.                             $newClaim->setPropertyDamageType(null);
  381.                         }
  382.                         if(isset($AutoclaimFields['treaty_number'])) {
  383.                             $newClaim->setTreatyNumber($AutoclaimFields['treaty_number']);
  384.                         }else{
  385.                             $newClaim->setTreatyNumber(null);
  386.                         }
  387.                         if(isset($AutoclaimFields['sub_treaty_number'])) {
  388.                             $newClaim->setSubTreatyNumber($AutoclaimFields['sub_treaty_number']);
  389.                         }else{
  390.                             $newClaim->setSubTreatyNumber(null);
  391.                         }
  392.                         if ($response['error'] === false) {
  393.                             $em->persist($newClaim);
  394.                             $em->flush();
  395.                         }
  396.                         if ($newClaim->getPlanId()) {
  397.                             $PlanId $em->getRepository("ClaimManagementBundle:PlanID")->find($newClaim->getPlanId()->getId());
  398.                             $PlanId->setWasUsedOnClaim(true);
  399.                             $em->persist($PlanId);
  400.                             $em->flush();
  401.                         }
  402.                         # for Update Auto claim
  403.                         $AutoClaim $em->getRepository("ClaimManagementBundle:AutoClaim")->findOneBy(['claim'=>$newClaim]);
  404.                         if(!empty($AutoClaim)){
  405.                            
  406.                             $AutoClaim->setIssueDate(new \DateTime($claimFormSubmission['policyStartDate']));
  407.                             $AutoClaim->setEffDate(new \DateTime($AutoclaimFields['eff_date']));
  408.                             $AutoClaim->setExpiryDate(new \DateTime($claimFormSubmission['policyEndDate']));
  409.                             $AutoClaim->setYear($AutoclaimFields['year']);
  410.                             $AutoClaim->setMake($AutoclaimFields['make']);
  411.                             $AutoClaim->setModel($AutoclaimFields['model']);
  412.                             $AutoClaim->setMileage($AutoclaimFields['mileage']);
  413.                             $AutoClaim->setVinId($AutoclaimFields['vin_id']);
  414.                             if(!empty($claimExtraFields['compType'])) {
  415.                                 $compType $em->getRepository("CompanyManagementBundle:CompType")->find(intval($claimExtraFields['compType']));
  416.                                 $AutoClaim->setCompType($compType);
  417.                             }else{
  418.                                 $AutoClaim->setCompType(null);
  419.                             }
  420.                             if(!empty($claimExtraFields['compCode'])) {
  421.                                 $compCode $em->getRepository("CompanyManagementBundle:CompCode")->find(intval($claimExtraFields['compCode']));
  422.                                 $AutoClaim->setCompCode($compCode);
  423.                             }else{
  424.                                 $AutoClaim->setCompCode(null);
  425.                             }
  426.                             $AutoClaim->setUpdatedAt(new \DateTime());
  427.                             //dd($AutoClaim);
  428.                             $em->persist($AutoClaim);
  429.                             $em->flush();
  430.                         }
  431.                         # for Update Auto claim
  432.                         return new JsonResponse($response);
  433.                     } else {
  434.                         /*/
  435.                         foreach ($form as $formField) {
  436.                             $response['error'] = true;
  437.                             $errorString = (string)$formField->getErrors();
  438.                             if ($errorString != "") {
  439.                                 $response['data']['errors'][] = [
  440.                                     'id' => $form->getName() . "_" . $formField->getName(),
  441.                                     'text' => $errorString
  442.                                 ];
  443.                             }
  444.                         }
  445.                         return new JsonResponse($response);
  446.                         //*/
  447.                         $newClaim $form->getData();
  448.                         $data = array();
  449.                         $errors2 = array();
  450.                         $alert = array();
  451.                         # Get Validation Error Messages
  452.                         $errors $this->get("validator")->validate($newClaim);
  453.                         if (count($errors) > 0) {
  454.                             $data = [
  455.                                 "errors" => array()
  456.                             ];
  457.                             foreach ($errors as $error) {
  458.                                 $nextError = array();
  459.                                 $nextError['id'] = $form->getName() . "_" $error->getPropertyPath();
  460.                                 $nextError['text'] = $error->getMessage();
  461.                                 $data['errors'][] = $nextError;
  462.                             }
  463.                         }
  464.                         /*if(!$county_pass)
  465.                         {
  466.                             $data['errors'][] = [
  467.                                 'id' => 'claim_main_fragment_lossCounty',
  468.                                 'text' => 'This customer requires you to have a loss county'
  469.                             ];
  470.                         }*/
  471.                         if(!$tpa_pass)
  472.                         {
  473.                             if(!$umrValue){
  474.                                 $data['errors'][] = [
  475.                                     'id' => 'claim_tpa_fragment_umr',
  476.                                     'text' => 'This customer requires a UMR number'
  477.                                 ];
  478.                             }
  479.                             if(!$propertyTypeInbound){
  480.                                 $data['errors'][] = [
  481.                                     'id' => 'claim_tpa_fragment_property_type',
  482.                                     'text' => 'Please select a Property Type'
  483.                                 ];
  484.                             }
  485.                         }
  486.                         # Return JSON Errors Object
  487.                         $retVal = array(
  488.                             "result" => "fail",
  489.                             "error_msgs" => $errors2,
  490.                             "error" => true,
  491.                             "data" => $data
  492.                         );
  493.                         return new JsonResponse($retVal);
  494.                     }
  495.                 }
  496.                 // --------------------------------------------------------------------------------
  497.                 $claim_switch_action "";
  498.                 $session = new Session();
  499.                 if ($session->has("claim_switch_action")) {
  500.                     $claim_switch_action $session->get("claim_switch_action");
  501.                     $session->remove("claim_switch_action");
  502.                 }
  503.                 #get the peril type and sub peril type information
  504.                 # Make sure valid claim object was passed
  505.                 if ($claim === null) {
  506.                     throw $this->createNotFoundException("Claim does not exist");
  507.                 }
  508.                 $em $this->container->get("doctrine.orm.entity_manager");
  509.                 $rootPeril null;
  510.                 $rootPerilId 0;
  511.                 if ($claim->getPeril()) {
  512.                     //$rootPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getPeril()->getId());
  513.                     //$rootPerilId = $rootPeril->getId();
  514.                     $rootPeril $claim->getPeril();
  515.                     $rootPerilId $claim->getPeril()->getId();
  516.                 }
  517.                 $RootPerils $em->getRepository("ClaimManagementBundle:Peril")->getRootPerils();
  518.                 $subPeril null;
  519.                 $subPerilId 0;
  520.                 if ($claim->getSubPeril()) {
  521.                     //$subPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getSubPeril()->getId());
  522.                     //$subPerilId = $subPeril->getId();
  523.                     $subPeril $claim->getSubPeril();
  524.                     $subPerilId $claim->getSubPeril()->getId();
  525.                 }
  526.                 $ChildrenPerils = array();
  527.                 if ($rootPeril !== null) {
  528.                    $ChildrenPerils $em->getRepository("ClaimManagementBundle:Peril")->getPerilChildren($rootPerilId);
  529.                 }
  530.                 # load up all the property types
  531.                 //$PropertyTypeRepo = $em->getRepository("ClaimManagementBundle:PropertyType");
  532.                 //$PropertyTypes = $PropertyTypeRepo->findBy([],['propertyType'=>'ASC']);
  533.                 $PropertyStatuses $PropertyStatusRepo->findAll();
  534.                 $claimRep $claim->getClaimRep();
  535.                 /*$qb = $em->getRepository('ResourceManagementBundle:Resource')->createQueryBuilder('resource');
  536.                 $qb->select('resource')
  537.                 ->where($qb->expr()->eq('resource.isActive',":is_active"))
  538.                     ->andWhere($qb->expr()->eq('resource.customerResources.customer',":customer"));
  539.                 $qb->setParameter("is_active", true);
  540.                 $qb->setParameter("customer", $claim->getCustomer());
  541.                 $qb->addOrderBy("resource.firstName", 'ASC');
  542.                 $resources = $qb->getQuery()->getResult();*/
  543.                 $sql "SELECT r.id, r.first_name, r.last_name
  544.                          FROM resource r 
  545.                          INNER JOIN customer_resource cr ON r.id = cr.resource_id
  546.                          WHERE r.is_active = :is_active
  547.                          AND cr.customer_id = :cust_id
  548.                          ORDER BY r.first_name";
  549.                 $dataParams = array();
  550.                 $dataParams['is_active'] = 1;
  551.                 $dataParams['cust_id'] = 0;
  552.                 if ($claim->getCustomer()) {
  553.                     $dataParams['cust_id'] = $claim->getCustomer()->getId();
  554.                 }
  555.                 $stmt $em->getConnection()->prepare($sql);
  556.                 $stmt->execute($dataParams);
  557.                 $claimRepResources $stmt->fetchAll( \PDO::FETCH_ASSOC );
  558.                 $dateOpened $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
  559.                 $dateClosed $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
  560.                 if($dateClosed $dateOpened){
  561.                     $dateClosed = new \DateTime('now');
  562.                 }
  563.                 $difference date_diff($dateOpened,$dateClosed);
  564.                 $difference = (array)$difference;
  565.                 $daysOpen = array();
  566.                 $daysOpen['days'] = $difference['days'];
  567.                 $daysOpen['h'] = $difference['h'];
  568.                 $daysOpen['m'] = $difference['m'];
  569.                 $systemParamService $this->container->get('core.system_parameter_control');
  570.                 $swbc_payments false;
  571.                 $swbc_payments $systemParamService->isEnabledControl('SWBC_payment_letter');
  572.                 # 3) If this wasn't a form submission, we render the screen
  573.                 $systemAdminUsers $systemParamService->getAccessArray('Invoicing_access');
  574.                 
  575.                 $bShowInvoiceAccessTab false;
  576.                 $user $this->get('security.token_storage')->getToken()->getUser();
  577.                 if (!empty($systemAdminUsers) && in_array($user->getId(),$systemAdminUsers)) {
  578.                     $bShowInvoiceAccessTab true;
  579.                 }
  580.                 $bShowSymbilityRefUrl false;
  581.                 $bShowRefUrl false;
  582.                 $session = new Session();
  583.                 if ($claim->getStatus()>=10) {
  584.                     $bShowRefUrl true;
  585.                     #check for Symbility Refer Url
  586.                     if ($claim->getAssignmentId()) {
  587.                         $bShowSymbilityRefUrl true;
  588.                         $bReferSymbilityUrl=$systemParamService->getParameterValue('symbilityLiveReferUrl','url_token');
  589.                         $session->set("claimSymbilityUrl"$bReferSymbilityUrl);
  590.                     }
  591.                     # End of the check
  592.                 }
  593.                 # check if the External Resource Widget is allowed to show for TPA Customer
  594.                 $TpaCustomer $this->getDoctrine()->getRepository("CompanyManagementBundle:TpaCustomer")->findOneBy(['customerId'=>$claim->getCustomer()->getId()]);
  595.                 $isTpaCustomerAllowed=false;
  596.                 if(!empty($TpaCustomer)){
  597.                     $isTpaCustomerAllowed=true;
  598.                 }
  599.                 # load up all the sub loss types
  600.                 $sql "SELECT *
  601.                              FROM perils p 
  602.                              WHERE p.peril_id is null OR p.peril_id <> 0
  603.                              ORDER BY p.description";
  604.                 $dataParams = array();
  605.                 $stmt $em->getConnection()->prepare($sql);
  606.                 $stmt->execute($dataParams);
  607.                 $ChildrenPerils $stmt->fetchAll( \PDO::FETCH_ASSOC );
  608.                 $SubPerilIdArray =[];
  609.                 if(!empty($ChildrenPerils)){
  610.                     foreach ($ChildrenPerils as $ky=>$childrenPeril){
  611.                         $SubPerilIdArray[$childrenPeril['id']]=$childrenPeril['description'];
  612.                     }
  613.                 }
  614.                 # load up all the sub damage types
  615.                 $propertyDamageTypes $em->getRepository("ClaimManagementBundle:PropertyDamageType")->findAll();
  616.                 $CompType $em->getRepository("CompanyManagementBundle:CompType")->getActiveCompType();
  617.                 $CompCode $em->getRepository("CompanyManagementBundle:CompCode")->getActiveCompCode();
  618.                 //dd($claim->getLiabilityType());
  619.                 //dd($SubPerilIdArray);
  620.                 return $this->render('ClaimManagementBundle:ClaimFlowScreen/Fragments:main-fragment.html.twig', [
  621.                     'active' => 'main',
  622.                     'claim' => $claim,
  623.                     'claimStatus' => $claimStatus,
  624.                     'form' => $form->createView(),
  625.                     'claim_switch_action' => $claim_switch_action,
  626.                     'insured_form' => $insuredForm,
  627.                     "rootPerilId" => $rootPerilId,
  628.                     "rootPeril" => $rootPeril,
  629.                     "SubPerilId" => $subPerilId,
  630.                     "subPeril" => $subPeril,
  631.                     "RootPerils" => $RootPerils,
  632.                     "ChildrenPerils" => $ChildrenPerils,
  633.                     'PropertyTypes' => $PropertyTypes,
  634.                     'PropertyStatuses' => $PropertyStatuses,
  635.                     'claimRep' => $claimRep,
  636.                     'resources' => $claimRepResources,
  637.                     "company" => $company,
  638.                     "daysOpen" => $daysOpen,
  639.                     "CwopReasons" => $CwopReasons,
  640.                     "swbc_payments" => $swbc_payments,
  641.                     "SettlementTypes" => $SettlementTypes,
  642.                     'bShowInvoiceAccessTab' => $bShowInvoiceAccessTab,
  643.                     "isTpaCustomer" => $isTpaCustomer,
  644.                     'tPACustomer' => $tpacust,
  645.                     "ShowRefUrl" =>$bShowRefUrl,
  646.                     "isTpaCustomerAllowed" => $isTpaCustomerAllowed,
  647.                     "SubPerilIdArray" => $SubPerilIdArray,
  648.                     "propertyDamageTypes" => $propertyDamageTypes,
  649.                     'comptypeArray' => $CompType,
  650.                     'compcodeArray' => $CompCode,
  651.                     'bShowSymbilityRefUrl' => $bShowSymbilityRefUrl
  652.                 ]);
  653.         } else {
  654.             throw new NotFoundHttpException('Could not find this claim!');
  655.         }
  656.     }
  657.     /**
  658.      * @Route("/create/{id}", defaults={"id" = null})
  659.      */
  660.     public function createclaimAction(Request $request$id)
  661.     {
  662.         $em $this->getDoctrine()->getManager();
  663.         // IF we're a Carrier acct
  664.         $claimStatus 5;
  665.         $isCarrier='N';
  666.         /*
  667.          * 01/24/2020
  668.          *
  669.          * TBCA - We want to make sure that the feature is enabled before actually doing
  670.          * any of the row work.
  671.          *
  672.          */
  673.         $parentClaim false;
  674.         $form $this->createForm(ClaimMainFragmentCarrier::class, new Claim());
  675.         # Load Extra Field Values
  676.         $insuredFirstName "";
  677.         $insuredLastName "";
  678.         $SubPeril null;
  679.         $countyId 0;
  680.         $county "";
  681.         $LossCounty null;
  682.         if ($request->getMethod() === "POST") {
  683.             # Request in Extra Fields
  684.             $insuredFirstName $request->request->get("insured_first_name");
  685.             $insuredLastName $request->request->get("insured_last_name");
  686.             $sub_peril = ($request->request->has("sub_peril")) ? intval($request->request->get("sub_peril")) : 0;
  687.             $county_id intval($request->request->get("county_id"));
  688.             $claim_rep_id intval($request->request->get("claim_rep"));
  689.             # Grab the serialized submission data
  690.             $claimFormSubmission $request->request->get('claim_main_fragment_carrier');
  691.             $claimNumber $claimFormSubmission['claimNumber'];
  692.             $lossZip $claimFormSubmission['lossZip'];
  693.             $lossDate $claimFormSubmission['lossDate'];
  694.             $get_peril_id $claimFormSubmission['peril'];
  695.             # Submit the actual forms
  696.             $form->submit($claimFormSubmission);
  697.             # If the first form was ok, SUBMIT the insured form. Otherwise, archive the errors.
  698.             if ($form->isValid()) {
  699.                 /** @var Claim $newClaim */
  700.                 $newClaim $form->getData();
  701.                 if (!$lossDate || $lossDate == "") {
  702.                     $response['error'] = true;
  703.                     $response['data'] = array();
  704.                     $response['data']['errors'] = array();
  705.                     $response['data']['errors'][] = [
  706.                         'id' => "claim_main_fragment_carrier_lossDate",
  707.                         'text' => "ERROR: This value should not be blank."
  708.                     ];
  709.                     return new JsonResponse($response);
  710.                 }
  711.                 if (!$lossZip) {
  712.                     $response['error'] = true;
  713.                     $response['data'] = array();
  714.                     $response['data']['errors'] = array();
  715.                     $response['data']['errors'][] = [
  716.                         'id' => "claim_main_fragment_carrier_lossZip",
  717.                         'text' => "ERROR: This value should not be blank."
  718.                     ];
  719.                 } else if (strlen($lossZip) != 5) {
  720.                     $response['error'] = true;
  721.                     $response['data'] = array();
  722.                     $response['data']['errors'] = array();
  723.                     $response['data']['errors'][] = [
  724.                         'id' => "claim_main_fragment_carrier_lossZip",
  725.                         'text' => "ERROR: This value should be a valid zip code."
  726.                     ];
  727.                 }
  728.                 # Validate Peril
  729.                 if (!$get_peril_id) {
  730.                     $response['error'] = true;
  731.                     $response['data'] = array();
  732.                     $response['data']['errors'] = array();
  733.                     $response['data']['errors'][] = [
  734.                         'id' => "claim_main_fragment_carrier_peril",
  735.                         'text' => "ERROR: This value should not be blank."
  736.                     ];
  737.                     $response['error'] = true;
  738.                     return new JsonResponse($response);
  739.                 }
  740.                 $claimNumber $newClaim->getClaimNumber();
  741.                 $Claim $em->getRepository("ClaimManagementBundle:Claim")->findOneBy([
  742.                     "claimNumber" => $claimNumber
  743.                 ]);
  744.                 if ($Claim) {
  745.                     $response['error'] = true;
  746.                     $response['data'] = array();
  747.                     $response['data']['errors'] = array();
  748.                     $response['data']['errors'][] = [
  749.                         'id' => "claim_main_fragment_carrier_claimNumber",
  750.                         'text' => "ERROR: Claim Number already exists."
  751.                     ];
  752.                     $response['error'] = true;
  753.                     return new JsonResponse($response);
  754.                 }
  755.                 if ($get_peril_id) {
  756.                     $Peril $em->getRepository("ClaimManagementBundle:Peril")->find($get_peril_id);
  757.                     if ($Peril) {
  758.                         $newClaim->setPeril($Peril);
  759.                     }
  760.                 }
  761.                 if ($sub_peril) {
  762.                     $SubPeril $em->getRepository("ClaimManagementBundle:Peril")->find($sub_peril);
  763.                     if ($SubPeril) {
  764.                         $newClaim->setSubPeril($SubPeril);
  765.                     }
  766.                 }
  767.                 if ($county_id) {
  768.                     $County $em->getRepository("ResourceManagementBundle:Counties")->find($county_id);
  769.                     if ($County) {
  770.                         $newClaim->setLossCounty($County);
  771.                     }
  772.                 }
  773.                 if ($claim_rep_id) {
  774.                     $ClaimRep $em->getRepository("ResourceManagementBundle:Resource")->find($claim_rep_id);
  775.                     if ($ClaimRep) {
  776.                         $newClaim->setClaimRep($ClaimRep);
  777.                     }
  778.                 }
  779.                 $ClaimService $this->container->get("claim.service");
  780.                 $claimId $ClaimService->saveNewClaim($newClaim$insuredFirstName$insuredLastName);
  781.                 $response = [
  782.                     'error' => false'data' => ["claim_id" => $claimId]
  783.                 ];
  784.                 return new JsonResponse($response);
  785.             } else {
  786.                 # Validate Insured Name
  787.                 $response['error'] = true;
  788.                 $response['data'] = array();
  789.                 $response['data']['errors'] = array();
  790.                 if (!$insuredFirstName || !$insuredLastName) {
  791.                     if (!$insuredFirstName) {
  792.                         $response['data']['errors'][] = [
  793.                             'id' => "insured_first_name",
  794.                             'text' => "ERROR: This value should not be blank."
  795.                         ];
  796.                     }
  797.                     if (!$insuredLastName) {
  798.                         $response['data']['errors'][] = [
  799.                             'id' => "insured_last_name",
  800.                             'text' => "ERROR: This value should not be blank."
  801.                         ];
  802.                     }
  803.                 }
  804.                 if (!$get_peril_id) {
  805.                     $response['data']['errors'][] = [
  806.                         'id' => "claim_main_fragment_carrier_peril",
  807.                         'text' => "ERROR: This value should not be blank."
  808.                     ];
  809.                 }
  810.                 $Claim $em->getRepository("ClaimManagementBundle:Claim")->findOneBy([
  811.                     "claimNumber" => $claimNumber
  812.                 ]);
  813.                 if ($Claim) {
  814.                     $response['data']['errors'][] = [
  815.                         'id' => "claim_main_fragment_carrier_claimNumber",
  816.                         'text' => "ERROR: Claim Number already exists."
  817.                     ];
  818.                 }
  819.                 foreach ($form as $formField) {
  820.                     $response['error'] = true;
  821.                     $errorString = (string)$formField->getErrors(truefalse);
  822.                     if ($errorString != "") {
  823.                         $response['data']['errors'][] = [
  824.                             'id' => $form->getName() . "_" $formField->getName(),
  825.                             'text' => $errorString
  826.                         ];
  827.                     }
  828.                 }
  829.                 return new JsonResponse($response);
  830.             }
  831.         }
  832.         // --------------------------------------------------------------------------------
  833.         $claim_switch_action "";
  834.         $session = new Session();
  835.         if ($session->has("claim_switch_action")) {
  836.             $claim_switch_action $session->get("claim_switch_action");
  837.             $session->remove("claim_switch_action");
  838.         }
  839.         $coassign $this->get('core.coassignment');
  840.         
  841.         
  842.         # 3) If this wasn't a form submission, we render the screen
  843.         return $this->render('ClaimManagementBundle:ClaimFlowScreen/Fragments:new-claim-carrier.html.twig', [
  844.          'active' => 'main',
  845.          'claimStatus' => 5,
  846.          'form' => $form->createView(),
  847.          'claim_switch_action' => $claim_switch_action,
  848.          "insuredFirstName" => $insuredFirstName,
  849.          "insuredLastName" => $insuredLastName,
  850.          "SubPeril" => $SubPeril,
  851.          "countyId" => $countyId,
  852.          "county" => $county,
  853.          "ommitMenu" => true,
  854.          "parent_claim_number" => $parentClaim,
  855.          "isCarrier" => $isCarrier,
  856.          "next_index" => ((($parentClaim === false) || empty($parentClaim)) ? $coassign->assignSubTaskId($parentClaim))
  857.      ]);
  858.     }
  859.     /**
  860.      * Action to update session that allows you to override
  861.      * isCarrier Parameter from Environment. If you pass isCarrier 0,
  862.      * you can view the ICM version of the Claim Details Tabs
  863.      *
  864.      * @Route("/switch_claims_carrier/{isCarrier}")
  865.      */
  866.     public function switchClaimTabsIsCarrier($isCarrier)
  867.     {
  868.         $session = new Session();
  869.         if ($isCarrier) {
  870.             $session->remove("ForceICM");
  871.         } else {
  872.             $session->set("ForceICM"1);
  873.         }
  874.         return new JsonResponse([
  875.             "error" => false
  876.         ]);
  877.     }
  878.     /**
  879.      * Used by Main Claim Tab on Carrier to
  880.      * get counties from state_id param
  881.      *
  882.      * @Route("/search_county")
  883.      * @Method({"POST"})
  884.      */
  885.     public function getCountiesByState(Request $request)
  886.     {
  887.         $em $this->getDoctrine();
  888.         $term $request->request->get("term");
  889.         $state_id intval($request->request->get("state_id"));
  890.         $dataParams = array();
  891.         $sql "SELECT c.id, county, s.id as state_id, s.stateCode
  892.                 FROM counties c
  893.                 LEFT JOIN state s
  894.                   ON c.stateId = s.id 
  895.                 WHERE 1 = 1 ";
  896.         if ($term) {
  897.             $sql .= "AND county LIKE :term ";
  898.             $dataParams['term'] = $term '%';
  899.         }
  900.         if ($state_id 0) {
  901.             $sql .= "AND c.stateId = :state_id ";
  902.             $dataParams['state_id'] = $state_id;
  903.         }
  904.         $sql .= "GROUP BY county, stateCode 
  905.                  ORDER BY county, stateCode DESC";
  906.         $stmt $em->getConnection()->prepare($sql);
  907.         $stmt->execute($dataParams);
  908.         $Counties $stmt->fetchAll(\PDO::FETCH_ASSOC);
  909.         return new JsonResponse([
  910.             "error" => false,
  911.             "data" => $Counties
  912.         ]);
  913.     }
  914.     /**
  915.      * Use by Main Claim Tab on Carrier to
  916.      * identify the state and county when zip
  917.      * code is entered
  918.      *
  919.      * @Route("/search_zip")
  920.      * @Method({"POST"})
  921.      */
  922.     public function searchZipCodesAjax(Request $request)
  923.     {
  924.         $em $this->getDoctrine();
  925.         $term $request->request->get("term");
  926.         $dataParams = array();
  927.         $sql "SELECT z.state_id, c.id as county_id, c.county, z.zip
  928.                 FROM zip_codes z
  929.                 INNER JOIN counties c
  930.                   ON z.county_id = c.id
  931.                 WHERE z.zip = :term
  932.                 LIMIT 1 ";
  933.         $Zip = array();
  934.         $dataParams['term'] = $term;
  935.         $stmt $em->getConnection()->prepare($sql);
  936.         $stmt->execute($dataParams);
  937.         $Zips $stmt->fetchAll(\PDO::FETCH_ASSOC);
  938.         if (count($Zips) > 0) {
  939.             $Zip $Zips[0];
  940.         }
  941.         return new JsonResponse([
  942.             "error" => false,
  943.             "data" => $Zip
  944.         ]);
  945.     }
  946.     /**
  947.      * @Route("/main/coverages/{id}")
  948.      */
  949.     public function showClaimCoveragesAction(Claim $claim)
  950.     {
  951.         # Make sure valid claim object was passed
  952.         if ($claim === null) {
  953.             throw $this->createNotFoundException("Claim does not exist");
  954.         }
  955.         # Get Insured Form Instance from Form Helper (will use without form tags)
  956.         $em $this->container->get("doctrine.orm.entity_manager");
  957.         $InsuredTypes $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->findAll();
  958.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/coverages-widget.html.twig", [
  959.             "claim" => $claim,
  960.             "insuredTypes" => $InsuredTypes
  961.         ]);
  962.     }
  963.     /**
  964.      * @Route("/main/coverages_data/{id}")
  965.      */
  966.     public function getCoveragesDatatablesData(Claim $claim)
  967.     {
  968.         /** @var EntityManager $em */
  969.         $em $this->getDoctrine();
  970.         /** @var \PDO $conn */
  971.         $conn $em->getConnection();
  972.         # Start by opening a new Coverages array
  973.         $Coverages = [];
  974.         # Prepared statements we need
  975.         // $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 = ?");
  976.         $fetch_coverages $conn->prepare("SELECT id, amount, name, reserve FROM coverage WHERE claim_id = ?");
  977.         $fetch_coverages->execute([$claim->getId()]);
  978.         //$fetch_reserve = $conn->prepare("SELECT amount FROM coverage_reserve WHERE coverage_id = ? ORDER BY date_modified DESC LIMIT 1");
  979.         # Go through each result and add to Coverages
  980.         while($cov $fetch_coverages->fetch(\PDO::FETCH_ASSOC))
  981.         {
  982.             # Get the reserve for this
  983.             /*$fetch_reserve->execute([$cov['id']]);
  984.             $reserve = $fetch_reserve->fetch(\PDO::FETCH_ASSOC);*/
  985.             $Coverages[] = [
  986.                 'id' => $cov['id'],
  987.                 'name' => $cov['name'],
  988.                 'amount' => $cov['amount'],
  989.                 'reserve' => $cov['reserve']
  990.             ];
  991.         }
  992.         return new JsonResponse([
  993.             "recordsTotal" => count($Coverages),
  994.             "recordsFiltered" => count($Coverages),
  995.             "data" => $Coverages,
  996.         ]);
  997.     }
  998.     /**
  999.      * @Route("/main/deductibles_data/{id}")
  1000.      */
  1001.     public function getDeductiblesDatatablesData(Claim $claim)
  1002.     {
  1003.         $em $this->getDoctrine();
  1004.         $sql "SELECT d.id,d.claim_id,d.deductible_name_id,d.amount, dn.name as deductibleName 
  1005.                 FROM deductible d
  1006.                 INNER JOIN deductible_name dn 
  1007.                   ON d.deductible_name_id = dn.id 
  1008.                 WHERE d.claim_id = :claim_id ";
  1009.         $stmt $em->getConnection()->prepare($sql);
  1010.         $stmt->execute([
  1011.             "claim_id" => $claim->getId()
  1012.         ]);
  1013.         $Deductibles $stmt->fetchAll(\PDO::FETCH_ASSOC);
  1014.         return new JsonResponse([
  1015.             "recordsTotal" => count($Deductibles),
  1016.             "recordsFiltered" => count($Deductibles),
  1017.             "data" => $Deductibles,
  1018.         ]);
  1019.     }
  1020.     /**
  1021.      * @Route("/main/limits/{id}")
  1022.      */
  1023.     public function showClaimLimitsAction(Claim $claim)
  1024.     {
  1025.         # Make sure valid claim object was passed
  1026.         if ($claim === null) {
  1027.             throw $this->createNotFoundException("Claim does not exist");
  1028.         }
  1029.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1030.         $em $this->container->get("doctrine.orm.entity_manager");
  1031.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/claim-limits-widget.html.twig", [
  1032.             "claim" => $claim
  1033.         ]);
  1034.     }
  1035.     /**
  1036.      * @Route("/main/deductibles/{id}")
  1037.      */
  1038.     public function showClaimDeductiblesAction(Claim $claim)
  1039.     {
  1040.         # Make sure valid claim object was passed
  1041.         if ($claim === null) {
  1042.             throw $this->createNotFoundException("Claim does not exist");
  1043.         }
  1044.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1045.         $em $this->container->get("doctrine.orm.entity_manager");
  1046.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/deductibles-widget.html.twig", [
  1047.             "claim" => $claim
  1048.         ]);
  1049.     }
  1050.     /**
  1051.      * @Route("/main/insureds/{id}")
  1052.      */
  1053.     public function showClaimInsuredAction(Claim $claim)
  1054.     {
  1055.         $em $this->container->get("doctrine.orm.entity_manager");
  1056.         # Make sure valid claim object was passed
  1057.         if ($claim === null) {
  1058.             throw $this->createNotFoundException("Claim does not exist");
  1059.         }
  1060.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1061.         $InsuredTypes $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->findAll();
  1062.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/insured-widget.html.twig", [
  1063.             "claim" => $claim,
  1064.             "insuredTypes" => $InsuredTypes
  1065.         ]);
  1066.     }
  1067.     /**
  1068.      * @Route("/main/other-parties/{id}")
  1069.      */
  1070.     public function showClaimOtherPartiesAction(Claim $claim)
  1071.     {
  1072.         $em $this->container->get("doctrine.orm.entity_manager");
  1073.         # Make sure valid claim object was passed
  1074.         if ($claim === null) {
  1075.             throw $this->createNotFoundException("Claim does not exist");
  1076.         }
  1077.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1078.         $otherPartyTypes $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->findAll();
  1079.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/other-parties-widget.html.twig", [
  1080.             "claim" => $claim,
  1081.             "insuredTypes" => $otherPartyTypes
  1082.         ]);
  1083.     }
  1084.     /**
  1085.      * @Route("/main/resources/{id}")
  1086.      */
  1087.     public function showClaimResourcesAction(Claim $claim)
  1088.     {
  1089.         # Make sure valid claim object was passed
  1090.         if ($claim === null) {
  1091.             throw $this->createNotFoundException("Claim does not exist");
  1092.         }
  1093.         $em $this->container->get("doctrine.orm.entity_manager");
  1094.         $assignmentService $this->get('claim.assignment');
  1095.         $alertMessageDateExpiryArray $assignmentService->validLicense($claim);
  1096.         $alertMessageDateExpiry $alertMessageDateExpiryArray['alertMessageDateExpiry'];
  1097.         $licenseDataArray $alertMessageDateExpiryArray['licenseDataArray'];
  1098.         $adjusterRepo $em->getRepository("ResourceManagementBundle:Resource");
  1099.         $claimTeamRepo $em->getRepository("ClaimManagementBundle:ClaimTeam");
  1100.         //$adjusters = $adjusterRepo->findBy(['resourceType'=>array(2,3,4)]);
  1101.         $claimTeams $claimTeamRepo->findBy(['enabled'=>true]);
  1102.         $resourceTypes $em->getRepository("ResourceManagementBundle:ResourceType")->findAll();
  1103.         $assignmentParties $em->getRepository("AssignmentBundle:AssignmentParty")->findAll();
  1104.         /*$sql = "SELECT count(id) as resource_count
  1105.                    FROM claim_resource cr
  1106.                    WHERE cr.claim_id = :claim_id";*/
  1107.         $sql "SELECT count(id) as resource_count
  1108.                    FROM assignments cr 
  1109.                    WHERE cr.claim_id = :claim_id
  1110.                     AND IFNULL(cr.next_assignment_id,0) = 0
  1111.                     AND cr.is_current_assignment = 1 ";
  1112.         $stmt $em->getConnection()->prepare($sql);
  1113.         $stmt->execute([
  1114.             "claim_id"=>$claim->getId()
  1115.         ]);
  1116.         $resourceCountResults $stmt->fetchAll(\PDO::FETCH_ASSOC);
  1117.         $resourceCount 0;
  1118.         foreach ($resourceCountResults as $resourceCountRow){
  1119.             $resourceCount $resourceCountRow['resource_count'];
  1120.         }
  1121.         # check if the External Resource Widget is allowed to show for TPA Customer
  1122.         $TpaCustomer $this->getDoctrine()->getRepository("CompanyManagementBundle:TpaCustomer")->findOneBy(['customerId'=>$claim->getCustomer()->getId()]);
  1123.         $isTpaCustomerAllowed=false;
  1124.         if(!empty($TpaCustomer)){
  1125.             $isTpaCustomerAllowed=true;
  1126.         }
  1127.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/resources-widget.html.twig", [
  1128.             "claim" => $claim,
  1129.             'resourceTypes' => $resourceTypes,
  1130.             'assignmentParties' => $assignmentParties,
  1131.             'teams' => $claimTeams,
  1132.             'resourceCount' => $resourceCount,
  1133.             'licenseDataArray' => $licenseDataArray,
  1134.             'alertMessageDateExpiry' =>$alertMessageDateExpiry,
  1135.             'isTpaCustomerAllowed' =>$isTpaCustomerAllowed
  1136.         ]);
  1137.     }
  1138.     /**
  1139.      * @Route("/main/coverage/add/{id}")
  1140.      */
  1141.     public function addClaimCoverageAction(Claim $claim)
  1142.     {
  1143.         # Make sure valid claim object was passed
  1144.         if ($claim === null) {
  1145.             throw $this->createNotFoundException("Claim does not exist");
  1146.         }
  1147.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1148.         $em $this->container->get("doctrine.orm.entity_manager");
  1149.         # Check Permissions
  1150.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1151.         $formFactory $this->container->get("form.factory");
  1152.         $CoverageFormHelper = new CoverageFormHelper($em$formFactoryfalse);
  1153.         $form $CoverageFormHelper->getAddForm();
  1154.         # 1) Create a Form for the Claim. It will be a PARTIAL form
  1155.         //$form = $this->createForm(ClaimPolicyFragment::class, $claim);
  1156.         $CoverageTypes $em->getRepository("ClaimManagementBundle:CoverageType")->findBy([], ['coverageType' => 'ASC']);
  1157.         $dateOpened $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
  1158.         $dateClosed $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
  1159.         if($dateClosed $dateOpened){
  1160.             $dateClosed = new \DateTime('now');
  1161.         }
  1162.         $difference date_diff($dateOpened,$dateClosed);
  1163.         $difference = (array)$difference;
  1164.         $daysOpen = array();
  1165.         $daysOpen['days'] = $difference['days'];
  1166.         $daysOpen['h'] = $difference['h'];
  1167.         $daysOpen['m'] = $difference['m'];
  1168.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-coverage-modal.html.twig", [
  1169.             'CoverageTypes' => $CoverageTypes,
  1170.             'claim' => $claim,
  1171.             'coverageForm' => $form->createView(),
  1172.             "daysOpen" => $daysOpen
  1173.         ]);
  1174.     }
  1175.     /**
  1176.      * @Route("/main/coverage/edit/{id}")
  1177.      */
  1178.     public function editClaimCoverageAction(Coverage $coverage)
  1179.     {
  1180.         # Make sure valid claim object was passed
  1181.         if ($coverage === null) {
  1182.             throw $this->createNotFoundException("Coverage does not exist");
  1183.         }
  1184.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1185.         $em $this->container->get("doctrine.orm.entity_manager");
  1186.         # 1) Create a Form for the Claim. It will be a PARTIAL form
  1187.         $claim $coverage->getClaim();
  1188.         # Check Permissions
  1189.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1190.         $coverageName $coverage->getName();
  1191.         //$coverageForm = $this->createForm(ClaimPolicyFragment::class, $claim);
  1192.         $CoverageTypes $em->getRepository("ClaimManagementBundle:CoverageType")->findAll();
  1193.         $formFactory $this->container->get("form.factory");
  1194.         $CoverageFormHelper = new CoverageFormHelper($em$formFactoryfalse);
  1195.         $form $CoverageFormHelper->getEditForm($coverage);
  1196.         $dateOpened $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
  1197.         $dateClosed $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
  1198.         if($dateClosed $dateOpened){
  1199.             $dateClosed = new \DateTime('now');
  1200.         }
  1201.         $difference date_diff($dateOpened,$dateClosed);
  1202.         $difference = (array)$difference;
  1203.         $daysOpen = array();
  1204.         $daysOpen['days'] = $difference['days'];
  1205.         $daysOpen['h'] = $difference['h'];
  1206.         $daysOpen['m'] = $difference['m'];
  1207.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-coverage-modal.html.twig", [
  1208.             'CoverageTypes' => $CoverageTypes,
  1209.             'coverage' => $coverage,
  1210.             'claim' => $claim,
  1211.             'coverageForm' => $form->createView(),
  1212.             'coverageName' => $coverageName,
  1213.             "daysOpen" => $daysOpen
  1214.         ]);
  1215.     }
  1216.     /**
  1217.      * @Route("/main/coverage/delete/{id}")
  1218.      */
  1219.     public function deleteClaimCoverageAction(Request $request,$id)
  1220.     {
  1221.         $em $this->container->get("doctrine.orm.entity_manager");
  1222.         $ClaimCoverage $em->getRepository("ClaimManagementBundle:Coverage")->find($id);
  1223.         $claim $ClaimCoverage->getClaim();
  1224.         # Check Permissions
  1225.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1226.         if($ClaimCoverage){
  1227.             $em->remove($ClaimCoverage);
  1228.             $em->flush();
  1229.         }
  1230.         # Return JSON Errors Object
  1231.         $retVal = array(
  1232.             "result" => "success",
  1233.             "error_msgs" => "",
  1234.             "error" => false,
  1235.             "data" => "Claim Coverage Deleted Sucessfully"
  1236.         );
  1237.         return new JsonResponse($retVal);
  1238.     }
  1239.     /**
  1240.      * @Route("/main/claim_limit/add/{id}")
  1241.      */
  1242.     public function addClaimLimitAction(Claim $claim)
  1243.     {
  1244.         # Make sure valid claim object was passed
  1245.         if ($claim === null) {
  1246.             throw $this->createNotFoundException("Claim does not exist");
  1247.         }
  1248.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1249.         $em $this->container->get("doctrine.orm.entity_manager");
  1250.         # Check Permissions
  1251.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1252.         $formFactory $this->container->get("form.factory");
  1253.         $ClaimLimitFormHelper = new ClaimLimitFormHelper($em$formFactoryfalse);
  1254.         $form $ClaimLimitFormHelper->getAddForm();
  1255.         $dateOpened $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
  1256.         $dateClosed $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
  1257.         if($dateClosed $dateOpened){
  1258.             $dateClosed = new \DateTime('now');
  1259.         }
  1260.         $difference date_diff($dateOpened,$dateClosed);
  1261.         $difference = (array)$difference;
  1262.         $daysOpen = array();
  1263.         $daysOpen['days'] = $difference['days'];
  1264.         $daysOpen['h'] = $difference['h'];
  1265.         $daysOpen['m'] = $difference['m'];
  1266.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-claim-limit-modal.html.twig", [
  1267.             'claim' => $claim,
  1268.             'claimLimitForm' => $form->createView(),
  1269.             "daysOpen" => $daysOpen
  1270.         ]);
  1271.     }
  1272.     /**
  1273.      * @Route("/main/deductible/add/{id}")
  1274.      */
  1275.     public function addClaimDeductibleAction(Claim $claim)
  1276.     {
  1277.         # Make sure valid claim object was passed
  1278.         if ($claim === null) {
  1279.             throw $this->createNotFoundException("Claim does not exist");
  1280.         }
  1281.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1282.         $em $this->container->get("doctrine.orm.entity_manager");
  1283.         # Check Permissions
  1284.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1285.         $formFactory $this->container->get("form.factory");
  1286.         $DeductibleFormHelper = new DeductibleFormHelper($em$formFactoryfalse);
  1287.         $form $DeductibleFormHelper->getAddForm();
  1288.         $dateOpened $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
  1289.         $dateClosed $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
  1290.         if($dateClosed $dateOpened){
  1291.             $dateClosed = new \DateTime('now');
  1292.         }
  1293.         $difference date_diff($dateOpened,$dateClosed);
  1294.         $difference = (array)$difference;
  1295.         $daysOpen = array();
  1296.         $daysOpen['days'] = $difference['days'];
  1297.         $daysOpen['h'] = $difference['h'];
  1298.         $daysOpen['m'] = $difference['m'];
  1299.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-deductible-modal.html.twig", [
  1300.             'claim' => $claim,
  1301.             'deductibleForm' => $form->createView(),
  1302.             "daysOpen" => $daysOpen
  1303.         ]);
  1304.     }
  1305.     /**
  1306.      * @Route("/main/claim_limit/edit/{id}")
  1307.      */
  1308.     public function editClaimLimitAction(ClaimLimit $claimLimit)
  1309.     {
  1310.         # Make sure valid claim object was passed
  1311.         if ($claimLimit === null) {
  1312.             throw $this->createNotFoundException("Claim Limit does not exist");
  1313.         }
  1314.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1315.         $em $this->container->get("doctrine.orm.entity_manager");
  1316.         $formFactory $this->container->get("form.factory");
  1317.         $claim $claimLimit->getClaim();
  1318.         # Check Permissions
  1319.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1320.         $ClaimLimitFormHelper = new ClaimLimitFormHelper($em$formFactoryfalse);
  1321.         $form $ClaimLimitFormHelper->getEditForm($claimLimit);
  1322.         $dateOpened $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
  1323.         $dateClosed $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
  1324.         if($dateClosed $dateOpened){
  1325.             $dateClosed = new \DateTime('now');
  1326.         }
  1327.         $difference date_diff($dateOpened,$dateClosed);
  1328.         $difference = (array)$difference;
  1329.         $daysOpen = array();
  1330.         $daysOpen['days'] = $difference['days'];
  1331.         $daysOpen['h'] = $difference['h'];
  1332.         $daysOpen['m'] = $difference['m'];
  1333.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-claim-limit-modal.html.twig", [
  1334.             'claim' => $claim,
  1335.             'claimLimit' => $claimLimit,
  1336.             'claimLimitForm' => $form->createView(),
  1337.             "daysOpen" => $daysOpen
  1338.         ]);
  1339.     }
  1340.     /**
  1341.      * @Route("/main/deductible/edit/{id}")
  1342.      */
  1343.     public function editClaimDeductibleAction(Deductible $deductible)
  1344.     {
  1345.         # Make sure valid claim object was passed
  1346.         if ($deductible === null) {
  1347.             throw $this->createNotFoundException("Deductible does not exist");
  1348.         }
  1349.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1350.         $em $this->container->get("doctrine.orm.entity_manager");
  1351.         $formFactory $this->container->get("form.factory");
  1352.         $claim $deductible->getClaim();
  1353.         # Check Permissions
  1354.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1355.         $DeductibleFormHelper = new DeductibleFormHelper($em$formFactoryfalse);
  1356.         $form $DeductibleFormHelper->getEditForm($deductible);
  1357.         $dateOpened $claim->getDateReopened() ? $claim->getDateReopened() : ($claim->getDateOpened() ? $claim->getDateOpened() :$claim->getDateCreated());
  1358.         $dateClosed $claim->getDateClosed()? $claim->getDateClosed(): new \DateTime('now');
  1359.         if($dateClosed $dateOpened){
  1360.             $dateClosed = new \DateTime('now');
  1361.         }
  1362.         $difference date_diff($dateOpened,$dateClosed);
  1363.         $difference = (array)$difference;
  1364.         $daysOpen = array();
  1365.         $daysOpen['days'] = $difference['days'];
  1366.         $daysOpen['h'] = $difference['h'];
  1367.         $daysOpen['m'] = $difference['m'];
  1368.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-deductible-modal.html.twig", [
  1369.             'claim' => $claim,
  1370.             'deductible' => $deductible,
  1371.             'deductibleForm' => $form->createView(),
  1372.             "daysOpen" => $daysOpen
  1373.         ]);
  1374.     }
  1375.     /**
  1376.      * @Route("/main/claim_limit/delete/{id}")
  1377.      */
  1378.     public function deleteClaimLimitAction(Request $request$id)
  1379.     {
  1380.         $em $this->container->get("doctrine.orm.entity_manager");
  1381.         $ClaimLimit $em->getRepository("ClaimManagementBundle:ClaimLimit")->find($id);
  1382.         $claim $ClaimLimit->getClaim();
  1383.         # Check Permissions
  1384.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1385.         if($ClaimLimit){
  1386.             $em->remove($ClaimLimit);
  1387.             $em->flush();
  1388.         }
  1389.         # Return JSON Errors Object
  1390.         $retVal = array(
  1391.             "result" => "success",
  1392.             "error_msgs" => "",
  1393.             "error" => false,
  1394.             "data" => "Claim Limit sucessfully removed"
  1395.         );
  1396.         return new JsonResponse($retVal);
  1397.     }
  1398.     /**
  1399.      * @Route("/main/deductible/delete/{id}")
  1400.      */
  1401.     public function deleteClaimDeductibleAction(Request $request,$id)
  1402.     {
  1403.         $em $this->container->get("doctrine.orm.entity_manager");
  1404.         $ClaimDeductible $em->getRepository("ClaimManagementBundle:Deductible")->find($id);
  1405.         $claim $ClaimDeductible->getClaim();
  1406.         # Check Permissions
  1407.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1408.         if($ClaimDeductible){
  1409.             $em->remove($ClaimDeductible);
  1410.             $em->flush();
  1411.         }
  1412.         # Return JSON Errors Object
  1413.         $retVal = array(
  1414.             "result" => "success",
  1415.             "error_msgs" => "",
  1416.             "error" => false,
  1417.             "data" => "Claim Coverage Deductible Sucessfully"
  1418.         );
  1419.         return new JsonResponse($retVal);
  1420.     }
  1421.     /**
  1422.      * @Route("/main/resource/add/{id}")
  1423.      * @deprecated
  1424.      */
  1425.     public function addClaimResourceAction(Claim $claimRequest $request)
  1426.     {
  1427.         # Make sure valid claim object was passed
  1428.         if ($claim === null) {
  1429.             throw $this->createNotFoundException("Claim does not exist");
  1430.         }
  1431.         # Check Permissions
  1432.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1433.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1434.         $em $this->container->get("doctrine.orm.entity_manager");
  1435.         $resourceId intval($request->request->get("res_id"));
  1436.         $Resource = array();
  1437.         $claimResource = array();
  1438.         if($resourceId <> 0){
  1439.             $Resource $em->getRepository("ResourceManagementBundle:Resource")->find($resourceId);
  1440.             $claimResource $em->getRepository("ClaimManagementBundle:ClaimResource")->findOneBy(
  1441.                 ["resource" => $Resource"claim" => $claim]
  1442.             );
  1443.         }
  1444.         $teams $em->getRepository("ClaimManagementBundle:ClaimTeam")->findBy(['enabled'=>true]);
  1445.         $resourceTypes $em->getRepository("ResourceManagementBundle:ResourceType")->findAll();
  1446.         $assignmentParties $em->getRepository("AssignmentBundle:AssignmentParty")->findAll();
  1447.         $hasAdjusters $em->getRepository("ClaimManagementBundle:ClaimResource")->getAdjustersByClaim($claim);
  1448.         $adjusterRepo $em->getRepository("ResourceManagementBundle:Resource");
  1449.         $claimTeamRepo $em->getRepository("ClaimManagementBundle:ClaimTeam");
  1450.         $claimTeams $claimTeamRepo->findBy(['enabled'=>true]);
  1451.         if (count($hasAdjusters) > 0)
  1452.             $hasAdjusters true;
  1453.         else
  1454.             $hasAdjusters false;
  1455.         $claimTeamId $claimTeamName '';
  1456.         $claimTeamObj $claim->getClaimTeam();
  1457.         if(!empty($claimTeamObj)){
  1458.             $claimTeamId     $claim->getClaimTeam()->getId();
  1459.             $claimTeamName  $claim->getClaimTeam()->getName();
  1460.         }
  1461.         //return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/share-resource-modal.html.twig", [
  1462.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/share-multple-resource-modal.html.twig", [
  1463.             'claim' => $claim,
  1464.             'teams' => $teams,
  1465.             "hasAdjusters" => $hasAdjusters,
  1466.             'resourceTypes' => $resourceTypes,
  1467.             'assignmentParties' => $assignmentParties,
  1468.             'resourceId'=>$resourceId,
  1469.             "Resource" => $Resource,
  1470.             "claimResource" => $claimResource,
  1471.             "claimTeamId" => $claimTeamId,
  1472.             "claimTeamName" => $claimTeamName
  1473.         ]);
  1474.     }
  1475.     /**
  1476.      * @Route("/main/resource/change_team_cust/{id}")
  1477.      */
  1478.     public function changeTeamCustomer(Claim $claimRequest $request)
  1479.     {
  1480.         # Make sure valid claim object was passed
  1481.         if ($claim === null) {
  1482.             throw $this->createNotFoundException("Claim does not exist");
  1483.         }
  1484.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1485.         $em $this->container->get("doctrine.orm.entity_manager");
  1486.         # entities needed for form
  1487.         $teams $em->getRepository("ClaimManagementBundle:ClaimTeam")->findBy(['enabled'=>true], ['name' => 'ASC']);
  1488.         $customers $em->getRepository("CustomerManagementBundle:Customer")->findBy([], ['companyName' => 'ASC']);
  1489.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/change-team-customer-modal.html.twig", [
  1490.             'claim' => $claim,
  1491.             'customers' => $customers,
  1492.             'teams' => $teams
  1493.         ]);
  1494.     }
  1495.     /**
  1496.      * @Route("/main/resource/reassign/{id}")
  1497.      * @deprecated
  1498.      */
  1499.     public function reassignClaimResourceAction(Claim $claimRequest $request)
  1500.     {
  1501.         # Make sure valid claim object was passed
  1502.         if ($claim === null) {
  1503.             throw $this->createNotFoundException("Claim does not exist");
  1504.         }
  1505.         # Check Permissions
  1506.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1507.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1508.         $em $this->container->get("doctrine.orm.entity_manager");
  1509.         $resourceId intval($request->request->get("res_id"));
  1510.         $Resource = array();
  1511.         $claimResources = array();
  1512.         $claimResources $em->getRepository("ClaimManagementBundle:ClaimResource")->findBy(
  1513.             [ "claim" => $claim]
  1514.         );
  1515.         if($claim->getClaimTeam()){
  1516.             $teams $em->getRepository("ClaimManagementBundle:ClaimTeam")->find($claim->getClaimTeam()->getId());
  1517.         }else{
  1518.             $teams $em->getRepository("ClaimManagementBundle:ClaimTeam")->findAll();
  1519.         }
  1520.         $resourceTypes $em->getRepository("ResourceManagementBundle:ResourceType")->findAll();
  1521.         $assignmentParties $em->getRepository("AssignmentBundle:AssignmentParty")->findAll();
  1522.         $hasAdjusters $em->getRepository("ClaimManagementBundle:ClaimResource")->getAdjustersByClaim($claim);
  1523.         //$claimTeamRepo = $em->getRepository("ClaimManagementBundle:ClaimTeam");
  1524.         if (count($hasAdjusters) > 0)
  1525.             $hasAdjusters true;
  1526.         else
  1527.             $hasAdjusters false;
  1528.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/reassign-resource-modal.html.twig", [
  1529.             'claim' => $claim,
  1530.             'teams' => $teams,
  1531.             "hasAdjusters" => $hasAdjusters,
  1532.             'resourceTypes' => $resourceTypes,
  1533.             'assignmentParties' => $assignmentParties,
  1534.             'resourceId'=>$resourceId,
  1535.             "Resource" => $Resource,
  1536.             "claimResources" => $claimResources
  1537.         ]);
  1538.     }
  1539.     /**
  1540.      * @Route("/main/other-parties/add/{id}")
  1541.      */
  1542.     public function addClaimOtherPartiesAction(Claim $claim)
  1543.     {
  1544.         # Make sure valid claim object was passed
  1545.         if ($claim === null) {
  1546.             throw $this->createNotFoundException("Claim does not exist");
  1547.         }
  1548.         # Check Permissions
  1549.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1550.         # Get Other Parties Form Instance from Form Helper (will use without form tags)
  1551.         $em $this->container->get("doctrine.orm.entity_manager");
  1552.         $formFactory $this->container->get("form.factory");
  1553.         $otherPartyFormHelper = new OtherPartyFormHelper($em$formFactorytrue);
  1554.         $otherPartyForm $otherPartyFormHelper->getAddForm();
  1555.         $otherPartyTypes $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->findAll();
  1556.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-other-party-modal.html.twig", [
  1557.             "claim" => $claim,
  1558.             'other_party_form' => $otherPartyForm->createView(),
  1559.             "otherPartyTypes" => $otherPartyTypes
  1560.         ]);
  1561.     }
  1562.     /**
  1563.      * @Route("/main/insureds/add/{id}")
  1564.      */
  1565.     public function addClaimInsuredAction(Claim $claim)
  1566.     {
  1567.         # Make sure valid claim object was passed
  1568.         if ($claim === null) {
  1569.             throw $this->createNotFoundException("Claim does not exist");
  1570.         }
  1571.         # Check Permissions
  1572.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1573.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1574.         $em $this->container->get("doctrine.orm.entity_manager");
  1575.         $formFactory $this->container->get("form.factory");
  1576.         $InsuredFormHelper = new InsuredFormHelper($em$formFactorytrue);
  1577.         $insuredForm $InsuredFormHelper->getAddForm();
  1578.         $InsuredTypes $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->findAll();
  1579.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/add-insured-modal.html.twig", [
  1580.             "claim" => $claim,
  1581.             'insured_form' => $insuredForm->createView(),
  1582.             "insuredTypes" => $InsuredTypes
  1583.         ]);
  1584.     }
  1585.     /**
  1586.      * @Route("/main/insureds/update/{claimId}/{claimInsuredId}")
  1587.      */
  1588.     public function updateClaimInsuredAction($claimId$claimInsuredId)
  1589.     {
  1590.         $em $this->getDoctrine()->getManager();
  1591.         $claim $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
  1592.         # Make sure valid claim object was passed
  1593.         if ($claim === null) {
  1594.             throw $this->createNotFoundException("Claim does not exist");
  1595.         }
  1596.         # Check Permissions
  1597.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1598.         $claimInsured $em->getRepository("ClaimManagementBundle:ClaimsInsured")->find($claimInsuredId);
  1599.         # Get Insured Form Instance from Form Helper (will use without form tags)
  1600.         $formFactory $this->container->get("form.factory");
  1601.         $InsuredFormHelper = new InsuredFormHelper($em$formFactorytrue);
  1602.         $insuredForm $InsuredFormHelper->getEditForm($claimInsured->getInsured());
  1603.         $InsuredTypes $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->findAll();
  1604.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-insured-modal.html.twig", [
  1605.             "claim" => $claim,
  1606.             'insured_form' => $insuredForm->createView(),
  1607.             "insuredTypes" => $InsuredTypes,
  1608.             "claimInsuredId" => $claimInsuredId,
  1609.             "claimInsured" => $claimInsured //added to save minor dob
  1610.         ]);
  1611.     }
  1612.     /**
  1613.      * Modular Route that allows user to add/modify perils on claim,
  1614.      * by calling twig render function
  1615.      *
  1616.      * @Route("/main/perils/{id}")
  1617.      */
  1618.     public function showClaimPerilsAction(Claim $claim)
  1619.     {
  1620.         # Make sure valid claim object was passed
  1621.         if ($claim === null) {
  1622.             throw $this->createNotFoundException("Claim does not exist");
  1623.         }
  1624.         $em $this->container->get("doctrine.orm.entity_manager");
  1625.         $rootPeril null;
  1626.         $rootPerilId 0;
  1627.         if ($claim->getPeril()) {
  1628.            // $rootPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getPeril()->getId());
  1629.            // $rootPerilId = $rootPeril->getId();
  1630.             $rootPeril $claim->getPeril();
  1631.             $rootPerilId =$claim->getPeril()->getId();
  1632.         }
  1633.         $RootPerils $em->getRepository("ClaimManagementBundle:Peril")->getRootPerils();
  1634.         $subPeril null;
  1635.         $subPerilId 0;
  1636.         if ($claim->getSubPeril()) {
  1637.             //$subPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getSubPeril()->getId());
  1638.             //$subPerilId = $subPeril->getId();
  1639.             $subPeril $claim->getSubPeril();
  1640.             $subPerilId =$claim->getSubPeril()->getId();
  1641.         }
  1642.         $ChildrenPerils = array();
  1643.         if ($rootPeril !== null) {
  1644.             $ChildrenPerils $em->getRepository("ClaimManagementBundle:Peril")->getPerilChildren($rootPerilId);
  1645.         }
  1646.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/perils-widget.html.twig", [
  1647.             "claim" => $claim,
  1648.             "rootPerilId" => $rootPerilId,
  1649.             "rootPeril" => $rootPeril,
  1650.             "SubPerilId" => $subPerilId,
  1651.             "subPeril" => $subPeril,
  1652.             "RootPerils" => $RootPerils,
  1653.             "ChildrenPerils" => $ChildrenPerils,
  1654.         ]);
  1655.     }
  1656.     /**
  1657.      * Action to show Modal "Edit Perils" box,
  1658.      * to edit perils on claim
  1659.      *
  1660.      * @Route("/main/edit_peril/{id}")
  1661.      */
  1662.     public function showEditClaimPerilsAction(Claim $claim)
  1663.     {
  1664.         # Make sure valid claim object was passed
  1665.         if ($claim === null) {
  1666.             throw $this->createNotFoundException("Claim does not exist");
  1667.         }
  1668.         $em $this->container->get("doctrine.orm.entity_manager");
  1669.         # Check Permissions
  1670.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1671.         $rootPeril null;
  1672.         $rootPerilId 0;
  1673.         if ($claim->getPeril()) {
  1674.            // $rootPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getPeril()->getId());
  1675.             //$rootPerilId = $rootPeril->getId();
  1676.             $rootPeril $claim->getPeril();
  1677.             $rootPerilId =$claim->getPeril()->getId();
  1678.         }
  1679.         $RootPerils $em->getRepository("ClaimManagementBundle:Peril")->getRootPerils();
  1680.         $subPeril null;
  1681.         $subPerilId 0;
  1682.         if ($claim->getSubPeril()) {
  1683.             //$subPeril = $em->getRepository("ClaimManagementBundle:Peril")->find($claim->getSubPeril()->getId());
  1684.             //$subPerilId = $subPeril->getId();
  1685.             $subPeril $claim->getSubPeril();
  1686.             $subPerilId =$claim->getSubPeril()->getId();
  1687.         }
  1688.         $ChildrenPerils = array();
  1689.         if ($rootPeril !== null) {
  1690.             $ChildrenPerils $em->getRepository("ClaimManagementBundle:Peril")->getPerilChildren($rootPerilId);
  1691.         }
  1692.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit_perils_modal.html.twig", [
  1693.             "claim" => $claim,
  1694.             "rootPerilId" => $rootPerilId,
  1695.             "rootPeril" => $rootPeril,
  1696.             "SubPerilId" => $subPerilId,
  1697.             "subPeril" => $subPeril,
  1698.             "RootPerils" => $RootPerils,
  1699.             "ChildrenPerils" => $ChildrenPerils,
  1700.         ]);
  1701.     }
  1702.     /**
  1703.      * Action to save Edit Perils Action, coming
  1704.      * from Edit Perils Modal Box
  1705.      *
  1706.      * @Route("/main/save_edit_peril/{id}")
  1707.      * @Method(methods={"POST"})
  1708.      */
  1709.     public function saveEditPerilsAction(Claim $claimRequest $request)
  1710.     {
  1711.         # Make sure valid claim object was passed
  1712.         if ($claim === null) {
  1713.             throw $this->createNotFoundException("Claim does not exist");
  1714.         }
  1715.         # Check Permissions
  1716.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1717.         $em $this->container->get("doctrine.orm.entity_manager");
  1718.         # Check Permissions
  1719.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1720.         $peril $request->request->get("peril");
  1721.         if (intval($peril) == 0) {
  1722.             $response['error'] = true;
  1723.             $response['data']['errors'][] = [
  1724.                 'id' => "primary_loss_dropdown",
  1725.                 'text' => "You did not select a Loss Type."
  1726.             ];
  1727.             return new JsonResponse($response);
  1728.         }
  1729.         # Save the Perils to the Claim using the Peril Helper Class
  1730.         $ClaimNote $this->container->get("claim.note_provider");
  1731.         $perilHelper = new PerilHelper($em$ClaimNote$request);
  1732.         $perilHelper->saveClaimPerils($claim->getId());
  1733.         $response['error'] = false;
  1734.         $response['data'] = [];
  1735.         return new JsonResponse($response);
  1736.     }
  1737.     /**
  1738.      * Called by Perils Module Twig Route to request children peril
  1739.      * of a Peril
  1740.      *
  1741.      * @Route("/main/sub_perils/{parentPerilId}")
  1742.      */
  1743.     public function getSubPerilsAction($parentPerilId)
  1744.     {
  1745.         $em $this->container->get("doctrine.orm.entity_manager");
  1746.         $SubPerils $em->getRepository("ClaimManagementBundle:Peril")->getPerilChildren($parentPerilId);
  1747.         if (count($SubPerils) > 0) {
  1748.             $getSubPerils = array();
  1749.             foreach ($SubPerils as $getPeril) {
  1750.                 $eachPeril = [
  1751.                     "id" => $getPeril->getId(),
  1752.                     "description" => $getPeril->getDescription()
  1753.                 ];
  1754.                 $getSubPerils[] = $eachPeril;
  1755.             }
  1756.             return new JsonResponse([
  1757.                 "error" => false,
  1758.                 "data" => $getSubPerils
  1759.             ]);
  1760.         } else {
  1761.             return new JsonResponse([
  1762.                 "error" => true,
  1763.                 "data" => [],
  1764.                 "errors" => [
  1765.                     "No Sub Perils exist for this Parent Peril."
  1766.                 ]
  1767.             ]);
  1768.         }
  1769.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/perils-widget.html.twig", [
  1770.             "SubPerils" => $SubPerils
  1771.         ]);
  1772.     }
  1773.     /**
  1774.      * @Route("/main/insureds/search/{id}")
  1775.      */
  1776.     public function getClaimInsuredDataAjaxAction(Request $requestClaim $claim)
  1777.     {
  1778.         ## Use PaginatorService to return paginated results to DataTables Ajax Request
  1779.         if ($claim === null) {
  1780.             throw $this->createNotFoundException("Claim does not exist");
  1781.         }
  1782.         $em $this->container->get("doctrine.orm.entity_manager");
  1783.         $claimId $claim->getId();
  1784.         # Array of columns that will be sorted
  1785.         $columnsArr = array(
  1786.             "insuredName",
  1787.             "insuredEmail",
  1788.             "insured_type",
  1789.             "is_primary",
  1790.             "stateCode"
  1791.         );
  1792.         # Build Query and PDO Parameters that will be passed to PaginatorService class
  1793.         $dataParams = array();
  1794.         $sql "SELECT
  1795.                 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
  1796.                 FROM claims_insured ci
  1797.                 INNER JOIN insured i
  1798.                   ON ci.insured_id = i.id
  1799.                 INNER JOIN claim_insured_types cit
  1800.                   ON ci.claim_insured_type_id = cit.id
  1801.                 LEFT JOIN state s
  1802.                   ON i.state_id = s.id
  1803.                 WHERE 1 = 1 ";
  1804.         # Search By Claim ID
  1805.         if ($claimId 0) {
  1806.             $sql .= "AND ci.claim_id = :claimId ";
  1807.             $dataParams['claimId'] = $claimId;
  1808.         }
  1809.         # build keyword filter, which is requested by datatables ajax when someone types into keyword field
  1810.         //$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) ";
  1811.         # call PaginatorService
  1812.         $paginator $this->container->get("resource.paginator_service");
  1813.         $retVal $paginator->getPaginationResults($request$sql$dataParams"ci.id ASC"$columnsArr"search_keyword""""keyword""");
  1814.         return new JsonResponse($retVal);
  1815.     }
  1816.     /**
  1817.      * Load Claims Insured Record
  1818.      *
  1819.      * @Route("/main/claims_insureds/{id}")
  1820.      */
  1821.     public function loadClaimInsured(ClaimsInsured $ClaimInsured)
  1822.     {
  1823.         $em $this->getDoctrine();
  1824.         if ($ClaimInsured === null) {
  1825.             $this->createNotFoundException("Claims Insured record does not exist");
  1826.         }
  1827.         $Insured $ClaimInsured->getInsured();
  1828.         if ($Insured === null) {
  1829.             $this->createNotFoundException("Insured entity does not exist on Claims Insured");
  1830.         }
  1831.         # Return loaded ClaimsInsured Entity as Json
  1832.         /*/
  1833.         $encoders = array(new XmlEncoder(), new JsonEncoder());
  1834.         $normalizers = array(new ObjectNormalizer());
  1835.         $serializer = new Serializer($normalizers, $encoders);
  1836.         $insured_object = $serializer->serialize($Insured, 'json');
  1837.         //*/
  1838.         $sql "SELECT * FROM insured WHERE id = :id ";
  1839.         $stmt $em->getConnection()->prepare($sql);
  1840.         $stmt->execute([
  1841.             "id"=>$ClaimInsured->getClaim()->getId()
  1842.         ]);
  1843.         $insuredResults $stmt->fetchAll(\PDO::FETCH_ASSOC);
  1844.         echo "<pre>";print_r($insuredResults);die;
  1845.         if (count($insuredResults) > 0){
  1846.             $insured $insuredResults[0];
  1847.         }
  1848.         $claimInsuredType $ClaimInsured->getClaimInsuredType();
  1849.         $insuredTypeId $claimInsuredType->getId();
  1850.         $minor_bday "";
  1851.         if ($ClaimInsured->getMinorBday()) {
  1852.             $minor_bday $ClaimInsured->getMinorBday()->format("Y-m-d");
  1853.         }
  1854.         $insuredTypes $em->getRepository('ClaimManagementBundle:ClaimInsuredType')->findAll();
  1855.         $retVal = [
  1856.             "insured" => $insured,
  1857.             "minor_bday" => $minor_bday,
  1858.             "isPrimary" => ($ClaimInsured->getIsPrimary() === true) ? "1" "0",
  1859.             "insuredTypeId" => $insuredTypeId
  1860.         ];
  1861.         return new JsonResponse($retVal);
  1862.     }
  1863.     /**
  1864.      * @Route("/main/insured/save_add/{id}")
  1865.      */
  1866.     public function saveClaimInsuredAction(Request $requestClaim $claim)
  1867.     {
  1868.         # Make sure valid claim object was passed
  1869.         if ($claim === null) {
  1870.             throw $this->createNotFoundException("Claim does not exist");
  1871.         }
  1872.         $em $this->container->get("doctrine.orm.entity_manager");
  1873.         $user $this->getUser();
  1874.         # Check Permissions
  1875.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  1876.         $minorInvolved = ($request->request->get('minorInvolved') == "1") ? true false//Added to save minor dob
  1877.         $minor_dob $request->request->get('minor_dob');//Added to save minor dob
  1878.         # Check CSRF Token
  1879.         $submittedToken $request->request->get("_csrf_token");
  1880.         if (!($user instanceof Resource)) {  // if invalid user
  1881.             # Send back error
  1882.             $data = [
  1883.                 "errors" => array()
  1884.             ];
  1885.             $nextError = array();
  1886.             $nextError['id'] = "";
  1887.             $nextError['text'] = "You do not have permission to submit this form.";
  1888.             $data['errors'][] = $nextError;
  1889.             $retVal = array(
  1890.                 "result" => "fail",
  1891.                 "error_msgs" => array(),
  1892.                 "error" => true,
  1893.                 "data" => $data
  1894.             );
  1895.             return new JsonResponse($retVal);
  1896.         }
  1897.         $em $this->container->get("doctrine.orm.entity_manager");
  1898.         $formFactory $this->container->get("form.factory");
  1899.         $InsuredFormHelper = new InsuredFormHelper($em$formFactorytrue);
  1900.         $insuredForm $InsuredFormHelper->getAddForm();
  1901.         $formSubmission $request->request->get('form');
  1902.         # Manually submit form
  1903.         $insuredForm->submit($formSubmission);
  1904.         # Get Form Fields
  1905.         $insuredTypeId $request->request->get("insuredType");
  1906.         $isPrimary intval($request->request->get("isPrimary"));
  1907.         $HasPrimary $em->getRepository("ClaimManagementBundle:ClaimsInsured")->findOneBy([
  1908.             "claim" => $claim,
  1909.             "isPrimary" => true
  1910.         ]);
  1911.         if (!$HasPrimary) {
  1912.             $isPrimary 1;
  1913.         }
  1914.         $claimInsuredType $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->find($insuredTypeId);
  1915.         $Insured $insuredForm->getData();
  1916.         # Validate Entity set from Request
  1917.         $errors $this->get("validator")->validate($Insured);
  1918.         //added code to save county
  1919.         if(!empty($formSubmission["county"])) {
  1920.             $county $em->getRepository("ResourceManagementBundle:Counties")->findOneById($formSubmission["county"]);
  1921.             if(!empty($county)) {
  1922.                 $Insured->setCounty($county);
  1923.             }
  1924.         }
  1925.         $data = array();
  1926.         $errors2 = array();
  1927.         if (count($errors) == 0) {  // if form is valid
  1928.             //Added to save minor dob
  1929.             if ($minorInvolved == 1) {
  1930.                 if ($minor_dob == "") {
  1931.                     $retVal = array();
  1932.                     $retVal['error'] = true;
  1933.                     $retVal['data'] = array();
  1934.                     $errorsArr = [
  1935.                         "id" => "minor_dob",
  1936.                         "text" => "Minor Date of Birth is required."
  1937.                     ];
  1938.                     $retVal['data']['errors'][] = $errorsArr;
  1939.                     return new JsonResponse($retVal);
  1940.                 }
  1941.             }
  1942.             # Persist Document
  1943.             $em->persist($Insured);
  1944.    
  1945.             # Create ClaimsInsured Record
  1946.             $ClaimsInsureds = new ClaimsInsured();
  1947.             $ClaimsInsureds->setClaim($claim);
  1948.             $ClaimsInsureds->setInsured($Insured);
  1949.             //Added to save minor dob
  1950.             $ClaimsInsureds->setMinorInvolved($minorInvolved);
  1951.             if ($minorInvolved === true) {
  1952.                 $ClaimsInsureds->setMinorDOB(new \DateTime($minor_dob));
  1953.             }
  1954.             # Set Insured Type
  1955.             if ($claimInsuredType) {
  1956.                 $ClaimsInsureds->setClaimInsuredType($claimInsuredType);
  1957.             }
  1958.             $em->persist($ClaimsInsureds);
  1959.             # Persist to DB
  1960.             $em->flush();
  1961.             $claimInsured $claim->getClaimsInsureds();
  1962.             if (count($claimInsured) == 1) {
  1963.                 $isPrimary true;
  1964.             }
  1965.             if ($isPrimary === true) {  // if need to set to primary
  1966.                 # Use Claim Insured Helper to set this claimInsured record to primary, and all others on claim to isPrimary = false
  1967.                 $claimsInsuredHelper = new ClaimsInsuredHelper($em);
  1968.                 $claimsInsuredHelper->makeClaimInsuredPrimary($ClaimsInsureds$claim);
  1969.             }
  1970.             # Log adding Claim Insured using Monolog
  1971.             $logger $this->get('monolog.logger.claims_log');
  1972.             $logger->info('Claim Insured Created - Claim Insured ID: ' $ClaimsInsureds->getId() . ", for Insured ID: " $Insured->getId() . ", on Claim ID: " $claim->getId());
  1973.             $comment 'Claim Insured Created - Claim Insured ID: ' $ClaimsInsureds->getId() . ", for Insured ID: " $Insured->getId() . ", on Claim ID: " $claim->getId();
  1974.             $userNoteLog $this->container->get("app.resource_note_logger");
  1975.             $user $this->container->get("security.token_storage")->getToken()->getUser();
  1976.             $resource $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
  1977.             $userNoteLog->logNote($comment$resource,10,$claim);
  1978.             /**
  1979.              * @date 8/11/2017
  1980.              *
  1981.              * Added a Claim Note here to denote that an INSURED (CLAIMANT) was added to our Claim here.
  1982.              *
  1983.              */
  1984.             $ClaimNotes $this->get('claim.note_provider');
  1985.             //Status note = 65 Claimant
  1986.             $ClaimNotes->addClaimNote$ClaimsInsureds->getClaim(), "Claimant added to claim! First name: ".$ClaimsInsureds->getInsured()->getFirstName(), false65);
  1987.             $retVal = array(
  1988.                 "status" => "success",
  1989.                 "error_msgs" => []
  1990.             );
  1991.             return new JsonResponse($retVal);
  1992.         } else {  // if form not valid
  1993.             # Send back errors to client
  1994.             $data = array();
  1995.             $errors2 = array();
  1996.             $errors $this->get("validator")->validate($Insured);
  1997.             if (count($errors) > 0) {
  1998.                 $data = [
  1999.                     "errors" => array()
  2000.                 ];
  2001.                 foreach ($errors as $error) {
  2002.                     $nextError = array();
  2003.                     $nextError['id'] = $error->getPropertyPath();
  2004.                     $nextError['text'] = $error->getMessage();
  2005.                     $data['errors'][] = $nextError;
  2006.                 }
  2007.             }
  2008.             $retVal = array(
  2009.                 "result" => "fail",
  2010.                 "error_msgs" => $errors2,
  2011.                 "error" => true,
  2012.                 "data" => $data
  2013.             );
  2014.             return new JsonResponse($retVal);
  2015.         }
  2016.     }
  2017.     /**
  2018.      * @Route("/main/team_cust/save/{id}")
  2019.      */
  2020.     public function saveTeamCustChanges(Claim $claimRequest $request)
  2021.     {
  2022.         $em $this->getDoctrine()->getManager();
  2023.         $claimTeamManager $this->get('claimteam.manager');
  2024.         $formSubmission $request->request->get('teamCustForm');
  2025.         # Make sure valid claim object was passed
  2026.         if ($claim === null) {
  2027.             throw $this->createNotFoundException("Claim does not exist");
  2028.         }
  2029.         $customer $claim->getCustomer();
  2030.         $customerSubmitted $formSubmission['customer'];
  2031.         $claimTeamSubmitted $formSubmission['claimTeam'];
  2032.         $response = [];
  2033.         $ResourceInTeam=[];
  2034.         $OldTeam='';
  2035.         $NewTeam='';
  2036.         /**
  2037.          * Change Customer Validations
  2038.          */
  2039.         # Don't change customer on XACT or Symbility claims
  2040.         /*if ($claim->getTransactionId()) {
  2041.             if ($claim->failsChangeCustomerValidation($customer, $formSubmission)) {
  2042.                 $response['error'] = "You can not change the customer of this claim!";
  2043.             }
  2044.         } else {*/
  2045.             # dont throw error but throw alert message for user
  2046.             if ($customer->getId() != $customerSubmitted) {
  2047.                 $response['alert'] = [
  2048.                     'title' => "Internal Rep Removed",
  2049.                     'content' => "Customer has been changed, removing internal rep"
  2050.                 ];
  2051.                 $newCustomer $em->getRepository('CustomerManagementBundle:Customer')->find($customerSubmitted);
  2052.                 $claim->removeClaimRep();
  2053.                 $claim->setCustomer($newCustomer);
  2054.                 $em->persist($claim);
  2055.                 $em->flush();
  2056.             }
  2057.         //}
  2058.         # Save Claim Team
  2059.         if ($claim->getClaimTeam() != $claimTeamSubmitted) {
  2060.             $newClaimTeam $em->getRepository('ClaimManagementBundle:ClaimTeam')->find($claimTeamSubmitted);
  2061.             $NewTeam=$newClaimTeam->getName();
  2062.             // added for error handling null
  2063.             if ($claim->getClaimTeam() === null) {
  2064.             }else{
  2065.                 $OldTeam=$claim->getClaimTeam()->getName();
  2066.             }
  2067.             // added for error handling null
  2068.             $claim->setClaimTeam($newClaimTeam);
  2069.             $em->persist($claim);
  2070.             $em->flush();
  2071.         }
  2072.         /**
  2073.          * Change ClaimTeam Validations
  2074.          */
  2075.         $claimResources $claim->getResources();
  2076.         $claimTeam $em->getRepository('ClaimManagementBundle:ClaimTeam')->find($claimTeamSubmitted);
  2077.         # loop through our resources on the claim
  2078.         foreach($claimResources as $claimResource) {
  2079.             $adjuster $claimResource->getResource();
  2080.             # Assign the resource to the team if he is not on the team
  2081.             $clamTeamResources $em->getRepository("ClaimManagementBundle:ClaimTeamResource")
  2082.                 ->findBy(['claimTeam' => $claimTeam,'resource' => $adjuster]);
  2083.             if(empty($clamTeamResources)){
  2084.                 $claimTeamManager->addResourceToClaimTeam($adjuster,$claimTeam);
  2085.             }
  2086.             $OldAdjuster $em->find("ResourceManagementBundle:Resource"intval($adjuster->getId()));
  2087.             $ResourceInTeam[]=$OldAdjuster;
  2088.         }
  2089.         if ($claim->getClaimTeam() != $claimTeamSubmitted) {
  2090.             # First to Call Un-assigned event
  2091.             $dispatcher $this->get('event_dispatcher');
  2092.             $dispatcher->dispatch(new ChangeTeamEvent($claim$ResourceInTeam,$OldTeam,false), ChangeTeamEvent::NAME);
  2093.             #second to call assign event
  2094.             $dispatcher->dispatch(new ChangeTeamEvent($claim$ResourceInTeam,$NewTeam,true), ChangeTeamEvent::NAME);
  2095.         }
  2096.         return new JsonResponse($response);
  2097.     }
  2098.     /**
  2099.      * @Route("/main/insured/save_update/{claimId}/{claimInsuredId}")
  2100.      */
  2101.     public function saveUpdateClaimInsuredAction(Request $request$claimId$claimInsuredId)
  2102.     {
  2103.         $em $this->container->get("doctrine.orm.entity_manager");
  2104.         $claim $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
  2105.         $ClaimsInsureds $em->getRepository("ClaimManagementBundle:ClaimsInsured")->find($claimInsuredId);
  2106.         # Check Permissions
  2107.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  2108.         $minorInvolved = ($request->request->get('minorInvolved') == "1") ? true false//Added to save minor dob
  2109.         $minor_dob $request->request->get('minor_dob');//Added to save minor dob
  2110.         # Make sure valid claim object was passed
  2111.         if ($claim === null) {
  2112.             throw $this->createNotFoundException("Claim does not exist");
  2113.         }
  2114.         # Make sure valid Claims Insured Record exists
  2115.         if ($ClaimsInsureds === null) {
  2116.             throw $this->createNotFoundException("Claims Insured Record does not exist");
  2117.         }
  2118.         # Make sure Insured Record exists
  2119.         $Insured $ClaimsInsureds->getInsured();
  2120.         if ($Insured === null) {
  2121.             throw $this->createNotFoundException("Claim does not have insured record");
  2122.         }
  2123.         # Check CSRF Token
  2124.         $submittedToken $request->request->get("_csrf_token");
  2125.         // if (!$this->isCsrfTokenValid('edit_claim_insured', $submittedToken)) {  // if invalid csrf token
  2126.         if (!($this->getUser() instanceof Resource)) {
  2127.             # Send back error
  2128.             $data = [
  2129.                 "errors" => array()
  2130.             ];
  2131.             $nextError = array();
  2132.             $nextError['id'] = "";
  2133.             $nextError['text'] = "You do not have permission to submit this form.";
  2134.             $data['errors'][] = $nextError;
  2135.             $retVal = array(
  2136.                 "result" => "fail",
  2137.                 "error_msgs" => array(),
  2138.                 "error" => true,
  2139.                 "data" => $data
  2140.             );
  2141.             return new JsonResponse($retVal);
  2142.         }
  2143.         $em $this->container->get("doctrine.orm.entity_manager");
  2144.         $formFactory $this->container->get("form.factory");
  2145.         $InsuredFormHelper = new InsuredFormHelper($em$formFactorytrue);
  2146.         $insuredForm $InsuredFormHelper->getEditForm($Insured);
  2147.         # Get Form Fields
  2148.         $formSubmission $request->request->get('form');
  2149.         # Manually submit form
  2150.         $insuredForm->submit($formSubmission);
  2151.         $insuredTypeId $request->request->get("insuredType");
  2152.         $isPrimary intval($request->request->get("isPrimary"));
  2153.         $claimInsuredType $em->getRepository("ClaimManagementBundle:ClaimInsuredType")->find($insuredTypeId);
  2154.         $Insured $insuredForm->getData();
  2155.         $Insured2 $Insured;
  2156.         ## Code checks if changes were made to Insured Object ##
  2157.         # Get Current Resource on DB
  2158.         $insured_compare = new InsuredCompareHelper($em);
  2159.         $insured_compare->setCurInsured($Insured2);
  2160.         $ClaimInsured $em->getRepository("ClaimManagementBundle:ClaimsInsured")->loadByClaimAndInsured($claim$Insured);
  2161.         if ($claimInsuredType) {
  2162.             $ClaimInsured->setClaimInsuredType($claimInsuredType);
  2163.         }
  2164.         ###
  2165.         # Deal with setting Claim Insured Type, Minor Birthday, verifying if these fields have changed on this update
  2166.         # Do some checking to check if Claim Insured Type Changed
  2167.         //*/
  2168.         $claimInsuredChanged false;
  2169.         $insuredTypeChanged false;
  2170.         $ClaimInsuredHelper = new ClaimInsuredChangesHelper($em);
  2171.         $changedInsuredType $ClaimInsuredHelper->insuredTypeDidChange($claim$Insured$claimInsuredType);
  2172.         $claimInsuredChanged $ClaimInsuredHelper->minorBDayDidChange($ClaimsInsureds$minor_dob); //Added to save the minor involved and minor dob change
  2173.         if ($changedInsuredType != "") {
  2174.             $insuredTypeChanged true;
  2175.         }
  2176.         //added code to save county
  2177.         if(!empty($formSubmission["county"])) {
  2178.             $county $em->getRepository("ResourceManagementBundle:Counties")->findOneById($formSubmission["county"]);
  2179.             if(!empty($county)) {
  2180.                 $Insured->setCounty($county);
  2181.             }
  2182.         }
  2183.         #
  2184.         ###
  2185.         # Set Claim Insured Type
  2186.         # Validate Entity set from Request
  2187.         $errors $this->get("validator")->validate($Insured);
  2188.         $data = array();
  2189.         $errors2 = array();
  2190.         if (count($errors) == 0) {  // if form is valid
  2191.             //Added to save the minor involved and minor dob change
  2192.             if ($minorInvolved == 1) {
  2193.                if ($minor_dob == "") {
  2194.                     $retVal = array();
  2195.                     $retVal['error'] = true;
  2196.                     $retVal['data'] = array();
  2197.                     $errorsArr = [
  2198.                         "id" => "minor_dob",
  2199.                         "text" => "Minor Date of Birth is required."
  2200.                     ];
  2201.                     $retVal['data']['errors'][] = $errorsArr;
  2202.                     return new JsonResponse($retVal);
  2203.                 }
  2204.                 $ClaimInsured->setMinorInvolved($minorInvolved);
  2205.                 $ClaimInsured->setMinorDOB(new \DateTime($minor_dob));
  2206.             }
  2207.             else{
  2208.                 $ClaimInsured->setMinorInvolved($minorInvolved);
  2209.                 $ClaimInsured->setMinorDOB(null);
  2210.             }
  2211.             # Compare 2 objects to see if there were any changes made
  2212.             $insured_compare->setNewInsured($Insured);
  2213.             $hasChanges $insured_compare->compareObjects();
  2214.             # Persist Document
  2215.             $em->persist($Insured);
  2216.             $em->persist($ClaimInsured);
  2217.             $em->flush();
  2218.             if ($hasChanges || $claimInsuredChanged) {  // check if whether Insured Entity or Claim Insured Entity was changed
  2219.                 $getChanges = array();
  2220.                 if ($hasChanges) {
  2221.                     $changeLog $insured_compare->changeLog;
  2222.                     $getChanges2 array_merge($getChanges$changeLog);
  2223.                 } else {
  2224.                     $getChanges2 $getChanges;
  2225.                 }
  2226.                 $ClaimNote $this->container->get("claim.note_provider");
  2227.                 $ClaimNote->addClaimNote($claim"Claim Insured was updated. " implode(" "$getChanges2), false52);
  2228.             }
  2229.             if ($isPrimary === 1) {  // if set to primary
  2230.                 # Use Claim Insured Helper to set this claimInsured record to primary, and all others on claim to isPrimary = false
  2231.                 $claimsInsuredHelper = new ClaimsInsuredHelper($em);
  2232.                 $claimsInsuredHelper->makeClaimInsuredPrimary($ClaimInsured$claim);
  2233.             }
  2234.             # Log updating Claim Insured using Monolog
  2235.             $logger $this->get('monolog.logger.claims_log');
  2236.             $logger->info("Claim Insured Updated - Insured ID: " $Insured->getId() . ", with ClaimInsuredID: " $ClaimInsured->getId() . ", on Claim ID: " $claim->getId());
  2237.             $comment 'Claim Insured Updated - Claim Insured ID: ' $Insured->getId() . ",  with ClaimInsuredID: " $ClaimInsured->getId() . ", on Claim ID: " $claim->getId();
  2238.             $userNoteLog $this->container->get("app.resource_note_logger");
  2239.             $user $this->container->get("security.token_storage")->getToken()->getUser();
  2240.             $resource $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
  2241.             $userNoteLog->logNote($comment$resource,10,$claim);
  2242.             $ClaimNotes $this->get('claim.note_provider');
  2243.             $ClaimNotes->addClaimNote$ClaimsInsureds->getClaim(), "Insured edited! First name: "$Insured->getFirstName() , false52);
  2244.             $retVal = array(
  2245.                 "status" => "success",
  2246.                 "error_msgs" => []
  2247.             );
  2248.             return new JsonResponse($retVal);
  2249.         } else {  // if form not valid
  2250.             # Send back errors to client
  2251.             $data = array();
  2252.             $errors2 = array();
  2253.             $errors $this->get("validator")->validate($Insured);
  2254.             if (count($errors) > 0) {
  2255.                 $data = [
  2256.                     "errors" => array()
  2257.                 ];
  2258.                 foreach ($errors as $error) {
  2259.                     $nextError = array();
  2260.                     $nextError['id'] = $error->getPropertyPath();
  2261.                     $nextError['text'] = $error->getMessage();
  2262.                     $data['errors'][] = $nextError;
  2263.                 }
  2264.             }
  2265.             $retVal = array(
  2266.                 "result" => "fail",
  2267.                 "error_msgs" => $errors2,
  2268.                 "error" => true,
  2269.                 "data" => $data
  2270.             );
  2271.             return new JsonResponse($retVal);
  2272.         }
  2273.     }
  2274.     /**
  2275.      * @Route("/main/insured/delete")
  2276.      * @Method(methods={"POST"})
  2277.      */
  2278.     public function deleteClaimInsuredAction(Request $request)
  2279.     {
  2280.         $em $this->container->get("doctrine.orm.entity_manager");
  2281.         # Request ID to delete
  2282.         $id intval($request->request->get("id"));
  2283.         # Delete Certificate
  2284.         $ClaimsInsured $em->getRepository("ClaimManagementBundle:ClaimsInsured")->find($id);
  2285.         if ($ClaimsInsured->getIsPrimary()) {
  2286.             $retVal = [
  2287.                 'error' => true,
  2288.                 'error_msgs' => ["You cannot remove the Primary Insured."]
  2289.             ];
  2290.             return new JsonResponse($retVal);
  2291.         }
  2292.         # Get claim, claim insured objects while they exist
  2293.         $insured $ClaimsInsured->getInsured();
  2294.         $insuredId $insured->getId();
  2295.         $claim $ClaimsInsured->getClaim();
  2296.         $claimId $claim->getId();
  2297.         # Check Permissions
  2298.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  2299.         $em->remove($ClaimsInsured->getInsured());
  2300.         $em->remove($ClaimsInsured);
  2301.         $em->flush();
  2302.         # Get all claim insureds after removing one of them
  2303.         $claimInsured $claim->getClaimsInsureds();
  2304.         if (count($claimInsured) == 1) {  // if there is only one insured on the claim
  2305.             # Make that insured primary
  2306.             $getClaimInsured $claimInsured[0];
  2307.             $claimsInsuredHelper = new ClaimsInsuredHelper($em);
  2308.             $claim $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
  2309.             $claimsInsuredHelper->makeClaimInsuredPrimary($getClaimInsured$claim);
  2310.         }
  2311.         # Log deleting Claim Insured using Monolog
  2312.         $logger $this->get('monolog.logger.claims_log');
  2313.         $logger->info("Claim Insured Deleted - Insured ID: " $insuredId ", with ClaimInsuredID: " $id ", on Claim ID: " $claimId);
  2314.         $comment =  "Claim Insured Deleted - Insured ID: " $insuredId ", with ClaimInsuredID: " $id ", on Claim ID: " $claimId;
  2315.         $userNoteLog $this->container->get("app.resource_note_logger");
  2316.         $user $this->container->get("security.token_storage")->getToken()->getUser();
  2317.         $resource $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
  2318.         $userNoteLog->logNote($comment$resource,10,$claim);
  2319.         /*$retVal = array(
  2320.             "status" => "success",
  2321.             "error_msgs" => []
  2322.         );*/
  2323.         $retVal = [
  2324.             'error' => false,
  2325.             'error_msgs' => []
  2326.         ];
  2327.         return new JsonResponse($retVal);
  2328.     }
  2329.     /**
  2330.      * @Route("/main/resource/save_add/{id}")
  2331.      */
  2332.     public function saveClaimResourceAction(Request $request$id)
  2333.     {
  2334.         // entity manager
  2335.         $em $this->container->get("doctrine.orm.entity_manager");
  2336.         // Default response
  2337.         $response = [
  2338.             'error' => false
  2339.         ];
  2340.         return new JsonResponse($response);
  2341.     }
  2342.     /**
  2343.      * @Route("/main/claim_limit/save_add/{id}")
  2344.      */
  2345.     public function saveClaimLimitAction(Request $request$id)
  2346.     {
  2347.         // entity manager
  2348.         $em $this->container->get("doctrine.orm.entity_manager");
  2349.         $Claim $em->getRepository("ClaimManagementBundle:Claim")->find($id);
  2350.         if ($Claim === null) {
  2351.             return new NotFoundHttpException("Claim does not exist");
  2352.         }
  2353.         # Check Permissions
  2354.         $this->denyAccessUnlessGranted("edit_claim_tab"$Claim);
  2355.         // Default response
  2356.         $response = [
  2357.             'error' => false
  2358.         ];
  2359.         $formFactory $this->container->get("form.factory");
  2360.         $ClaimLimitFormHelper = new ClaimLimitFormHelper($em$formFactoryfalse);
  2361.         $form $ClaimLimitFormHelper->getAddForm();
  2362.         # Handle request
  2363.         $form->handleRequest($request);
  2364.         $ClaimLimit $form->getData();
  2365.         if ($form->isValid()) {  // if form is valid
  2366.             //test for duplicate
  2367.             $sql "SELECT COUNT(*) as claim_count
  2368.                     FROM claim_limit
  2369.                     WHERE claim_id = :claim_id
  2370.                     AND claim_limit_type_id =:claim_limit_type_id";
  2371.             $claimLimitType $ClaimLimit->getClaimLimitType();
  2372.             $stmt $em->getConnection()->prepare($sql);
  2373.             $stmt->execute([
  2374.                 "claim_limit_type_id" => $claimLimitType->getId(),
  2375.                 'claim_id' => $Claim->getId()
  2376.             ]);
  2377.             $claim_count $stmt->fetchAll( \PDO::FETCH_ASSOC );
  2378.             if( $claim_count[0]['claim_count'] > ){
  2379.                 $retVal = array(
  2380.                     "error" => true,
  2381.                     'msg' => 'Claim limit "'.$claimLimitType->getName().'"" has already been set'
  2382.                 );
  2383.                 return new JsonResponse($retVal);
  2384.             }
  2385.             $ClaimLimit->setClaim($Claim);
  2386.             $em->persist($ClaimLimit);
  2387.             $em->flush();
  2388.             # Return JSON Errors Object
  2389.             $retVal = array(
  2390.                 "error" => false
  2391.             );
  2392.             return new JsonResponse($retVal);
  2393.         }else{
  2394.             $data = array();
  2395.             $errors2 = array();
  2396.             # Get Validation Error Messages
  2397.             $errors $this->get("validator")->validate($ClaimLimit);
  2398.             if (count($errors) > 0) {
  2399.                 $data = [
  2400.                     "errors" => array()
  2401.                 ];
  2402.                 foreach ($errors as $error) {
  2403.                     $nextError = array();
  2404.                     $nextError['id'] = $error->getPropertyPath();
  2405.                     $nextError['text'] = $error->getMessage();
  2406.                     $data['errors'][] = $nextError;
  2407.                 }
  2408.             }
  2409.             # Return JSON Errors Object
  2410.             $retVal = array(
  2411.                 "result" => "fail",
  2412.                 "error_msgs" => $errors2,
  2413.                 "error" => true,
  2414.                 "data" => $data
  2415.             );
  2416.             return new JsonResponse($retVal);
  2417.         }
  2418.         return new JsonResponse($response);
  2419.     }
  2420.     /**
  2421.      * @Route("/main/deductible/save_add/{id}")
  2422.      */
  2423.     public function saveClaimDeductibleAction(Request $request$id)
  2424.     {
  2425.         // entity manager
  2426.         $em $this->container->get("doctrine.orm.entity_manager");
  2427.         $Claim $em->getRepository("ClaimManagementBundle:Claim")->find($id);
  2428.         if ($Claim === null) {
  2429.             return new NotFoundHttpException("Claim does not exist");
  2430.         }
  2431.         # Check Permissions
  2432.         $this->denyAccessUnlessGranted("edit_claim_tab"$Claim);
  2433.         // Default response
  2434.         $response = [
  2435.             'error' => false
  2436.         ];
  2437.         $formFactory $this->container->get("form.factory");
  2438.         $DeductibleFormHelper = new DeductibleFormHelper($em$formFactoryfalse);
  2439.         $form $DeductibleFormHelper->getAddForm();
  2440.         # Handle request
  2441.         $form->handleRequest($request);
  2442.         $Deductible $form->getData();
  2443.         if ($form->isValid()) {  // if form is valid
  2444.             $Deductible->setClaim($Claim);
  2445.             $deductibleName $Deductible->getDeductibleName();
  2446.             //test for duplicate
  2447.             $sql "SELECT COUNT(*) as deductible_count
  2448.                     FROM deductible
  2449.                     WHERE claim_id = :claim_id
  2450.                     AND deductible_name_id = :deductible_name_id";
  2451.             $stmt $em->getConnection()->prepare($sql);
  2452.             $stmt->execute([
  2453.                 "deductible_name_id" => $deductibleName->getId(),
  2454.                 'claim_id' => $Claim->getId()
  2455.             ]);
  2456.             $deductible_count $stmt->fetchAll( \PDO::FETCH_ASSOC );
  2457.             if( $deductible_count[0]['deductible_count'] > ){
  2458.                 $retVal = array(
  2459.                     "error" => true,
  2460.                     'msg' => 'Claim limit "'.$deductibleName->getName().'"" has already been set'
  2461.                 );
  2462.                 return new JsonResponse($retVal);
  2463.             }
  2464.             $em->persist($Deductible);
  2465.             $em->flush();
  2466.             # Return JSON Errors Object
  2467.             $retVal = array(
  2468.                 "error" => false,
  2469.             );
  2470.             return new JsonResponse($retVal);
  2471.         }else{
  2472.             $data = array();
  2473.             $errors2 = array();
  2474.             # Get Validation Error Messages
  2475.             $errors $this->get("validator")->validate($Deductible);
  2476.             if (count($errors) > 0) {
  2477.                 $data = [
  2478.                     "errors" => array()
  2479.                 ];
  2480.                 foreach ($errors as $error) {
  2481.                     $nextError = array();
  2482.                     $nextError['id'] = $error->getPropertyPath();
  2483.                     $nextError['text'] = $error->getMessage();
  2484.                     $data['errors'][] = $nextError;
  2485.                 }
  2486.             }
  2487.             # Return JSON Errors Object
  2488.             $retVal = array(
  2489.                 "result" => "fail",
  2490.                 "error_msgs" => $errors2,
  2491.                 "error" => true,
  2492.                 "data" => $data
  2493.             );
  2494.             return new JsonResponse($retVal);
  2495.         }
  2496.         return new JsonResponse($response);
  2497.     }
  2498.     /**
  2499.      * @Route("/main/claim_limit/save_edit/{id}")
  2500.      */
  2501.     public function saveEditClaimLimitAction(Request $request$id)
  2502.     {
  2503.         // entity manager
  2504.         $em $this->container->get("doctrine.orm.entity_manager");
  2505.         $Claim $em->getRepository("ClaimManagementBundle:Claim")->find($id);
  2506.         if ($Claim === null) {
  2507.             return new NotFoundHttpException("Claim does not exist");
  2508.         }
  2509.         # Check Permissions
  2510.         $this->denyAccessUnlessGranted("edit_claim_tab"$Claim);
  2511.         // Default response
  2512.         $response = [
  2513.             'error' => false
  2514.         ];
  2515.         $claim_limit_id $request->request->get("claim_limit_id");
  2516.         $ClaimLimit $em->getRepository("ClaimManagementBundle:ClaimLimit")->find($claim_limit_id);
  2517.         $formFactory $this->container->get("form.factory");
  2518.         $ClaimLimitFormHelper = new ClaimLimitFormHelper($em$formFactoryfalse);
  2519.         $form $ClaimLimitFormHelper->getEditForm($ClaimLimit);
  2520.         # Handle request
  2521.         $form->handleRequest($request);
  2522.         /** @var ClaimLimit $ClaimLimit */
  2523.         $ClaimLimit $form->getData();
  2524.         if ($form->isValid()) {  // if form is valid
  2525.             $ClaimLimit->setClaim($Claim);
  2526.             $em->persist($ClaimLimit);
  2527.             $em->flush();
  2528.             # Return JSON Errors Object
  2529.             $retVal = array(
  2530.                 "error" => false,
  2531.             );
  2532.             return new JsonResponse($retVal);
  2533.         }else{
  2534.             $data = array();
  2535.             $errors2 = array();
  2536.             # Get Validation Error Messages
  2537.             $errors $this->get("validator")->validate($ClaimLimit);
  2538.             if (count($errors) > 0) {
  2539.                 $data = [
  2540.                     "errors" => array()
  2541.                 ];
  2542.                 foreach ($errors as $error) {
  2543.                     $nextError = array();
  2544.                     $nextError['id'] = $error->getPropertyPath();
  2545.                     $nextError['text'] = $error->getMessage();
  2546.                     $data['errors'][] = $nextError;
  2547.                 }
  2548.             }
  2549.             # Return JSON Errors Object
  2550.             $retVal = array(
  2551.                 "result" => "fail",
  2552.                 "error_msgs" => $errors2,
  2553.                 "error" => true,
  2554.                 "data" => $data
  2555.             );
  2556.             return new JsonResponse($retVal);
  2557.         }
  2558.         return new JsonResponse($response);
  2559.     }
  2560.     /**
  2561.      * @Route("/main/deductible/save_edit/{id}")
  2562.      */
  2563.     public function saveEditClaimDeductibleAction(Request $request$id)
  2564.     {
  2565.         // entity manager
  2566.         $em $this->container->get("doctrine.orm.entity_manager");
  2567.         $Claim $em->getRepository("ClaimManagementBundle:Claim")->find($id);
  2568.         if ($Claim === null) {
  2569.             return new NotFoundHttpException("Claim does not exist");
  2570.         }
  2571.         # Check Permissions
  2572.         $this->denyAccessUnlessGranted("edit_claim_tab"$Claim);
  2573.         // Default response
  2574.         $response = [
  2575.             'error' => false
  2576.         ];
  2577.         $deductible_id $request->request->get("deductible_id");
  2578.         $Deductible $em->getRepository("ClaimManagementBundle:Deductible")->find($deductible_id);
  2579.         $formFactory $this->container->get("form.factory");
  2580.         $DeductibleFormHelper = new DeductibleFormHelper($em$formFactoryfalse);
  2581.         $form $DeductibleFormHelper->getEditForm($Deductible);
  2582.         # Handle request
  2583.         $form->handleRequest($request);
  2584.         $Deductible $form->getData();
  2585.         if ($form->isValid()) {  // if form is valid
  2586.             $Deductible->setClaim($Claim);
  2587.             $em->persist($Deductible);
  2588.             $em->flush();
  2589.             # Return JSON Errors Object
  2590.             $retVal = array(
  2591.                 "error" => false,
  2592.             );
  2593.             return new JsonResponse($retVal);
  2594.         }else{
  2595.             $data = array();
  2596.             $errors2 = array();
  2597.             # Get Validation Error Messages
  2598.             $errors $this->get("validator")->validate($Deductible);
  2599.             if (count($errors) > 0) {
  2600.                 $data = [
  2601.                     "errors" => array()
  2602.                 ];
  2603.                 foreach ($errors as $error) {
  2604.                     $nextError = array();
  2605.                     $nextError['id'] = $error->getPropertyPath();
  2606.                     $nextError['text'] = $error->getMessage();
  2607.                     $data['errors'][] = $nextError;
  2608.                 }
  2609.             }
  2610.             # Return JSON Errors Object
  2611.             $retVal = array(
  2612.                 "result" => "fail",
  2613.                 "error_msgs" => $errors2,
  2614.                 "error" => true,
  2615.                 "data" => $data
  2616.             );
  2617.             return new JsonResponse($retVal);
  2618.         }
  2619.         return new JsonResponse($response);
  2620.     }
  2621.     /**
  2622.      * @Route("/main/coverage/save_add/{id}")
  2623.      */
  2624.     public function saveClaimCoverageAction(Request $request$id)
  2625.     {
  2626.         // entity manager
  2627.         $em $this->container->get("doctrine.orm.entity_manager");
  2628.         $Claim $em->getRepository("ClaimManagementBundle:Claim")->find($id);
  2629.         if ($Claim === null) {
  2630.             return new NotFoundHttpException("Claim does not exist");
  2631.         }
  2632.         # Check Permissions
  2633.         $this->denyAccessUnlessGranted("edit_claim_tab"$Claim);
  2634.         // Default response
  2635.         $response = [
  2636.             'error' => false
  2637.         ];
  2638.         $coverageType $em->getRepository("ClaimManagementBundle:CoverageType")->find($request->request->get("coverage_type"));
  2639.         $formFactory $this->container->get("form.factory");
  2640.         $CoverageFormHelper = new CoverageFormHelper($em$formFactoryfalse);
  2641.         $form $CoverageFormHelper->getAddForm();
  2642.         # Figure out the current user
  2643.         $current_user $this->get('security.token_storage')->getToken()->getUser();
  2644.         # Handle request
  2645.         $form->handleRequest($request);
  2646.         $Coverage $form->getData();
  2647.         $Coverage->setClaim($Claim);
  2648.         if ($coverageType) {
  2649.             $Coverage->setCoverageType($coverageType);
  2650.             $Coverage->setName($coverageType->getCoverageType());
  2651.         }
  2652.         $Coverage->setDateChangeddate_create() );
  2653.         // Create the new Reserve here
  2654.         $covReserve = new CoverageReserve();
  2655.         $covReserve->setAmount($Coverage->getReserve());
  2656.         $covReserve->setCoverage($Coverage);
  2657.         $covReserve->setDateModified( new \DateTime() );
  2658.         $covReserve->setReason($Coverage->getReasonChanged());
  2659.         $covReserve->setResource($current_user);
  2660.         $em->persist($covReserve);
  2661.         $errors $this->get("validator")->validate($Coverage);
  2662.         if (count($errors) == 0) {
  2663.             $em->persist($Coverage);
  2664.             $em->flush();
  2665.             # Return JSON Errors Object
  2666.             $retVal = array(
  2667.                 "error" => false,
  2668.             );
  2669.             return new JsonResponse($retVal);
  2670.         } else {
  2671.             $data = array();
  2672.             $errors2 = array();
  2673.             # Get Validation Error Messages
  2674.             $errors $this->get("validator")->validate($Coverage);
  2675.             if (count($errors) > 0) {
  2676.                 $data = [
  2677.                     "errors" => array()
  2678.                 ];
  2679.                 foreach ($errors as $error) {
  2680.                     $nextError = array();
  2681.                     $nextError['id'] = $error->getPropertyPath();
  2682.                     $nextError['text'] = $error->getMessage();
  2683.                     $data['errors'][] = $nextError;
  2684.                 }
  2685.             }
  2686.             # Return JSON Errors Object
  2687.             $retVal = array(
  2688.                 "result" => "fail",
  2689.                 "error_msgs" => $errors2,
  2690.                 "error" => true,
  2691.                 "data" => $data
  2692.             );
  2693.             return new JsonResponse($retVal);
  2694.         }
  2695.     }
  2696.     /**
  2697.      * @Route("/main/coverage/save_edit/{id}")
  2698.      */
  2699.     public function saveEditClaimCoverageAction(Request $request$id)
  2700.     {
  2701.         // entity manager
  2702.         $em $this->container->get("doctrine.orm.entity_manager");
  2703.         $Claim $em->getRepository("ClaimManagementBundle:Claim")->find($id);
  2704.         if ($Claim === null) {
  2705.             return new NotFoundHttpException("Claim does not exist");
  2706.         }
  2707.         # Check Permissions
  2708.         $this->denyAccessUnlessGranted("edit_claim_tab"$Claim);
  2709.         // Default response
  2710.         $response = [
  2711.             'error' => false
  2712.         ];
  2713.         $coverageType $request->request->get("coverage_type");
  2714.         $coverageId $request->request->get("coverage_id");
  2715.         /** @var Coverage $Coverage */
  2716.         $Coverage $em->getRepository("ClaimManagementBundle:Coverage")->find($coverageId);
  2717.         $origVal $Coverage->getReserve();
  2718.         # Figure out the current user
  2719.         $current_user $this->get('security.token_storage')->getToken()->getUser();
  2720.         $formFactory $this->container->get("form.factory");
  2721.         $CoverageFormHelper = new CoverageFormHelper($em$formFactoryfalse);
  2722.         $form $CoverageFormHelper->getEditForm($Coverage);
  2723.         # Handle request
  2724.         $form->handleRequest($request);
  2725.         $Coverage $form->getData();
  2726.         $Coverage->setName($coverageType);
  2727.         $Coverage->setClaim($Claim);
  2728.         $errors $this->get("validator")->validate($Coverage);
  2729.         if (count($errors) == 0) {
  2730.             // Add the user doing it, and the current date (but only if.. hmm.. the change was different?)
  2731.             if(floatval($Coverage->getReserve()) !== $origVal)
  2732.             {
  2733.                 $Coverage->setDateChanged( new \DateTime() );
  2734.                 $Coverage->setUserChanged$current_user );
  2735.             }
  2736.             // Create the new Reserve here
  2737.             $covReserve = new CoverageReserve();
  2738.             $covReserve->setAmount($Coverage->getReserve());
  2739.             $covReserve->setCoverage($Coverage);
  2740.             $covReserve->setDateModified( new \DateTime() );
  2741.             $covReserve->setReason($Coverage->getReasonChanged());
  2742.             $covReserve->setResource($current_user);
  2743.             $em->persist($Coverage);
  2744.             $em->persist($covReserve);
  2745.             $em->flush();
  2746.             # Return JSON Errors Object
  2747.             $retVal = array(
  2748.                 "error" => false,
  2749.             );
  2750.             return new JsonResponse($retVal);
  2751.         }else{
  2752.             $data = array();
  2753.             $errors2 = array();
  2754.             # Get Validation Error Messages
  2755.             $errors $this->get("validator")->validate($Coverage);
  2756.             if (count($errors) > 0) {
  2757.                 $data = [
  2758.                     "errors" => array()
  2759.                 ];
  2760.                 foreach ($errors as $error) {
  2761.                     $nextError = array();
  2762.                     $nextError['id'] = $error->getPropertyPath();
  2763.                     $nextError['text'] = $error->getMessage();
  2764.                     $data['errors'][] = $nextError;
  2765.                 }
  2766.             }
  2767.             # Return JSON Errors Object
  2768.             $retVal = array(
  2769.                 "result" => "fail",
  2770.                 "error_msgs" => $errors2,
  2771.                 "error" => true,
  2772.                 "data" => $data
  2773.             );
  2774.             return new JsonResponse($retVal);
  2775.         }
  2776.     }
  2777.     /**
  2778.      * @Route("/unassign/{claimId}")
  2779.      * @deprecated
  2780.      */
  2781.     public function unassignClaim$claimId )
  2782.     {
  2783.         $assignmentService $this->get('claim.assignment');
  2784.         // Set default response mesage
  2785.         $response = [
  2786.             'error' => false,
  2787.             'message' => 'Claim Successfully Unassigned'
  2788.         ];
  2789.         $em $this->getDoctrine()->getManager();
  2790.         # Check Permissions
  2791.         // $this->denyAccessUnlessGranted("edit_claim_tab", $claim);
  2792.         $sql "UPDATE claim SET status_id = 5, claim_team_id = NULL, full_file_assignment = 0, loss_notes = '', updated_at = NOW() WHERE id = :claimId";
  2793.         $stmt $em->getConnection()->prepare($sql);
  2794.         if( !( $stmt->execute([
  2795.             "claimId" => $claimId
  2796.         ])) ){
  2797.             $response = [
  2798.                 'error' => TRUE,
  2799.                 'message' => 'Unable to remove claim team'
  2800.             ];
  2801.             return new JsonResponse($response);
  2802.         }
  2803.         # Remove all adjusters
  2804.         $claim $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
  2805.         $assignmentService->removePrevAdjuster($claim);
  2806.         # 2020 MARCH -- NOTES FOR SUB TASKS
  2807.         $cns $this->get('claim.note_provider');
  2808.         if ($claim->getParentTask() && $claim->getSubTaskIndex()) {
  2809.             $cns->addClaimNote($claim->getParentTask(), "A sub-task was unassigned: Sub task ID " $claim->getSubTaskIndex());
  2810.         }
  2811.         return new JsonResponse($response);
  2812.     }
  2813.     /**
  2814.      * @Route("/main/resource/delete")
  2815.      * @deprecated
  2816.      */
  2817.     public function deleteClaimResourceAction(Request $request)
  2818.     {
  2819.         $em $this->container->get("doctrine.orm.entity_manager");
  2820. //        $diaryEntry = $this->getDoctrine()->getRepository('ClaimManagementBundle:DiaryEntry')->find($diary_id);
  2821. //        $diaryEntry->setStatus(1);
  2822.         # Request ID to delete
  2823.         $resource_id intval($request->request->get("res_id"));
  2824.         $claim_id intval($request->request->get("claim_id"));
  2825.         $Claim $em->getRepository("ClaimManagementBundle:Claim")->find($claim_id);
  2826.         $Resource $em->getRepository("ResourceManagementBundle:Resource")->find($resource_id);
  2827.         # Check Permissions
  2828.         $this->denyAccessUnlessGranted("edit_claim_tab"$Claim);
  2829.         # Delete Claim Resource
  2830.         /** @var ClaimResource $ClaimResource */
  2831.         $ClaimResource $em->getRepository("ClaimManagementBundle:ClaimResource")->findOneBy([
  2832.             'claim' => $Claim,
  2833.             'resource' => $Resource,
  2834.         ]);
  2835.         if( (is_countable($ClaimResource) && count($ClaimResource) == 0) || !is_object($ClaimResource)){
  2836.             $retVal = [
  2837.                 'error' => true,
  2838.                 'error_msgs' => ['No resource Found!']
  2839.             ];
  2840.             return new JsonResponse($retVal);
  2841.         }
  2842.         # Create a new entry in claim_resource_previous table
  2843.         $claimResourcesPrev $em->getRepository("ClaimManagementBundle:ClaimResourcePrevious")->findBy([
  2844.             'claim' => $Claim,
  2845.             'resource' => $Resource,
  2846.         ]);
  2847.         if(count($claimResourcesPrev)>0){
  2848.             foreach ($claimResourcesPrev as $claimResourcePrevious){
  2849.                 $claimResourcePrevious->setClaim($Claim);
  2850.                 $claimResourcePrevious->setResource($Resource);
  2851.                 $em->persist($claimResourcePrevious);
  2852.                 $em->flush();
  2853.             }
  2854.         }else {
  2855.             $claimResourcePrevious = new ClaimResourcePrevious();
  2856.             $claimResourcePrevious->setClaim($Claim);
  2857.             $claimResourcePrevious->setIsPrimary($ClaimResource->getIsPrimaryAdjuster());
  2858.             $claimResourcePrevious->setResource($Resource);
  2859.             $em->persist($claimResourcePrevious);
  2860.             $em->flush();
  2861.         }
  2862.         # remove resource from claim
  2863.         /** @var ClaimNotesProviderService $noteService */
  2864.         $noteService $this->get('claim.note_provider');
  2865.         $format "%s was removed from the Claim";
  2866.         $noteService->addClaimNote($Claim, (sprintf($format$ClaimResource->getResource()->getFullName())), true52);
  2867.         $em->remove($ClaimResource);
  2868.         $em->flush();
  2869.         /*
  2870.          * Check diary objects and set them to Complete for the resource removed
  2871.          */
  2872.         $sql "select id from diary_entry where resource_id = :resource_id  and claim_id = :claim_id  ";
  2873.         $dataParams['resource_id'] = $resource_id;
  2874.         $dataParams['claim_id'] = $claim_id;
  2875.         $stmt $em->getConnection()->prepare($sql);
  2876.         $stmt->execute($dataParams);
  2877.         $diaryObjectsIds $stmt->fetchAll(\PDO::FETCH_ASSOC);
  2878.         if ($diaryObjectsIds){
  2879.             foreach ($diaryObjectsIds as $getID) {
  2880.                 //echo $getID['id'];
  2881.                 $diaryEntry $this->getDoctrine()->getRepository('ClaimManagementBundle:DiaryEntry')->find($getID['id']);
  2882.                 $diaryEntry->setStatus(1);
  2883.                 $em $this->getDoctrine()->getManager();
  2884.                 $em->persist($diaryEntry);
  2885.                 $em->flush();
  2886.             }
  2887.         }
  2888.         # Get all claim resources
  2889.         # after removing one of them
  2890.         $claimResources $em->getRepository("ClaimManagementBundle:ClaimResource")->findBy([
  2891.             'claim' => $Claim,
  2892.         ]);
  2893.         if (count($claimResources) > 0) {
  2894.             //check if any primary adjuster exists
  2895.             $isPrimaryExists false;
  2896.             foreach ($claimResources as $claimResource) {
  2897.                 if ($claimResource->getIsPrimaryAdjuster() ) {
  2898.                     $isPrimaryExists true;
  2899.                 }
  2900.             }
  2901.             //if not make one as primary adjuster
  2902.             if(!$isPrimaryExists){
  2903.                 $claimResource $claimResources[0];
  2904.                 $claimResource->setIsPrimaryAdjuster(true);
  2905.                 $em->persist($claimResource);
  2906.             }
  2907.             $em->flush();
  2908.         }else{
  2909.             $Claim->setStatus(5);
  2910.             $Claim->setClaimTeam(null);
  2911.             $em->persist($Claim);
  2912.             $em->flush();
  2913.         }
  2914.         $retVal = [
  2915.             'error' => false,
  2916.             'error_msgs' => []
  2917.         ];
  2918.         return new JsonResponse($retVal);
  2919.     }
  2920.     /**
  2921.      * @Route("/main/resource/validate")
  2922.      */
  2923.     public function validateResourcesOnTeam(Request $request)
  2924.     {
  2925.         $em $this->getDoctrine()->getManager();
  2926.         # Request ID to delete
  2927.         $claimId intval($request->request->get("claim_id"));
  2928.         $teamId intval($request->request->get("team_id"));
  2929.         $Claim $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
  2930.         $Team $em->getRepository("ClaimManagementBundle:ClaimTeam")->find($teamId);
  2931.         $claimResources $Claim->getResources();
  2932.         $json_response = [
  2933.             'error' => false,
  2934.             'errors' => [],
  2935.             'data' => []
  2936.         ];
  2937.         foreach($claimResources as $claimResource) {
  2938.             $Adjuster $claimResource->getResource();
  2939.             $claimTeamResource $em->getRepository("ClaimManagementBundle:ClaimTeamResource")->findBy(['claimTeam' => $Team'resource' => $Adjuster]);
  2940.             if (empty($claimTeamResource)) {
  2941.                 $json_response['error'] = true;
  2942.                 $json_response['errors'][] = "{$Adjuster->getFullName()} does not belong to the team {$Team->getName()} ! ";
  2943.             }
  2944.         }
  2945.         return new JsonResponse($json_response);
  2946.     }
  2947.     public function slugify($text)
  2948.     {
  2949.         $delimiter "_";
  2950.         $text iconv('utf-8''us-ascii//TRANSLIT'$text);
  2951.         return strtolower(preg_replace('/[^A-Za-z0-9-]+/'$delimiter$text));
  2952.     }
  2953.     /**
  2954.      * @Route("/main/other-party/save_add/{id}")
  2955.      */
  2956.     public function saveClaimOtherPartyAction(Request $requestClaim $claim)
  2957.     {
  2958.         # Make sure valid claim object was passed
  2959.         if ($claim === null) {
  2960.             throw $this->createNotFoundException("Claim does not exist");
  2961.         }
  2962.         $user $this->getUser();
  2963.         # Check Permissions
  2964.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  2965.         $minorInvolved = ($request->request->get('minorInvolved') == "1") ? true false//Added to save minor dob
  2966.         $minor_dob $request->request->get('minor_dob');//Added to save minor dob
  2967.         # Check CSRF Token
  2968.         $submittedToken $request->request->get("_csrf_token");
  2969.         if (!($user instanceof Resource)) {  // if invalid user
  2970.             # Send back error
  2971.             $data = [
  2972.                 "errors" => array()
  2973.             ];
  2974.             $nextError = array();
  2975.             $nextError['id'] = "";
  2976.             $nextError['text'] = "You do not have permission to submit this form.";
  2977.             $data['errors'][] = $nextError;
  2978.             $retVal = array(
  2979.                 "result" => "fail",
  2980.                 "error_msgs" => array(),
  2981.                 "error" => true,
  2982.                 "data" => $data
  2983.             );
  2984.             return new JsonResponse($retVal);
  2985.         }
  2986.         $em $this->container->get("doctrine.orm.entity_manager");
  2987.         $formFactory $this->container->get("form.factory");
  2988.         $otherPartyFormHelper = new OtherPartyFormHelper($em$formFactorytrue);
  2989.         $otherPartyForm $otherPartyFormHelper->getAddForm();
  2990.         $formSubmission $request->request->get('form');
  2991.         # Manually submit form
  2992.         $otherPartyForm->submit($formSubmission);
  2993.         # Get Form Fields
  2994.         $otherPartyTypeId $request->request->get("otherPartyType");
  2995.         $isPrimary intval($request->request->get("isPrimary"));
  2996.         $HasPrimary $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->findOneBy([
  2997.             "claim" => $claim,
  2998.             "isPrimary" => true
  2999.         ]);
  3000.         if (!$HasPrimary) {
  3001.             $isPrimary 1;
  3002.         }
  3003.         $claimOtherPartyType $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->find($otherPartyTypeId);
  3004.         $otherParty $otherPartyForm->getData();
  3005.         # Validate Entity set from Request
  3006.         $errors $this->get("validator")->validate($otherParty);
  3007.         //added code to save county
  3008.         if(!empty($formSubmission["county"])) {
  3009.             $county $em->getRepository("ResourceManagementBundle:Counties")->findOneById($formSubmission["county"]);
  3010.             if(!empty($county)) {
  3011.                 $otherParty->setCounty($county);
  3012.             }
  3013.         }
  3014.         $data = array();
  3015.         $errors2 = array();
  3016.         if (count($errors) == 0) {  // if form is valid
  3017.             //Added to save minor dob
  3018.             if ($minorInvolved == 1) {
  3019.                 if ($minor_dob == "") {
  3020.                     $retVal = array();
  3021.                     $retVal['error'] = true;
  3022.                     $retVal['data'] = array();
  3023.                     $errorsArr = [
  3024.                         "id" => "minor_dob",
  3025.                         "text" => "Minor Date of Birth is required."
  3026.                     ];
  3027.                     $retVal['data']['errors'][] = $errorsArr;
  3028.                     return new JsonResponse($retVal);
  3029.                 }
  3030.             }
  3031.             # Persist Document
  3032.             $em->persist($otherParty);
  3033.             # Create ClaimOtherParty Record
  3034.             $claimOtherParty = new ClaimsOtherParty();
  3035.             $claimOtherParty->setClaim($claim);
  3036.             $claimOtherParty->setOtherParty($otherParty);
  3037.             //Added to save minor dob
  3038.             $claimOtherParty->setMinorInvolved($minorInvolved);
  3039.             if ($minorInvolved === true) {
  3040.                 $claimOtherParty->setMinorDOB(new \DateTime($minor_dob));
  3041.             }
  3042.             # Set Other Party Type
  3043.             if ($claimOtherPartyType) {
  3044.                 $claimOtherParty->setClaimOtherPartyType($claimOtherPartyType);
  3045.             }
  3046.             $em->persist($claimOtherParty);
  3047.             # Persist to DB
  3048.             $em->flush();
  3049.             $claimOtherParties $claim->getOtherPartyOther();
  3050.             if (count($claimOtherParties) == 1) {
  3051.                 $isPrimary true;
  3052.             }
  3053.             if ($isPrimary === true) {  // if need to set to primary
  3054.                 # Use Claim Other Party Helper to set this claimInsured record to primary, and all others on claim to isPrimary = false
  3055.                 $claimsOtherPartyHelper = new ClaimsOtherPartyHelper($em);
  3056.                 $claimsOtherPartyHelper->makeClaimOtherPartyPrimary($claimOtherParty$claim);
  3057.             }
  3058.             # Log adding Claim Insured using Monolog
  3059.             $logger $this->get('monolog.logger.claims_log');
  3060.             $logger->info('Claim Other Party added - Claim Other Party ID: ' $claimOtherParty->getId() . ", for Other Party ID: " $otherParty->getId() . ", on Claim ID: " $claim->getId());
  3061.             $comment 'Claim Other Party added - Claim Other Party ID: ' $claimOtherParty->getId() . ", for Other Party ID: " $otherParty->getId() . ", on Claim ID: " $claim->getId();
  3062.             $userNoteLog $this->container->get("app.resource_note_logger");
  3063.             $user $this->container->get("security.token_storage")->getToken()->getUser();
  3064.             $resource $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
  3065.             $userNoteLog->logNote($comment$resource,10,$claim);
  3066.             /**
  3067.              * @date 8/11/2017
  3068.              *
  3069.              * Added a Claim Note here to denote that an INSURED (CLAIMANT) was added to our Claim here.
  3070.              *
  3071.              */
  3072.             $ClaimNotes $this->get('claim.note_provider');
  3073.             //Status note = 65 Claimant
  3074.             $ClaimNotes->addClaimNote$claimOtherParty->getClaim(), "Other Party added to claim! First name: ".$claimOtherParty->getOtherParty()->getFirstName(), false65);
  3075.             $retVal = array(
  3076.                 "status" => "success",
  3077.                 "error_msgs" => []
  3078.             );
  3079.             return new JsonResponse($retVal);
  3080.         } else {  // if form not valid
  3081.             # Send back errors to client
  3082.             $data = array();
  3083.             $errors2 = array();
  3084.             $errors $this->get("validator")->validate($otherParty);
  3085.             if (count($errors) > 0) {
  3086.                 $data = [
  3087.                     "errors" => array()
  3088.                 ];
  3089.                 foreach ($errors as $error) {
  3090.                     $nextError = array();
  3091.                     $nextError['id'] = $error->getPropertyPath();
  3092.                     $nextError['text'] = $error->getMessage();
  3093.                     $data['errors'][] = $nextError;
  3094.                 }
  3095.             }
  3096.             $retVal = array(
  3097.                 "result" => "fail",
  3098.                 "error_msgs" => $errors2,
  3099.                 "error" => true,
  3100.                 "data" => $data
  3101.             );
  3102.             return new JsonResponse($retVal);
  3103.         }
  3104.     }
  3105.     /**
  3106.      * @Route("/main/other-parties/search/{id}")
  3107.      */
  3108.     public function getClaimOtherPartiesDataAjaxAction(Request $requestClaim $claim)
  3109.     {
  3110.         ## Use PaginatorService to return paginated results to DataTables Ajax Request
  3111.         if ($claim === null) {
  3112.             throw $this->createNotFoundException("Claim does not exist");
  3113.         }
  3114.         $em $this->container->get("doctrine.orm.entity_manager");
  3115.         $claimId $claim->getId();
  3116.         # Array of columns that will be sorted
  3117.         $columnsArr = array(
  3118.             "insuredName",
  3119.             "other_party_type",
  3120.             "is_primary",
  3121.             "stateCode"
  3122.         );
  3123.         # Build Query and PDO Parameters that will be passed to PaginatorService class
  3124.         $dataParams = array();
  3125.         $sql "SELECT
  3126.                 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
  3127.                 FROM claims_other_party cop
  3128.                 INNER JOIN other_party op
  3129.                   ON cop.other_party_id = op.id
  3130.                 INNER JOIN claim_other_party_type copt
  3131.                   ON cop.claim_other_party_type_id = copt.id
  3132.                 LEFT JOIN state s
  3133.                   ON op.state_id = s.id
  3134.                 WHERE 1 = 1 ";
  3135.         # Search By Claim ID
  3136.         if ($claimId 0) {
  3137.             $sql .= "AND cop.claim_id = :claimId ";
  3138.             $dataParams['claimId'] = $claimId;
  3139.         }
  3140.         # build keyword filter, which is requested by datatables ajax when someone types into keyword field
  3141.         //$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) ";
  3142.         # call PaginatorService
  3143.         $paginator $this->container->get("resource.paginator_service");
  3144.         $retVal $paginator->getPaginationResults($request$sql$dataParams"cop.id ASC"$columnsArr"search_keyword""""keyword""");
  3145.         return new JsonResponse($retVal);
  3146.     }
  3147.     /**
  3148.      * @Route("/main/other-party/update/{claimId}/{claimOtherPartyId}")
  3149.      */
  3150.     public function updateClaimOtherPartyAction($claimId$claimOtherPartyId)
  3151.     {
  3152.         $em $this->getDoctrine()->getManager();
  3153.         $claim $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
  3154.         # Make sure valid claim object was passed
  3155.         if ($claim === null) {
  3156.             throw $this->createNotFoundException("Claim does not exist");
  3157.         }
  3158.         # Check Permissions
  3159.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  3160.         $claimOtherParty $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->find($claimOtherPartyId);
  3161.         # Get Insured Form Instance from Form Helper (will use without form tags)
  3162.         $formFactory $this->container->get("form.factory");
  3163.         $otherPartyFormHelper = new OtherPartyFormHelper($em$formFactorytrue);
  3164.         $otherPartyForm $otherPartyFormHelper->getEditForm($claimOtherParty->getOtherParty());
  3165.         $otherPartyTypes $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->findAll();
  3166.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/modals/edit-other-party-modal.html.twig", [
  3167.             "claim" => $claim,
  3168.             'other_party_form' => $otherPartyForm->createView(),
  3169.             "otherPartyTypes" => $otherPartyTypes,
  3170.             "claimOtherPartyId" => $claimOtherPartyId,
  3171.             "claimOtherParty" => $claimOtherParty //added to save minor dob
  3172.         ]);
  3173.     }
  3174.     /**
  3175.      * @Route("/main/other-party/save_update/{claimId}/{claimOtherPartyId}")
  3176.      */
  3177.     public function saveUpdateClaimOtherPartyAction(Request $request$claimId$claimOtherPartyId)
  3178.     {
  3179.         $em $this->container->get("doctrine.orm.entity_manager");
  3180.         $claim $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
  3181.         $claimsOtherParty $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->find($claimOtherPartyId);
  3182.         # Check Permissions
  3183.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  3184.         $minorInvolved = ($request->request->get('minorInvolved') == "1") ? true false//Added to save minor dob
  3185.         $minor_dob $request->request->get('minor_dob');//Added to save minor dob
  3186.         # Make sure valid claim object was passed
  3187.         if ($claim === null) {
  3188.             throw $this->createNotFoundException("Claim does not exist");
  3189.         }
  3190.         # Make sure valid Claims Insured Record exists
  3191.         if ($claimsOtherParty === null) {
  3192.             throw $this->createNotFoundException("Claims Other Party Record does not exist");
  3193.         }
  3194.         # Make sure Insured Record exists
  3195.         $otherParty $claimsOtherParty->getOtherParty();
  3196.         if ($otherParty === null) {
  3197.             throw $this->createNotFoundException("Claim does not have other party record");
  3198.         }
  3199.         # Check CSRF Token
  3200.         $submittedToken $request->request->get("_csrf_token");
  3201.         // if (!$this->isCsrfTokenValid('edit_claim_insured', $submittedToken)) {  // if invalid csrf token
  3202.         if (!($this->getUser() instanceof Resource)) {
  3203.             # Send back error
  3204.             $data = [
  3205.                 "errors" => array()
  3206.             ];
  3207.             $nextError = array();
  3208.             $nextError['id'] = "";
  3209.             $nextError['text'] = "You do not have permission to submit this form.";
  3210.             $data['errors'][] = $nextError;
  3211.             $retVal = array(
  3212.                 "result" => "fail",
  3213.                 "error_msgs" => array(),
  3214.                 "error" => true,
  3215.                 "data" => $data
  3216.             );
  3217.             return new JsonResponse($retVal);
  3218.         }
  3219.         $em $this->container->get("doctrine.orm.entity_manager");
  3220.         $formFactory $this->container->get("form.factory");
  3221.         $otherPartyFormHelper = new OtherPartyFormHelper($em$formFactorytrue);
  3222.         $otherPartyForm $otherPartyFormHelper->getEditForm($otherParty);
  3223.         # Get Form Fields
  3224.         $formSubmission $request->request->get('form');
  3225.         # Manually submit form
  3226.         $otherPartyForm->submit($formSubmission);
  3227.         $otherPartyTypeId $request->request->get("otherPartyType");
  3228.         $isPrimary intval($request->request->get("isPrimary"));
  3229.         $claimOtherPartyType $em->getRepository("ClaimManagementBundle:ClaimOtherPartyType")->find($otherPartyTypeId);
  3230.         $otherParty $otherPartyForm->getData();
  3231.         $otherParty2 $otherParty;
  3232.         ## Code checks if changes were made to Insured Object ##
  3233.         # Get Current Resource on DB
  3234.         $otherPartyCompare = new OtherPartyCompareHelper($em);
  3235.         $otherPartyCompare->setCurOtherParty($otherParty2);
  3236.         $claimOtherParty $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->loadByClaimAndOtherParty($claim$otherParty);
  3237.         if ($claimOtherPartyType) {
  3238.             $claimOtherParty->setClaimOtherPartyType($claimOtherPartyType);
  3239.         }
  3240.         ###
  3241.         # Deal with setting Claim Insured Type, Minor Birthday, verifying if these fields have changed on this update
  3242.         # Do some checking to check if Claim Insured Type Changed
  3243.         //*/
  3244.         $claimOtherPartyChanged false;
  3245.         $otherPartyTypeChanged false;
  3246.         $claimOtherPartyChangesHelper = new ClaimOtherPartyChangesHelper($em);
  3247.         $changedOtherPartyType $claimOtherPartyChangesHelper->otherPartyTypeDidChange($claim$otherParty$claimOtherPartyType);
  3248.         $claimOtherPartyChanged $claimOtherPartyChangesHelper->minorBDayDidChange($claimsOtherParty$minor_dob); //Added to save the minor involved and minor dob change
  3249.         if ($changedOtherPartyType != "") {
  3250.             $otherPartyTypeChanged true;
  3251.         }
  3252.         //added code to save county
  3253.         if(!empty($formSubmission["county"])) {
  3254.             $county $em->getRepository("ResourceManagementBundle:Counties")->findOneById($formSubmission["county"]);
  3255.             if(!empty($county)) {
  3256.                 $otherParty->setCounty($county);
  3257.             }
  3258.         }
  3259.         #
  3260.         ###
  3261.         # Set Claim Insured Type
  3262.         # Validate Entity set from Request
  3263.         $errors $this->get("validator")->validate($otherParty);
  3264.         $data = array();
  3265.         $errors2 = array();
  3266.         if (count($errors) == 0) {  // if form is valid
  3267.             //Added to save the minor involved and minor dob change
  3268.             if ($minorInvolved == 1) {
  3269.                 if ($minor_dob == "") {
  3270.                     $retVal = array();
  3271.                     $retVal['error'] = true;
  3272.                     $retVal['data'] = array();
  3273.                     $errorsArr = [
  3274.                         "id" => "minor_dob",
  3275.                         "text" => "Minor Date of Birth is required."
  3276.                     ];
  3277.                     $retVal['data']['errors'][] = $errorsArr;
  3278.                     return new JsonResponse($retVal);
  3279.                 }
  3280.                 $claimOtherParty->setMinorInvolved($minorInvolved);
  3281.                 $claimOtherParty->setMinorDOB(new \DateTime($minor_dob));
  3282.             }
  3283.             else{
  3284.                 $claimOtherParty->setMinorInvolved($minorInvolved);
  3285.                 $claimOtherParty->setMinorDOB(null);
  3286.             }
  3287.             # Compare 2 objects to see if there were any changes made
  3288.             $otherPartyCompare->setNewOtherParty($otherParty);
  3289.             $hasChanges $otherPartyCompare->compareObjects();
  3290.             # Persist Document
  3291.             $em->persist($otherParty);
  3292.             $em->persist($claimOtherParty);
  3293.             $em->flush();
  3294.             if ($hasChanges || $claimOtherPartyChanged) {  // check if whether Insured Entity or Claim Insured Entity was changed
  3295.                 $getChanges = array();
  3296.                 if ($hasChanges) {
  3297.                     $changeLog $otherPartyCompare->changeLog;
  3298.                     $getChanges2 array_merge($getChanges$changeLog);
  3299.                 } else {
  3300.                     $getChanges2 $getChanges;
  3301.                 }
  3302.                 $ClaimNote $this->container->get("claim.note_provider");
  3303.                 $ClaimNote->addClaimNote($claim"Claim Other Party was updated. " implode(" "$getChanges2), false52);
  3304.             }
  3305.             if ($isPrimary === 1) {  // if set to primary
  3306.                 # Use Claim Insured Helper to set this claimInsured record to primary, and all others on claim to isPrimary = false
  3307.                 $claimsOtherPartyHelper = new ClaimsOtherPartyHelper($em);
  3308.                 $claimsOtherPartyHelper->makeClaimOtherPartyPrimary($claimOtherParty$claim);
  3309.             }
  3310.             # Log updating Claim Insured using Monolog
  3311.             $logger $this->get('monolog.logger.claims_log');
  3312.             $logger->info("Claim Other party Updated - Other party ID: " $otherParty->getId() . ", with ClaimOtherPartyID: " $claimOtherParty->getId() . ", on Claim ID: " $claim->getId());
  3313.             $comment "Claim Other party Updated - Other party ID: " $otherParty->getId() . ", with ClaimOtherPartyID: " $claimOtherParty->getId() . ", on Claim ID: " $claim->getId();
  3314.             $userNoteLog $this->container->get("app.resource_note_logger");
  3315.             $user $this->container->get("security.token_storage")->getToken()->getUser();
  3316.             $resource $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
  3317.             $userNoteLog->logNote($comment$resource,10,$claim);
  3318.             $ClaimNotes $this->get('claim.note_provider');
  3319.             $ClaimNotes->addClaimNote$claimsOtherParty->getClaim(), "Other Party edited! First name: "$otherParty->getFirstName() , false52);
  3320.             $retVal = array(
  3321.                 "status" => "success",
  3322.                 "error_msgs" => []
  3323.             );
  3324.             return new JsonResponse($retVal);
  3325.         } else {  // if form not valid
  3326.             # Send back errors to client
  3327.             $data = array();
  3328.             $errors2 = array();
  3329.             $errors $this->get("validator")->validate($otherParty);
  3330.             if (count($errors) > 0) {
  3331.                 $data = [
  3332.                     "errors" => array()
  3333.                 ];
  3334.                 foreach ($errors as $error) {
  3335.                     $nextError = array();
  3336.                     $nextError['id'] = $error->getPropertyPath();
  3337.                     $nextError['text'] = $error->getMessage();
  3338.                     $data['errors'][] = $nextError;
  3339.                 }
  3340.             }
  3341.             $retVal = array(
  3342.                 "result" => "fail",
  3343.                 "error_msgs" => $errors2,
  3344.                 "error" => true,
  3345.                 "data" => $data
  3346.             );
  3347.             return new JsonResponse($retVal);
  3348.         }
  3349.     }
  3350.     /**
  3351.      * @Route("/main/other-party/delete")
  3352.      * @Method(methods={"POST"})
  3353.      */
  3354.     public function deleteClaimOtherPartyAction(Request $request)
  3355.     {
  3356.         $em $this->container->get("doctrine.orm.entity_manager");
  3357.         # Request ID to delete
  3358.         $id intval($request->request->get("id"));
  3359.         # Delete ClaimOtherParty
  3360.         $claimOtherParty $em->getRepository("ClaimManagementBundle:ClaimsOtherParty")->find($id);
  3361.         if ($claimOtherParty->getIsPrimary()) {
  3362.             $retVal = [
  3363.                 'error' => true,
  3364.                 'error_msgs' => ["You cannot remove the Primary Other party."]
  3365.             ];
  3366.             return new JsonResponse($retVal);
  3367.         }
  3368.         # Get claim, claim insured objects while they exist
  3369.         $otherParty $claimOtherParty->getOtherParty();
  3370.         $otherPartyId $otherParty->getId();
  3371.         /**
  3372.          * @var $claim Claim
  3373.          */
  3374.         $claim $claimOtherParty->getClaim();
  3375.         $claimId $claim->getId();
  3376.         # Check Permissions
  3377.         $this->denyAccessUnlessGranted("edit_claim_tab"$claim);
  3378.         $em->remove($claimOtherParty->getOtherParty());
  3379.         $em->remove($claimOtherParty);
  3380.         $em->flush();
  3381.         # Get all claim other parties after removing one of them
  3382.         $claimOtherParties $claim->getClaimsOtherParties();
  3383.         if (count($claimOtherParties) == 1) {  // if there is only one insured on the claim
  3384.             # Make that other party primary
  3385.             $getClaimOtherParty $claimOtherParties[0];
  3386.             $claimsInsuredHelper = new ClaimsOtherPartyHelper($em);
  3387.             $claim $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
  3388.             $claimsInsuredHelper->makeClaimOtherPartyPrimary($getClaimOtherParty$claim);
  3389.         }
  3390.         # Log deleting Claim Other Parties using Monolog
  3391.         $logger $this->get('monolog.logger.claims_log');
  3392.         $logger->info("Claim Other Party Deleted - Other party ID: " $otherPartyId ", with ClaimOtherPartyID: " $id ", on Claim ID: " $claimId);
  3393.         $comment "Claim Other Party Deleted - Other party ID: " $otherPartyId ", with ClaimOtherPartyID: " $id ", on Claim ID: " $claimId;
  3394.         $userNoteLog $this->container->get("app.resource_note_logger");
  3395.         $user $this->container->get("security.token_storage")->getToken()->getUser();
  3396.         $resource $em->getRepository("ResourceManagementBundle:Resource")->find($user->getId());
  3397.         $userNoteLog->logNote($comment$resource,10,$claim);
  3398.         $retVal = [
  3399.             'error' => false,
  3400.             'error_msgs' => []
  3401.         ];
  3402.         return new JsonResponse($retVal);
  3403.     }
  3404.     /**
  3405.      * @Route("/street-view-iframe/{id}", defaults={"id" = "none"})
  3406.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  3407.      */
  3408.     public function streetViewWidgetIframeAction(Claim $claimRequest $request)
  3409.     {
  3410.         $data = [
  3411.             "apiKey" => "",
  3412.             "lat" => 15,
  3413.             "lng" => 15
  3414.         ];
  3415.         $metaData $this->container->get('core.system_parameter_control')->getSystemControlMetaData(
  3416.             SystemControlRepository::GOOGLE_MAP_API
  3417.         );
  3418.         if (is_array($metaData)) {
  3419.             $apiKey $metaData[SystemControlMetadataRepository::META_GOOGLE_MAP_API_KEY] ?? "";
  3420.             if (!empty($apiKey)) {
  3421.                 $data['apiKey'] = $apiKey;
  3422.                 $latLong GoogleGeocoder::getLatLongFromLossAddress(
  3423.                     $apiKey,
  3424.                     $claim->getLossStreet(),
  3425.                     $claim->getLossCity(),
  3426.                     $claim->getLossState(),
  3427.                     $claim->getLossZip()
  3428.                 );
  3429.                 $data['lat'] = $latLong['lat'];
  3430.                 $data['lng'] = $latLong['lng'];
  3431.             }
  3432.         }
  3433.         return $this->render('ClaimManagementBundle:ClaimFlowScreen/Fragments/widgets:street-view-widget-iframe.html.twig', [
  3434.             'data' => $data
  3435.         ]);
  3436.     }
  3437.     /**
  3438.      * @Route("/street-view-iframe-preload/{id}", defaults={"id" = "none"})
  3439.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  3440.      */
  3441.     public function streetViewWidgetIframePreloadAction(Claim $claimRequest $request)
  3442.     {
  3443.         return $this->render('ClaimManagementBundle:ClaimFlowScreen/Fragments/widgets:street-view-widget-iframe-preload.html.twig', [
  3444.             'loadIframe' => ($claim instanceof Claim),
  3445.             'claim' => $claim
  3446.         ]);
  3447.     }
  3448.     /**
  3449.      * @Route("/media-proxy/{id}", defaults={"id" = "none"}, name="claim_media_proxy")
  3450.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  3451.      */
  3452.     public function claimMediaProxyAction(Claim $claimRequest $request)
  3453.     {
  3454.         $response = new Response();
  3455.         $url $this->get('claim.media')->googleStreetViewUrl($claim);
  3456.         $ch curl_init();
  3457.         curl_setopt($chCURLOPT_URL,$url);
  3458.         curl_setopt($chCURLOPT_RETURNTRANSFER,1);
  3459.         $content curl_exec($ch);
  3460.         curl_close ($ch);
  3461.         if ($content === false) {
  3462.             $content file_get_contents($this->get('kernel')->getProjectDir()."/web/img/location-not-found.jpg");
  3463.         }
  3464.         $filename sprintf("%s.jpg"$claim->getId());
  3465.         $response->headers->set('Cache-Control''private');
  3466.         $response->headers->set('Content-type''image/jpg' );
  3467.         $response->headers->set('Content-Disposition''attachment; filename="' $filename '";');
  3468.         $response->headers->set('Content-length',  strlen($content));
  3469.         $response->sendHeaders();
  3470.         $response->setContent($content);
  3471.         return $response;
  3472.     }
  3473.     /**
  3474.      * @Route("/main/externalclaimresources/{id}")
  3475.      */
  3476.     public function externalclaimresourcesAction(Claim $claim)
  3477.     {
  3478.         # Make sure valid claim object was passed
  3479.         if ($claim === null) {
  3480.             throw $this->createNotFoundException("Claim does not exist");
  3481.         }
  3482.         $em $this->container->get("doctrine.orm.entity_manager");
  3483.         $assignmentService $this->get('claim.assignment');
  3484.         $alertMessageDateExpiryArray $assignmentService->validLicenseExternal($claim);
  3485.         $alertMessageDateExpiry $alertMessageDateExpiryArray['alertMessageDateExpiry'];
  3486.         $licenseDataArray $alertMessageDateExpiryArray['licenseDataArray'];
  3487.         $adjusterRepo $em->getRepository("ResourceManagementBundle:Resource");
  3488.         $claimTeamRepo $em->getRepository("ClaimManagementBundle:ClaimTeam");
  3489.         //$adjusters = $adjusterRepo->findBy(['resourceType'=>array(2,3,4)]);
  3490.         $claimTeams $claimTeamRepo->findBy(['enabled'=>true]);
  3491.         $resourceTypes $em->getRepository("ResourceManagementBundle:ResourceType")->findAll();
  3492.         $assignmentParties $em->getRepository("AssignmentBundle:AssignmentParty")->findAll();
  3493.         /*$sql = "SELECT count(id) as resource_count
  3494.                    FROM claim_resource cr
  3495.                    WHERE cr.claim_id = :claim_id";*/
  3496.         $sql "SELECT count(id) as resource_count
  3497.                    FROM assignments_external cr 
  3498.                    WHERE cr.claim_id = :claim_id
  3499.                     AND IFNULL(cr.next_assignment_id,0) = 0
  3500.                     AND cr.is_current_assignment = 1 ";
  3501.         $stmt $em->getConnection()->prepare($sql);
  3502.         $stmt->execute([
  3503.             "claim_id"=>$claim->getId()
  3504.         ]);
  3505.         $resourceCountResults $stmt->fetchAll(\PDO::FETCH_ASSOC);
  3506.         $resourceCount 0;
  3507.         foreach ($resourceCountResults as $resourceCountRow){
  3508.             $resourceCount $resourceCountRow['resource_count'];
  3509.         }
  3510.         return $this->render("@ClaimManagement/ClaimFlowScreen/Fragments/widgets/resources-external-widget.html.twig", [
  3511.             "claim" => $claim,
  3512.             'resourceTypes' => $resourceTypes,
  3513.             'assignmentParties' => $assignmentParties,
  3514.             'teams' => $claimTeams,
  3515.             'resourceCount' => $resourceCount,
  3516.             'licenseDataArray' => $licenseDataArray,
  3517.             'alertMessageDateExpiry' =>$alertMessageDateExpiry
  3518.         ]);
  3519.     }
  3520.     /**
  3521.      * @Route("/main/resource/verify_claim_api/{id}")
  3522.      */
  3523.     public function verifyClaimApi(Claim $claimRequest $request)
  3524.     {
  3525.         # Make sure valid claim object was passed
  3526.         if ($claim === null) {
  3527.             throw $this->createNotFoundException("Claim does not exist");
  3528.         }
  3529.         $session = new Session();
  3530.         $systemParamService $this->container->get('core.system_parameter_control');
  3531.         if ($session->has("claimPublishedID")) {
  3532.             $session_claim_no $session->get("claimPublishedNo");
  3533.             if($session_claim_no !== $claim->getClaimNumber()){
  3534.                 $bReferUrl=$systemParamService->getParameterValue('api_publisher','api_publisher_host');
  3535.                 $apiPublisherService $this->container->get('core.api_publisher_service');
  3536.                 $apiResponseValues=$apiPublisherService->publishRetrieveClaimApi($claim->getId(), 'GET''json');
  3537.                 $session->set("claimPublishedID"0);
  3538.                 if(!empty($apiResponseValues)){
  3539.                     $session->set("claimPublishedID"$apiResponseValues);
  3540.                     $session->set("claimPublishedUrl"$bReferUrl);
  3541.                     $session->set("claimPublishedNo"$claim->getId());
  3542.                     $retVal = [
  3543.                         'error' => false,
  3544.                         'claimPublishedID' => $apiResponseValues,
  3545.                         'claimPublishedUrl' => $bReferUrl,
  3546.                         'claimPublishedNo' =>  $claim->getId()
  3547.                     ];
  3548.                     return new JsonResponse($retVal);
  3549.                 }else{
  3550.                     $retVal = [
  3551.                         'error' => true
  3552.                     ];
  3553.                     return new JsonResponse($retVal);
  3554.                 }
  3555.             }else{
  3556.                 $retVal = [
  3557.                     'error' => false,
  3558.                     'claimPublishedID' => $session->get("claimPublishedID"),
  3559.                     'claimPublishedUrl' => $session->get("claimPublishedUrl"),
  3560.                     'claimPublishedNo' =>  $claim->getId()
  3561.                 ];
  3562.                 return new JsonResponse($retVal);
  3563.             }
  3564.         }else{
  3565.             $bReferUrl=$systemParamService->getParameterValue('api_publisher','api_publisher_host');
  3566.             $apiPublisherService $this->container->get('core.api_publisher_service');
  3567.             $apiResponseValues=$apiPublisherService->publishRetrieveClaimApi($claim->getId(), 'GET''json');
  3568.             $session->set("claimPublishedID"0);
  3569.             if(!empty($apiResponseValues)){
  3570.                 $session->set("claimPublishedID"$apiResponseValues);
  3571.                 $session->set("claimPublishedUrl"$bReferUrl);
  3572.                 $session->set("claimPublishedNo"$claim->getId());
  3573.                 $retVal = [
  3574.                     'error' => false,
  3575.                     'claimPublishedID' => $apiResponseValues,
  3576.                     'claimPublishedUrl' => $bReferUrl,
  3577.                     'claimPublishedNo' =>  $claim->getId()
  3578.                 ];
  3579.                 return new JsonResponse($retVal);
  3580.             }else{
  3581.                 $retVal = [
  3582.                     'error' => true
  3583.                 ];
  3584.                 return new JsonResponse($retVal);
  3585.             }
  3586.         }
  3587.     }
  3588. }