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

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