src/Globals/ResourceManagementBundle/Controller/ResourceController.php line 434

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: AHawley
  5.  * Date: 3/13/2017
  6.  * Time: 10:58 AM
  7.  */
  8. namespace Globals\ResourceManagementBundle\Controller;
  9. use Globals\CoreBundle\Entity\SystemControlMetadata;
  10. use Globals\CoreBundle\Helpers\MailHelper;
  11. use Globals\ResourceManagementBundle\DependencyInjection\ExportFileUtils;
  12. use Globals\ResourceManagementBundle\Entity\UserNote;
  13. use Globals\ResourceManagementBundle\Form\ResourceType;
  14. use Doctrine\ORM\EntityManager;
  15. use Globals\ResourceManagementBundle\DependencyInjection\FormHelpers\ResourceFormHelper;
  16. use Globals\ResourceManagementBundle\Entity\Resource;
  17. use Globals\ResourceManagementBundle\Entity\TeamsNotUsed;
  18. use Globals\ResourceManagementBundle\Entity\ResourceWingspanGroupMap;
  19. use Globals\ResourceManagementBundle\Entity\UserToken;
  20. use Globals\ResourceManagementBundle\Enum\ResourceRoleEnum;
  21. use Globals\ResourceManagementBundle\Service\PaginatorSQL;
  22. use Globals\ResourceManagementBundle\Service\SLogger;
  23. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\HttpFoundation\Session\Session;
  28. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  29. use Symfony\Component\Routing\Annotation\Route;
  30. use Globals\ResourceManagementBundle\Event\ResourceCreatedEvent;
  31. use Globals\ResourceManagementBundle\Event\ResourceUpdatedEvent;
  32. use Globals\MailManagementBundle\Entity\Mail;
  33. use Globals\MailManagementBundle\Entity\MailRecipient;
  34. use Globals\ResourceManagementBundle\Entity\AdjusterComment;
  35. use Globals\ResourceManagementBundle\Service\WingSpanService;
  36. use Globals\ResourceManagementBundle\Entity\Contract;
  37. class ResourceController extends AbstractController
  38. {
  39.     /**
  40.      * Base Route (Vaughn's style)
  41.      *
  42.      * @Route("/administration/resource")
  43.      */
  44.     public function resources2Action()
  45.     {
  46.         return $this->render("ResourceManagementBundle:resources:index2.html.twig", []);
  47.     }
  48.     /**
  49.      * @Route("/administration/resource/check_blob")
  50.      */
  51.     public function checkBlobLineItem()
  52.     {
  53.         $em $this->getDoctrine()->getManager();
  54.         $sql "SELECT * FROM commission_report cr WHERE cr.invoice_id = :invoice_id AND invoice_type_id <> 4 ";
  55.         $stmt $em->getConnection()->prepare($sql);
  56.         echo "<pre>";
  57.         $stmt->execute([
  58.             "invoice_id" => 201749,
  59.         ]);
  60.         $results $stmt->fetchAll(\PDO::FETCH_ASSOC);
  61.         if (count($results) > 0) {
  62.             $Item $results[0];
  63.             print_r(json_decode($Item['report_data']));
  64.         }
  65.         dump("script completed"); die;
  66.     }
  67.     /**
  68.      * @Route("/administration/resource/undo_cm/{invoiceId}")
  69.      */
  70.     public function undoCreditMemo($invoiceId)
  71.     {
  72.         $em $this->getDoctrine()->getManager();
  73.         $sql "DELETE FROM commission_report 
  74.                 WHERE invoice_id = :id AND invoice_type_id = 4 ";
  75.         $stmt_delete_commission_report $em->getConnection()->prepare($sql);
  76.         $sql "DELETE FROM invoice_cm 
  77.                 WHERE invoice_id = :invoice_id  ";
  78.         $stmt_delete_invoice_cm $em->getConnection()->prepare($sql);
  79.         $sql "SELECT id 
  80.                 FROM invoice_cm
  81.                 WHERE invoice_id = :invoice_id ";
  82.         $stmt $em->getConnection()->prepare($sql);
  83.         $stmt->execute([
  84.             "invoice_id" => $invoiceId
  85.         ]);
  86.         $results $stmt->fetchAll(\PDO::FETCH_ASSOC);
  87.         foreach ($results as $getEach) {
  88.             $sql "DELETE FROM commission_report WHERE invoice_id = :id AND invoice_type_id = 4 ";
  89.             echo "<pre>";
  90.             echo "sql: $sql \n";
  91.             print_r([
  92.                 "id" => $getEach['id']
  93.             ]);
  94.             //*/
  95.             $stmt_delete_commission_report->execute([
  96.                 "id" => $getEach['id']
  97.             ]);
  98.             //*/
  99.             $sql "DELETE FROM invoice_cm 
  100.                     WHERE invoice_id = :invoice_id;";
  101.             //*/
  102.             $stmt_delete_invoice_cm->execute([
  103.                 "invoice_id" => $invoiceId,
  104.             ]);
  105.             //*/
  106.             echo "<pre>";
  107.             echo "sql: $sql \n";
  108.             print_r([
  109.                 "invoice_id" => $invoiceId,
  110.             ]);
  111.         }
  112.         dump("script completed"); die;
  113.     }
  114.     /**
  115.      * @Route("/administration/resource/regrind_cm/{invoiceId}")
  116.      */
  117.     public function regrindCreditMemo($invoiceId)
  118.     {
  119.         $em $this->getDoctrine()->getManager();
  120.         $sql "SELECT * 
  121.                 FROM commission_report 
  122.                 WHERE invoice_id = :invoice_id 
  123.                 AND invoice_type_id <> 4 ";
  124.         $stmt $em->getConnection()->prepare($sql);
  125.         $stmt->execute([
  126.             "invoice_id" => $invoiceId
  127.         ]);
  128.         $CommReports $stmt->fetchAll(\PDO::FETCH_ASSOC);
  129.         if (count($CommReports) > 0) {
  130.             $GetCommReport $CommReports[0];
  131.             $report_data json_decode($GetCommReport['report_data']);
  132.             $report_data $this->negateCreditMemoBlob($report_data$invoiceId);
  133.             $sql "SELECT id FROM invoice_cm WHERE invoice_id = :invoice_id ";
  134.             $stmt $em->getConnection()->prepare($sql);
  135.             $stmt->execute([
  136.                 "invoice_id" => $invoiceId
  137.             ]);
  138.             $InvoiceCMs $stmt->fetchAll(\PDO::FETCH_ASSOC);
  139.             if (count($InvoiceCMs) > 0) {
  140.                 $InvoiceCM $InvoiceCMs[0];
  141.                 $sql "UPDATE commission_report  
  142.                         SET report_data = :report_data,
  143.                         updated_at = :updated_at
  144.                         WHERE invoice_id = :invoice_id 
  145.                         AND invoice_type_id = 4 ";
  146.                 $stmt $em->getConnection()->prepare($sql);
  147.                 $stmt->execute([
  148.                     "report_data" => json_encode($report_data),
  149.                     "invoice_id" => $InvoiceCM['id'],
  150.                     "updated_at" => date("Y-m-d H:i:s")
  151.                 ]);
  152.             }
  153.         }
  154.         dump("Script Completed"); die();
  155.     }
  156.     private function negateCreditMemoBlob($report_data$originalInvId)
  157.     {
  158.         $em $this->getDoctrine()->getManager();
  159.         $sql "SELECT id
  160.                     FROM invoice_cm  
  161.                     WHERE invoice_id = :invoice_id LIMIT 1 ";
  162.         $stmt $em->getConnection()->prepare($sql);
  163.         $stmt->execute([
  164.             "invoice_id" => $originalInvId
  165.         ]);
  166.         $InvoiceCMs $stmt->fetchAll(\PDO::FETCH_ASSOC);
  167.         if (count($InvoiceCMs) > 0) {
  168.             $invoiceCMId $InvoiceCMs[0]['id'];
  169.             $report_data->claimData->dateCreated date("Y-m-d H:i:s");
  170.             $report_data->claimData->TypeCode "CM";
  171.             $report_data->claimData->inv_id $invoiceCMId;
  172.             $report_data->claimData->invoice_type_id 4;
  173.             $report_data->claimData->netTotal = -floatval($report_data->claimData->netTotal);
  174.             $report_data->claimData->subTotal = -floatval($report_data->claimData->subTotal);
  175.             $report_data->claimData->taxTotal = -floatval($report_data->claimData->taxTotal);
  176.             $report_data->claimData->te_total = -floatval($report_data->claimData->te_total);
  177.             $report_data->claimData->serviceExpense = -floatval($report_data->claimData->serviceExpense);
  178.             $report_data->claimData->disbursementTotal = -floatval($report_data->claimData->disbursementTotal);
  179.             if (property_exists($report_data"invoice_resource_commission")) {
  180.                 foreach ($report_data->invoice_resource_commission as $index => $getCommission) {
  181.                     $report_data->invoice_resource_commission[$index]->amount = -floatval($report_data->invoice_resource_commission[$index]->amount);
  182.                 }
  183.             }
  184.             if (property_exists($report_data->claimData"discount_max_summary")) {
  185.                 foreach ($report_data->claimData->discount_max_summary as $expenseIndex => $getDiscount) {
  186.                     if (is_array($report_data->claimData->discount_max_summary)) {
  187.                         if (isset($report_data->claimData->discount_max_summary[$expenseIndex])
  188.                             && count($report_data->claimData->discount_max_summary[$expenseIndex]) > 0
  189.                             && property_exists($report_data->claimData->discount_max_summary[$expenseIndex], "subtotal")) {
  190.                             $report_data->claimData->discount_max_summary[$expenseIndex]->subtotal floatval($report_data->claimData->discount_max_summary[$expenseIndex]->subtotal) * -1;
  191.                         }
  192.                     } else {
  193.                         if (is_array(($report_data->claimData->discount_max_summary->$expenseIndex))) {
  194.                             if (isset($report_data->claimData->discount_max_summary->$expenseIndex["subtotal"])) {
  195.                                 $report_data->claimData->discount_max_summary->{$expenseIndex}["subtotal"] = floatval($report_data->claimData->discount_max_summary->{$expenseIndex}["subtotal"]) * -1;
  196.                             }
  197.                         } else {
  198.                             if (property_exists($report_data->claimData->discount_max_summary$expenseIndex)) {
  199.                                 if (property_exists($report_data->claimData->discount_max_summary->$expenseIndex"subtotal")) {
  200.                                     $report_data->claimData->discount_max_summary->$expenseIndex->subtotal floatval($report_data->claimData->discount_max_summary->$expenseIndex->subtotal) * -1;
  201.                                 }
  202.                             }
  203.                         }
  204.                     }
  205.                     if (is_array($report_data->claimData->discount_max_summary)) {
  206.                         if (isset($report_data->claimData->discount_max_summary[$expenseIndex])
  207.                             && count($report_data->claimData->discount_max_summary[$expenseIndex]) > 0
  208.                             && property_exists($report_data->claimData->discount_max_summary[$expenseIndex], "net_subtotal")) {
  209.                             $report_data->claimData->discount_max_summary[$expenseIndex]->net_subtotal floatval($report_data->claimData->discount_max_summary[$expenseIndex]->net_subtotal) * -1;
  210.                         }
  211.                     } else {
  212.                         if (is_array($report_data->claimData->discount_max_summary->$expenseIndex)) {
  213.                             if (count($report_data->claimData->discount_max_summary->$expenseIndex) > 0
  214.                                 && property_exists($report_data->claimData->discount_max_summary->$expenseIndex"net_subtotal")) {
  215.                                 $report_data->claimData->discount_max_summary->$expenseIndex->net_subtotal floatval($report_data->claimData->discount_max_summary->$expenseIndex->net_subtotal) * -1;
  216.                             }
  217.                         } else if (property_exists($report_data->claimData->discount_max_summary$expenseIndex)) {
  218.                             if (property_exists($report_data->claimData->discount_max_summary->{$expenseIndex}, "net_subtotal")) {
  219.                                 $report_data->claimData->discount_max_summary->{$expenseIndex}->net_subtotal floatval($report_data->claimData->discount_max_summary->{$expenseIndex}->net_subtotal) * -1;
  220.                             }
  221.                         }
  222.                     }
  223.                 }
  224.             }
  225.             foreach ($report_data->invoice_data as $expenseIndex => $getLineItem) {
  226.                 if (is_array($report_data->invoice_data)) {
  227.                     if (isset($report_data->invoice_data[$expenseIndex]) && property_exists($report_data->invoice_data[$expenseIndex], "subtotal")) {
  228.                         $report_data->invoice_data[$expenseIndex]->subtotal = (float)($report_data->invoice_data[$expenseIndex]->subtotal) * -1;
  229.                     }
  230.                     if (isset($report_data->invoice_data[$expenseIndex]) && property_exists($report_data->invoice_data[$expenseIndex], "net_subtotal")) {
  231.                         $report_data->invoice_data[$expenseIndex]->net_subtotal = (float)($report_data->invoice_data[$expenseIndex]->net_subtotal) * -1;
  232.                     }
  233.                 } else {
  234.                     if (property_exists($report_data->invoice_data->{$expenseIndex}, "subtotal")) {
  235.                         $report_data->invoice_data->{$expenseIndex}->subtotal = (float)($report_data->invoice_data->$expenseIndex->subtotal) * -1;
  236.                     }
  237.                     if (property_exists($report_data->invoice_data->{$expenseIndex}, "net_subtotal")) {
  238.                         $report_data->invoice_data->{$expenseIndex}->net_subtotal = (float)($report_data->invoice_data->$expenseIndex->net_subtotal) * -1;
  239.                     }
  240.                 }
  241.             }
  242.         }
  243.         return $report_data;
  244.     }
  245.     /**
  246.      * Show Datalist Page (Old DataBuilders style)
  247.      *
  248.      * @Route("/administration/resource/index")
  249.      */
  250.     public function showResources2Action()
  251.     {
  252.         return $this->render("ResourceManagementBundle:resources:show2.html.twig");
  253.     }
  254.     /**
  255.      * @Route("/administration/resource/check_negate_blob")
  256.      */
  257.     public function checkNegateBlob()
  258.     {
  259.         $em $this->getDoctrine()->getManager();
  260.         $originalInvId 202004;
  261.         $sql "SELECT id, report_data, has_admin_fee_change 
  262.                 FROM commission_report 
  263.                 WHERE invoice_id = :invoice_id 
  264.                 AND invoice_type_id <> 4 ";
  265.         $stmt $em->getConnection()->prepare($sql);
  266.         $stmt->execute([
  267.             "invoice_id" => $originalInvId
  268.         ]);
  269.         $CommissionReports $stmt->fetchAll(\PDO::FETCH_ASSOC);
  270.         if (count($CommissionReports) > 0) {
  271.             $CommReport $CommissionReports[0];
  272.             $report_data json_decode($CommReport['report_data']);
  273.             $sql "SELECT id
  274.                     FROM invoice_cm  
  275.                     WHERE invoice_id = :invoice_id LIMIT 1 ";
  276.             $stmt $em->getConnection()->prepare($sql);
  277.             $stmt->execute([
  278.                 "invoice_id" => $originalInvId
  279.             ]);
  280.             $InvoiceCMs $stmt->fetchAll(\PDO::FETCH_ASSOC);
  281.             if (count($InvoiceCMs) > 0) {
  282.                 $invoiceCMId $InvoiceCMs[0]['id'];
  283.                 $report_data->claimData->dateCreated date("Y-m-d H:i:s");
  284.                 $report_data->claimData->TypeCode "CM";
  285.                 $report_data->claimData->inv_id $invoiceCMId;
  286.                 $report_data->claimData->invoice_type_id 4;
  287.                 $report_data->claimData->netTotal = -floatval($report_data->claimData->netTotal);
  288.                 $report_data->claimData->subTotal = -floatval($report_data->claimData->subTotal);
  289.                 $report_data->claimData->taxTotal = -floatval($report_data->claimData->taxTotal);
  290.                 $report_data->claimData->te_total = -floatval($report_data->claimData->te_total);
  291.                 $report_data->claimData->serviceExpense = -floatval($report_data->claimData->serviceExpense);
  292.                 $report_data->claimData->disbursementTotal = -floatval($report_data->claimData->disbursementTotal);
  293.                 if (property_exists($report_data"invoice_resource_commission")) {
  294.                     foreach ($report_data->invoice_resource_commission as $index => $getCommission) {
  295.                         $report_data->invoice_resource_commission[$index]->amount = -floatval($report_data->invoice_resource_commission[$index]->amount);
  296.                     }
  297.                 }
  298.                 if (property_exists($report_data->claimData"discount_max_summary")) {
  299.                     foreach ($report_data->claimData->discount_max_summary as $expenseIndex => $getDiscount) {
  300.                         if (is_array($report_data->claimData->discount_max_summary)) {
  301.                             if (isset($report_data->claimData->discount_max_summary[$expenseIndex])
  302.                                 && count($report_data->claimData->discount_max_summary[$expenseIndex]) > 0
  303.                                 && property_exists($report_data->claimData->discount_max_summary[$expenseIndex], "subtotal")) {
  304.                                 $report_data->claimData->discount_max_summary[$expenseIndex]->subtotal floatval($report_data->claimData->discount_max_summary[$expenseIndex]->subtotal) * -1;
  305.                             }
  306.                         } else {
  307.                             if (is_array(($report_data->claimData->discount_max_summary->$expenseIndex))) {
  308.                                 if (isset($report_data->claimData->discount_max_summary->$expenseIndex["subtotal"])) {
  309.                                     $report_data->claimData->discount_max_summary->{$expenseIndex}["subtotal"] = floatval($report_data->claimData->discount_max_summary->{$expenseIndex}["subtotal"]) * -1;
  310.                                 }
  311.                             } else {
  312.                                 if (property_exists($report_data->claimData->discount_max_summary$expenseIndex)) {
  313.                                     if (property_exists($report_data->claimData->discount_max_summary->$expenseIndex"subtotal")) {
  314.                                         $report_data->claimData->discount_max_summary->$expenseIndex->subtotal floatval($report_data->claimData->discount_max_summary->$expenseIndex->subtotal) * -1;
  315.                                     }
  316.                                 }
  317.                             }
  318.                         }
  319.                         if (is_array($report_data->claimData->discount_max_summary)) {
  320.                             if (isset($report_data->claimData->discount_max_summary[$expenseIndex])
  321.                                 && count($report_data->claimData->discount_max_summary[$expenseIndex]) > 0
  322.                                 && property_exists($report_data->claimData->discount_max_summary[$expenseIndex], "net_subtotal")) {
  323.                                 $report_data->claimData->discount_max_summary[$expenseIndex]->net_subtotal floatval($report_data->claimData->discount_max_summary[$expenseIndex]->net_subtotal) * -1;
  324.                             }
  325.                         } else {
  326.                             if (is_array($report_data->claimData->discount_max_summary->$expenseIndex)) {
  327.                                 if (count($report_data->claimData->discount_max_summary->$expenseIndex) > 0
  328.                                     && property_exists($report_data->claimData->discount_max_summary->$expenseIndex"net_subtotal")) {
  329.                                     $report_data->claimData->discount_max_summary->$expenseIndex->net_subtotal floatval($report_data->claimData->discount_max_summary->$expenseIndex->net_subtotal) * -1;
  330.                                 }
  331.                             } else if (property_exists($report_data->claimData->discount_max_summary$expenseIndex)) {
  332.                                 if (property_exists($report_data->claimData->discount_max_summary->{$expenseIndex}, "net_subtotal")) {
  333.                                     $report_data->claimData->discount_max_summary->{$expenseIndex}->net_subtotal floatval($report_data->claimData->discount_max_summary->{$expenseIndex}->net_subtotal) * -1;
  334.                                 }
  335.                             }
  336.                         }
  337.                     }
  338.                 }
  339.                 foreach ($report_data->invoice_data as $expenseIndex => $getLineItem) {
  340.                     if (is_array($report_data->invoice_data)) {
  341.                         if (isset($report_data->invoice_data[$expenseIndex]) && property_exists($report_data->invoice_data[$expenseIndex], "subtotal")) {
  342.                             $report_data->invoice_data[$expenseIndex]->subtotal = (float)($report_data->invoice_data[$expenseIndex]->subtotal) * -1;
  343.                         }
  344.                         if (isset($report_data->invoice_data[$expenseIndex]) && property_exists($report_data->invoice_data[$expenseIndex], "net_subtotal")) {
  345.                             $report_data->invoice_data[$expenseIndex]->net_subtotal = (float)($report_data->invoice_data[$expenseIndex]->net_subtotal) * -1;
  346.                         }
  347.                     } else {
  348.                         if (property_exists($report_data->invoice_data->{$expenseIndex}, "subtotal")) {
  349.                             $report_data->invoice_data->{$expenseIndex}->subtotal = (float)($report_data->invoice_data->$expenseIndex->subtotal) * -1;
  350.                         }
  351.                         if (property_exists($report_data->invoice_data->{$expenseIndex}, "net_subtotal")) {
  352.                             $report_data->invoice_data->{$expenseIndex}->net_subtotal = (float)($report_data->invoice_data->$expenseIndex->net_subtotal) * -1;
  353.                         }
  354.                     }
  355.                 }
  356.             }
  357.         }
  358.         return $report_data;
  359.         //dump("script completed"); die;
  360.     }
  361.     /**
  362.      * @Route("/administration/resource/edit/{id}", defaults={"id" = null})
  363.      */
  364.     public function editResourceAjaxAction(Request $requestResource $resource)
  365.     {
  366.         # lets make sure user has access to this page (stronger than super admin rights)
  367.         $user $this->get('security.token_storage')->getToken()->getUser();
  368.         $systemParamService $this->get('core.system_parameter_control');
  369.         $access $systemParamService->getAccessArray('access_resource');
  370.         $specialAccess false;
  371.         if (in_array($user->getId(), $access)) {
  372.             $specialAccess true;
  373.         }
  374.         $em $this->container->get("doctrine.orm.entity_manager");
  375.         $wingSpanCollavoratorId $resource->getWingSpanCollaboratorId();
  376.         if(empty($wingSpanCollavoratorId)) {
  377.             $wingSpanService $this->container->get('resource.wingSpan');
  378.             $dataArray = array();
  379.             $dataArray['email'] = $resource->getEmail();
  380.             $dataArray['firstName'] = $resource->getFirstName();
  381.             $dataArray['lastName'] = $resource->getLastName();
  382.             $dataArray['memberCompany'] = 'CQ Digital';
  383.             $dataArray['memberId'] = (string)$resource->getId();
  384.             if (!empty($resource->getWingSpanCollaboratorGroupId())) {
  385.                // $response = $wingSpanService->CreateCollaborator($dataArray);
  386.                 // dd($response);
  387.                // $resource->setWingSpanCollaboratorId($response['collaboratorId']);
  388.                // $em->persist($resource);
  389.               //  $em->flush();
  390.                 // $wingSpanCollaboratorId = $response['collaboratorId'];
  391.                 //$wingSpanService->pushCollaboratorGroup($response['collaboratorId'], $resource->getWingSpanCollaboratorGroupId());
  392.             }
  393.         }
  394.         ini_set('display_errors'1);
  395.         ini_set('display_startup_errors'1);
  396.         error_reporting(E_ALL);
  397.         $i=0;
  398.         $envService $this->container->get("core.get_environment");
  399.        
  400. //die;
  401.        // dd($responseDocIdsArray);
  402.         # Variable that turns off client side validation on entire action
  403.         $onlyServerSideVal false;
  404.         # Clear Upload Image Session
  405.         $session = new Session();
  406.         $session->remove("resource_upload_image");
  407.         # Create Form Builder Object for "Edit Resource"
  408.         /** @var EntityManager $em */
  409.         $ClaimTeams $em->getRepository("ClaimManagementBundle:ClaimTeam")->findBy(['enabled' => true], ['name' => 'ASC']);
  410.         $WingSpanGroups $em->getRepository("CompanyManagementBundle:WingspanGroups")->findBy(['isActive' => 'Y'], ['wingspanGroup' => 'ASC']);
  411.         $alreadyNotUsedTeam $this->getDoctrine()->getRepository('ResourceManagementBundle:TeamsNotUsed')->findBy(array('resourceId' => $resource->getId(),'isActive'=>'Y'));
  412.         $alreadyNotUsedTeamArray = array();
  413.         if(!empty($alreadyNotUsedTeam)) {
  414.             foreach ($alreadyNotUsedTeam as $alreadyNotUsedTeam) {
  415.                 $alreadyNotUsedTeamArray[$alreadyNotUsedTeam->getTeamId()] = $alreadyNotUsedTeam->getTeamId();
  416.             }
  417.         }
  418.         $mappedWingspanGroups $this->getDoctrine()->getRepository('ResourceManagementBundle:ResourceWingspanGroupMap')->findBy(array('resourceId' => $resource->getId(),'isActive'=>'Y'));
  419.         $alreadyMappedWingspanArray = array();
  420.         if(!empty($mappedWingspanGroups)) {
  421.             foreach ($mappedWingspanGroups as $mappedWingspanGroups) {
  422.                 $alreadyMappedWingspanArray[$mappedWingspanGroups->getWingspanGroupId()] = $mappedWingspanGroups->getWingspanGroupId();
  423.             }
  424.         }
  425.       //  dd($alreadyMappedWingspanArray);
  426.         $niprTracking =  $resource->getNiprTracking();
  427.         if($niprTracking==1){
  428.             $niprNo =  $resource->getNiprNumber();
  429.             $agentSyncService $this->container->get('resource.agentSync');
  430.             $accessTokenArray $agentSyncService->getAccessToken();
  431.             if (!empty($accessTokenArray['access_token'])){
  432.                 //$agentSyncDataApi = $agentSyncService->createContactAgentSync($accessTokenArray,   $niprNo,$firstName,$LastName,$phone);
  433.                 $agentSyncContactDataApi $agentSyncService->getAgentSyncNiprContactData($accessTokenArray,   $niprNo);
  434.                 if($agentSyncContactDataApi['totalSize']>0){
  435.                     $resource->setAgentSyncResponse($agentSyncContactDataApi['records'][0]['agentsync__AgentSync_Status__c']);
  436.                     if($agentSyncContactDataApi['records'][0]['agentsync__AgentSync_Status__c']=='nipr_error'){
  437.                         $is_nipr_tracking 0;
  438.                         $resource->setNiprTracking($is_nipr_tracking);
  439.                     }
  440.                     $em->persist($resource);
  441.                     $em->flush();
  442.                 }else{
  443.                     $resource->setAgentSyncResponse('NpnNotFoundError');
  444.                     $em->persist($resource);
  445.                     $em->flush();
  446.                 }
  447.             }
  448.         }
  449.         $formFactory $this->container->get("form.factory");
  450.         $kernel $this->container->get("kernel");
  451.         $authChecker $this->container->get("security.authorization_checker");
  452.         $form_helper = new ResourceFormHelper($em$formFactory$kernel$onlyServerSideVal$authChecker);
  453.         $resourceForm $form_helper->getEditForm($resource);
  454.         # Variable that sets active tab
  455.         $active 'resource';
  456.         $image_id "";
  457.         $FileManager $em->getRepository("ResourceManagementBundle:FileManager")->loadByFileIDEntity($resource->getId(), "ResourceSignature");
  458.         if ($FileManager) {  // if signature file exists for this Resource
  459.             # fill variable used to validate is signature file was ever uploaded
  460.             $image_id $FileManager->getId();
  461.         }
  462.         $currentRole "ROLE_REGISTERED";
  463.         if ($resource->getRoles()) {
  464.             $getRole $resource->getRoles();
  465.             if (is_array($getRole) && count($getRole) > 0) {
  466.                 $currentRole $getRole[0];
  467.             }
  468.         }
  469.         $Roles = [
  470.             "ROLE_SUPER_ADMIN",
  471.             "ROLE_ADMIN",
  472.             "ROLE_EXAMINER",
  473.             "ROLE_TEAM_LEADER",
  474.             "ROLE_ADJUSTER",
  475.             "ROLE_REGISTERED"
  476.         ];
  477.         // user stats for ICM
  478.         $isCarrier $envService->getIsCarrier();
  479.         // check if resource has ever been deployed
  480.         $sql "SELECT count(c.id) as claim_count
  481.                 FROM claim as c, assignments as cr, resource as r
  482.                 WHERE c.id = cr.claim_id
  483.                 AND cr.resource_id = r.id
  484.                 AND r.id = :resource_id
  485.                 AND c.loss_state_id != r.state_id
  486.                 AND IFNULL(cr.next_assignment_id,0) = 0
  487.                 AND IFNULL(cr.is_current_assignment,0) = 1";
  488.         $stmt $em->getConnection()->prepare($sql);
  489.         $stmt->execute([
  490.             "resource_id" => $resource->getId()
  491.         ]);
  492.         $claim_count $stmt->fetchAll( \PDO::FETCH_ASSOC );
  493.         if( $claim_count[0]['claim_count'] > )
  494.             $hasBeenDeployed true;
  495.         else
  496.             $hasBeenDeployed false;
  497.         // count of all claims
  498.         // check if resource has ever been deployed
  499.         $sql "SELECT COUNT(*) as claim_count
  500.                 FROM claim c, assignments cr
  501.                 WHERE c.id = cr.claim_id
  502.                 AND cr.resource_id = :resource_id
  503.                 AND IFNULL(cr.next_assignment_id,0) = 0
  504.                 AND IFNULL(cr.is_current_assignment,0) = 1";
  505.         $stmt $em->getConnection()->prepare($sql);
  506.         $stmt->execute([
  507.             "resource_id" => $resource->getId()
  508.         ]);
  509.         $claim_count $stmt->fetchAll( \PDO::FETCH_ASSOC );
  510.         $resourceClaimCount $claim_count[0]['claim_count'];
  511.         $states $em->getRepository("ResourceManagementBundle:State")->findBy([],['stateName'=>'ASC']);
  512.         $activeForLastYear 'No';
  513.         $strCurrentDate date('Y-m-d');
  514.         $strPreviouYearDate date('Y-m-d'strtotime("-1 years"));
  515.         $dateLastAct $resource->getLastActivityAt();
  516.         if (!empty($dateLastAct)) {
  517.             $strResourceLastActDate $resource->getLastActivityAt()->format('Y-m-d');
  518.             if (($strResourceLastActDate >= $strPreviouYearDate) && ($strResourceLastActDate <= $strCurrentDate)){
  519.                $activeForLastYear 'yes';
  520.             }else{
  521.                $activeForLastYear 'no';
  522.             }
  523.         }
  524.         # get password change date
  525.         if(!empty($resource->getPasswordChangeDate())){
  526.             $passChangeDate=$resource->getPasswordChangeDate()->format('m/d/Y H:i:s');
  527.             $currentDate date('Y-m-d H:i:s');
  528.             $passwordChangeDate=$resource->getPasswordChangeDate()->format('Y-m-d H:i:s');
  529.             $dayDiff = (strtotime($currentDate) - strtotime($passwordChangeDate)) / (60 60 24);
  530.         }else{
  531.             $passChangeDate='';
  532.             $dayDiff =0;
  533.         }
  534.         $agentSyncResponse '';
  535.         $agentSyncResponse =$resource->getAgentSyncResponse();
  536.         #collect the Adjuster Comment
  537.         $sql "SELECT ac.comment, ac.commentDate, CONCAT(r.first_name, ' ', r.last_name) AS author_name
  538.               FROM adjuster_comments ac
  539.               LEFT JOIN resource r
  540.               ON ac.logged_in_user_id = r.id
  541.               WHERE ac.resource_id = :rid
  542.               ORDER BY ac.commentDate desc LIMIT 3";
  543.         $AdjusterComments = array();
  544.         $dataParams['rid'] = $resource->getId();
  545.         $stmt $em->getConnection()->prepare($sql);
  546.         //dd($stmt);
  547.         $stmt->execute($dataParams);
  548.         $AdjusterComments $stmt->fetchAll(\PDO::FETCH_ASSOC);
  549.         if (count($AdjusterComments) < 0) {
  550.             $AdjusterComments = array();
  551.         }
  552.        // dd($AdjusterComments);
  553.         return $this->render("ResourceManagementBundle:resources:edit.html.twig", [
  554.             "specialAccess" => $specialAccess,
  555.             "isTlg" => $resource->GetisTlg(),
  556.             "id" => $resource->getId(),
  557.             "resource" => $resource,
  558.             "useResource" => $resource,
  559.             "resourceForm" => $resourceForm->createView(),
  560.             "signature" => $resource->getSignature(),
  561.             "onlyServerSideVal" => $onlyServerSideVal,
  562.             "activeClass" => $active,
  563.             "image_id" => $image_id,
  564.             "Roles" => $Roles,
  565.             "CurrentRole" => $currentRole,
  566.             "isCarrier" => $isCarrier,
  567.             "hasBeenDeployed" => $hasBeenDeployed,
  568.             "resourceClaimCount" => $resourceClaimCount,
  569.             "States" => $states,
  570.             "activeForLastYear" => $activeForLastYear,
  571.             "passChangeDate" => $passChangeDate,
  572.             "dayDiff" => round($dayDiff),
  573.             "comments" => $AdjusterComments,
  574.             'agentSyncResponse' =>$agentSyncResponse,'ClaimTeams'=>$ClaimTeams,'alreadyNotUsedTeamArray'=>$alreadyNotUsedTeamArray,'WingSpanGroups'=>$WingSpanGroups,'alreadyMappedWingspanArray'=>$alreadyMappedWingspanArray
  575.         ]);
  576.     }
  577.     /**
  578.      * @Route("/administration/resource/make_tmp")
  579.      */
  580.     public function createTmpFolder()
  581.     {
  582.         $kernel $this->container->get("kernel");
  583.         $file_path $kernel->getRootDir() . "/../../tmp/licenses";
  584.         mkdir($file_path0775);
  585.         die("script completed");
  586.     }
  587.     /**
  588.      * method that checks if Resource has a signature
  589.      *
  590.      * @Route("/resource/has_signature_view/{id}")
  591.      */
  592.     public function hasSignatureImage(Resource $resource)
  593.     {
  594.         $retVal true;
  595.         if ($resource == null) {
  596.             $retVal false;
  597.         }
  598.         $file_manager $this->container->get("app.file_manager");
  599.         $retVal $file_manager->retrieveFilePathByEntity($resource->getId(), "ResourceSignature");
  600.         if (!$retVal) {
  601.             $retVal false;
  602.         }
  603.         if ($retVal == true) {
  604.             $json = array(
  605.                 "error" => false,
  606.                 "data" => []
  607.             );
  608.             return new JsonResponse($json);
  609.         } else {
  610.             $json = array(
  611.                 "error" => true,
  612.                 "data" => [],
  613.                 "messages" => ["This resource does not have a signature"]
  614.             );
  615.             return new JsonResponse($json);
  616.         }
  617.     }
  618.     /**
  619.      * Fetch the blob by invoice id
  620.      *
  621.      * @Route("/administration/resource/get_blob/item/{invoiceId}")
  622.      */
  623.     public function getBlob($invoiceId)
  624.     {
  625.         $em $this->container->get("doctrine.orm.entity_manager");
  626.         # Push Shreya's Changes
  627.         $sql "SELECT * FROM commission_report WHERE invoice_id = :invoice_id ";
  628.         $dataParams['invoice_id'] = $invoiceId;
  629.         $stmt $em->getConnection()->prepare($sql);
  630.         $stmt->execute($dataParams);
  631.         $resultset $stmt->fetchAll(\PDO::FETCH_ASSOC);
  632.         foreach ($resultset as $getItem) {
  633.             dump($getItem['report_data']);
  634.         }
  635.         die;
  636.         return new JsonResponse(array());
  637.     }
  638.     /**
  639.      * @Route("/administration/resource/signature_view/{id}/{randomNum}")
  640.      */
  641.     public function displaySignatureImage(Resource $resource$randomNum)
  642.     {
  643.         if ($resource === null) {
  644.             throw new NotFoundHttpException('Could not find this Resource!');
  645.         }
  646.         $file_manager $this->container->get("app.file_manager");
  647.         $retVal $file_manager->retrieveFilePathByEntity($resource->getId(), "ResourceSignature"1);
  648.         //return new NonCachableBinaryFileResponse($retVal);
  649.         if(isset($retVal) && !empty($retVal))
  650.             return new Response($retVal[0], $retVal[1], $retVal[2]);
  651.         else
  652.             return new Response(1);
  653.     }
  654.     /**
  655.      * @Route("/administration/resource/profile_view/{id}", defaults={"id"=null})
  656.      */
  657.     public function displayProfileImage(Resource $resource)
  658.     {
  659.         if ($resource === null) {
  660.             throw new NotFoundHttpException('Could not find this Resource!');
  661.         }
  662.         $file_manager $this->container->get("app.file_manager");
  663.         $file $file_manager->retrieveFilePathByEntity($resource->getId(), "ProfilePicture"1);
  664.         if($file){
  665.             //return new NonCachableBinaryFileResponse($file);
  666.             return new Response($file);
  667.         }else{
  668.             return "";
  669.         }
  670.     }
  671.     /**
  672.      * @Route("/administration/resource/add")
  673.      */
  674.     public function addResourceAjaxAction(Request $request)
  675.     {
  676. //        $this->denyAccessUnlessGranted('add');
  677.         # lets make sure user has access to this page (stronger than super admin rights)
  678.         $user $this->get('security.token_storage')->getToken()->getUser();
  679.         $systemParamService $this->get('core.system_parameter_control');
  680.         $access $systemParamService->getAccessArray('access_resource');
  681.         $specialAccess false;
  682.         if (in_array($user->getId(), $access)) {
  683.             $specialAccess true;
  684.         }
  685.         # Variable that turns off client side validation on entire action
  686.         $onlyServerSideVal true;
  687.         # Create Form Builder Object for "Add Resource"
  688.         $em $this->container->get("doctrine.orm.entity_manager");
  689.         $resource = new Resource();
  690.         $resourceForm $this->createForm(ResourceType::class, $resource, [
  691.             'isCarrier' => $this->get('core.get_environment')->getIsCarrier()
  692.         ]);
  693.         # Clear Upload Image Session
  694.         $session = new Session();
  695.         $session->remove("resource_upload_image");
  696.         $Roles = [
  697.             "ROLE_SUPER_ADMIN",
  698.             "ROLE_ADMIN",
  699.             "ROLE_EXAMINER",
  700.             "ROLE_TEAM_LEADER",
  701.             "ROLE_ADJUSTER",
  702.             "ROLE_REGISTERED"
  703.         ];
  704.         $states $em->getRepository("ResourceManagementBundle:State")->findBy([],['stateName'=>'ASC']);
  705.         return $this->render("ResourceManagementBundle:resources:addnew.html.twig", [
  706.             "specialAccess" => $specialAccess,
  707.             "resourceForm" => $resourceForm->createView(),
  708.             "onlyServerSideVal" => $onlyServerSideVal,
  709.             "Roles" => $Roles,
  710.             "resource" => $user,
  711.             "States" => $states
  712.         ]);
  713.     }
  714.     /**
  715.      * Save Add Resource Action
  716.      *
  717.      * @Route("/administration/resource/save_add")
  718.      */
  719.     public function saveAddResourceAjaxAction(Request $request)
  720.     {
  721.         $this->denyAccessUnlessGranted('add');
  722.         $dispatch $this->get('event_dispatcher');
  723.         # use "Add Resource" Form Object to get submitted form object
  724.         $em $this->container->get("doctrine.orm.entity_manager");
  725.         $envService $this->container->get("core.get_environment");
  726.         $resource = new Resource();
  727.         $resourceForm $this->createForm(ResourceType::class, $resource, [
  728.             'isCarrier' => $this->get('core.get_environment')->getIsCarrier()
  729.         ]);
  730.         $submittedForm $request->request->get("resource");
  731.         $roles $request->request->get("roles");
  732.        $ssn_ein = isset($submittedForm['ssn_ein']) ? $submittedForm['ssn_ein'] : "";
  733.        if(!empty($ssn_ein)){
  734.            $ssn_ein1 str_replace(' '''$ssn_ein);
  735.            $ssn_ein1 str_replace('-'''$ssn_ein1);
  736.        }else{
  737.            $ssn_ein1 '';
  738.        }
  739.         $form_supervisor = isset($submittedForm['supervisor']) ? $submittedForm['supervisor'] : "";
  740.         $form_npn_number = isset($submittedForm['niprNumber']) ? trim($submittedForm['niprNumber']) : "";
  741.         $is_nipr_tracking = ($request->get('is_nipr_tracking') == 'Yes') ? 0;
  742.         # isW2 isHourly conditions
  743.         if(isset($submittedForm['isW2'])){
  744.             $formIsW2 $submittedForm['isW2'];
  745.             if($formIsW2 == 1) {
  746.                 $formIsW2 true;
  747.                 $formIsHourly false;
  748.             }
  749.             elseif ($formIsW2 == -1) {
  750.                 $formIsW2 true;
  751.                 $formIsHourly true;
  752.             }
  753.             elseif ($formIsW2 == 0) {
  754.                 $formIsW2 false;
  755.                 $formIsHourly false;
  756.             }
  757.             $resource->setIsW2($formIsW2);
  758.             $resource->setIsHourly($formIsHourly);
  759.         }
  760.         # Set Supervisor
  761.         $Supervisor $em->getRepository("ResourceManagementBundle:Resource")->find($form_supervisor);
  762.         $resource->setSupervisor($Supervisor);
  763.         # Set NPN Number
  764.         if(!empty($form_npn_number)) {
  765.             $resource->setNiprNumber($form_npn_number);
  766.         }
  767.         # Manually submit form
  768.         $resourceForm->submit(
  769.             $submittedForm
  770.         );
  771.         $userNoteLog $this->container->get("app.resource_note_logger");
  772.         $user $this->container->get("security.token_storage")->getToken()->getUser();
  773.         if ($resource->getResourceType() instanceof \Globals\ResourceManagementBundle\Entity\ResourceType) {
  774.             $resourceTypeText $resource->getResourceType()->getResourceType();
  775.         } else {
  776.             /**
  777.              * Resource Type id 2 should be field adjuster
  778.              * better to search by int rather than string.
  779.              */
  780.             $resourceType $em->getRepository("ResourceManagementBundle:ResourceType")->find(2);
  781.             $resourceTypeText $resourceType->getResourceType();
  782.             $resource->setResourceType($resourceType);
  783.         }
  784.         if ($resource->getId() == $user->getId()) {
  785.             $comment $resource->getFullName() . " added the Resource Type $resourceTypeText.";
  786.         } else {
  787.             $comment "The Resource Type $resourceTypeText was added to the user " $resource->getFullName() . ", by " $user->getFullName() . ".";
  788.         }
  789.         # added 11/2018
  790.         # This will add the address information (validation will only occur if NON carrier)
  791.         $addr_form $request->request->get('addr_form');
  792.         if(!$addr_form['phone'] && !$envService->getIsCarrier())
  793.         {
  794.             $response = [];
  795.             $response['error'] = true;
  796.             $response['data']['errors'][] = [
  797.                 'id' => "form_phone",
  798.                 'text' => "This field needs a value, it cannot be blank!"
  799.             ];
  800.             return new JsonResponse($response);
  801.         }
  802.         if(!$addr_form['city'] && !$envService->getIsCarrier())
  803.         {
  804.             $response = [];
  805.             $response['error'] = true;
  806.             $response['data']['errors'][] = [
  807.                 'id' => "form_city",
  808.                 'text' => "This field needs a value, it cannot be blank!"
  809.             ];
  810.             return new JsonResponse($response);
  811.         }
  812.         if(!$addr_form['state'] && !$envService->getIsCarrier())
  813.         {
  814.             $response = [];
  815.             $response['error'] = true;
  816.             $response['data']['errors'][] = [
  817.                 'id' => "form_state",
  818.                 'text' => "This field needs a value, it cannot be blank!"
  819.             ];
  820.             return new JsonResponse($response);
  821.         }
  822.         if(!$addr_form['zip'] && !$envService->getIsCarrier())
  823.         {
  824.             $response = [];
  825.             $response['error'] = true;
  826.             $response['data']['errors'][] = [
  827.                 'id' => "form_zip",
  828.                 'text' => "This field needs a value, it cannot be blank!"
  829.             ];
  830.             return new JsonResponse($response);
  831.         }
  832.         if(!$addr_form['address'] && !$envService->getIsCarrier())
  833.         {
  834.             $response = [];
  835.             $response['error'] = true;
  836.             $response['data']['errors'][] = [
  837.                 'id' => "form_address",
  838.                 'text' => "This field needs a value, it cannot be blank!"
  839.             ];
  840.             return new JsonResponse($response);
  841.         }
  842.         if ($resourceForm->isValid()) {
  843.             # Validate Password not blank
  844.             if ($resource->getPassword() == "") {
  845.                 $response = [];
  846.                 $response['error'] = true;
  847.                 $response['data']['errors'][] = [
  848.                     'id' => "resource_password",
  849.                     'text' => "Please enter a password."
  850.                 ];
  851.                 return new JsonResponse($response);
  852.             }
  853.             # Validate for duplicate email
  854.             $HasEmail $em->getRepository("ResourceManagementBundle:Resource")->findBy(array("email" => $resource->getEmail()));
  855.             if ($HasEmail) {  // if duplicate
  856.                 $response = [];
  857.                 $response['error'] = true;
  858.                 $response['data']['errors'][] = [
  859.                     'id' => "resource_email",
  860.                     'text' => "This email already exists with a different account."
  861.                 ];
  862.                 return new JsonResponse($response);
  863.             }
  864.             # Validate for duplicate username
  865.             $HasUser $em->getRepository("ResourceManagementBundle:Resource")->findBy(array("username" => $resource->getUsername()));
  866.             if ($HasUser) {  // if duplicate
  867.                 $response = [];
  868.                 $response['error'] = true;
  869.                 $response['data']['errors'][] = [
  870.                     'id' => "resource_username",
  871.                     'text' => "This username already exists with a different account."
  872.                 ];
  873.                 return new JsonResponse($response);
  874.             }
  875.             if ($resource->getPassword() != "") {  // if set password
  876.                 # encrypt password with md5
  877.                 $resource->setPassword(md5($resource->getPassword()));
  878.             } else {
  879.                 $response = [];
  880.                 $response['error'] = true;
  881.                 $response['data']['errors'][] = [
  882.                     'id' => "resource_password",
  883.                     'text' => "Please enter a password."
  884.                 ];
  885.                 return new JsonResponse($response);
  886.             }
  887.             if (!$envService->getIsCarrier()) {
  888.                 if ($resource->getSsnEin()) {
  889.                     $resource->setSsnEin(md5($resource->getSsnEin()));
  890.                 } else {
  891.                     $response = [];
  892.                     $response['error'] = true;
  893.                     $response['data']['errors'][] = [
  894.                         'id' => "resource_ssn_ein",
  895.                         'text' => "This field is required."
  896.                     ];
  897.                     return new JsonResponse($response);
  898.                 }
  899.             }
  900.             # CUSTOM ADDRESS SAVING
  901.             $resource->setCity("");
  902.             if ($addr_form['city']) {
  903.                 $resource->setCity($addr_form['city']);
  904.             }
  905.             $State $em->getRepository("ResourceManagementBundle:State")->find(1);
  906.             $resource->setState($State);
  907.             if (intval($addr_form['state']) > 0) {
  908.                 $State $em->getRepository("ResourceManagementBundle:State")->find(intval($addr_form['state']));
  909.                 $resource->setState($State);
  910.             }
  911.             $resource->setAddress("");
  912.             if ($addr_form['address']) {
  913.                 $resource->setAddress($addr_form['address']);
  914.             }
  915.             $resource->setZip("");
  916.             if ($addr_form['zip']) {
  917.                 $resource->setZip($addr_form['zip']);
  918.             }
  919.             $resource->setPhone("");
  920.             if ($addr_form['phone']) {
  921.                 $resource->setPhone($addr_form['phone']);
  922.             }
  923.             if ($roles === "0") {
  924.                 $roles  "ROLE_ADJUSTER";
  925.                 $resource->setRoles('["ROLE_ADJUSTER"]');
  926.             } else {
  927.                 $resource->setRoles("[" '"' $roles '"' "]");
  928.             }
  929.             // For updating payroll id while creating new adjuster start
  930.             if($roles=='ROLE_ADJUSTER' || $roles=='ROLE_REGISTERED'){
  931.                 $payrollService $this->get('resource.payroll_service');
  932.                     $length 4;
  933.                     $payrollId $payrollService->randomStr($length);
  934.                     $resourceWithPayroll $this->getDoctrine()->getRepository('ResourceManagementBundle:Resource')->findBy(array('payrollId' => $payrollId));
  935.                     if (!empty($resourceWithPayroll)) {
  936.                         $payrollId $payrollService->randomStr($length);
  937.                     }
  938.                 $resource->setPayrollId($payrollId);
  939.             }
  940.             // For updating payroll id while creating new adjuster end
  941.             $em->flush();
  942.             # Persist to DB using Resource Profile Service method - saveAddResource()
  943.             $resource_profile $this->container->get("app.resource_profile");
  944.             $resource_profile->saveAddResource($resource);
  945.             $resource->setPasswordChangeDate(new \DateTime());
  946.             $resource->setNiprTracking($is_nipr_tracking);
  947.             # Persist once more
  948.             $em->persist($resource);
  949.             # Flush it all down
  950.             try {
  951.                 $em->flush();
  952.             } catch (\Exception $e) {
  953.             }
  954.             // to log the resource type changes
  955.             $userNoteLog->logNote($comment$resource);
  956.             $dispatcher $this->get('event_dispatcher');
  957.             $dispatcher->dispatch(new ResourceCreatedEvent($resource), ResourceCreatedEvent::RENAME );
  958.             $firstName $resource->getFirstName();
  959.             $LastName $resource->getLastName();
  960.             $niprNo =  $resource->getNiprNumber();
  961.             $phone =  $resource->getPhone();
  962.             $wingSpanService $this->container->get('resource.wingSpan');
  963.             $dataArray = array();
  964.             $dataArray['email'] = $resource->getEmail();
  965.             $dataArray['firstName'] = $resource->getFirstName();
  966.             $dataArray['lastName'] =  $resource->getLastName();;
  967.             $dataArray['memberCompany'] =  'CQ Digital';
  968.             $dataArray['memberId'] = $resource->getId();
  969.             if (!empty($resource->getWingSpanCollaboratorGroupId())) {
  970.                 //$response = $wingSpanService->CreateCollaborator($dataArray);
  971.                // $resource->setWingSpanCollaboratorId($response['collaboratorId']);
  972.                // $wingSpanService->pushCollaboratorGroup($response['collaboratorId'], $resource->getWingSpanCollaboratorGroupId());
  973.             }
  974.             $ssn_ein =  $ssn_ein1;
  975.             $niprTracking =  $resource->getNiprTracking();
  976.             if($niprTracking==1){
  977.                 $agentSyncService $this->container->get('resource.agentSync');
  978.                 $accessTokenArray $agentSyncService->getAccessToken();
  979.                 if (!empty($accessTokenArray['access_token'])){
  980.                     $agentSyncContactDataApi $agentSyncService->getAgentSyncNiprContactData($accessTokenArray,   $niprNo,$firstName,$LastName);
  981.                     if($agentSyncContactDataApi['totalSize']>0){
  982.                     }else{
  983.                         $agentSyncService->createContactAgentSync($accessTokenArray,   $niprNo,$firstName,$LastName,$phone,$ssn_ein,$resource->getId());
  984.                     }
  985.                 }
  986.             }
  987.             # Return success JSON
  988.             $retVal = array(
  989.                 "result" => "success",
  990.                 "error_msgs" => [],
  991.                 "roles" => $resource->getRoles(),
  992.                 "resource_id" => $resource->getId(),
  993.             );
  994.             $session = new Session();
  995.             $session->remove("resource_upload_image");
  996.             return new JsonResponse($retVal);
  997.         } else {
  998.             $response = [];
  999.             $response['error'] = true;
  1000.             $response['formError'] = (string)$resourceForm->getErrors(true);
  1001.             foreach($resourceForm as $formField){
  1002.                 $errorString = (string)$formField->getErrors();
  1003.                 if($errorString != ""){
  1004.                     $response['data']['errors'][] = [
  1005.                         'id' => $resourceForm->getName()."_".$formField->getName(),
  1006.                         'text' => $errorString
  1007.                     ];
  1008.                 }
  1009.             }
  1010.             return new JsonResponse($response);
  1011.         }
  1012.     }
  1013.     /**
  1014.      * @Route("/administration/fix/claim_report_duplicates")
  1015.      */
  1016.     public function deleteDupClaimReport() {
  1017.         $em $this->getDoctrine();
  1018.         $sql "SELECT * FROM claim_report cr 
  1019.                 WHERE claim_id = :claim_id 
  1020.                 AND invoice_id = :invoice_id 
  1021.                 AND document_type_id = :document_type_id AND cr.file_title = :file_title 
  1022.                 AND document_type_id = 9
  1023.                 AND invoice_id <> 0 ";
  1024.         $stmt_select_like_reports $em->getConnection()->prepare($sql);
  1025.         $sql "SELECT cr.* 
  1026.                 FROM claim_report cr 
  1027.                 INNER JOIN claim_report cr2 
  1028.                   ON cr.claim_id = cr2.claim_id
  1029.                 AND cr.invoice_id = cr.invoice_id
  1030.                 AND cr.document_type_id = cr2.document_type_id
  1031.                 AND cr.file_title = cr2.file_title 
  1032.                   AND cr.id != cr2.id
  1033.                 WHERE cr.document_type_id = 9
  1034.                   AND cr.invoice_id != 0
  1035.                 ORDER BY cr.invoice_id ";
  1036.         $stmt $em->getConnection()->prepare($sql);
  1037.         $stmt->execute();
  1038.         $results $stmt->fetchAll(\PDO::FETCH_ASSOC);
  1039.         foreach ($results as $getEach) {
  1040.             $sql "SELECT id, claim FROM claim_report cr 
  1041.                 WHERE claim_id = :claim_id 
  1042.                 AND invoice_id = :invoice_id 
  1043.                 AND document_type_id = :document_type_id AND cr.file_title = :file_title 
  1044.                 AND document_type_id = 9
  1045.                 AND invoice_id <> 0 ";
  1046.             $stmt_select_like_reports->execute([
  1047.                 "claim_id" => $getEach['claim_id'],
  1048.                 "invoice_id" => $getEach['invoice_id'],
  1049.                 "document_type_id" => $getEach['document_type_id'],
  1050.                 "file_title" => $getEach['file_title']
  1051.             ]);
  1052.             $i 0;
  1053.             $LikeResults $stmt_select_like_reports->fetchAll(\PDO::FETCH_ASSOC);
  1054.             foreach ($LikeResults as $getLike) {
  1055.                 if ($i count($LikeResults) - 1) {
  1056.                     // delete
  1057.                     /*/
  1058.                     DELETE FROM claim_report where id = :id
  1059.                     $getLike['id']
  1060.                     //*/
  1061.                 }
  1062.                 $i++;
  1063.             }
  1064.         }
  1065.         dump("Script completed"); die;
  1066.     }
  1067.     /**
  1068.      * @Route("/datatables/save/numperpage", methods={"POST"})
  1069.      */
  1070.     public function saveNumberPerPage(Request $request)
  1071.     {
  1072.         $numPerPage $request->request->has("num_per_page") ? $request->request->get("num_per_page") : 10;
  1073.         $session = new Session();
  1074.         $session->set("NumPerPage"$numPerPage);
  1075.         /*$user = $this->container->get("security.token_storage")->getToken()->getUser();
  1076.         if (!is_scalar($user)) {
  1077.             $user->setNumPerPage($numPerPage);
  1078.         }*/
  1079.         return new JsonResponse([
  1080.            "error" => false
  1081.         ]);
  1082.     }
  1083.     /**
  1084.      * Save Update Resource Action
  1085.      *
  1086.      * @Route("/administration/resource/sendwingspanlink/{id}")
  1087.      */
  1088.     public function sendwingspanlink(Request $requestResource $resource)
  1089.     {
  1090.         $em $this->container->get("doctrine.orm.entity_manager");
  1091.         $tokenStorage $this->container->get('security.token_storage');
  1092.         $user $tokenStorage->getToken()->getUser();
  1093.         $mailer $this->container->get('mail_management.mailer');
  1094.         $email_from $user->getEmail();
  1095.         //$mailer->replaceParam = array('strImagePath' => "", 'imageUrl' => "");
  1096.         $mailer->setSendingConfig();
  1097.         $wingspanlinkObj $em->getRepository('CoreBundle:SystemControlMetadata')->findOneBy(['cmetaKey' => 'wing_span_link']);
  1098.         $email_body "<p><strong>Hello ".$resource->getFirstName()." ".$resource->getLastName().",</strong></p>";
  1099.         $email_body .="<p></p><p>The second step in onboarding with Davies is for you to create a profile in the Wingspan system. Once complete, you will be able to log in and sign our 1099 contract.</p>";
  1100.         $email_body .= "<p>Please click below link for registration on wingspan</p>";
  1101.         $email_body .= "<p><a href='".$wingspanlinkObj->getCmetaValue()."'>Register</a></p>";
  1102.         $email_body .= "<p></p><p>You can reach out to recruiting if you have any questions.</p>";
  1103.             $email_body .= "<br/> Thanks </br/> The Recruiting Department ";
  1104.             $Mail = new Mail();
  1105.                 # SETTING THE SUBJECT
  1106.                 # ######################################################
  1107.                 $email_to $resource->getEmail();
  1108.                 # Recipient
  1109.                 $Recipient = new MailRecipient();
  1110.                 $Recipient->setEmail($email_to);
  1111.                 $Recipient->setMail($Mail);
  1112.                 $Recipient->setRecipientId($user->getId());
  1113.                 $entityName $em->getMetadataFactory()->getMetadataFor(get_class($user))->getName();
  1114.                 $Recipient->setRecipientType($entityName);
  1115.                 # Adds the single recipient (resource);
  1116.                 $Mail->addRecipient($Recipient);
  1117.                 $Mail->setSubject("Wing Span Registration - Notification");
  1118.             # Finalize the MAIL object
  1119.             $Mail->setBody($email_body);
  1120.             $Mail->setSenderName(MailHelper::getMailSenderName($tokenStorage));
  1121.             $mailer->sendEmail($Mail$email_from"");
  1122.         # Return JSON with Error Messages
  1123.         $retVal = array(
  1124.             "result" => "success",
  1125.             "error_msgs" => 'send',
  1126.             "error" => false
  1127.         );
  1128.         return new JsonResponse($retVal);
  1129.     }
  1130.     /**
  1131.      * Save Update Resource Action
  1132.      *
  1133.      * @Route("/administration/resource/save_edit/{id}")
  1134.      */
  1135.     public function saveEditResourceAjaxAction(Request $requestResource $resource)
  1136.     {
  1137.         $this->denyAccessUnlessGranted('edit'$resource);
  1138.         # "Edit Resource" Form Object, get submitted form object
  1139.         $em $this->container->get("doctrine.orm.entity_manager");
  1140.         $formFactory $this->container->get("form.factory");
  1141.         $AddressInfo='';
  1142.         $OldAddressInfo='';
  1143.         $workType='';
  1144.         $oldworkType='';
  1145.         $session = new Session();
  1146.         $session->remove("ResourceChanged");
  1147.         $session->remove("ResourceChanges");
  1148.         $envService $this->container->get("core.get_environment");
  1149.         $kernel $this->container->get("kernel");
  1150.         $authChecker $this->container->get("security.authorization_checker");
  1151.         $onlyServerSideVal false;
  1152.         $form_helper = new ResourceFormHelper($em$formFactory$kernel$onlyServerSideVal$authChecker);
  1153.         $oldSsnEin $resource->getSsnEin();
  1154.         $form $request->request->get("form");
  1155.        // if(!empty($wingSpanCollaboratorId)){
  1156.            // $wingSpanService = $this->container->get('resource.wingSpan');
  1157.             //$responseDocIdsArray = $wingSpanService->fetchCollaboratorDocumentIDs($wingSpanCollavoratorId);
  1158.            
  1159.             //foreach($responseDocIdsArray as $keyDocId=>$valueDocId){
  1160.                /// $clientIdData =  $wingSpanService->fetchDocumentDetails($valueDocId);
  1161.                // $fieldId = $clientIdData['client'];
  1162.                // $title = $clientIdData['docName'];
  1163.                // $filecontent =  $wingSpanService->downloadFile($fieldId);
  1164.                // $kernel = $this->container->get("kernel");
  1165.                // $env = $kernel->getEnvironment();
  1166.                // $env = str_replace("_dev", "", $env);
  1167.                // $env = 1000;
  1168.                // $new_file_path = $kernel->getRootDir() . "/../web/" . $env . "/wingSpanData/".$resource->getId();
  1169.                // if (!file_exists($new_file_path)) {
  1170.                //     mkdir($new_file_path, 0775);
  1171.               //  }else{
  1172.               //  }
  1173. // Then just save it like this
  1174.               //  file_put_contents( $new_file_path.'/'.$title, $filecontent );
  1175.           //  }
  1176.        // }
  1177.         //$wingSpanService = $this->container->get('resource.wingSpan');
  1178.         // $dataArray = array();
  1179.         //$response =  $wingSpanService->CreateCollaborator($dataArray);
  1180.         $employement_form $request->request->get("employment_form");
  1181.         $form_ssn_ein = isset($form['ssn_ein']) ? $form['ssn_ein'] : "";
  1182.         $xactAddress = ($request->request->has("xactAddress")) ? $request->request->get("xactAddress") : "";
  1183.         $symbilityAddress = ($request->request->has("symbilityAddress")) ? $request->request->get("symbilityAddress") : "";
  1184.         $form_supervisor = isset($form['supervisor']) ? $form['supervisor'] : "";
  1185.         $enabled = isset($form['isActive']) ? $form['isActive'] : "";
  1186.         $oldSupervisor $resource->getSupervisor();
  1187.         if(!empty($form['resource_type']))
  1188.             $resourceType $em->getRepository("ResourceManagementBundle:ResourceType")->find($form['resource_type']);
  1189.         /**
  1190.          * When disabling a vendor we need to remove all of their percentages so they dont get claims
  1191.          */
  1192.         if ($enabled == && $resource->getResourceType() && $resource->getResourceType()->getId() == 3) {
  1193.             # only use resource service here so just call the function directly
  1194.             $this->container->get("resource.service")->removeVendorPercentages($resource);
  1195.         }
  1196.         if(isset($form['supervisor'])){
  1197.             $newSupervisor $em->getRepository("ResourceManagementBundle:Resource")->find($form['supervisor']);
  1198.         }else{
  1199.             $newSupervisor "";
  1200.         }
  1201.         $didSupervisorChange false;
  1202.         if($oldSupervisor != $newSupervisor && ($oldSupervisor=="" || $newSupervisor=="")){
  1203.             $didSupervisorChange true;
  1204.         }
  1205.         # isW2 isHourly conditions
  1206.         if(isset($employement_form['isW2'])){
  1207.             $formIsW2 $employement_form['isW2'];
  1208.             if($formIsW2 == 1) {
  1209.                 $formIsW2 true;
  1210.                 $formIsHourly false;
  1211.             }
  1212.             elseif ($formIsW2 == -1) {
  1213.                 $formIsW2 true;
  1214.                 $formIsHourly true;
  1215.             }
  1216.             elseif ($formIsW2 == 0) {
  1217.                 $formIsW2 false;
  1218.                 $formIsHourly false;
  1219.             }
  1220.             ##
  1221.             $DbIsW2=intval($resource->getIsW2());
  1222.             $DbIsHourly=intval($resource->getIsHourly());
  1223.             $DbRadioValue=0;
  1224.             if($DbIsW2===&& $DbIsHourly===0){ $DbRadioValue=1;}
  1225.             if($DbIsW2===&& $DbIsHourly===1){ $DbRadioValue= -1;}
  1226.             if($DbIsW2===&& $DbIsHourly===0){ $DbRadioValue=0;}
  1227.             if($DbRadioValue !==intval($employement_form['isW2']) ){
  1228.                 $oldworkType= ($DbRadioValue == 1) ? "Salary" : (($DbRadioValue == -1)  ? "Hourly" "1099");
  1229.                 $workType = (intval($employement_form['isW2']) == 1) ? "Salary" : ((intval($employement_form['isW2']) == -1)  ? "Hourly" "1099");
  1230.             }
  1231.             ##
  1232.             $resource->setIsW2($formIsW2);
  1233.             $resource->setIsHourly($formIsHourly);
  1234.             if ($xactAddress) {
  1235.                 $resource->setXactAddress($xactAddress);
  1236.             }
  1237.             if ($symbilityAddress) {
  1238.                 $resource->setSymbilityAddress($symbilityAddress);
  1239.             }
  1240.         }
  1241.         # Request security role
  1242.         $role $request->request->get("role");
  1243.         $resourceForm $form_helper->getEditForm($resource);
  1244.         # this function must be called before $resourceForm->getData()
  1245.         $password $request->request->get("changepass");
  1246.         # Get Days Available Info from Request
  1247.         $weekDays = array();
  1248.         # Get Submitted Form Resource Object
  1249.         $resourceForm->handleRequest($request);
  1250.         $resource $resourceForm->getData();
  1251.         # Check if new Ssn EIn was entered
  1252.         if ($form_ssn_ein) {  // if yes
  1253.             # md5 the value
  1254.             $resource->setSsnEin(md5($form_ssn_ein));
  1255.         } else {  // if not
  1256.         }
  1257.         // save auth code
  1258.         $sms_authetication $request->request->get('sms_authetication');
  1259.         if ($sms_authetication) {
  1260.             $resource->setSmsAuthetication($sms_authetication);
  1261.         }
  1262.         // save SMS ADJUSTER ACCEPT code
  1263.         $sms_accept_message $request->request->get('sms_accept_message');
  1264.         if ($sms_accept_message) {
  1265.             $resource->setSmsAcceptMessage($sms_accept_message);
  1266.         }else{
  1267.             $resource->setSmsAcceptMessage(0);
  1268.         }
  1269.         $alreadyNotUsedTeam $this->getDoctrine()->getRepository('ResourceManagementBundle:TeamsNotUsed')->findBy(array('resourceId' => $resource->getId()));
  1270.         if(!empty($alreadyNotUsedTeam)){
  1271.             foreach($alreadyNotUsedTeam as $alreadyNotUsedTeam){
  1272.                 $alreadyNotUsedTeam->setIsActive('N');
  1273.                 $em->persist($alreadyNotUsedTeam);
  1274.             }
  1275.         }
  1276.         $team_not_used $request->request->get('team_not_used');
  1277.         if(!empty($team_not_used)){
  1278.             foreach($team_not_used as $key=>$value){
  1279.                 $teamNotUsed = new TeamsNotUsed();
  1280.                 $teamNotUsed->setResourceId($resource->getId());
  1281.                 $teamNotUsed->setTeamId($value);
  1282.                 $teamNotUsed->setIsActive('Y');
  1283.                 $teamNotUsed->setCreatedDate(new \DateTime());
  1284.                 $teamNotUsed->setUpdatedDate(new \DateTime());
  1285.                 $em->persist($teamNotUsed);
  1286.             }
  1287.         }
  1288.         # added 11/2018
  1289.         # This will add the address information (validation will only occur if NON carrier)
  1290.         # for saving wingspan groups starts
  1291.        // $alreadymappedWingspanGroups = $this->getDoctrine()->getRepository('ResourceManagementBundle:ResourceWingspanGroupMap')->findBy(array('resourceId' => $resource->getId()));
  1292.       //  if(!empty($alreadymappedWingspanGroups)){
  1293.            // foreach($alreadymappedWingspanGroups as $alreadymappedWingspanGroups){
  1294.                // $alreadymappedWingspanGroups->setIsActive('N');
  1295.               //  $em->persist($alreadymappedWingspanGroups);
  1296.            // }
  1297.        // }
  1298.         $wingspan_group_id $request->request->get('wingspan_group_id');
  1299.         if(!empty($wingspan_group_id)){
  1300.             $sent_id '';
  1301.             $wingSpanCollavoratorId $resource->getWingSpanCollaboratorId();
  1302.             $wingSpanService $this->container->get('resource.wingSpan');
  1303.             if(empty($wingSpanCollavoratorId)) {
  1304.                 $dataArray = array();
  1305.                 $dataArray['email'] = $resource->getEmail();
  1306.                 $dataArray['firstName'] = $resource->getFirstName();
  1307.                 $dataArray['lastName'] = $resource->getLastName();
  1308.                 $dataArray['memberCompany'] = 'CQ Digital';
  1309.                 $dataArray['memberId'] = $resource->getId();
  1310.                // if (!empty($resource->getWingSpanCollaboratorGroupId())) {
  1311.                     $response $wingSpanService->CreateCollaborator($dataArray);
  1312.                     $resource->setWingSpanCollaboratorId($response['collaboratorId']);
  1313.                     $wingSpanCollaboratorId $response['collaboratorId'];
  1314.                     // $wingSpanService->pushCollaboratorGroup($response['collaboratorId'], $resource->getWingSpanCollaboratorGroupId());
  1315.                 //}
  1316.             }
  1317.             foreach($wingspan_group_id as $key=>$value){
  1318.                 $alreadymappedWingspanGroups $this->getDoctrine()->getRepository('ResourceManagementBundle:ResourceWingspanGroupMap')->findBy(array('resourceId'=>$resource->getId(),'wingspanGroupId'=>$value));
  1319.                 if(!empty($alreadymappedWingspanGroups)){
  1320.                 }else {
  1321.                     $ResourceWingspanGroupMap = new ResourceWingspanGroupMap();
  1322.                     $ResourceWingspanGroupMap->setResourceId($resource->getId());
  1323.                     $ResourceWingspanGroupMap->setWingspanGroupId($value);
  1324.                     $ResourceWingspanGroupMap->setIsActive('Y');
  1325.                     $ResourceWingspanGroupMap->setPushedWingspan('Y');
  1326.                     $ResourceWingspanGroupMap->setCreatedDate(new \DateTime());
  1327.                     $ResourceWingspanGroupMap->setUpdatedDate(new \DateTime());
  1328.                     $em->persist($ResourceWingspanGroupMap);
  1329.                    $wingSpanService->pushCollaboratorGroup($resource->getWingSpanCollaboratorId(), $value);
  1330.                     if(!empty($sent_id))
  1331.                         $sent_id .= ', '.$value;
  1332.                     else
  1333.                         $sent_id $value;
  1334.                 }
  1335.                 // tag wingspan group to collaborator
  1336.                 // tag wingspan group to collaborator
  1337.             }
  1338.             if(!empty($sent_id)) {
  1339.                 $user $this->get('security.token_storage')->getToken()->getUser();
  1340.                 $comment "The resource, " $resource->getFirstName() . " " $resource->getLastName() . ", was updated by " $user ", with the following changes: added wingspan group $sent_id.";
  1341.                 $UserNote = new UserNote();
  1342.                 $UserNote->setComment($comment);
  1343.                 $UserNote->setCommentDate(new \DateTime());
  1344.                 $UserNote->setCommentByResource($user);
  1345.                 $UserNote->setResource($resource);
  1346.                 $UserNote->setUserNotesTypeId(9);
  1347.                 $UserNote->setEntryDate(new \DateTime());
  1348.                 $em->persist($UserNote);
  1349.             }
  1350.         }
  1351.         # for saving wingspan groups ends
  1352.         $addr_form $request->request->get('addr_form');
  1353.         if(!$addr_form['phone'] && !$envService->getIsCarrier())
  1354.         {
  1355.             $nextError['id'] = "phone";
  1356.             $nextError['text'] = "This field needs a value, it cannot be blank!";
  1357.             $data['errors'][] = $nextError;
  1358.             $retVal = array(
  1359.                 "result" => "fail",
  1360.                 "error_msgs" => $data['errors'],
  1361.                 "error" => true,
  1362.                 "data" => $data
  1363.             );
  1364.             return new JsonResponse($retVal);
  1365.         }
  1366.         if(!$addr_form['city'] && !$envService->getIsCarrier())
  1367.         {
  1368.             $nextError['id'] = "city";
  1369.             $nextError['text'] = "This field needs a value, it cannot be blank!";
  1370.             $data['errors'][] = $nextError;
  1371.             $retVal = array(
  1372.                 "result" => "fail",
  1373.                 "error_msgs" => $data['errors'],
  1374.                 "error" => true,
  1375.                 "data" => $data
  1376.             );
  1377.             return new JsonResponse($retVal);
  1378.         }
  1379.         if(!$addr_form['state'] && !$envService->getIsCarrier())
  1380.         {
  1381.             $nextError['id'] = "state";
  1382.             $nextError['text'] = "This field needs a value, it cannot be blank!";
  1383.             $data['errors'][] = $nextError;
  1384.             $retVal = array(
  1385.                 "result" => "fail",
  1386.                 "error_msgs" => $data['errors'],
  1387.                 "error" => true,
  1388.                 "data" => $data
  1389.             );
  1390.             return new JsonResponse($retVal);
  1391.         }
  1392.         if(!$addr_form['zip'] && !$envService->getIsCarrier())
  1393.         {
  1394.             $nextError['id'] = "zip";
  1395.             $nextError['text'] = "This field needs a value, it cannot be blank!";
  1396.             $data['errors'][] = $nextError;
  1397.             $retVal = array(
  1398.                 "result" => "fail",
  1399.                 "error_msgs" => $data['errors'],
  1400.                 "error" => true,
  1401.                 "data" => $data
  1402.             );
  1403.             return new JsonResponse($retVal);
  1404.         }
  1405.         if(!$addr_form['address'] && !$envService->getIsCarrier())
  1406.         {
  1407.             $nextError['id'] = "address";
  1408.             $nextError['text'] = "This field needs a value, it cannot be blank!";
  1409.             $data['errors'][] = $nextError;
  1410.             $retVal = array(
  1411.                 "result" => "fail",
  1412.                 "error_msgs" => $data['errors'],
  1413.                 "error" => true,
  1414.                 "data" => $data
  1415.             );
  1416.             return new JsonResponse($retVal);
  1417.         }
  1418.         $resID null;
  1419.         if(!empty($resource))
  1420.             $resID $resource->getId();
  1421.         if ($resourceType instanceof \Globals\ResourceManagementBundle\Entity\ResourceType) {
  1422.             $resource->setResourceType($resourceType);
  1423.         } else {
  1424.             /**
  1425.              * Resource Type id 2 should be field adjuster
  1426.              * better to search by int rather than string.
  1427.              */
  1428.             $resourceType $em->getRepository("ResourceManagementBundle:ResourceType")->find(2);
  1429.             $resource->setResourceType($resourceType);
  1430.         }
  1431.         # Compare 2 objects to see if there were any changes made
  1432.         if ($resourceForm->isValid()) {  // if form is valid
  1433.             # Validate for duplicate email
  1434.             $HasEmail $em->getRepository("ResourceManagementBundle:Resource")->checkEmailExists($resource->getEmail(), $resource->getId());
  1435.             if ($HasEmail) {
  1436.                 $errors2 = array();
  1437.                 $data = [
  1438.                     "errors" => array()
  1439.                 ];
  1440.                 $nextError = array();
  1441.                 $nextError['id'] = "email";
  1442.                 $nextError['text'] = "This email already exists with a different account.";
  1443.                 $data['errors'][] = $nextError;
  1444.                 $retVal = array(
  1445.                     "result" => "fail",
  1446.                     "error_msgs" => $errors2,
  1447.                     "error" => true,
  1448.                     "data" => $data
  1449.                 );
  1450.                 return new JsonResponse($retVal);
  1451.             }
  1452.             # Validate for duplicate username
  1453.             $HasUser $em->getRepository("ResourceManagementBundle:Resource")->checkUsernameExists($resource->getUsername(), $resource->getId());
  1454.             if ($HasUser) {
  1455.                 $errors2 = array();
  1456.                 $data = [
  1457.                     "errors" => array()
  1458.                 ];
  1459.                 $nextError = array();
  1460.                 $nextError['id'] = "username";
  1461.                 $nextError['text'] = "This username already exists with a different account.";
  1462.                 $data['errors'][] = $nextError;
  1463.                 $retVal = array(
  1464.                     "result" => "fail",
  1465.                     "error_msgs" => $errors2,
  1466.                     "error" => true,
  1467.                     "data" => $data
  1468.                 );
  1469.                 return new JsonResponse($retVal);
  1470.             }
  1471.             # If password field was updated
  1472.             if ($password) {
  1473.                 # encrypt submitted password
  1474.                 $resource->setPassword(md5($password));
  1475.                 $resource->setPasswordChangeDate(new \DateTime());
  1476.             }
  1477.             # If is being changed to Adjuster and does not have PayCom ID
  1478.             if ($resource->getResourceType() == "Adjuster") {
  1479.                 if (!$resource->getPayrollId()) {
  1480.                     # Add Paycom ID
  1481.                     $payrollService $this->get('resource.payroll_service');
  1482.                     $payrollIdExists true;
  1483.                     do {
  1484.                         $length 4;
  1485.                         $payrollId $payrollService->randomStr($length);
  1486.                         $resourceWithPayroll $this->getDoctrine()->getRepository('ResourceManagementBundle:Resource')->findBy(array('payrollId' => $payrollId));
  1487.                         if (empty($resourceWithPayroll)) {
  1488.                             $payrollIdExists false;
  1489.                         }
  1490.                     } while ($payrollIdExists === true);
  1491.                     $resource->setPayrollId($payrollId);
  1492.                 }
  1493.             }
  1494.             if ($role) {  // if role passed
  1495.                 # Set Security Role as Json
  1496.                 $roleArr[] = $role;
  1497.                 $resource->setRoles(json_encode($roleArr));
  1498.             }
  1499.             if($didSupervisorChange){
  1500.                 /** @var Resource $user */
  1501.                 $user $this->get('security.token_storage')->getToken()->getUser();
  1502.                 $oldSupervisor is_null($oldSupervisor)?"NULL":$oldSupervisor;
  1503.                 $newSupervisor is_null($newSupervisor)?"NULL":$newSupervisor;
  1504.                 $comment "The resource, "$resource->getFirstName()." ".$resource->getLastName().", was updated by " $user ", with the following changes: Supervisor was changed from $oldSupervisor to $newSupervisor.";
  1505.                 $UserNote = new UserNote();
  1506.                 $UserNote->setComment($comment);
  1507.                 $UserNote->setCommentDate(new \DateTime());
  1508.                 $UserNote->setCommentByResource($user);
  1509.                 $UserNote->setResource($resource);
  1510.                 $UserNote->setUserNotesTypeId(9);
  1511.                 $UserNote->setEntryDate(new \DateTime());
  1512.                 $em->persist($UserNote);
  1513.             }
  1514.             # compare the Db value with post value data
  1515.             $DbAddress=$resource->getAddress();
  1516.             $checkAddress strcmp(trim($addr_form['address']),trim($DbAddress));
  1517.             if ($checkAddress !=0){
  1518.                 $OldAddressInfo .=$DbAddress.', ';
  1519.                 $AddressInfo .=$addr_form['address'].', ';
  1520.             }
  1521.             $DbCity=$resource->getCity();
  1522.             $checkCity strcmp(trim($addr_form['city']),trim($DbCity));
  1523.             if ($checkCity !=0){
  1524.                 $OldAddressInfo .=$DbCity.', ';
  1525.                 $AddressInfo .=$addr_form['city'].', ';
  1526.             }
  1527.             $DbState=$resource->getState()->getId();
  1528.             if (intval($addr_form['state']) != $DbState){
  1529.                 $NewStateName $em->getRepository("ResourceManagementBundle:State")->find(intval($addr_form['state']));
  1530.                 $OldAddressInfo .=$resource->getState()->getStateName().', ';
  1531.                 $AddressInfo .=$NewStateName->getStateName();
  1532.             }
  1533.             $DbZip=$resource->getZip();
  1534.             $checkZip strcmp(trim($addr_form['zip']),trim($DbZip));
  1535.             if ($checkZip !=0){
  1536.                 $OldAddressInfo .=$DbZip.', ';
  1537.                 $AddressInfo .=$addr_form['zip'].', ';
  1538.             }
  1539.             $DbPhone=$resource->getPhone();
  1540.             if ($addr_form['phone'] != $DbPhone){
  1541.                 $OldAddressInfo .=" Phone No: ".$DbPhone;
  1542.                 $AddressInfo .=" Phone No: "$addr_form['phone'];
  1543.             }
  1544.             # compare the Db value with post value data
  1545.             # 11/2018
  1546.             # CUSTOM ADDRESS SAVING
  1547.             $resource->setAddress("");
  1548.             if($addr_form['address'])
  1549.             {
  1550.                 $resource->setAddress($addr_form['address']);
  1551.             }
  1552.             $resource->setCity("");
  1553.             if($addr_form['city'])
  1554.             {
  1555.                 $resource->setCity($addr_form['city']);
  1556.             }
  1557.             $State $em->getRepository("ResourceManagementBundle:State")->find(1);
  1558.             $resource->setState($State);
  1559.             if(intval($addr_form['state']) > 0)
  1560.             {
  1561.                 $State $em->getRepository("ResourceManagementBundle:State")->find(intval($addr_form['state']));
  1562.                 $resource->setState($State);
  1563.             }
  1564.             $resource->setZip("");
  1565.             if($addr_form['zip'])
  1566.             {
  1567.                 $resource->setZip($addr_form['zip']);
  1568.             }
  1569.             $resource->setPhone("");
  1570.             if($addr_form['phone'])
  1571.             {
  1572.                 $resource->setPhone($addr_form['phone']);
  1573.             }
  1574.             # Check if Resource Entity Changed (from Resource Event Listener)
  1575.             $session->remove("ResourceChanged");
  1576.             $session->remove("ResourceChanges");
  1577.             # Persist to DB using Resource Profile Service method - saveUpdateResouce()
  1578.             $resource_profile $this->container->get("app.resource_profile");
  1579.             $resource_profile->saveUpdateResource($resourcefalse);
  1580.             $dispatcher $this->get('event_dispatcher');
  1581.            $dispatcher->dispatch(new ResourceUpdatedEvent($resource), ResourceUpdatedEvent::RENAME );
  1582.             # send mail to Finance  team if Profile of resource updated
  1583.             $FinanceTeamEmail $em->getRepository('CoreBundle:SystemControlMetadata')->findOneBy(['cmetaKey' => 'fin_team_emails_to_send']);
  1584.             $tokenStorage $this->container->get('security.token_storage');
  1585.             $user  $tokenStorage->getToken()->getUser();
  1586.             $mailer $this->container->get('mail_management.mailer');
  1587.             $email_from $user->getEmail();
  1588.             //$mailer->replaceParam = array('strImagePath' => "", 'imageUrl' => "");
  1589.             $mailer->setSendingConfig();
  1590.             $addresses explode(','$FinanceTeamEmail instanceof SystemControlMetadata $FinanceTeamEmail->getCmetaValue() : "");
  1591.             $email_body ="<p><strong>Hi Team,</strong></p>";
  1592.             $email_body .="<p>User Profile: ".$resource->getFullName()." has been updated</p>";
  1593.             if(!empty($AddressInfo) ){
  1594.                 $email_body .="<p><strong>Old Address: </strong>".$OldAddressInfo."</p>";
  1595.                 $email_body .="<p><strong>New Address: </strong>".$AddressInfo."</p><br/>";
  1596.             }
  1597.             if(!empty($workType) ){
  1598.                 $email_body .="<p><strong>Old Employee Type: </strong>".$oldworkType."</p>";
  1599.                 $email_body .="<p><strong>New Employee Type: </strong>".$workType."</p><br/>";
  1600.             }
  1601.             if(!empty($AddressInfo) ||  !empty($workType)){
  1602.                 $email_body .="<br/> Thanks </br/> system Admin";
  1603.                 $Mail = new Mail();
  1604.                 foreach ($addresses as $address) {
  1605.                     # SETTING THE SUBJECT
  1606.                     # ######################################################
  1607.                     $email_to $address;
  1608.                     # Recipient
  1609.                     $Recipient = new MailRecipient();
  1610.                     $Recipient->setEmail($email_to);
  1611.                     $Recipient->setMail($Mail);
  1612.                     $Recipient->setRecipientId($user->getId());
  1613.                     $entityName $em->getMetadataFactory()->getMetadataFor(get_class($user))->getName();
  1614.                     $Recipient->setRecipientType($entityName);
  1615.                     # Adds the single recipient (resource);
  1616.                     $Mail->addRecipient($Recipient);
  1617.                     $Mail->setSubject("User Profile updated - Notification");
  1618.                 }
  1619.                 # Finalize the MAIL object
  1620.                 $Mail->setBody($email_body);
  1621.                 $Mail->setSenderName(MailHelper::getMailSenderName($tokenStorage));
  1622.                 $mailer->sendEmail($Mail$email_from"");
  1623.             }
  1624.             # Return JSON Success Object
  1625.             $retVal = array(
  1626.                 "result" => "success",
  1627.                 "error_msgs" => []
  1628.             );
  1629.             return new JsonResponse($retVal);
  1630.         } else {
  1631.             $data = [];
  1632.             # Get Form Errors using Validator Service
  1633.             $errors $this->get("validator")->validate($resource);dd($errors);
  1634.             $errors2 = array();
  1635.             if (count($errors) > 0) {
  1636.                 $data = [
  1637.                     "errors" => array()
  1638.                 ];
  1639.                 foreach ($errors as $error) {
  1640.                     $nextError = array();
  1641.                     $nextError['id'] = $error->getPropertyPath();
  1642.                     $nextError['text'] = $error->getMessage();
  1643.                     $data['errors'][] = $nextError;
  1644.                 }
  1645.             }
  1646.             # Return JSON with Error Messages
  1647.             $retVal = array(
  1648.                 "result" => "fail",
  1649.                 "error_msgs" => $errors2,
  1650.                 "error" => true,
  1651.                 "data" => $data
  1652.             );
  1653.             return new JsonResponse($retVal);
  1654.         }
  1655.     }
  1656.     /**
  1657.      * Handle Upload Signature File Action
  1658.      * recieves file object and saves to session for later use
  1659.      *
  1660.      * @Route("/administration/resource/upload_image")
  1661.      */
  1662.     public function saveUploadImageResourceAjaxAction(Request $request)
  1663.     {
  1664.         if (isset($_FILES['files']) && count($_FILES['files']['name']) > 0) {  // if file uploaded
  1665.             $session = new Session();
  1666.             # Extract File Object from $_FILES object
  1667.             $useFile = array();
  1668.             foreach ($_FILES['files'] as $key => $value) {
  1669.                 $useFile[$key] = $value[0];
  1670.             }
  1671.             $pathArr pathinfo(strtolower($useFile['name']));
  1672.             # Add File Extension to File Object Array
  1673.             $useFile['file_ext'] = $pathArr['extension'];
  1674.             # Validate file type
  1675.             $allowed_file_types = ["jpg""jpeg""png""gif"];
  1676.             if (!in_array($useFile['file_ext'], $allowed_file_types)) {  // if uploaded invalid file type
  1677.                 # pass back validation message of bad file type, instead of file name
  1678.                 $retVal = [
  1679.                     "files" => [
  1680.                         [
  1681.                             "name" => "File type not allowed"
  1682.                         ]
  1683.                     ]
  1684.                 ];
  1685.                 return new JsonResponse($retVal);
  1686.             }
  1687.             # create unique hash for filename, without extension
  1688.             $path $useFile['tmp_name'];
  1689.             $get_num md5(uniqid());
  1690.             $new_file_name is_numeric($get_num) ? $this->getRandomLargeNumber() : $get_num;
  1691.             $new_file_path "/tmp/" $new_file_name;
  1692.             $useFile['new_file_name'] = $new_file_name;
  1693.             $Log = new SLogger();
  1694.             $Log->log("new_file_name: " $new_file_name);
  1695.             # make note where file came from
  1696.             $useFile['used_by_module'] = "EditResource";
  1697.             $orig_file_name $useFile['name'];
  1698.             # save to session
  1699.             $session->set("resource_upload_image"$useFile);
  1700.             # copy as new file with unique id filename in /tmp folder, since original tmp file will be deleted after page runs
  1701.             move_uploaded_file($path$new_file_path);
  1702.         }
  1703.         # Return file name back to upload plugin
  1704.         $retVal = [
  1705.             "files" => [
  1706.                 [
  1707.                     "name" => $orig_file_name
  1708.                 ]
  1709.             ]
  1710.         ];
  1711.         return new JsonResponse($retVal);
  1712.     }
  1713.     /**
  1714.      * Modify Adjuster Positions Action
  1715.      *
  1716.      * @Route("/administration/resource/adjuster_position/edit/{id}")
  1717.      */
  1718.     public function editResourceAdjusterPositionAjaxAction(Resource $resource)
  1719.     {
  1720.         # lets make sure user has access to this page (stronger than super admin rights)
  1721.         $em $this->container->get("doctrine.orm.entity_manager");
  1722.         $user $this->get('security.token_storage')->getToken()->getUser();
  1723.         $systemParamService $this->get('core.system_parameter_control');
  1724.         $access $systemParamService->getAccessArray('access_resource');
  1725.         if (in_array($user->getId(), $access)) {
  1726.             $specialAccess true;
  1727.         }
  1728.         # Create Form Builder Object for "Edit Adjuster Positions"
  1729.         $formFactory $this->container->get("form.factory");
  1730.         $kernel $this->container->get("kernel");
  1731.         $authChecker $this->container->get("security.authorization_checker");
  1732.         $onlyServerSideVal=false;
  1733.         $form_helper = new ResourceFormHelper($em$formFactory$kernel$onlyServerSideVal$authChecker);
  1734.         $resourcePositionForm $form_helper->getAdjusterPositionEditForm($resource);
  1735.         # Get Current Adjuster Positions for this Resource
  1736.         $adjusterPositions = array();
  1737.         $adjusterPosIDs = array();
  1738.         foreach ($resource->getAdjusterPositions() as $adjusterPosition) {
  1739.             $adjusterPositions[] = $adjusterPosition;
  1740.             $adjusterPosIDs[] = $adjusterPosition->getId();
  1741.         }
  1742.         # Create array that contians whether or not each Adjuster Position exists on db for this Resource
  1743.         $SelAdjustersLoop = [];
  1744.         $AllAdjusterPositions $em->getRepository("ResourceManagementBundle:AdjusterPosition")->findBy(array(),array('positionName' => 'ASC') );
  1745.         foreach ($AllAdjusterPositions as $getPosition) {
  1746.             if (in_array($getPosition->getId(), $adjusterPosIDs)) {
  1747.                 $SelAdjustersLoop[] = 1;
  1748.             } else {
  1749.                 $SelAdjustersLoop[] = 0;
  1750.             }
  1751.         }
  1752.         # Variable that sets active tab
  1753.         $active 'adjusterPositions';
  1754.         $apiEndPointUsers $systemParamService->getAccessArray('PushNotificaton_tab');
  1755.         $bShowAPIEndPointTab false;
  1756.         if (!empty($apiEndPointUsers) && in_array($user->getId(),$apiEndPointUsers)) {
  1757.             $bShowAPIEndPointTab true;
  1758.         }
  1759.         return $this->render("ResourceManagementBundle:resources/adjuster_position:edit.html.twig", [
  1760.             "specialAccess" => isset($specialAccess),
  1761.             "resourcePositionForm" => $resourcePositionForm->createView(),
  1762.             "id" => $resource->getId(),
  1763.             "resource" => $resource,
  1764.             "useResource" => $resource,
  1765.             "SelAdjustersLoop" => $SelAdjustersLoop,
  1766.             "AllAdjusterPositions" => $AllAdjusterPositions,
  1767.             "activeClass" => $active,
  1768.             "bShowAPIEndPointTab" => $bShowAPIEndPointTab
  1769.         ]);
  1770.     }
  1771.     /**
  1772.      * Save Adjuster Positions Action
  1773.      *
  1774.      * @Route("/administration/resource/adjuster_position/save_edit/{id}")
  1775.      */
  1776.     public function saveEditResourceAdjusterPositionAjaxAction(Request $requestResource $resource)
  1777.     {
  1778.         # use "Edit Adjuster Positsions" Form Object to get submitted form object
  1779.         $em $this->container->get("doctrine.orm.entity_manager");
  1780.         $formFactory $this->container->get("form.factory");
  1781.         $kernel $this->container->get("kernel");
  1782.         $authChecker $this->container->get("security.authorization_checker");
  1783.         $onlyServerSideVal false;
  1784.         $form_helper = new ResourceFormHelper($em$formFactory$kernel$onlyServerSideVal,$authChecker);
  1785.         $form $form_helper->getAdjusterPositionEditForm($resource);
  1786.         # Log Changes to User Note
  1787.         $user $this->container->get("security.token_storage")->getToken()->getUser();
  1788.         $userNoteLog $this->container->get("app.resource_note_logger");
  1789.         # Handle Request
  1790.         $form->handleRequest($request);
  1791.         $resource $form->getData();
  1792.         #Check the adjuster positions that a user alreday has
  1793.         $sql "SELECT adjuster_position_id 
  1794.                 FROM resource_adjuster_position 
  1795.                 WHERE resource_id = :resource_id ";
  1796.         $stmt $em->getConnection()->prepare($sql);
  1797.         $stmt->execute(array("resource_id" => $resource->getId()));
  1798.         $resourcePositions $stmt->fetchAll(\PDO::FETCH_ASSOC);
  1799.         $slog = new SLogger();
  1800.         $slog->log('$resourcePositions');
  1801.         $slog->log($resourcePositions);
  1802.         $existingPositions  = array();
  1803.         foreach ($resourcePositions as $resourcePosition){
  1804.             $existingPositions[] = $resourcePosition['adjuster_position_id'];
  1805.         }
  1806.         $slog->log('$existingPositions');
  1807.         $slog->log($existingPositions);
  1808.         ## Handle updating of adjuster position checkboxes
  1809.         # First, Delete all relations between resource and adjuster positions
  1810.         $sql "DELETE FROM resource_adjuster_position WHERE resource_id = :resource_id ";
  1811.         $stmh $em->getConnection()->prepare($sql);
  1812.         $stmh->execute(array("resource_id" => $resource->getId()));
  1813.         # Will then add back adjuster positions that were checked on form
  1814.         $sql "INSERT INTO resource_adjuster_position
  1815.                 ( resource_id,  adjuster_position_id) VALUES
  1816.                 (:resource_id, :adjuster_position_id) ";
  1817.         $stmh_insert_resource_aduster $em->getConnection()->prepare($sql);
  1818.         $positions $request->request->get("chkPosition");
  1819.         $slog->log('$positions');
  1820.         $slog->log($positions);
  1821.         if ($positions) {
  1822.             foreach ($positions as $getPosition) {
  1823.                 $positionAdded true;
  1824.                 $sql "INSERT INTO resource_adjuster_position
  1825.                     ( resource_id,  adjuster_position_id) VALUES
  1826.                     (:resource_id, :adjuster_position_id) ";
  1827.                 # add back adjuster positions that were checked on form
  1828.                 $stmh_insert_resource_aduster->execute(array(
  1829.                     "resource_id" => $resource->getId(),
  1830.                     "adjuster_position_id" => $getPosition
  1831.                 ));
  1832.                 if($existingPositions) {
  1833.                     if (in_array($getPosition$existingPositions)) {
  1834.                         $positionAdded false;
  1835.                     }
  1836.                 }
  1837.                 $AdjusterPosition $em->getRepository("ResourceManagementBundle:AdjusterPosition")->find($getPosition);
  1838.                 if($positionAdded){
  1839.                     #log the user note
  1840.                     if ($resource->getId() == $user->getId()) {
  1841.                         $comment $resource->getFullName() . " added the position" $AdjusterPosition->getPositionName() . " to his profile.";
  1842.                     } else {
  1843.                         $comment "The position "  $AdjusterPosition->getPositionName() . ", was added to the user " $resource->getFullName() . ", by " $user->getFullName() . ".";
  1844.                     }
  1845.                     $userNoteLog->logNote($comment$resource);
  1846.                 }
  1847.             }
  1848.         }
  1849.         if($existingPositions){
  1850.             foreach ($existingPositions as $existingPosition){
  1851.                 $positionRemoved true;
  1852.                 if($positions) {
  1853.                     if (in_array($existingPosition$positions)) {
  1854.                         $positionRemoved false;
  1855.                     }
  1856.                 }
  1857.                 $AdjusterPosition $em->getRepository("ResourceManagementBundle:AdjusterPosition")->find($existingPosition);
  1858.                 if($positionRemoved){
  1859.                     #log the user note
  1860.                     if ($resource->getId() == $user->getId()) {
  1861.                         $comment $resource->getFullName() . " removed the position" $AdjusterPosition->getPositionName() . " from his profile.";
  1862.                     } else {
  1863.                         $comment "The position "  $AdjusterPosition->getPositionName() . ", was removed from the user " $resource->getFullName() . ", by " $user->getFullName() . ".";
  1864.                     }
  1865.                     $userNoteLog->logNote($comment$resource);
  1866.                 }
  1867.             }
  1868.         }
  1869.         # Save Other Resource Fields on Adjuster Positions Form
  1870.         $em->persist($resource);
  1871.         $em->flush();
  1872.         // for saving data of adjuster position tab update start
  1873.         $dispatcher $this->get('event_dispatcher');
  1874.         $dispatcher->dispatch(new ResourceUpdatedEvent($resource), ResourceUpdatedEvent::RENAME );
  1875.         // for saving data of adjuster position tab update end
  1876.         # Return Success JSON
  1877.         $retVal = array(
  1878.             "error" => false,
  1879.             "error_msgs" => []
  1880.         );
  1881.         return new JsonResponse($retVal);
  1882.     }
  1883.     /**
  1884.      * Show Datatable Ajax Data Action (for Old DataBuilders Style)
  1885.      *
  1886.      * @Route("/administration/resources2/search")
  1887.      */
  1888.     public function showResources2DataTablesAction(Request $request)
  1889.     {
  1890.         $User $this->container->get("security.token_storage")->getToken()->getUser();
  1891.         # Array of columns that will be sorted
  1892.         $columnsArr = array(
  1893.             "id",
  1894.             "username",
  1895.             "first_name",
  1896.             "last_name",
  1897.             "city",
  1898.             "state",
  1899.             "zip",
  1900.             "payroll_id",
  1901.             "show_active"
  1902.         );
  1903.         $active intval($request->query->get("active"));
  1904.         $dataParams = array();
  1905.         $sql "SELECT sr.*, S.stateName state, CASE WHEN ifnull(sr.is_active, 0) = 1 THEN 'Yes' ELSE 'No' END as show_active
  1906.                 FROM resource sr
  1907.                 LEFT JOIN state S
  1908.                   ON sr.state_id = S.id
  1909.                 WHERE roles NOT LIKE '%REGISTERED%' AND roles NOT LIKE '%BRANCH%' AND roles IS NOT NULL ";
  1910.         if ($active == 1) {
  1911.             $sql .= "AND sr.is_active = 1 ";
  1912.         } else if ($active == 0) {
  1913.             $sql .= "AND sr.is_active = 0 ";
  1914.         }
  1915.         $systemParamService             $this->container->get('core.system_parameter_control');
  1916.         if(in_array('ROLE_TEAM_LEADER',$User->getRoles()) ) {
  1917.             $sql_recur "SELECT sr.*, S.stateName state, CASE WHEN ifnull(sr.is_active, 0) = 1 THEN 'Yes' ELSE 'No' END as show_active
  1918.                 FROM resource sr
  1919.                 LEFT JOIN state S
  1920.                   ON sr.state_id = S.id
  1921.                 WHERE isSupervisees(:supervisor_id,sr.id) = 1 OR sr.ID = :supervisor_id_2
  1922.                 AND sr.roles NOT LIKE '%REGISTERED%' AND sr.roles NOT LIKE '%BRANCH%' AND sr.roles IS NOT NULL ";
  1923.             if ($active == 1) {
  1924.                 $sql_recur .= "AND sr.is_active = 1 ";
  1925.             } else if ($active == 0) {
  1926.                 $sql_recur .= "AND sr.is_active = 0 ";
  1927.             }
  1928.             //$sql .=" AND sr.supervisor_id = :supervisor_id";
  1929.             $dataParams['supervisor_id'] = $User->getId();
  1930.             $dataParams['supervisor_id_2'] = $User->getId();
  1931.             $slog = new SLogger();
  1932.             $slog->log("$sql_recur");
  1933.             $slog->log($sql_recur);
  1934.             $sql $sql_recur;
  1935.         }
  1936.         # if search keyword input was typed
  1937.         $keyword_filter "AND ( concat_ws(' ',first_name,last_name) like :keyword or sr.id like :keyword or first_name like :keyword or last_name like :keyword or username like :keyword or city like :keyword or zip like :keyword or payroll_id like :keyword) ";
  1938.         $paginator $this->container->get("resource.paginator_service");
  1939.         $retVal $paginator->getPaginationResults($request$sql$dataParams"sr.first_name ASC"$columnsArr""$keyword_filter"keyword""""POST");
  1940.         # Manipulate the resultset to be recieved by datatable
  1941.         $Results2 $retVal['data'];
  1942.         $Results = array();
  1943.         foreach ($Results2 as $index => $getResult) {
  1944.             $getResult2 $getResult;
  1945.             $getResult2['is_active'] = $getResult['is_active'] == "Yes" "No";
  1946.             $rolesArr2 = array();
  1947.             $rolesArr json_decode($getResult['roles']);
  1948.             if (is_array($rolesArr)) {
  1949.                 foreach ($rolesArr as $getRole) {
  1950.                     $rolesArr2[] = ResourceRoleEnum::getTypeName($getRole);
  1951.                 }
  1952.             } else {
  1953.                 $rolesArr2[] = ResourceRoleEnum::getTypeName($rolesArr);
  1954.             }
  1955.             $getResult2['roles'] = implode(", "$rolesArr2);
  1956.             unset($getResult2['entryDate']);
  1957.             $Results[$index] = $getResult2;
  1958.         }
  1959.         $retVal['data'] = $Results;
  1960.         return new JsonResponse($retVal);
  1961.     }
  1962.     /**
  1963.      * @param $sql
  1964.      * @return array
  1965.      *
  1966.      * This creates a paginator from raw sql
  1967.      */
  1968.     public function paginateSQL($sql$params)
  1969.     {
  1970.         $em $this->container->get("doctrine.orm.entity_manager");
  1971.         $paginator = new PaginatorSQL($em$sql$params);
  1972.         return $paginator;
  1973.     }
  1974.     /**
  1975.      * @Route("/administration/resource/delete", methods={"POST"})
  1976.      */
  1977.     public function deleteResourceAction(Request $request)
  1978.     {
  1979.         if ($this->get('security.authorization_checker')->isGranted('delete') === false) {
  1980.             $retVal = [
  1981.                 'error' => false,
  1982.                 'error_msgs' => ['You Do Not Have Access To Delete']
  1983.             ];
  1984.             return new JsonResponse($retVal);
  1985.         }
  1986.         $em $this->getDoctrine()->getManager();
  1987.         # Request ID to delete
  1988.         $id intval($request->request->get("id"));
  1989.         # Delete Resource
  1990.         $Resource $em->getRepository("ResourceManagementBundle:Resource")->find($id);
  1991.         if (empty($Resource)) {
  1992.             $retVal = [
  1993.                 'error' => true,
  1994.                 'error_msgs' => ['The resource does not exists']
  1995.             ];
  1996.         }
  1997.         $retVal $this->container->get("resource.service")->isResourceAvailableForDeletion($Resource);
  1998.         if (!empty($retVal) && isset($retVal['error']) && $retVal['error'] === false ) {
  1999.             $strResFullName $Resource->getFullName();
  2000.             $em->getConnection()->query('SET FOREIGN_KEY_CHECKS=0');
  2001.             $em->remove($Resource);
  2002.             $em->flush();
  2003.             $em->getConnection()->query('SET FOREIGN_KEY_CHECKS=1');
  2004.             $LoggedInUser = (string)$this->get("security.token_storage")->getToken()->getUser();
  2005.             $companyNoteService $this->get('company.note_logger');
  2006.             $notes "$strResFullName was deleted by $LoggedInUser.";
  2007.             $companyNoteService->addCompanyNote($notes);
  2008.             $retVal = [
  2009.                 'error' => false,
  2010.                 'error_msgs' => [],
  2011.                 'status' => 'success'
  2012.             ];
  2013.         }
  2014.         return new JsonResponse($retVal);
  2015.     }
  2016.     /**
  2017.      * @Route("/error/show500")
  2018.      */
  2019.     public function showError()
  2020.     {
  2021.         return $this->render("@ResourceManagement/error.html.twig");
  2022.     }
  2023.     /**
  2024.      * @Route("/administration/get_notifications/{resource_id}")
  2025.      */
  2026.     public function getNotifications($resource_id)
  2027.     {
  2028.         $notificationFinder $this->container->get('resource.notification_service');
  2029.         return new JsonResponse($notificationFinder->getNotificationData($resource_id));
  2030.     }
  2031.     /**
  2032.      * @Route("/administration/test_slog")
  2033.      */
  2034.     public function testSLog()
  2035.     {
  2036.         $slog = new SLogger();
  2037.         $slog->log("did slogger work?");
  2038.         dump("completed"); die;
  2039.     }
  2040.     private function getRandomLargeNumber()
  2041.     {
  2042.         return (string)rand(10000002000000) . (string)rand(10000002000000);
  2043.     }
  2044.     /**
  2045.      * @param Request $request
  2046.      * @param $hash
  2047.      * @return Response
  2048.      * @throws \Exception
  2049.      * Reset Password Action
  2050.      * shown when user comes from forgot password email
  2051.      *
  2052.      * @Route("/administration/user/password/forgot/{hash}")
  2053.      */
  2054.     public function showForgotPasswordAction(Request $request$hash)
  2055.     {
  2056.         # Remove old forgot password sessions
  2057.         $session = new Session();
  2058.         $session->remove("hash_user_token");
  2059.         $session->remove("hash_user_id");
  2060.         $em $this->container->get("doctrine.orm.entity_manager");
  2061.         # Find user token record by hash
  2062.         $user_tokens $em->getRepository('ResourceManagementBundle:UserToken')
  2063.             ->createQueryBuilder("u")
  2064.             ->where("u.hash = :hash")
  2065.             ->setParameter("hash"$hash)
  2066.             ->orderBy("u.entryDate""DESC")
  2067.             ->getQuery()
  2068.             ->getResult();
  2069.         $user_token = new UserToken();
  2070.         if (count($user_tokens) > 0) {
  2071.             $user_token $user_tokens[0];
  2072.         } else {  // if can't find token
  2073.             return $this->render("@ResourceManagement/emails/invalid.html.twig");
  2074.         }
  2075.         if ($user_token->getAction() != "ForgotPassword") {  // if token is not for "Forgot Password"
  2076.             return $this->render("@ResourceManagement/emails/invalid.html.twig");
  2077.         }
  2078.         # Make sure token is still valid (expires after 3 days)
  2079.         $entryDate $user_token->getEntryDate();
  2080.         $curDate = new \DateTime(date("Y-m-d H:i:s"));
  2081.         $interval $entryDate->diff($curDate);
  2082.         $daysDiff $interval->format('%a');
  2083.         $resource_profile $this->container->get("app.resource_profile");
  2084.         if ($daysDiff >= $resource_profile->daysValid) {
  2085.             return $this->render("@ResourceManagement/emails/invalid.html.twig");
  2086.         }
  2087.         # Get User from token record
  2088.         $resource $em->getRepository("ResourceManagementBundle:Resource")->find($user_token->getUserId());
  2089.         # Save sessions to be used by "Save Reset Password Action"
  2090.         $session->set("hash_user_token"$hash);
  2091.         $session->set("hash_user_id"$resource->getId());
  2092.         # Create Reset Password Form Object
  2093.         $onlyServerSideVal false;
  2094.         $em $this->container->get("doctrine.orm.entity_manager");
  2095.         $formFactory $this->container->get("form.factory");
  2096.         $kernel $this->container->get("kernel");
  2097.         $form_helper = new ResourceFormHelper($em$formFactory$kernel$onlyServerSideVal);
  2098.         $resourceForm $form_helper->getUpdatePasswordForm();
  2099.         # Create Custom CSRF Token
  2100.         $UserToken = new  UserToken();
  2101.         $js_hash md5($request->getClientIp() . $UserToken->salt_keyword2 substr($request->headers->get('User-Agent'), 017));
  2102.         return $this->render("ResourceManagementBundle:resources/templates:reset_password.html.twig", [
  2103.             "id" => $resource->getId(),
  2104.             "resource" => $resource,
  2105.             "hash" => $js_hash,
  2106.             "resourceForm" => $resourceForm->createView(),
  2107.             "onlyServerSideVal" => $onlyServerSideVal
  2108.         ]);
  2109.     }
  2110.     /**
  2111.      * Save Reset Password Action
  2112.      *
  2113.      * @Route("/administration/user/password/save_forgot")
  2114.      */
  2115.     public function saveForgotPasswordAction(Request $request)
  2116.     {
  2117.         $session = new Session();
  2118.         $em $this->container->get("doctrine.orm.entity_manager");
  2119.         # check if session contains user token information
  2120.         if (!$session->has("hash_user_token")) {  // if session not exists
  2121.             # send error message
  2122.             $errors2 = array();
  2123.             $data = [
  2124.                 "errors" => array()
  2125.             ];
  2126.             $nextError = array();
  2127.             $nextError['id'] = "password";
  2128.             $nextError['text'] = "This link has expired.";
  2129.             $data['errors'][] = $nextError;
  2130.             $retVal = array(
  2131.                 "result" => "fail",
  2132.                 "error_msgs" => $errors2,
  2133.                 "error" => true,
  2134.                 "data" => $data
  2135.             );
  2136.             return new JsonResponse($retVal);
  2137.         }
  2138.         # load user by session from token
  2139.         $resource $em->getRepository("ResourceManagementBundle:Resource")->find($session->get("hash_user_id"));
  2140.         # Validate Custom CSRF Token
  2141.         $UserToken = new  UserToken();
  2142.         $js_hash md5($request->getClientIp() . $UserToken->salt_keyword2 substr($request->headers->get('User-Agent'), 017));
  2143.         $form_hash $request->request->get("globals_hash_key");
  2144.         if ($js_hash != $form_hash) {  // if Custom CSRF token is invalid
  2145.             # send error message
  2146.             $errors2 = array();
  2147.             $data = [
  2148.                 "errors" => array()
  2149.             ];
  2150.             $nextError = array();
  2151.             $nextError['id'] = "password";
  2152.             $nextError['text'] = "This link has expired.";
  2153.             $data['errors'][] = $nextError;
  2154.             $retVal = array(
  2155.                 "result" => "fail",
  2156.                 "error_msgs" => $errors2,
  2157.                 "error" => true,
  2158.                 "data" => $data
  2159.             );
  2160.             return new JsonResponse($retVal);
  2161.         }
  2162.         $form $request->request->get("form");
  2163.         $password $form['password'];
  2164.         if ($password != "") {  // if password entered
  2165.             # Update password
  2166.             $resource->setPassword(md5($password));
  2167.             $em->persist($resource);
  2168.             $em->flush();
  2169.             $retVal = array(
  2170.                 "result" => "success",
  2171.                 "error_msgs" => []
  2172.             );
  2173.             # Remove token used for forgot password
  2174.             $sql "DELETE FROM user_token WHERE hash = :hash";
  2175.             $stmt $em->getConnection()->prepare($sql);
  2176.             $stmt->execute(array(
  2177.                 "hash" => $session->get("hash_user_token")
  2178.             ));
  2179.             # remove token session info
  2180.             $session->remove("hash_user_token");
  2181.             $session->remove("hash_user_id");
  2182.             return new JsonResponse($retVal);
  2183.         } else {  // if password is blank
  2184.             # send error message
  2185.             $errors2 = array();
  2186.             $data = [
  2187.                 "errors" => array()
  2188.             ];
  2189.             $nextError = array();
  2190.             $nextError['id'] = "password";
  2191.             $nextError['text'] = "You did not enter a password to update.";
  2192.             $data['errors'][] = $nextError;
  2193.             $retVal = array(
  2194.                 "result" => "fail",
  2195.                 "error_msgs" => $errors2,
  2196.                 "error" => true,
  2197.                 "data" => $data
  2198.             );
  2199.             return new JsonResponse($retVal);
  2200.         }
  2201.     }
  2202.     /**
  2203.      * @Route("/resource/adjuster-comment/{id}")
  2204.      */
  2205.     public function adjusterCommentAction(Request $request)
  2206.     {
  2207.         # logged in user
  2208.         $user $this->get('security.token_storage')->getToken()->getUser();
  2209.         //dd($user->getId());
  2210.         $em $this->container->get("doctrine.orm.entity_manager");
  2211.         $response = ['error'=>false'data'=>[]];
  2212.         $comment $request->request->get('adjustercomment');
  2213.         $ResourceId $request->get('id');
  2214.         # Check for post #
  2215.         if ($comment) {
  2216.             $ResourceEdited $em->getRepository("ResourceManagementBundle:Resource")->find($ResourceId);
  2217.             $AdjComment = new AdjusterComment();
  2218.             $AdjComment->setComment($comment);
  2219.             $AdjComment->setCommentDate(new \DateTime());
  2220.             $AdjComment->setLoggedInUserId($user->getId());
  2221.             $AdjComment->setResourceId($ResourceEdited->getId());
  2222.             $em->persist($AdjComment);
  2223.             //dd($AdjComment);
  2224.             $em->flush();
  2225.             #collect the Adjuster Comment
  2226.             $sql "SELECT ac.comment, ac.commentDate, CONCAT(r.first_name, ' ', r.last_name) AS author_name
  2227.               FROM adjuster_comments ac
  2228.               LEFT JOIN resource r
  2229.               ON ac.logged_in_user_id = r.id
  2230.               WHERE ac.resource_id = :rid
  2231.               ORDER BY ac.commentDate desc LIMIT 3";
  2232.             $AdjusterComments = array();
  2233.             $dataParams['rid'] = $ResourceEdited->getId();
  2234.             $stmt $em->getConnection()->prepare($sql);
  2235.             //dd($stmt);
  2236.             $stmt->execute($dataParams);
  2237.             $AdjusterComments $stmt->fetchAll(\PDO::FETCH_ASSOC);
  2238.             if (count($AdjusterComments) < 0) {
  2239.                 $AdjusterComments = array();
  2240.             }else{
  2241.                 $response=['error'=>false'data'=>$AdjusterComments];
  2242.             }
  2243.             //dd($response);
  2244.             return new JsonResponse($response);
  2245.         }else{
  2246.             return new JsonResponse(['error' => 'Adjuster Comment\'s Cannot Be Blank']);
  2247.         }
  2248.     }
  2249.     /**
  2250.      * @Route("/resource/all-adjuster-comment/")
  2251.      */
  2252.     public function allAdjusterCommentAction(Request $request)
  2253.     {
  2254.         # logged in user
  2255.         $user $this->get('security.token_storage')->getToken()->getUser();
  2256.         //dd($user->getId());
  2257.         $em $this->container->get("doctrine.orm.entity_manager");
  2258.         $response = ['error'=>false'data'=>[]];
  2259.         $ResourceId $request->request->get('resId');
  2260.         # Check for post #
  2261.         if ($ResourceId) {
  2262.             #collect the Adjuster Comment
  2263.             $sql "SELECT ac.comment, ac.commentDate, CONCAT(r.first_name, ' ', r.last_name) AS author_name
  2264.               FROM adjuster_comments ac
  2265.               LEFT JOIN resource r
  2266.               ON ac.logged_in_user_id = r.id
  2267.               WHERE ac.resource_id = :rid
  2268.               ORDER BY ac.commentDate desc";
  2269.             $AdjusterComments = array();
  2270.             $dataParams['rid'] = $ResourceId;
  2271.             $stmt $em->getConnection()->prepare($sql);
  2272.             //dd($stmt);
  2273.             $stmt->execute($dataParams);
  2274.             $AdjusterComments $stmt->fetchAll(\PDO::FETCH_ASSOC);
  2275.             if (count($AdjusterComments) < 0) {
  2276.                 $AdjusterComments = array();
  2277.             }
  2278.             return $this->render('@ResourceManagement/resources/popup-adj-comments.html.twig', [
  2279.                 "AllComments" => $AdjusterComments
  2280.             ]);
  2281.         }else{
  2282.             return new JsonResponse(['error' => 'Adjuster Comment\'s Cannot Be Blank']);
  2283.         }
  2284.     }
  2285. }