src/Globals/ClaimManagementBundle/Controller/ClaimFlowCrudController.php line 581

Open in your IDE?
  1. <?php
  2. namespace Globals\ClaimManagementBundle\Controller;
  3. use Doctrine\ORM\EntityManager;
  4. use Globals\ClaimManagementBundle\DependencyInjection\CompareHelpers\DisbursementCompareHelper;
  5. use Globals\ClaimManagementBundle\DependencyInjection\ExpensesHelper;
  6. use Globals\ClaimManagementBundle\Entity\Claim;
  7. use Globals\ClaimManagementBundle\Entity\ClaimNoteMedia;
  8. use Globals\ClaimManagementBundle\Entity\DiaryEntry;
  9. use Globals\ClaimManagementBundle\Entity\DiaryOtherResource;
  10. use Globals\ClaimManagementBundle\Event\ClaimDiaryAssignedEvent;
  11. use Globals\ClaimManagementBundle\Event\ClaimDiaryCompleteEvent;
  12. use Globals\ClaimManagementBundle\Form\Coverage;
  13. use Globals\ClaimManagementBundle\Form\Deductible;
  14. use Globals\ClaimManagementBundle\Form\DiaryFormType;
  15. use Globals\ClaimManagementBundle\Form\DisbursementTimeLogType;
  16. use Globals\CoreBundle\Helpers\MailHelper;
  17. use Globals\CustomerManagementBundle\DependencyInjection\DisbursementHelper;
  18. use Globals\MailManagementBundle\Entity\Mail;
  19. use Globals\MailManagementBundle\Entity\MailRecipient;
  20. use Globals\ResourceManagementBundle\Entity\Resource;
  21. use Globals\ResourceManagementBundle\Service\SLogger;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  23. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  24. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  25. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  26. use Symfony\Component\Finder\Finder;
  27. use Symfony\Component\Form\Form;
  28. use Symfony\Component\HttpFoundation\File\UploadedFile;
  29. use Symfony\Component\HttpFoundation\JsonResponse;
  30. use Symfony\Component\HttpFoundation\Request;
  31. use Globals\ClaimManagementBundle\Entity\Coverage as CoverageEntity;
  32. use Symfony\Component\HttpFoundation\Response;
  33. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  34. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  35. use Globals\InvoiceManagementBundle\Entity\Disbursement;
  36. use Globals\ClaimManagementBundle\Event\ClaimDuplicatedEvent;
  37. use DateTime;
  38. /**
  39.  * @Route("/administration/claims/api")
  40.  */
  41. class ClaimFlowCrudController extends Controller
  42. {
  43.     
  44.     /**
  45.      * @Route("/clone/{id}")
  46.      * @Method("POST")
  47.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  48.      */
  49.     public function cloneExistingClaim(Claim $claim)
  50.     {
  51.         if($claim){
  52.         }else{
  53.             throw new NotFoundHttpException("Couldn't find this claim!");
  54.         }
  55.     }
  56.     /**
  57.      * @Route("/update/{id}")
  58.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  59.      */
  60.     public function updateClaimFlowAction(Claim $claim)
  61.     {
  62.         /** @var Claim $claim */
  63.         return new JsonResponse(['claim_number'=>$claim->getClaimNumber()]);
  64.     }
  65.     /**
  66.      * @Route("/create/deductible")
  67.      */
  68.     public function createDeductibleAction(Request $request)
  69.     {
  70.         # 1) If we are POST-ing *only*
  71.         if($request->getMethod() == "POST"){
  72.             $deductibleData $request->request->get('newDeductible');
  73.             $deductibleData['name'] = 'Deductible';
  74.             
  75.             $form $this->createForm(Deductible::class, new \Globals\ClaimManagementBundle\Entity\Deductible());
  76.             $form->submit($deductibleData);
  77.             if($form->isValid()){
  78.                 $newDeductible $form->getData();
  79.                 $em $this->getDoctrine()->getManager();
  80.                 $em->persist($newDeductible);
  81.                 $em->flush();
  82.                 # Add Claim Note that Deductible was added
  83.                 $ClaimNote $this->container->get("claim.note_provider");
  84.                 //Status note = 68 Claim Deductible
  85.                 $ClaimNote->addClaimNote($newDeductible->getClaim(), "Claim Deductible was added."false68);
  86.                 return new JsonResponse(['error'=>false]);
  87.             }else{
  88.                 $errors = [];
  89.                 foreach($form as $formField){
  90.                     if((string)$formField->getErrors(true)){
  91.                         $errors[] = [
  92.                             'id'=>$formField->getName(),
  93.                             'text'=>(string)$formField->getErrors(true)
  94.                         ];
  95.                     }
  96.                 }
  97.                 return new JsonResponse(['error'=>true'data' => ['errors' => $errors]]);
  98.             }
  99.         }else{
  100.             return new JsonResponse(['error'=>true]);
  101.         }
  102.     }
  103.     /**
  104.      * @Route("/create/coverage")
  105.      */
  106.     public function createCoverageAction(Request $request)
  107.     {
  108.         # 1) If we are POST-ing *only*
  109.         if($request->getMethod() == "POST"){
  110.             
  111.             $coverageData $request->request->get('newCoverage');
  112.             
  113.             $form $this->createForm(Coverage::class, new CoverageEntity());
  114.             $form->submit($coverageData);
  115.             if($form->isValid()){
  116.                 $newCoverage $form->getData();
  117.                 $em $this->getDoctrine()->getManager();
  118.                 $em->persist($newCoverage);
  119.                 $em->flush();
  120.                 return new JsonResponse(['error'=>false]);
  121.             }else{
  122.                 $errors = [];
  123.                 foreach($form as $formField){
  124.                     if((string)$formField->getErrors(true)){
  125.                         $errors[] = [
  126.                             'id'=>$formField->getName(),
  127.                             'text'=>(string)$formField->getErrors(true)
  128.                         ];
  129.                     }
  130.                 }
  131.                 return new JsonResponse(['error'=>true'data' => ['errors' => $errors]]);
  132.             }
  133.         }else{
  134.             return new JsonResponse(['error'=>true]);
  135.         }
  136.     }
  137.     /**
  138.      * @Route("/update/set-inspection-date/{id}")
  139.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  140.      */
  141.     public function setInspectionDate(Claim $claimRequest $request)
  142.     {
  143.         # logged in user
  144.         $user $this->get('security.token_storage')->getToken()->getUser();
  145.         $response = ['error'=>false'data'=>[]];
  146.         if($claim){
  147.             $incoming_date $request->request->get('date');
  148.             $incoming_time $request->request->get('time');
  149.             $incoming_note $request->request->get('note');
  150.             $needs_inspection $request->request->get('needs_inspection');
  151.             $needs_inspection $needs_inspection == false:true;
  152.             # combine date and time
  153.             $Date = new \DateTime($incoming_date);
  154.             if(($needs_inspection) && (empty($incoming_time) || is_null($incoming_time) || $incoming_time == '00:00 AM'))
  155.             {
  156.                 $response = ['error'=>true'data'=>['message'=>'Time inspected is missing.']];
  157.                 return new JsonResponse($response);
  158.             }
  159.             if ($needs_inspection){
  160.                 $Time DateTime::createFromFormat('Y-m-d H:i A',$Date->format('Y-m-d')." ".$incoming_time); //new \DateTime($incoming_time);
  161.                 $mergeDateTime $Time->format'Y-m-d H:i' );
  162.             } else {
  163.                 $mergeDateTime "";
  164.             }
  165.             $claim->setNeedsInspection($needs_inspection);
  166.             $em $this->getDoctrine()->getManager();
  167.             $em->persist($claim);
  168.             $em->flush();
  169.             if( $this->get('claim.status_update')->setInspectionDate$claim$mergeDateTime$incoming_note ) ){
  170.                 # create our note
  171.                 $inspectionDate = new DateTime($incoming_date);
  172.                 $inspectionNote "" $user->getUsername() . sprintf(" has inspected the claim: %s, note: %s"$inspectionDate->format('m/d/Y h:i A'), $incoming_note);
  173.                 if ($claim->getTransactionId() && $claim->getTransactionId() != "") {
  174.                     # send our xml to xact
  175.                     $xactService $this->get('integration.xact.outbound');
  176.                     $xactService->exportAddNotes(
  177.                         [
  178.                             'transactionId' => $claim->getTransactionId(),
  179.                             'userName' => $user->getFullName(),
  180.                             'dateTime' => $inspectionDate->getTimeStamp(),
  181.                             'noteType' => 'Inspected',
  182.                             'notes' => $inspectionNote
  183.                         ]
  184.                     );
  185.                 }
  186.                 if($claim->getAssignmentId()){
  187.                     $symService $this->get('integration.symbility.outbound');
  188.                     $symService->pushInspectionDate($inspectionDate->format('m/d/Y'), $claim->getClaimNumber(), $claim->getAssignmentId());
  189.                 }
  190.             } else {
  191.                 $response = ['error'=>true'data'=>['message'=>'Could not set inspection date. Please try again.']];
  192.             }
  193.             return new JsonResponse($response);
  194.         }else{
  195.             throw new NotFoundHttpException("Couldn't find this claim!");
  196.         }
  197.     }
  198.     /**
  199.      * @Route("/update/set-planned-inspection-date/{id}")
  200.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  201.      */
  202.     public function setPlannedInspectionDate(Claim $claimRequest $request)
  203.     {
  204.         # logged in user
  205.         $user $this->get('security.token_storage')->getToken()->getUser();
  206.         $response = ['error'=>false'data'=>[]];
  207.         if($claim){
  208.             $incoming_date $request->request->get('date');
  209.             $incoming_time $request->request->get('time');
  210.             // Ensure $incoming_date is a valid date string before creating DateTime object
  211.             $Date = new \DateTime($incoming_date);
  212.             // Format the DateTime object to string
  213.             $formattedDate $Date->format('Y-m-d');
  214.             // Combine the formatted date string with the incoming time and convert it to a timestamp
  215.             $combinedDT date('Y-m-d H:i'strtotime("$formattedDate $incoming_time"));
  216.             $dt = new \DateTime($combinedDT);
  217.             $claim->setPlannedInspectionDate($dt);
  218.             $em $this->getDoctrine()->getManager();
  219.             $em->persist($claim);
  220.             $em->flush();
  221.             $ClaimNote $this->container->get("claim.note_provider");
  222.             //Status note = 69 Claim Disbursement
  223.             $ClaimNote->addClaimNote($claim"Planned Inspection date has been changed to " .$incoming_datefalse69);
  224.             return new JsonResponse($response);
  225.         }else{
  226.             throw new NotFoundHttpException("Couldn't find this claim!");
  227.         }
  228.     }
  229.     /**
  230.      * @Route("/update/set-first-contact-date/{id}")
  231.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  232.      */
  233.     public function setFirstContactDate(Claim $claimRequest $request)
  234.     {
  235.         # logged in user
  236.         $user $this->get('security.token_storage')->getToken()->getUser();
  237.         $response = ['error'=>false'data'=>[]];
  238.         if($claim){
  239.             $incoming_date $request->request->get('date');
  240.             $incoming_time $request->request->get('time');
  241.             $incoming_note $request->request->get('note');
  242.             # combine date and time
  243.             $Date = new \DateTime($incoming_date);
  244.             $Time = new \DateTime($incoming_time);
  245.             $mergeDateTime $Date->format('Y-m-d') . ' ' $Time->format('H:i:s');
  246.             # create our note
  247.             $contactDate = new DateTime($incoming_date);
  248.             $contactDateTime = new \DateTime($mergeDateTime);
  249.             if( $contactDateTime $claim->getDateReceived()){
  250.                 $response['error'] = true;
  251.                 $response['data']['errors'][] = 'Date contacted cannot be before date received!';
  252.                 return new JsonResponse($response);
  253.             }
  254.             $contactNote "" $user->getUsername() . sprintf(" has made  First Contact: %s, note: %s"$contactDate->format('m/d/Y'), $incoming_note);
  255.             if($incoming_date){
  256.                 $note "";
  257.                 if($incoming_note){
  258.                     $note $incoming_note;
  259.                 }
  260.                 # export to xact to let them know first contact has been made
  261.                 if( $this->get('claim.status_update')->setFirstContactDate($claim$mergeDateTime$note) ){
  262.                     # If Xact claim, lets do export
  263.                     if ($claim->getTransactionId()) {
  264.                         $xactService $this->get('integration.xact.outbound');
  265.                         $xactService->exportAddNotes(
  266.                             [
  267.                                 'transactionId' => $claim->getTransactionId(),
  268.                                 'userName' => $user->getFullName(),
  269.                                 'dateTime' => $contactDate->getTimeStamp(),
  270.                                 'noteType' => 'Contacted',
  271.                                 'notes' => $contactNote
  272.                             ]
  273.                         );
  274.                     }
  275.                     if($claim->getAssignmentId()){
  276.                         // commented as we not need to send first contact dateto symbility
  277.                       //  $symService = $this->get('integration.symbility.outbound');
  278.                        // $symService->pushFirstContactDate($contactDate->format('m/d/Y'.' '. $Time->format('H:i:s')), $claim->getClaimNumber(), $claim->getAssignmentId());
  279.                     }
  280.                 } else {
  281.                     $response['error'] = true;
  282.                     $response['data']['errors'][] = 'The date cannot be set in the future!';
  283.                 }
  284.             }else{
  285.                 $response['error'] = true;
  286.                 $response['data']['errors'][] = 'You are missing the date!';
  287.             }
  288.             return new JsonResponse($response);
  289.         }else{
  290.             throw new NotFoundHttpException("Couldn't find this claim!");
  291.         }
  292.     }
  293.     /**
  294.      * @Route("/update/set-review-date/{id}")
  295.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  296.      */
  297.     public function setReadyForReviewDate(Claim $claimRequest $request)
  298.     {
  299.         $response = ['error'=>false'data'=>[]];
  300.         if($claim){
  301.             $em $this->getDoctrine()->getManager();
  302.             $currentDate = new \DateTime();
  303.             $result $this->get('claim.status_update')->setReadyForReviewDate($claim$currentDate->format("m/d/Y h:i A"));
  304.             if($result) {
  305.                 $slog = new SLogger();
  306.                 $claim->setReportPDFStacking(1);
  307.                 $em->persist($claim);
  308.                 $em->flush();
  309.                 $slog->log($claim->getReportPDFStacking());
  310.                 if($claim->getAssignmentId()){
  311.                     $symService $this->get('integration.symbility.outbound');
  312.                     $symService->pushReadyForReview($claim->getClaimNumber(), $claim->getAssignmentId());
  313.                 }
  314.             }
  315.             return new JsonResponse($response);
  316.         }else{
  317.             throw new NotFoundHttpException("Couldn't find this claim!");
  318.         }
  319.     }
  320.     /**
  321.      * @Route("/update/undo-ready-review/{id}")
  322.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  323.      */
  324.     public function setUndoReadyReview(Claim $claimRequest $request)
  325.     {
  326.         $response = ['error'=>false'data'=>[]];
  327.         if($claim){
  328.             $this->get('claim.status_update')->undoReadyForReview($claim);
  329.             if($claim->getIsLocked()){
  330.                 $this->get('claim.status_update')->unlockClaim($claim);
  331.             }
  332.             return new JsonResponse($response);
  333.         }else{
  334.             throw new NotFoundHttpException("Couldn't find this claim!");
  335.         }
  336.     }
  337.     /**
  338.      * @Route("/update/reopen-claim/{id}")
  339.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  340.      */
  341.     public function reopenClaim(Claim $claimRequest $request)
  342.     {
  343.         $reason $request->request->get("reason");
  344.         $settlement_type_reopen $request->request->get("settlement_type_reopen");
  345.         $cwop_reason_reopen $request->request->get("cwop_reason_reopen");
  346.         $denial_description_line_reopen $request->request->get("denial_description_line_reopen");
  347.         $response = ['error'=>false'data'=>[]];
  348.         $strCWOPReason ='';
  349.         if($claim){
  350.             $this->get('claim.status_update')->reopenClaim($claim$reason);
  351.             if (!empty($claim->getCustomer()->isTpaUi())) {
  352.                 $em $this->container->get("doctrine.orm.entity_manager");
  353.                 if (!empty($cwop_reason_reopen)) {
  354.                     $objCwopReason $em->getRepository("ClaimManagementBundle:CwopReason")->findOneBy(['id' => $cwop_reason_reopen]);
  355.                     if (!empty($objCwopReason)) {
  356.                         $claim->setReopenCwopRsn($objCwopReason);
  357.                         $claim->setReopenDenialDescriptionLine($denial_description_line_reopen);
  358.                         $strCWOPReason $objCwopReason->getDescription();
  359.                     }
  360.                 }
  361.                 $objSettlementType $em->getRepository("ClaimManagementBundle:SettlementType")->find($settlement_type_reopen);
  362.                 if (!empty($objSettlementType)) {
  363.                     $claim->setReopenSettlementType($objSettlementType);
  364.                 }
  365.                 $em->persist($claim);
  366.                 $em->flush();
  367.                 $ClaimNote $this->container->get("claim.note_provider");
  368.                 if(!empty($strCWOPReason)){
  369.                     $ClaimNote->addClaimNote($claim"Reopen CWOP Reason ($strCWOPReason) added to the claim with Denial Description as ($denial_description_line_reopen)."false);
  370.                 }
  371.             }
  372.             return new JsonResponse($response);
  373.         }else{
  374.             throw new NotFoundHttpException("Couldn't find this claim!");
  375.         }
  376.     }
  377.     /**
  378.      * @Route("/update/reinspect-claim/{id}")
  379.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  380.      */
  381.     public function reInspectClaim(Claim $claimRequest $request)
  382.     {
  383.         $reason $request->request->get("reason");
  384.         $response = ['error'=>false'data'=>[]];
  385.         if($claim){
  386.             $this->get('claim.status_update')->reInspectClaim($claim$reason);
  387.             return new JsonResponse($response);
  388.         }else{
  389.             throw new NotFoundHttpException("Couldn't find this claim!");
  390.         }
  391.     }
  392.     /**
  393.      * @Route("/update/set-in-progress/{id}")
  394.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  395.      */
  396.     public function setInProgress(Claim $claimRequest $request)
  397.     {
  398.         $response = ['error'=>false'data'=>[]];
  399.         if($claim){
  400.             $this->get('claim.status_update')->setInProgress($claim);
  401.             return new JsonResponse($response);
  402.         }else{
  403.             throw new NotFoundHttpException("Couldn't find this claim!");
  404.         }
  405.     }
  406.     /**
  407.      * @Route("/create/claim-note/{id}")
  408.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  409.      */
  410.     public function addClaimNote(Claim $claimRequest $request)
  411.     {
  412.         # logged in user
  413.         $user $this->get('security.token_storage')->getToken()->getUser();
  414.         $response = ['error'=>false'data'=>[]];
  415.         $comment $request->request->get('comment');
  416.         $outbound $request->request->get('outbound');
  417.         $send false;
  418.         if( $outbound != "" ){
  419.             $send $outbound == 1;
  420.         }
  421.         # Check for post #
  422.         if ($comment) {
  423.             if ($claim) {
  424.                 /**
  425.                  * @var $file UploadedFile
  426.                  */
  427.                 $file $request->files->all()['media'] ?? null;
  428.                 $claimNoteMediaService $this->get('claim_note.media');
  429.                 $newFilename uniqid();
  430.                 if ($file instanceof UploadedFile) {
  431.                     $mediaValid $claimNoteMediaService->validateClaimNoteMedia($file);
  432.                     if ($mediaValid['error']) {
  433.                         return new JsonResponse(['error' => $mediaValid['message']]);
  434.                     }
  435.                     $copyMedia $claimNoteMediaService->copyClaimNoteMedia($file$newFilename$claim->getId());
  436.                     if ($copyMedia !== true) {
  437.                         return new JsonResponse(['error' => (is_bool($copyMedia) ? "Failed to copy the uploaded media" $copyMedia)]);
  438.                     }
  439.                 }
  440.                 $em $this->getDoctrine()->getManager();
  441.                 $claimNote $this->get('claim.note_provider')->addClaimNote($claim$comment);
  442.                 $em->refresh($claimNote);
  443.                 if ($file instanceof UploadedFile) {
  444.                     try {
  445.                         $em->getRepository(ClaimNoteMedia::class)->createClaimNoteMedia(
  446.                             $claim->getId(),
  447.                             $claimNote->getId(),
  448.                             $file->getClientOriginalExtension(),
  449.                             $file->getClientOriginalName(),
  450.                             sprintf("%s.%s"$newFilename$file->getClientOriginalExtension()),
  451.                             $file->getClientMimeType()
  452.                         );
  453.                     } catch (\Exception $exception) {
  454.                         $em->remove($claimNote);
  455.                         return new JsonResponse([
  456.                             'error' => sprintf("Failed to store ClaimNoteMedia Error: %s"$exception->getMessage())
  457.                         ]);
  458.                     }
  459.                 }
  460.                 # log note to xact
  461.                 if($send && $claim->getTransactionId()){
  462.                     $xactService $this->get('integration.xact.outbound');
  463.                     $xactService->exportAddNotes(
  464.                         [
  465.                             'transactionId' => $claim->getTransactionId(),
  466.                             'userName' => $user->getFullName(),
  467.                             'dateTime' => time(),
  468.                             'notes' => $comment
  469.                         ]
  470.                     );
  471.                 }
  472.                 if($send && $claim->getAssignmentId()){
  473.                     $symService $this->get('integration.symbility.outbound');
  474.                     $symService->addNotes(
  475.                         [
  476.                             'transactionId' => $claim->getClaimNumber(),
  477.                             'userName' => $user->getFullName(),
  478.                             'dateTime' => time(),
  479.                             'assignmentID' =>$claim->getAssignmentId(),
  480.                             'notes' => $comment
  481.                         ]
  482.                     );
  483.                 }
  484.                 
  485.                 return new JsonResponse($response);
  486.             } else {
  487.                 throw new NotFoundHttpException("Couldn't find this claim!");
  488.             }
  489.         }else{
  490.             return new JsonResponse(['error' => 'File Note\'s Cannot Be Blank']);
  491.         }
  492.     }
  493.     /**
  494.      * @Route("/update/lock/{id}")
  495.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  496.      */
  497.     public function lockClaim(Claim $claim)
  498.     {
  499.         $this->get('claim.assignment')->assignCurrentUserAsExaminer($claim);
  500.         $this->get('claim.status_update')->lockClaim($claim);
  501.         return new JsonResponse(['error'=>false]);
  502.     }
  503.     /**
  504.      * @Route("/update/unlock/{id}")
  505.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  506.      */
  507.     public function unlockClaim(Claim $claim)
  508.     {
  509.         $this->get('claim.status_update')->unlockClaim($claim);
  510.         return new JsonResponse(['error'=>false]);
  511.     }
  512.     /**
  513.      * @Route("/update/in-progress/{id}")
  514.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  515.      */
  516.     public function markInExaminerProgress(Claim $claim)
  517.     {
  518.         $this->get('claim.status_update')->markInProgressExaminer($claim);
  519.         return new JsonResponse(['error'=>false]);
  520.     }
  521.     /**
  522.      * @Route("/update/claim-status/{id}")
  523.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  524.      */
  525.     public function updateClaimStatus(Claim $claimRequest $request)
  526.     {
  527.         $status_id $request->request->get('status_id');
  528.         if($status_id==97){
  529.             $status_id=30;
  530.             $em $this->container->get("doctrine.orm.entity_manager");
  531.             $stmt $em->getConnection()->prepare("UPDATE claim SET date_closed = NOW(), updated_at = NOW() WHERE id = ? ");
  532.             $stmt->execute([$claim->getId()]);
  533.         }//Claim Tech closing
  534.         $this->get('claim.status_update')->changeStatus($claim,$status_id);
  535.         return new JsonResponse(['error'=>false]);
  536.     }
  537.     /**
  538.      * @Route("/update/examiner-hold/{id}")
  539.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  540.      */
  541.     public function markInExaminerHold(Claim $claim)
  542.     {
  543.         $this->get('claim.status_update')->markInHoldExaminer($claim);
  544.         return new JsonResponse(['error'=>false]);
  545.     }
  546.     /**
  547.      * @Route("/update/qa-approved/{id}")
  548.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  549.      */
  550.     public function markQaApproved($claim)
  551.     {
  552.         $resource $this->get('security.token_storage')->getToken()->getUser();
  553.         $currentDate = new \DateTime();
  554.         $this->get('claim.status_update')->markQaApproved$claim$resource$currentDate->format("m/d/Y h:i A") );
  555.         return new JsonResponse(['error'=>false]);
  556.     }
  557.     /**
  558.      * @Route("/update/qa-rejected/{id}")
  559.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  560.      */
  561.     public function markQaRejected($claimRequest $request)
  562.     {
  563.         $resource $this->get('security.token_storage')->getToken()->getUser();
  564.         $reason $request->request->get('reason');
  565.         $reasonCodeIds $request->request->get('reason_code');
  566.         $ReasonCodeIds = array();
  567.         if (strpos($reasonCodeIds',') !== false) {
  568.             $ReasonCodeIds explode(","$reasonCodeIds);
  569.         }else{
  570.             $ReasonCodeIds[0]= $reasonCodeIds;
  571.         }
  572.         $em $this->getDoctrine()->getManager();
  573.         $currentDate = new \DateTime();
  574.         $ClaimReportRepo $em->getRepository("ClaimManagementBundle:XactClaimReport");
  575.         $ClaimReport $ClaimReportRepo->findOneBy(['claimNumber' => $claim->getClaimNumber()]);
  576.         if (!empty($ClaimReport)) {
  577.             $ClaimReport->setReturnedDate($currentDate);
  578.             $em->persist($ClaimReport);
  579.             $em->flush();
  580.         }
  581.         $this->get('claim.status_update')->markQaRejected$claim$resource,$reason$ReasonCodeIds$currentDate->format("m/d/Y h:i A") );
  582.         return new JsonResponse(['error'=>false]);
  583.     }
  584.     /**
  585.      * @Route("/claim-diary/complete/{diary_id}", defaults={"diary_id" = null})
  586.      */
  587.     public function diaryComplete($diary_id)
  588.     {
  589.         $dispatch $this->get('event_dispatcher');
  590.         $diaryEntry $this->getDoctrine()->getRepository('ClaimManagementBundle:DiaryEntry')->find($diary_id);
  591.         $diaryEntry->setStatus(1);
  592.         $em $this->getDoctrine()->getManager();
  593.         $em->persist($diaryEntry);
  594.         $em->flush();
  595.         /**
  596.          * @date 08/11/2017
  597.          *
  598.          * Implementing service to push a note to the Claim
  599.          *
  600.          */
  601.         $NoteService $this->get('claim.note_provider');
  602.         // Todo ClaimDiaryAssignedEvent listener for this event
  603.         $dispatch->dispatch(ClaimDiaryCompleteEvent::NAME, new ClaimDiaryCompleteEvent($diaryEntry));
  604.         $NoteService->addClaimNote$diaryEntry->getClaim(), "Diary entry '" $diaryEntry->getDescription() . "' was completed!"false,70 );
  605.         return new JsonResponse(['diary'=> $diaryEntry->getId()]);
  606.     }
  607.     /**
  608.      * @Route("/create/claim-diary/{claim_id}/{diary_id}", defaults={"diary_id" = null})
  609.      */
  610.     public function addNewDiaryEntry($claim_id$diary_idRequest $request)
  611.     {
  612.         $dispatch $this->get('event_dispatcher');
  613.         // This is the EM we'll use
  614.         $em $this->getDoctrine()->getManager();
  615.         $LoggedInUser $this->container->get("security.token_storage")->getToken()->getUser();
  616.         if($claim_id){
  617.             $claim $this->getDoctrine()->getRepository('ClaimManagementBundle:Claim')->find($claim_id);
  618.             $diaryFormData $request->request->get('diary_form');
  619.             $isUpdate false;
  620.             if ($diary_id) {
  621.                 $isUpdate true;
  622.                 $diary $this->getDoctrine()->getRepository('ClaimManagementBundle:DiaryEntry')->find($diary_id);
  623.             } else {
  624.                 $diary = new DiaryEntry();
  625.             }
  626.             $diaryForm $this->createFormDiaryFormType::class, $diary, ['claim_id' => $claim_id]);
  627.             $diaryForm->submit$diaryFormData );
  628.             if($diaryForm->isValid()){
  629.                 /** @var DiaryEntry $DiaryEntry */
  630.                 $DiaryEntry $diaryForm->getData();
  631.                 $DiaryEntry->setClaim($claim);
  632.                 $DiaryEntry->setAuthor($LoggedInUser);
  633.                 $DiaryEntry->setStatus(0);
  634.                 $DiaryEntry->setDateCreated( new \DateTime() );
  635.                 /**
  636.                  * @date 08/11/2017
  637.                  *
  638.                  * Implementing service to push a note to the Claim
  639.                  *
  640.                  */
  641.                 $NoteService $this->get('claim.note_provider');
  642.                 // Todo ClaimDiaryAssignedEvent listener for this event
  643.                 if ($isUpdate == false) {
  644.                     $dispatch->dispatch(ClaimDiaryAssignedEvent::NAME, new ClaimDiaryAssignedEvent($diary));
  645.                     $NoteService->addClaimNote($DiaryEntry->getClaim(), "Diary entry '" $DiaryEntry->getDescription() . "' was created!"false70);
  646.                 } else {
  647.                     $NoteService->addClaimNote($DiaryEntry->getClaim(), "Diary entry '" $DiaryEntry->getDescription() . "' was updated!"false70);
  648.                 }
  649.                 /**
  650.                  * @date 08/31/2017
  651.                  *
  652.                  * Implementing multiple diary resources (if they exist)
  653.                  *
  654.                  */
  655.                 $other_resources $request->request->get('extra-diary-resources');
  656.                 if($other_resources && !empty($other_resources)){
  657.                     foreach($other_resources as $resource_id){
  658.                         $ActualResource $em->find("ResourceManagementBundle:Resource"$resource_id);
  659.                         $DiaryResource = new DiaryOtherResource();
  660.                         $DiaryResource->setDateAdded( new \DateTime() );
  661.                         $DiaryResource->setDiaryEntry$DiaryEntry );
  662.                         $DiaryResource->setResource$ActualResource );
  663.                         $em->persist($DiaryResource);
  664.                     }
  665.                 }
  666.                 $em->persist($DiaryEntry);
  667.                 $em->flush();
  668.                 $response['error'] = false;
  669.             }else{
  670.                 $response = [];
  671.                 $response['error'] = true;
  672.                 $response['formError'] = (string)$diaryForm->getErrors(true);
  673.                 foreach($diaryForm as $formField){
  674.                     $errorString = (string)$formField->getErrors();
  675.                     if($errorString != ""){
  676.                         $response['data']['errors'][] = [
  677.                             'id' => $diaryForm->getName()."_".$formField->getName(),
  678.                             'text' => $errorString
  679.                         ];
  680.                     }
  681.                 }
  682.             }
  683.             return new JsonResponse($response);
  684.         }else{
  685.             throw new NotFoundHttpException("Couldn't find this claim!");
  686.         }
  687.     }
  688.     /**
  689.      * @Route("/create/auto_disbursement")
  690.      */
  691.     public function addNewAutoDisbursement(Request $request)
  692.     {
  693.         // This is the EM we'll use
  694.         $em $this->getDoctrine()->getManager();
  695.         $claimId $request->request->get('claim');
  696.         $lastIdentifier $request->request->get('lastIdentifier');
  697.         # JsonResponseObj
  698.         $rtnVal = [
  699.             'error' => false,
  700.             'errors' => [],
  701.             'data' => []
  702.         ];
  703.         $nHasQty 0;
  704.         for($i 0$i $lastIdentifier$i++) {
  705.             $autoExpense $request->request->get('auto-expense-' $i);
  706.             if(!$autoExpense) {
  707.                 # if section of form doesnt exist, stop
  708.                 return new JsonResponse($rtnVal);
  709.             } else if ($autoExpense['qty'] == "") {
  710.                 # if quantity was not set, do not submit
  711.                 $rtnVal['error'] = true;
  712.                 $rtnVal['errors'][] = "Must set a quantity!";
  713.             } else {
  714.                 $nHasQty++;
  715.                 # set values
  716.                 $cost  floatval(ltrim($autoExpense['amount'], '$'));
  717.                 $description $autoExpense['description'];
  718.                 $qty $autoExpense['qty'];
  719.                 $customerExpense $autoExpense['customerExpense'];
  720.                 $expense $autoExpense['expense'];
  721.                 $resource $this->get('security.token_storage')->getToken()->getUser()->getId();
  722.                 # prepared statement for fast entries
  723.                 /*$sql = "INSERT INTO disbursement
  724.                     (claim_id, invoice_id, resource_id, expense_id, customer_expense_id, quantity, cost, description, dateCreated)
  725.                         VALUES
  726.                     ('" . $claimId . "', NULL,'" . $resource . "','" . $expense . "', '" . $customerExpense . "', '" . $qty . "', '" . $cost . "', '" . $description . "', NOW())";
  727.                 $stmt = $em->getConnection()->prepare($sql);
  728.                 $stmt->execute();*/
  729.                 $disbursement = new Disbursement();
  730.                 $disbursement->setClaim$em->find("ClaimManagementBundle:Claim"$claimId) );
  731.                 $disbursement->setResource$em->find("ResourceManagementBundle:Resource"$resource) );
  732.                 $disbursement->setExpense$em->find("CompanyManagementBundle:Expense"$expense) );
  733.                 $disbursement->setCustomerExpense$em->find("InvoiceManagementBundle:CustomerExpense"$customerExpense) );
  734.                 $disbursement->setQuantity($qty);
  735.                 $disbursement->setCost($cost);
  736.                 $disbursement->setDescription$description );
  737.                 $disbursement->setDateCreated( new \DateTime() );
  738.                 $em->persist($disbursement);
  739.                 $em->flush();
  740.             }
  741.         }
  742.         //Give Error only if none of expenses have Qty
  743.         if (!empty($nHasQty)) {
  744.             $rtnVal = [
  745.                 'error' => false,
  746.                 'errors' => [],
  747.                 'data' => []
  748.             ];
  749.         }
  750.         //Give Error only if none of expenses have Qty
  751.         return new JsonResponse($rtnVal);
  752.     }
  753.     /**
  754.      * @Route("/create/expense/{id}")
  755.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  756.      */
  757.     public function createClaimExpenseAction($claimRequest $request)
  758.     {
  759.         // This is the EM we'll use
  760.         $em $this->getDoctrine()->getManager();
  761.         // This extract gets submitted through the form builder
  762.         $time_log $request->request->get('disbursement_time_log');
  763.         // This extract gets used only if the form submitted fully (to complete adding a new disbursement)
  764.         $time_log_extras $request->request->get('disbursement_other');
  765.         
  766.         if ($time_log['expense'] < 1) {
  767.             $errors2 = array();
  768.             $data = [
  769.                 "errors" => array()
  770.             ];
  771.             $nextError = array();
  772.             $nextError['id'] = "choose-expense";
  773.             $nextError['text'] = "Please choose an expense.";
  774.             $data['errors'][] = $nextError;
  775.             # return json error objects
  776.             $retVal = array(
  777.                 "status" => "fail",
  778.                 "error_msgs" => $errors2,
  779.                 "error" => true,
  780.                 "data" => $data
  781.             );
  782.             return new JsonResponse($retVal);
  783.         }
  784.         # validate the resource on expense model with resource which assignments
  785.         $resourceId $time_log['resource'];
  786.         /** @var \PDO $pdo */
  787.         $pdo $em->getConnection();
  788.         $chkAdjusterAssinged $pdo->prepare("SELECT resource_id, assignment_party_id, is_primary_adjuster  FROM assignments WHERE claim_id = ? AND resource_id = ? AND is_current_assignment = 1;");
  789.         $chkAdjusterAssinged->execute([$claim->getId(), $resourceId]);
  790.         if ($chkAdjusterAssinged->rowCount() == 0) {
  791.             # return json error objects
  792.             $nextError = array();
  793.             $nextError['id'] = "resource";
  794.             $nextError['text'] = "Resource set for expense is not assinged to claim.";
  795.             $data['errors'][] = $nextError;
  796.             $retVal = array(
  797.                 "status" => "fail",
  798.                 "error_msgs" => array(),
  799.                 "error" => true,
  800.                 "data" => $data
  801.             );
  802.             return new JsonResponse($retVal);
  803.         }
  804.         // Create the form
  805.         $form $this->createForm(DisbursementTimeLogType::class, new Disbursement(), array('claim_id' => $claim->getId()));
  806.         /**
  807.          * @date 8/14/2017
  808.          *
  809.          * Fix to pre-select a date even if one has'nt been chosen in the front end.
  810.          * We always default to today's date.
  811.          */
  812.         /*$today = new \DateTime();
  813.         $time_log['dateCreated'] = $today->format("Y-m-d");*/
  814.         $form->submit($time_log);
  815.         if($form->isValid()){  // if form is valid
  816.             /** @var Disbursement $Disbursement */
  817.             $Disbursement $form->getData();
  818.             $Disbursement->setClaim($claim);
  819.             if( $time_log_extras['customerExpense'] > ){
  820.                 $CustomerExpense $em->find('InvoiceManagementBundle:CustomerExpense'intval($time_log_extras['customerExpense']));
  821.                 $Disbursement->setCustomerExpense($CustomerExpense);
  822.             }
  823.             $Disbursement->setCost($time_log['cost']);
  824.             $Disbursement->setExcludeInvoicing($Disbursement->getExpense()->getExcludeInvoicing());// for excluding when expense default rate is 100
  825.             $em->persist($Disbursement);
  826.             $em->flush();
  827.             if (!$Disbursement->getExpense()->getExcludeInvoicing()) {
  828.                 # Update the Discount Amounts on the Disbursements, such as DiscountQty and MaxAmounts
  829.                 $invoiceService $this->container->get("app.invoice_helper");
  830.                 $invoiceService->updateDisbursementDiscounts($claim);
  831.             }
  832.             $ClaimNote $this->container->get("claim.note_provider");
  833.             //Status note = 69 Claim Disbursement
  834.             $ClaimNote->addClaimNote($claim"Disbursement " $Disbursement->getExpense()->getExpenseName() . " was added on Claim."false69);
  835.             # pass json response success
  836.             $retVal = array(
  837.                 "status" => "success",
  838.                 "error_msgs" => []
  839.             );
  840.             return new JsonResponse($retVal);
  841.         }else{  // if form has errors
  842.             $data = array();
  843.             $errors2 = array();
  844.             $errorsArr = array();
  845.             # Get Error Messages
  846.             $error_str = (string)$form->getErrors(truefalse);
  847.             $slog = new SLogger();
  848.             $slog->log("error_str at 2: ");
  849.             $slog->log($error_str);
  850.             $errorsArr2 explode("\n"$error_str);
  851.             foreach ($errorsArr2 as $getError) {
  852.                 if (trim($getError) != "") {
  853.                     $errorsArr[] = trim($getError);
  854.                 }
  855.             }
  856.             $i 1;
  857.             if (count($errorsArr) > 0) {
  858.                 $data = [
  859.                     "errors" => array()
  860.                 ];
  861.                 foreach ($errorsArr as $getItem) {
  862.                     if ($i == 1) {
  863.                         $nextError = array();
  864.                         $nextError['id'] = substr($getItem0strlen($getItem) - 1);
  865.                     } else {
  866.                         $nextError['text'] = $getItem;
  867.                         $data['errors'][] = $nextError;
  868.                     }
  869.                     if ($i 2) {
  870.                         $i++;
  871.                     } else {
  872.                         $i 1;
  873.                     }
  874.                 }
  875.             }
  876.             # return json error objects
  877.             $retVal = array(
  878.                 "status" => "fail",
  879.                 "error_msgs" => $errors2,
  880.                 "error" => true,
  881.                 "data" => $data
  882.             );
  883.             return new JsonResponse($retVal);
  884.         }
  885.     }
  886.     /**
  887.      * @Route("/update/expense/{claimId}/{disbursementId}")
  888.      */
  889.     public function updateClaimExpenseAction(Request $request$claimId$disbursementId)
  890.     {
  891.         // This is the EM we'll use
  892.         $em $this->getDoctrine()->getManager();
  893.         $claim $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
  894.         $disbursement $em->getRepository("InvoiceManagementBundle:Disbursement")->find($disbursementId);
  895.         ## Code checks if changes were made to Claim Object ##
  896.         # Get Current Resource on DB
  897.         $disbursement_compare = new DisbursementCompareHelper($em);
  898.         # this function must be called before $form->getData()
  899.         $disbursement_compare->setCurDisbursement($disbursement);
  900.         // This extract gets submitted through the form builder
  901.         $time_log $request->request->get('disbursement_time_log');
  902.         // This extract gets used only if the form submitted fully (to complete adding a new disbursement)
  903.         $time_log_extras $request->request->get('disbursement_other');
  904.         // This extract gets used only if the expense cost is not editable
  905.         $editable $request->request->get('is_editable');
  906.         // Create the form
  907.         $form $this->createFormDisbursementTimeLogType::class, $disbursement, array('claim_id' => $claimId));
  908.         $form->submit($time_log);
  909.         // backend validation to validate cost cant be changed
  910.         if ($editable != 1) {
  911.             $cost $time_log['cost'];
  912.             if ($cost != $disbursement->getCost()) {
  913.                 $errors2 = array();
  914.                 $data = [
  915.                     "errors" => array()
  916.                 ];
  917.                 $nextError = array();
  918.                 $nextError['id'] = "not-editable";
  919.                 $nextError['text'] = "The cost is not editable for this claim.";
  920.                 $data['errors'][] = $nextError;
  921.                 # return json error objects
  922.                 $retVal = array(
  923.                     "status" => "fail",
  924.                     "error_msgs" => $errors2,
  925.                     "error" => true,
  926.                     "data" => $data
  927.                 );
  928.                 return new JsonResponse($retVal);
  929.             }
  930.         }
  931.         if ($time_log['expense'] < 1) {
  932.             $errors2 = array();
  933.             $data = [
  934.                 "errors" => array()
  935.             ];
  936.             $nextError = array();
  937.             $nextError['id'] = "choose-expense";
  938.             $nextError['text'] = "Please choose an expense.";
  939.             $data['errors'][] = $nextError;
  940.             # return json error objects
  941.             $retVal = array(
  942.                 "status" => "fail",
  943.                 "error_msgs" => $errors2,
  944.                 "error" => true,
  945.                 "data" => $data
  946.             );
  947.             return new JsonResponse($retVal);
  948.         }
  949.         if($form->isValid()){  // if form is valid
  950.             /** @var Disbursement $Disbursement */
  951.             $Disbursement $form->getData();
  952.             if( $time_log_extras['customerExpense'] > ){
  953.                 $CustomerExpense $em->find('InvoiceManagementBundle:CustomerExpense'intval($time_log_extras['customerExpense']));
  954.                 $Disbursement->setCustomerExpense($CustomerExpense);
  955.             }
  956.             if( $time_log['expense'] > ){
  957.                 $Expense $em->find("CompanyManagementBundle:Expense"intval($time_log['expense']));
  958.                 $Disbursement->setExpense($Expense);
  959.             }
  960.             $Disbursement->setExcludeInvoicing($Disbursement->getExpense()->getExcludeInvoicing());// for excluding when expense default rate is 100
  961.             # Get Submitted Form Claim Object
  962.             $disbursement_compare->setNewDisbursement($Disbursement);
  963.             # Compare 2 objects to see if there were any changes made
  964.             $hasChanges $disbursement_compare->compareObjects();
  965.             if ($hasChanges) {
  966.                 $em->persist($Disbursement);
  967.                 $em->flush();
  968.                 $ClaimNote $this->container->get("claim.note_provider");
  969.                 //Status note = 69 Claim Disbursement
  970.                 $ClaimNote->addClaimNote($claim"Disbursement " $Disbursement->getExpense()->getExpenseName() . " was updated on Claim. " implode(" "$disbursement_compare->changeLog), false69);
  971.             }
  972.             if (!$Disbursement->getExpense()->getExcludeInvoicing()) {
  973.                 # Update the Discount Amounts on the Disbursements, such as DiscountQty and MaxAmounts
  974.                 $invoiceService $this->container->get("app.invoice_helper");
  975.                 $invoiceService->updateDisbursementDiscounts($claim);
  976.             }
  977.             # pass json response success
  978.             $retVal = array(
  979.                 "status" => "success",
  980.                 "error" => false
  981.             );
  982.             return new JsonResponse($retVal);
  983.         }else{  // if form has errors
  984.             # Catch errors in a array
  985.             $response = [];
  986.             $response['error'] = true;
  987.             $response['formError'] = (string)$form->getErrors(true);
  988.             # foreach through each field for validation
  989.             foreach($form as $formField){
  990.                 $errorString = (string)$formField->getErrors();
  991.                 if($errorString != ""){
  992.                     $response['data']['errors'][] = [
  993.                         'id' => $form->getName()."_".$formField->getName(),
  994.                         'text' => $errorString
  995.                     ];
  996.                 }
  997.             }
  998.             return new JsonResponse($response);
  999.         }
  1000.     }
  1001.     /**
  1002.      * @Route("/make/document_templates")
  1003.      */
  1004.     public function makeGlobalDocumentTemplates()
  1005.     {
  1006.         $kernel $this->container->get("kernel");
  1007.         $file_path $kernel->getRootDir() . "/Resources/doc_library";
  1008.         $finder = new Finder();
  1009.         $finder->files()->in($file_path);
  1010.         $fileArr = array();
  1011.         foreach ($finder as $file) {
  1012.             $file_name $file->getRelativePathname();
  1013.             $file_path $file->getRealPath();
  1014.             $fileNameArr explode("-"$file_name);
  1015.             $index $fileNameArr[0];
  1016.             $fileArr[$index] = [
  1017.                 "name" => $fileNameArr[1],
  1018.                 "path" => $file_path
  1019.             ];
  1020.         }
  1021.         ksort($fileArr);
  1022.         $idsArr = [
  1023.             "1" => 638,
  1024.             "2" => 639,
  1025.             "3" => 640,
  1026.             "4" => 641,
  1027.             "5" => 642,
  1028.             "6" => 643,
  1029.             "7" => 644
  1030.         ];
  1031.         $file_manager $this->container->get("app.file_manager");
  1032.         foreach ($fileArr as $index => $getFile) {
  1033.             $fh fopen($getFile['path'], 'r');
  1034.             $content fread($fhfilesize($getFile['path']));
  1035.             fclose($fh);
  1036.             # Convert HTML Content to PDF file in /tmp folder
  1037.             $get_num md5(uniqid());
  1038.             $new_file_name $get_num;
  1039.             $new_file_path "/tmp/" $new_file_name;
  1040.             $fh1 fopen($new_file_path'w');
  1041.             fwrite($fh1$content);
  1042.             fclose($fh1);
  1043.             # Create file from temp file using file manager service
  1044.             $useFile['new_file_name'] = $new_file_name;
  1045.             $useFile['used_by_module'] = "DocumentLibraryGlobal";
  1046.             $useFile['name'] = $new_file_name;
  1047.             $useFile['type'] = "text/html";
  1048.             $useFile['error'] = 0;
  1049.             $useFile['size'] = filesize($new_file_path);
  1050.             $useFile['file_ext'] = "twig";
  1051.             # Save file by passing file object, id, and entity name
  1052.             $file_manager->saveFile($useFile$idsArr[$index], "DocumentLibraryGlobal");
  1053.         }
  1054.         dump("Script completed");
  1055.         die;
  1056.     }
  1057.     /**
  1058.      * @Route("/make/document_templates2")
  1059.      */
  1060.     public function makeGlobalDocumentTemplates2()
  1061.     {
  1062.         $kernel $this->container->get("kernel");
  1063.         $file_path $kernel->getRootDir() . "/Resources/doc_library2";
  1064.         $finder = new Finder();
  1065.         $finder->files()->in($file_path);
  1066.         $fileArr = array();
  1067.         foreach ($finder as $file) {
  1068.             $file_name $file->getRelativePathname();
  1069.             $file_path $file->getRealPath();
  1070.             $fileNameArr explode("-"$file_name);
  1071.             $index $fileNameArr[0];
  1072.             $fileArr[$index] = [
  1073.                 "name" => $fileNameArr[1],
  1074.                 "path" => $file_path
  1075.             ];
  1076.         }
  1077.         ksort($fileArr);
  1078.         $idsArr = [
  1079.             "8" => 645,
  1080.             "9" => 646,
  1081.             "10" => 647
  1082.         ];
  1083.         $file_manager $this->container->get("app.file_manager");
  1084.         foreach ($fileArr as $index => $getFile) {
  1085.             $fh fopen($getFile['path'], 'r');
  1086.             $content fread($fhfilesize($getFile['path']));
  1087.             fclose($fh);
  1088.             # Convert HTML Content to PDF file in /tmp folder
  1089.             $get_num md5(uniqid());
  1090.             $new_file_name $get_num;
  1091.             $new_file_path "/tmp/" $new_file_name;
  1092.             $fh1 fopen($new_file_path'w');
  1093.             fwrite($fh1$content);
  1094.             fclose($fh1);
  1095.             # Create file from temp file using file manager service
  1096.             $useFile['new_file_name'] = $new_file_name;
  1097.             $useFile['used_by_module'] = "DocumentLibraryGlobal";
  1098.             $useFile['name'] = $new_file_name;
  1099.             $useFile['type'] = "text/html";
  1100.             $useFile['error'] = 0;
  1101.             $useFile['size'] = filesize($new_file_path);
  1102.             $useFile['file_ext'] = "twig";
  1103.             # Save file by passing file object, id, and entity name
  1104.             $file_manager->saveFile($useFile$idsArr[$index], "DocumentLibraryGlobal");
  1105.         }
  1106.         dump("Script completed");
  1107.         die;
  1108.     }
  1109.     /**
  1110.      * @Route("/share/claim-resources/{id}")
  1111.      * @Method(methods={"POST"})
  1112.      * @deprecated
  1113.      */
  1114.     public function completeShareResource(Request $requestClaim $claim)
  1115.     {
  1116.         $em $this->container->get("doctrine.orm.entity_manager");
  1117.         if ($claim == null) {
  1118.             throw $this->createNotFoundException("Claim does not exist");
  1119.         }
  1120.         # Request Adjuster Info
  1121.         $roles $request->request->get("roles");
  1122.         $AdjustersArr $roles;
  1123.         # Check if duplicate adjusters have been passed
  1124.         $hasDuplicates false;
  1125.         $allAdjusters = array();
  1126.         $duplicateAdjusterType "";
  1127.         foreach ($AdjustersArr as $adjusterType => $adjusterIds) {
  1128.             foreach ($adjusterIds as $adjusterId) {
  1129.                 if (in_array($adjusterId$allAdjusters)) {
  1130.                     $hasDuplicates true;
  1131.                     $duplicateAdjusterType $adjusterType;
  1132.                     break;
  1133.                 }
  1134.                 $allAdjusters[] = $adjusterId;
  1135.             }
  1136.         }
  1137.         if ($hasDuplicates) {  // if duplicate adjusters were sent
  1138.             # Send Back Error
  1139.             $errors2 = array();
  1140.             $data = [
  1141.                 "errors" => array()
  1142.             ];
  1143.             $nextError = array();
  1144.             $nextError['id'] = $duplicateAdjusterType;
  1145.             $nextError['text'] = "You cannot assign the same Adjuster more than once on this Claim.";
  1146.             $data['errors'][] = $nextError;
  1147.             $response = array(
  1148.                 "result" => "fail",
  1149.                 "error_msgs" => $errors2,
  1150.                 "error" => true,
  1151.                 "data" => $data
  1152.             );
  1153.             return new JsonResponse($response);
  1154.         } else {
  1155.             # First Validate that all adjusters can be added
  1156.             $allErrors = array();
  1157.             foreach ($AdjustersArr as $adjusterType => $adjusterIds) {
  1158.                 $getAdjustertype $adjusterType;
  1159.                 $role $em->getRepository("ClaimManagementBundle:ClaimResourceRole")->findOneBy([
  1160.                     "role" => $getAdjustertype
  1161.                 ]);
  1162.                 foreach ($adjusterIds as $adjusterId) {
  1163.                     if ($getAdjustertype == "Field Adjuster" || $getAdjustertype == "Desk Adjuster") {  // if field or desk
  1164.                         $adjusters $em->getRepository("ClaimManagementBundle:ClaimResource")->getAdjustersByClaim($claim);
  1165.                         if (count($adjusters) == 0) {  // if no adjusters
  1166.                             # Set Primary
  1167.                             $isPrimary true;
  1168.                         } else {
  1169.                             if ($getAdjustertype == "Field Adjuster") {  // if current type is field adjuster
  1170.                                 $fieldAdjustersCount 0;
  1171.                                 foreach ($adjusters as $getAdjuster) {
  1172.                                     if ($getAdjuster->getResource->getRole()->getRole() == "Field Adjuster") {
  1173.                                         $fieldAdjustersCount++;
  1174.                                     }
  1175.                                 }
  1176.                                 if ($fieldAdjustersCount == 0) {  // if there are no other field adjusters
  1177.                                     # Set Primary
  1178.                                     $isPrimary true;
  1179.                                 } else {
  1180.                                     $isPrimary false;
  1181.                                 }
  1182.                             } else {
  1183.                                 $isPrimary false;
  1184.                             }
  1185.                         }
  1186.                     } else {
  1187.                         $isPrimary false;
  1188.                     }
  1189.                     $currentResource $em->getRepository("ResourceManagementBundle:Resource")->find($adjusterId);
  1190.                     # Attempt assigning the RESOURCE to the CLAIM
  1191.                     $retVal $this->get('claim.assignment')->validateAssignResourceToClaim(
  1192.                         $claim,
  1193.                         $currentResource,
  1194.                         $role,
  1195.                         new \DateTime(),
  1196.                         $isPrimary,
  1197.                         $currentResource->getPayrollId()
  1198.                     );
  1199.                     $errors $this->get('claim.assignment')->getErrors();
  1200.                     $allErrors $errors;
  1201.                     if ($retVal == false) {   // if adding some of the adjusters returned errors
  1202.                         # Send Error Messages
  1203.                         if (!empty($allErrors)) {
  1204.                             $errors2 = array();
  1205.                             $data = [
  1206.                                 "errors" => array()
  1207.                             ];
  1208.                             $nextError = array();
  1209.                             $nextError['id'] = "";
  1210.                             $nextError['text'] = implode("\n"$allErrors);
  1211.                             $data['errors'][] = $nextError;
  1212.                             $response = array(
  1213.                                 "result" => "fail",
  1214.                                 "error_msgs" => $errors2,
  1215.                                 "error" => true,
  1216.                                 "data" => $data
  1217.                             );
  1218.                             return new JsonResponse($response);
  1219.                             exit;
  1220.                         }
  1221.                     }
  1222.                 }
  1223.             }
  1224.             # If all adjusters can be added, go ahead and assign them
  1225.             foreach ($AdjustersArr as $adjusterType => $adjusterIds) {
  1226.                 $getAdjustertype $adjusterType;
  1227.                 $role $em->getRepository("ClaimManagementBundle:ClaimResourceRole")->findOneBy([
  1228.                     "role" => $getAdjustertype
  1229.                 ]);
  1230.                 foreach ($adjusterIds as $adjusterId) {
  1231.                     if ($getAdjustertype == "Field Adjuster" || $getAdjustertype == "Desk Adjuster") {  // if field or desk
  1232.                         $adjusters $em->getRepository("ClaimManagementBundle:ClaimResource")->getAdjustersByClaim($claim);
  1233.                         if (count($adjusters) == 0) {  // if no adjusters
  1234.                             # Set Primary
  1235.                             $isPrimary true;
  1236.                         } else {
  1237.                             if ($getAdjustertype == "Field Adjuster") {  // if current type is field adjuster
  1238.                                 $fieldAdjustersCount 0;
  1239.                                 foreach ($adjusters as $getAdjuster) {
  1240.                                     if ($getAdjuster->getRole()->getRole() == "Field Adjuster") {
  1241.                                         $fieldAdjustersCount++;
  1242.                                     }
  1243.                                 }
  1244.                                 if ($fieldAdjustersCount == 0) {  // if there are no other field adjusters
  1245.                                     # Set Primary
  1246.                                     $isPrimary true;
  1247.                                 } else {
  1248.                                     $isPrimary false;
  1249.                                 }
  1250.                             } else {
  1251.                                 $isPrimary false;
  1252.                             }
  1253.                         }
  1254.                     } else {
  1255.                         $isPrimary false;
  1256.                     }
  1257.                     $currentResource $em->getRepository("ResourceManagementBundle:Resource")->find($adjusterId);
  1258.                     $this->get('claim.assignment')->assignResourceToClaim(
  1259.                         $claim,
  1260.                         $currentResource,
  1261.                         $role,
  1262.                         new \DateTime(),
  1263.                         $isPrimary,
  1264.                         $currentResource->getPayrollId()
  1265.                     );
  1266.                 }
  1267.             }
  1268.             # Return success JSON
  1269.             $response = array(
  1270.                 "result" => "success",
  1271.                 "error_msgs" => []
  1272.             );
  1273.             return new JsonResponse($response);
  1274.         }
  1275.     }
  1276.     /**
  1277.      * @Route("/verify/claim-resource")
  1278.      */
  1279.     public function verifyShareResource(Request $request)
  1280.     {
  1281.         // We want to know what RESOURCE is going into WHAT role, and WHAT claim.. so.
  1282.         if($request && $request->get('claim') && $request->get('resource')){
  1283.             # Load the IDs from the GET request
  1284.             $claim_id $request->get('claim');
  1285.             $resource_id $request->get('resource');
  1286.             $role_name $request->get('role');
  1287.             # Load them now into the ENTITIES
  1288.             $em $this->getDoctrine()->getManager();
  1289.             # Entity mapping
  1290.             $Claim $em->find("ClaimManagementBundle:Claim"$claim_id);
  1291.             $Role $em->getRepository('ClaimManagementBundle:ClaimResourceRole')->findOneBy(['role'=>$role_name]);
  1292.             $Resource $em->find("ResourceManagementBundle:Resource"$resource_id);
  1293.             # Service to call
  1294.             $claimService $this->get('claim.assignment');
  1295.             # Create the JSON response
  1296.             $json_response = [
  1297.                 'result' => false,
  1298.                 'messages' => []
  1299.             ];
  1300.             # Now, we verify if this Resource can be shared onto this Claim.. or if not.
  1301.             if($claimService->canAssignResourceToClaim($Claim$Resource$Role)){
  1302.                 // Send a result saying that it can be assigned, allow it
  1303.                 $json_response['result'] = true;
  1304.             }else{
  1305.                 // Send a result saying that for some reason this guy can't be added
  1306.                 $json_response['messages'] = $claimService->getErrors();
  1307.                 $json_response['messages'][] = 'Claim could not be assigned.';
  1308.             }
  1309.             return new JsonResponse($json_response);
  1310.         }else{
  1311.             throw new BadRequestHttpException('Please submit a CLAIM, ROLE and RESOURCE with your request');
  1312.         }
  1313.     }
  1314.     public function slugify($text)
  1315.     {
  1316.         $delimiter "_";
  1317.         $text iconv('utf-8''us-ascii//TRANSLIT'$text);
  1318.         return strtolower(preg_replace('/[^A-Za-z0-9-]+/'$delimiter$text));
  1319.     }
  1320.     /**
  1321.      * @Route("ack-letter/send/{id}")
  1322.      */
  1323.     public function sendAckLetterEmail(Claim $claimRequest $request)
  1324.     {
  1325.         $em $this->container->get('doctrine')->getManager();
  1326.         $tokenStorage $this->container->get('security.token_storage');
  1327.         $user  $tokenStorage->getToken()->getUser();
  1328.         $incoming_internal_rep $request->request->get('intRepEmail');
  1329.         $incoming_addresses $request->request->get('otherEmail');
  1330.         $incoming_body $request->request->get('body');
  1331.         $kernel $this->container->get('kernel');
  1332.         $env $kernel->getEnvironment();
  1333.         $strImagePath $this->generateUrl('globals_companymanagement_company_getcompanylogo', array('id'=>$claim->getId()));
  1334.         $strImagePathTmp '';
  1335.         if ($claim->getCustomer()) {
  1336.             $ClaimCustomer $claim->getCustomer();
  1337.             if ($ClaimCustomer->getSubCompany()) {  // if has a Company ID on the Claim Team
  1338.                 # Use that Sub Company ID
  1339.                 $company_id $ClaimCustomer->getSubCompany()->getId();
  1340.                 $Company $em->getRepository("CompanyManagementBundle:Company")->findById($company_id);
  1341.                 if ($Company) {
  1342.                     $entity 'CompanyLogo';
  1343.                     $FileManager $em->getRepository("ResourceManagementBundle:FileManager")->loadByFileIDEntity($company_id$entity);
  1344.                     $fileName =  $this->slugify($Company[0]->getName());
  1345.                     $strImagePathTmp $request->server->get('DOCUMENT_ROOT'). "/" $kernel->getEnvironment() . "/" $entity "/" $fileName "." $FileManager->getExt();
  1346.                 }
  1347.             }
  1348.         }
  1349.         $imageUrl $request->server->get('DOCUMENT_ROOT')."/img/$env.jpg";
  1350.         if(!empty($strImagePathTmp)){
  1351.             $imageUrl $strImagePathTmp;
  1352.         }
  1353.         if($incoming_addresses && $incoming_internal_rep){
  1354.             $incoming_addresses .=  ";$incoming_internal_rep";
  1355.         }else{
  1356.             $incoming_addresses .=  $incoming_internal_rep;
  1357.         }
  1358.         if ($incoming_addresses && $claim->getClientEmail()) {
  1359.             $clientEmail $claim->getClientEmail();
  1360.             $incoming_addresses .=  ";$clientEmail";
  1361.         }
  1362.         
  1363.         $addresses explode(';'$incoming_addresses);
  1364.         $email_from $user->getEmail();
  1365.         $subject "Acknowledgment Letter";
  1366.         $email_body $incoming_body;
  1367.         $mailer $this->container->get('mail_management.mailer');
  1368.         $mailer->replaceParam = array('strImagePath' => $strImagePath'imageUrl' => $imageUrl);
  1369.         $Mail = new Mail();
  1370.         $mailer->setSendingConfig();
  1371.         foreach ($addresses as $address) {
  1372.             //Validate Emails
  1373.             if (!filter_var($addressFILTER_VALIDATE_EMAIL)) {
  1374.                 return new JsonResponse(['error'=>true'data' => ['errors' => "Wrong email format"]]);
  1375.             }
  1376.             $slog = new SLogger();
  1377.             $slog->log('address: '.$address);
  1378.             $email_to $address;
  1379.             # Recipient
  1380.             $Recipient = new MailRecipient();
  1381.             $Recipient->setEmail($email_to);
  1382.             $Recipient->setMail($Mail);
  1383.             $Recipient->setRecipientId($claim->getCustomer()->getId());
  1384.             $entityName $em->getMetadataFactory()->getMetadataFor(get_class($claim->getCustomer()))->getName();
  1385.             $Recipient->setRecipientType($entityName);
  1386.             //$em->persist( $Recipient ); 
  1387.             //$em->flush();
  1388.             # Adds the single recipient (resource);
  1389.             $Mail->addRecipient($Recipient);
  1390.             $Mail->setSubject($subject);
  1391.             # SETTING THE EXCEPTIONS
  1392.             # ######################################################
  1393.             $catcrew_exceptions false;
  1394.             $great_american_exception false;
  1395.             if($claim->getCustomer()->getId() == 5624)
  1396.             {
  1397.                 $great_american_exception true;;
  1398.             }
  1399.             if($claim->getCustomer()->getId() == 5727)
  1400.             {
  1401.                 $catcrew_exceptions true;
  1402.             }
  1403.         }
  1404.             # SETTING THE SUBJECT
  1405.             # ######################################################
  1406.             // $Mail->setSubject("Claim Assigned");
  1407.             $Mail->setSubject("Claim has been assigned - Claim Assigned Notification");
  1408.             if($great_american_exception)
  1409.             {
  1410.                 $SubjectClaim str_replace("-","",$claim->getClaimNumber());
  1411.                 $Mail->setSubject($SubjectClaim.";Documents;Other;Acknowledgement Davies;;;;Financial Institution Services;;;;;;;Spec Gen;;;;;N;;;");
  1412.             }
  1413.             if($catcrew_exceptions)
  1414.             {
  1415.                 $Mail->setSubject("Acknowledgement for Claim #" $claim->getClaimNumber());
  1416.             }
  1417.             # Finalize the MAIL object
  1418.             $Mail->setBody($email_body);
  1419.             $Mail->setSenderName(MailHelper::getMailSenderName($tokenStorage));
  1420.             $mailer->sendEmail($Mail$email_from"");
  1421.         /*
  1422.          * Create a Claim Note in the FileNotes
  1423.          */
  1424.         // status note = 71 Ack. Letter
  1425.         $this->container->get('claim.note_provider')->addClaimNote($claim"Ack. Letter sent to " $incoming_addresses " by " $email_from true71);
  1426.         /*
  1427.          * Call function that converts to PDF and attach to Attachments List
  1428.          */
  1429.         $slog = new SLogger();
  1430.         $slog->log("123 789");
  1431.         $this->convertToAttachmentsAckLetter($incoming_body$claim->getId(), $user->getId());
  1432.         //Update the claim table with pdfstatus in progress pdf stacking
  1433.         $update_claim_sql "UPDATE claim 
  1434.                                 SET pdfstatus = :pdfstatus,
  1435.                                 updated_at = NOW()
  1436.                                 WHERE id = :claim_id";
  1437.         $dataParams = array();
  1438.         $dataParams['claim_id'] = $claim->getId();
  1439.         $dataParams['pdfstatus'] = 1;
  1440.         $stmt $em->getConnection()->prepare($update_claim_sql);
  1441.         try{
  1442.             $stmt->execute($dataParams);
  1443.         }catch (\PDOException $e){
  1444.             return new Response("Exception occurred while Updating");
  1445.         }
  1446.         return new JsonResponse(['success' => true]);
  1447.     }
  1448.     /**
  1449.      * Function to Convert to PDF and Append to Attachments
  1450.      */
  1451.     public function convertToAttachmentsAckLetter($htmlBody$claimId$resourceId){
  1452.         $em $this->container->get("doctrine.orm.entity_manager");
  1453.         $fileManager $this->container->get("app.file_manager");
  1454.         $kernel $this->container->get("kernel");
  1455.         /*
  1456.          * Create Path and File name
  1457.          */
  1458.         $new_file_name md5(uniqid());
  1459.         $new_file_path "/tmp/" $new_file_name;
  1460.         $this->container->get("knp_snappy.pdf")->setTimeout(600);
  1461.         $slog = new SLogger();
  1462.         $slog->log("htmlBody at 712: " $htmlBody);
  1463.         $slog->log("new_file_path: $new_file_path");
  1464.         $rootDir $kernel->getRootDir();
  1465.         $rootDir str_replace("/app"""$rootDir);
  1466.         $htmlBody str_replace("/" $kernel->getEnvironment() . "/CompanyLogo/"$rootDir "/web/" $kernel->getEnvironment() . "/CompanyLogo/"$htmlBody);
  1467.         $slog->log("htmlBody after at 717: " $htmlBody);
  1468.         $this->container->get("knp_snappy.pdf")->generateFromHtml($htmlBody$new_file_path);
  1469.         $useFile['new_file_name'] = basename($new_file_path);
  1470.         $useFile['used_by_module'] = "ClaimReport";
  1471.         $useFile['name'] = basename($new_file_path);
  1472.         $useFile['type'] = "application/pdf";
  1473.         $useFile['error'] = 0;
  1474.         //            echo "<pre>";
  1475.         //                echo $new_file_path;
  1476.         //
  1477.         //                echo $htmlBody;
  1478.         //            echo "</pre>";
  1479.         try {
  1480.             $useFile['size'] = filesize($new_file_path);
  1481.         } catch (Exception $e) {
  1482.             return new JsonResponse(['error' => $e->getMessage()]);
  1483.         }
  1484.         /*
  1485.          * Insert into claim_report
  1486.          */
  1487.         $useFile['file_ext'] = "pdf";
  1488.         $sql "INSERT INTO
  1489.                 claim_report(file_title,file_size,ext,created_on,claim_id,document_type_id,adjuster_id,invoice_id,status)
  1490.                 VALUES (:file_title, :file_size, :ext, :created_on, :claim_id, :document_type_id, :adjuster_id, :invoice_id, :status_id)";
  1491.         $dataParams = array();
  1492.         $dataParams['file_title'] = 'Acknowledgment Letter';
  1493.         $dataParams['file_size'] = $useFile['size'];
  1494.         $dataParams['ext'] = 'pdf';
  1495.         $dataParams['created_on'] = date('Y-m-d');
  1496.         $dataParams['claim_id'] = $claimId;
  1497.         $dataParams['document_type_id'] = 10;
  1498.         $dataParams['adjuster_id'] = $resourceId;
  1499.         $dataParams['invoice_id'] = 0;
  1500.         $dataParams['status_id'] = 1;
  1501.         $stmt $em->getConnection()->prepare($sql);
  1502.         try {
  1503.             $stmt->execute($dataParams);
  1504.             $fileId $em->getConnection()->lastInsertId();
  1505.         } catch (Exception $e) {
  1506.             return new JsonResponse(['error' => $e->getMessage()]);
  1507.         }
  1508.         /*
  1509.          * Wasabi Save File
  1510.          */
  1511.         if ($fileId) {
  1512.             //$fileId = $result['id'];
  1513.             $fileSave $fileManager->saveFile($useFile$fileId"ClaimReport");
  1514.             if ($fileSave) {
  1515.                 # Return success JSON
  1516.                 $response = array(
  1517.                     "result" => "success",
  1518.                     "error_msgs" => [$fileSave]
  1519.                 );
  1520.             }else{
  1521.                 #if the file is not saved on wasabi delete it from claim report
  1522.                 $sql "DELETE FROM claim_report WHERE id = :id";
  1523.                 $dataParams = array();
  1524.                 $dataParams['id'] = $fileId;
  1525.                 $stmt $em->getConnection()->prepare($sql);
  1526.                 try {
  1527.                     $stmt->execute($dataParams);
  1528.                 } catch (Exception $e) {
  1529.                     return new JsonResponse(['error' => "Error deleting from claim report"]);
  1530.                 }
  1531.                 # Return wrong JSON
  1532.                 $response = array(
  1533.                     "result" => "error FileSave",
  1534.                     "error" => true,
  1535.                     "error_msgs" => [$fileSave]
  1536.                 );
  1537.             }
  1538.         }else{
  1539.             # Return wrong JSON
  1540.             $response = array(
  1541.                 "result" => "error fileId",
  1542.                 "error" => true,
  1543.                 "error_msgs" => [$fileId]
  1544.             );
  1545.         }
  1546.         return new JsonResponse($response);
  1547.     }
  1548.     /**
  1549.      * @Route("/update/duplicate-claim/{id}")
  1550.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  1551.      */
  1552.     public function duplicateClaim(Claim $claimRequest $request)
  1553.     {
  1554.         $response = ['error'=>false'data'=>[]];
  1555.         $em $this->container->get("doctrine.orm.entity_manager");
  1556.         if($claim){
  1557.             $sql "INSERT INTO claim 
  1558.                     (claim_number,
  1559.                     severity,
  1560.                     date_received,
  1561.                     status_id, 
  1562.                     claim_rep_id,
  1563.                     customer_id,
  1564.                     loss_date,
  1565.                     loss_street,
  1566.                     loss_city,
  1567.                     loss_state_id,
  1568.                     loss_zip,
  1569.                     peril_id,
  1570.                     sub_peril_id,
  1571.                     inspection_note,
  1572.                     policy_id,
  1573.                     policy_number,
  1574.                     policy_type,
  1575.                     policy_start_date,
  1576.                     policy_end_date,
  1577.                     loss_description,
  1578.                     loss_amount,
  1579.                     coinsurance,
  1580.                     mortgage,
  1581.                     form_numbers,
  1582.                     form_numbers_set,
  1583.                     report_due_date,
  1584.                     special_notes,
  1585.                     agent_id,
  1586.                     minor_bday,
  1587.                     parent,
  1588.                     date_created)
  1589.                     SELECT 
  1590.                     claim_number,
  1591.                     severity,
  1592.                     date_received,
  1593.                     5, 
  1594.                     claim_rep_id,
  1595.                     customer_id,
  1596.                     loss_date,
  1597.                     loss_street,
  1598.                     loss_city,
  1599.                     loss_state_id,
  1600.                     loss_zip,
  1601.                     peril_id,
  1602.                     sub_peril_id,
  1603.                     inspection_note,
  1604.                     policy_id,
  1605.                     policy_number,
  1606.                     policy_type,
  1607.                     policy_start_date,
  1608.                     policy_end_date,
  1609.                     loss_description,
  1610.                     loss_amount,
  1611.                     coinsurance,
  1612.                     mortgage,
  1613.                     form_numbers,
  1614.                     form_numbers_set,
  1615.                     report_due_date,
  1616.                     special_notes,
  1617.                     agent_id,
  1618.                     minor_bday,
  1619.                     id,
  1620.                     NOW()
  1621.                     FROM claim
  1622.                     WHERE id = :claim_id";
  1623.             $dataParams = array();
  1624.             $dataParams['claim_id'] = $claim->getId();
  1625.             $stmt $em->getConnection()->prepare($sql);
  1626.             try {
  1627.                 $stmt->execute($dataParams);
  1628.                 $newClaimId $em->getConnection()->lastInsertId();
  1629.             } catch (Exception $e) {
  1630.                 return new JsonResponse(['error' => true,'error_msg' => $e->getMessage()]);
  1631.             }
  1632.             #Copy the claim insured
  1633.             $sql "INSERT INTO claims_insured(claim_id, claim_insured_type_id, file_no, insured_id, is_primary, minor_dob, minor_involved )
  1634.                     SELECT :new_claim_id, claim_insured_type_id, :new_claim_id, insured_id, is_primary, minor_dob, minor_involved 
  1635.                     FROM claims_insured
  1636.                     WHERE claim_id = :claim_id";
  1637.             $dataParams = array();
  1638.             $dataParams['claim_id'] = $claim->getId();
  1639.             $dataParams['new_claim_id'] = $newClaimId;
  1640.             $stmt $em->getConnection()->prepare($sql);
  1641.             try {
  1642.                 $stmt->execute($dataParams);
  1643.             } catch (Exception $e) {
  1644.                 return new JsonResponse(['error' => true,'error_msg' => $e->getMessage()]);
  1645.             }
  1646.             #Copy the claim coverages
  1647.             $sql "INSERT INTO coverage(claim_id, name, amount, reserve, coverage_type_id, user_changed_id, dateChanged, reasonChanged)
  1648.                     SELECT :new_claim_id, name, amount, reserve, coverage_type_id, user_changed_id, dateChanged, reasonChanged
  1649.                     FROM coverage 
  1650.                     WHERE claim_id = :claim_id";
  1651.             $dataParams = array();
  1652.             $dataParams['claim_id'] = $claim->getId();
  1653.             $dataParams['new_claim_id'] = $newClaimId;
  1654.             $stmt $em->getConnection()->prepare($sql);
  1655.             try {
  1656.                 $stmt->execute($dataParams);
  1657.             } catch (Exception $e) {
  1658.                 return new JsonResponse(['error' => true,'error_msg' => $e->getMessage()]);
  1659.             }
  1660.             #Copy the claim deductibles
  1661.             $sql "INSERT INTO deductible(claim_id, name, amount, deductible_name_id)
  1662.                     SELECT :new_claim_id, name, amount, deductible_name_id
  1663.                     FROM deductible 
  1664.                     WHERE claim_id = :claim_id";
  1665.             $dataParams = array();
  1666.             $dataParams['claim_id'] = $claim->getId();
  1667.             $dataParams['new_claim_id'] = $newClaimId;
  1668.             $stmt $em->getConnection()->prepare($sql);
  1669.             try {
  1670.                 $stmt->execute($dataParams);
  1671.             } catch (Exception $e) {
  1672.                 return new JsonResponse(['error' => true,'error_msg' => $e->getMessage()]);
  1673.             }
  1674.             $newClaim $this->getDoctrine()->getRepository('ClaimManagementBundle:Claim')->find($newClaimId);
  1675.             $response['data'] = $newClaimId;
  1676.             # logged in user
  1677.             $user $this->get('security.token_storage')->getToken()->getUser();
  1678.             $NoteService $this->get('claim.note_provider');
  1679.             $strComment "New claim (copy claim) was duplicated from claim with FILE ID # ".$claim->getId()." by ".$user->getFullName(). " on "date('m/d/Y h:i A');
  1680.             $NoteService->addClaimNote$newClaim$strCommentfalse,13 );
  1681.             // Notify event Claim is created
  1682.             $dispatcher $this->get('event_dispatcher');
  1683.             $dispatcher->dispatch(new ClaimDuplicatedEvent($newClaim), ClaimDuplicatedEvent::NAME );
  1684.             return new JsonResponse($response);
  1685.         }else{
  1686.             throw new NotFoundHttpException("Couldn't find this claim!");
  1687.         }
  1688.     }
  1689.     /**
  1690.      * @Route("/update/claim-cwop-reason/{id}")
  1691.      * @ParamConverter("claim", class="ClaimManagementBundle:Claim")
  1692.      */
  1693.     public function updateClaimCwopReasonAction(Claim $claimRequest $request)
  1694.     {
  1695.         $cwop_reason $request->request->get('cwop_reason');
  1696.         $em $this->container->get("doctrine.orm.entity_manager");
  1697.         $denial_description_line $request->request->get('denial_description_line');
  1698.         $objCwopReason $em->getRepository("ClaimManagementBundle:CwopReason")->findOneBy(['id' => $cwop_reason]);
  1699.         if(empty($objCwopReason)){
  1700.             return new JsonResponse(['error'=>true'msg' => 'CWOP Reason not found']);
  1701.         }
  1702.         try{
  1703.             $ReopenDate $claim->getDateReopened();
  1704.             $strReopen "";
  1705.             if (!empty($ReopenDate)) {
  1706.                 $claim->setReopenCwopRsn($objCwopReason);
  1707.                 $claim->setReopenDenialDescriptionLine($denial_description_line);
  1708.                 $strReopen "Reopen";
  1709.             }else{
  1710.                 $claim->setCwopReason($objCwopReason);
  1711.                 $claim->setDenialDescriptionLine($denial_description_line);
  1712.             }
  1713.             $em->persist($claim);
  1714.             $em->flush();
  1715.             $ClaimNote $this->container->get("claim.note_provider");
  1716.             $strCWOPReason $objCwopReason->getDescription();
  1717.             $ClaimNote->addClaimNote($claim"$strReopen CWOP Reason ($strCWOPReason) added to the claim with Denial Description as ($denial_description_line)."false);
  1718.         }catch(Exception $e){
  1719.             return new JsonResponse(['error'=>true'msg' => $e->getMessage()]);
  1720.         }
  1721.         return new JsonResponse(['error'=>false]);
  1722.     }
  1723. }