<?php
/**
* Created by PhpStorm.
* User: AHawley
* Date: 3/13/2017
* Time: 10:58 AM
*/
namespace Globals\ResourceManagementBundle\Controller;
use Globals\CoreBundle\Entity\SystemControlMetadata;
use Globals\CoreBundle\Helpers\MailHelper;
use Globals\ResourceManagementBundle\DependencyInjection\ExportFileUtils;
use Globals\ResourceManagementBundle\Entity\UserNote;
use Globals\ResourceManagementBundle\Form\ResourceType;
use Doctrine\ORM\EntityManager;
use Globals\ResourceManagementBundle\DependencyInjection\FormHelpers\ResourceFormHelper;
use Globals\ResourceManagementBundle\Entity\Resource;
use Globals\ResourceManagementBundle\Entity\TeamsNotUsed;
use Globals\ResourceManagementBundle\Entity\ResourceWingspanGroupMap;
use Globals\ResourceManagementBundle\Entity\UserToken;
use Globals\ResourceManagementBundle\Enum\ResourceRoleEnum;
use Globals\ResourceManagementBundle\Service\PaginatorSQL;
use Globals\ResourceManagementBundle\Service\SLogger;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Globals\ResourceManagementBundle\Event\ResourceCreatedEvent;
use Globals\ResourceManagementBundle\Event\ResourceUpdatedEvent;
use Globals\MailManagementBundle\Entity\Mail;
use Globals\MailManagementBundle\Entity\MailRecipient;
use Globals\ResourceManagementBundle\Entity\AdjusterComment;
use Globals\ResourceManagementBundle\Service\WingSpanService;
use Globals\ResourceManagementBundle\Entity\Contract;
class ResourceController extends AbstractController
{
/**
* Base Route (Vaughn's style)
*
* @Route("/administration/resource")
*/
public function resources2Action()
{
return $this->render("ResourceManagementBundle:resources:index2.html.twig", []);
}
/**
* @Route("/administration/resource/check_blob")
*/
public function checkBlobLineItem()
{
$em = $this->getDoctrine()->getManager();
$sql = "SELECT * FROM commission_report cr WHERE cr.invoice_id = :invoice_id AND invoice_type_id <> 4 ";
$stmt = $em->getConnection()->prepare($sql);
echo "<pre>";
$stmt->execute([
"invoice_id" => 201749,
]);
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($results) > 0) {
$Item = $results[0];
print_r(json_decode($Item['report_data']));
}
dump("script completed"); die;
}
/**
* @Route("/administration/resource/undo_cm/{invoiceId}")
*/
public function undoCreditMemo($invoiceId)
{
$em = $this->getDoctrine()->getManager();
$sql = "DELETE FROM commission_report
WHERE invoice_id = :id AND invoice_type_id = 4 ";
$stmt_delete_commission_report = $em->getConnection()->prepare($sql);
$sql = "DELETE FROM invoice_cm
WHERE invoice_id = :invoice_id ";
$stmt_delete_invoice_cm = $em->getConnection()->prepare($sql);
$sql = "SELECT id
FROM invoice_cm
WHERE invoice_id = :invoice_id ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"invoice_id" => $invoiceId
]);
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($results as $getEach) {
$sql = "DELETE FROM commission_report WHERE invoice_id = :id AND invoice_type_id = 4 ";
echo "<pre>";
echo "sql: $sql \n";
print_r([
"id" => $getEach['id']
]);
//*/
$stmt_delete_commission_report->execute([
"id" => $getEach['id']
]);
//*/
$sql = "DELETE FROM invoice_cm
WHERE invoice_id = :invoice_id;";
//*/
$stmt_delete_invoice_cm->execute([
"invoice_id" => $invoiceId,
]);
//*/
echo "<pre>";
echo "sql: $sql \n";
print_r([
"invoice_id" => $invoiceId,
]);
}
dump("script completed"); die;
}
/**
* @Route("/administration/resource/regrind_cm/{invoiceId}")
*/
public function regrindCreditMemo($invoiceId)
{
$em = $this->getDoctrine()->getManager();
$sql = "SELECT *
FROM commission_report
WHERE invoice_id = :invoice_id
AND invoice_type_id <> 4 ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"invoice_id" => $invoiceId
]);
$CommReports = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($CommReports) > 0) {
$GetCommReport = $CommReports[0];
$report_data = json_decode($GetCommReport['report_data']);
$report_data = $this->negateCreditMemoBlob($report_data, $invoiceId);
$sql = "SELECT id FROM invoice_cm WHERE invoice_id = :invoice_id ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"invoice_id" => $invoiceId
]);
$InvoiceCMs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($InvoiceCMs) > 0) {
$InvoiceCM = $InvoiceCMs[0];
$sql = "UPDATE commission_report
SET report_data = :report_data,
updated_at = :updated_at
WHERE invoice_id = :invoice_id
AND invoice_type_id = 4 ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"report_data" => json_encode($report_data),
"invoice_id" => $InvoiceCM['id'],
"updated_at" => date("Y-m-d H:i:s")
]);
}
}
dump("Script Completed"); die();
}
private function negateCreditMemoBlob($report_data, $originalInvId)
{
$em = $this->getDoctrine()->getManager();
$sql = "SELECT id
FROM invoice_cm
WHERE invoice_id = :invoice_id LIMIT 1 ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"invoice_id" => $originalInvId
]);
$InvoiceCMs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($InvoiceCMs) > 0) {
$invoiceCMId = $InvoiceCMs[0]['id'];
$report_data->claimData->dateCreated = date("Y-m-d H:i:s");
$report_data->claimData->TypeCode = "CM";
$report_data->claimData->inv_id = $invoiceCMId;
$report_data->claimData->invoice_type_id = 4;
$report_data->claimData->netTotal = -1 * floatval($report_data->claimData->netTotal);
$report_data->claimData->subTotal = -1 * floatval($report_data->claimData->subTotal);
$report_data->claimData->taxTotal = -1 * floatval($report_data->claimData->taxTotal);
$report_data->claimData->te_total = -1 * floatval($report_data->claimData->te_total);
$report_data->claimData->serviceExpense = -1 * floatval($report_data->claimData->serviceExpense);
$report_data->claimData->disbursementTotal = -1 * floatval($report_data->claimData->disbursementTotal);
if (property_exists($report_data, "invoice_resource_commission")) {
foreach ($report_data->invoice_resource_commission as $index => $getCommission) {
$report_data->invoice_resource_commission[$index]->amount = -1 * floatval($report_data->invoice_resource_commission[$index]->amount);
}
}
if (property_exists($report_data->claimData, "discount_max_summary")) {
foreach ($report_data->claimData->discount_max_summary as $expenseIndex => $getDiscount) {
if (is_array($report_data->claimData->discount_max_summary)) {
if (isset($report_data->claimData->discount_max_summary[$expenseIndex])
&& count($report_data->claimData->discount_max_summary[$expenseIndex]) > 0
&& property_exists($report_data->claimData->discount_max_summary[$expenseIndex], "subtotal")) {
$report_data->claimData->discount_max_summary[$expenseIndex]->subtotal = floatval($report_data->claimData->discount_max_summary[$expenseIndex]->subtotal) * -1;
}
} else {
if (is_array(($report_data->claimData->discount_max_summary->$expenseIndex))) {
if (isset($report_data->claimData->discount_max_summary->$expenseIndex["subtotal"])) {
$report_data->claimData->discount_max_summary->{$expenseIndex}["subtotal"] = floatval($report_data->claimData->discount_max_summary->{$expenseIndex}["subtotal"]) * -1;
}
} else {
if (property_exists($report_data->claimData->discount_max_summary, $expenseIndex)) {
if (property_exists($report_data->claimData->discount_max_summary->$expenseIndex, "subtotal")) {
$report_data->claimData->discount_max_summary->$expenseIndex->subtotal = floatval($report_data->claimData->discount_max_summary->$expenseIndex->subtotal) * -1;
}
}
}
}
if (is_array($report_data->claimData->discount_max_summary)) {
if (isset($report_data->claimData->discount_max_summary[$expenseIndex])
&& count($report_data->claimData->discount_max_summary[$expenseIndex]) > 0
&& property_exists($report_data->claimData->discount_max_summary[$expenseIndex], "net_subtotal")) {
$report_data->claimData->discount_max_summary[$expenseIndex]->net_subtotal = floatval($report_data->claimData->discount_max_summary[$expenseIndex]->net_subtotal) * -1;
}
} else {
if (is_array($report_data->claimData->discount_max_summary->$expenseIndex)) {
if (count($report_data->claimData->discount_max_summary->$expenseIndex) > 0
&& property_exists($report_data->claimData->discount_max_summary->$expenseIndex, "net_subtotal")) {
$report_data->claimData->discount_max_summary->$expenseIndex->net_subtotal = floatval($report_data->claimData->discount_max_summary->$expenseIndex->net_subtotal) * -1;
}
} else if (property_exists($report_data->claimData->discount_max_summary, $expenseIndex)) {
if (property_exists($report_data->claimData->discount_max_summary->{$expenseIndex}, "net_subtotal")) {
$report_data->claimData->discount_max_summary->{$expenseIndex}->net_subtotal = floatval($report_data->claimData->discount_max_summary->{$expenseIndex}->net_subtotal) * -1;
}
}
}
}
}
foreach ($report_data->invoice_data as $expenseIndex => $getLineItem) {
if (is_array($report_data->invoice_data)) {
if (isset($report_data->invoice_data[$expenseIndex]) && property_exists($report_data->invoice_data[$expenseIndex], "subtotal")) {
$report_data->invoice_data[$expenseIndex]->subtotal = (float)($report_data->invoice_data[$expenseIndex]->subtotal) * -1;
}
if (isset($report_data->invoice_data[$expenseIndex]) && property_exists($report_data->invoice_data[$expenseIndex], "net_subtotal")) {
$report_data->invoice_data[$expenseIndex]->net_subtotal = (float)($report_data->invoice_data[$expenseIndex]->net_subtotal) * -1;
}
} else {
if (property_exists($report_data->invoice_data->{$expenseIndex}, "subtotal")) {
$report_data->invoice_data->{$expenseIndex}->subtotal = (float)($report_data->invoice_data->$expenseIndex->subtotal) * -1;
}
if (property_exists($report_data->invoice_data->{$expenseIndex}, "net_subtotal")) {
$report_data->invoice_data->{$expenseIndex}->net_subtotal = (float)($report_data->invoice_data->$expenseIndex->net_subtotal) * -1;
}
}
}
}
return $report_data;
}
/**
* Show Datalist Page (Old DataBuilders style)
*
* @Route("/administration/resource/index")
*/
public function showResources2Action()
{
return $this->render("ResourceManagementBundle:resources:show2.html.twig");
}
/**
* @Route("/administration/resource/check_negate_blob")
*/
public function checkNegateBlob()
{
$em = $this->getDoctrine()->getManager();
$originalInvId = 202004;
$sql = "SELECT id, report_data, has_admin_fee_change
FROM commission_report
WHERE invoice_id = :invoice_id
AND invoice_type_id <> 4 ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"invoice_id" => $originalInvId
]);
$CommissionReports = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($CommissionReports) > 0) {
$CommReport = $CommissionReports[0];
$report_data = json_decode($CommReport['report_data']);
$sql = "SELECT id
FROM invoice_cm
WHERE invoice_id = :invoice_id LIMIT 1 ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"invoice_id" => $originalInvId
]);
$InvoiceCMs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($InvoiceCMs) > 0) {
$invoiceCMId = $InvoiceCMs[0]['id'];
$report_data->claimData->dateCreated = date("Y-m-d H:i:s");
$report_data->claimData->TypeCode = "CM";
$report_data->claimData->inv_id = $invoiceCMId;
$report_data->claimData->invoice_type_id = 4;
$report_data->claimData->netTotal = -1 * floatval($report_data->claimData->netTotal);
$report_data->claimData->subTotal = -1 * floatval($report_data->claimData->subTotal);
$report_data->claimData->taxTotal = -1 * floatval($report_data->claimData->taxTotal);
$report_data->claimData->te_total = -1 * floatval($report_data->claimData->te_total);
$report_data->claimData->serviceExpense = -1 * floatval($report_data->claimData->serviceExpense);
$report_data->claimData->disbursementTotal = -1 * floatval($report_data->claimData->disbursementTotal);
if (property_exists($report_data, "invoice_resource_commission")) {
foreach ($report_data->invoice_resource_commission as $index => $getCommission) {
$report_data->invoice_resource_commission[$index]->amount = -1 * floatval($report_data->invoice_resource_commission[$index]->amount);
}
}
if (property_exists($report_data->claimData, "discount_max_summary")) {
foreach ($report_data->claimData->discount_max_summary as $expenseIndex => $getDiscount) {
if (is_array($report_data->claimData->discount_max_summary)) {
if (isset($report_data->claimData->discount_max_summary[$expenseIndex])
&& count($report_data->claimData->discount_max_summary[$expenseIndex]) > 0
&& property_exists($report_data->claimData->discount_max_summary[$expenseIndex], "subtotal")) {
$report_data->claimData->discount_max_summary[$expenseIndex]->subtotal = floatval($report_data->claimData->discount_max_summary[$expenseIndex]->subtotal) * -1;
}
} else {
if (is_array(($report_data->claimData->discount_max_summary->$expenseIndex))) {
if (isset($report_data->claimData->discount_max_summary->$expenseIndex["subtotal"])) {
$report_data->claimData->discount_max_summary->{$expenseIndex}["subtotal"] = floatval($report_data->claimData->discount_max_summary->{$expenseIndex}["subtotal"]) * -1;
}
} else {
if (property_exists($report_data->claimData->discount_max_summary, $expenseIndex)) {
if (property_exists($report_data->claimData->discount_max_summary->$expenseIndex, "subtotal")) {
$report_data->claimData->discount_max_summary->$expenseIndex->subtotal = floatval($report_data->claimData->discount_max_summary->$expenseIndex->subtotal) * -1;
}
}
}
}
if (is_array($report_data->claimData->discount_max_summary)) {
if (isset($report_data->claimData->discount_max_summary[$expenseIndex])
&& count($report_data->claimData->discount_max_summary[$expenseIndex]) > 0
&& property_exists($report_data->claimData->discount_max_summary[$expenseIndex], "net_subtotal")) {
$report_data->claimData->discount_max_summary[$expenseIndex]->net_subtotal = floatval($report_data->claimData->discount_max_summary[$expenseIndex]->net_subtotal) * -1;
}
} else {
if (is_array($report_data->claimData->discount_max_summary->$expenseIndex)) {
if (count($report_data->claimData->discount_max_summary->$expenseIndex) > 0
&& property_exists($report_data->claimData->discount_max_summary->$expenseIndex, "net_subtotal")) {
$report_data->claimData->discount_max_summary->$expenseIndex->net_subtotal = floatval($report_data->claimData->discount_max_summary->$expenseIndex->net_subtotal) * -1;
}
} else if (property_exists($report_data->claimData->discount_max_summary, $expenseIndex)) {
if (property_exists($report_data->claimData->discount_max_summary->{$expenseIndex}, "net_subtotal")) {
$report_data->claimData->discount_max_summary->{$expenseIndex}->net_subtotal = floatval($report_data->claimData->discount_max_summary->{$expenseIndex}->net_subtotal) * -1;
}
}
}
}
}
foreach ($report_data->invoice_data as $expenseIndex => $getLineItem) {
if (is_array($report_data->invoice_data)) {
if (isset($report_data->invoice_data[$expenseIndex]) && property_exists($report_data->invoice_data[$expenseIndex], "subtotal")) {
$report_data->invoice_data[$expenseIndex]->subtotal = (float)($report_data->invoice_data[$expenseIndex]->subtotal) * -1;
}
if (isset($report_data->invoice_data[$expenseIndex]) && property_exists($report_data->invoice_data[$expenseIndex], "net_subtotal")) {
$report_data->invoice_data[$expenseIndex]->net_subtotal = (float)($report_data->invoice_data[$expenseIndex]->net_subtotal) * -1;
}
} else {
if (property_exists($report_data->invoice_data->{$expenseIndex}, "subtotal")) {
$report_data->invoice_data->{$expenseIndex}->subtotal = (float)($report_data->invoice_data->$expenseIndex->subtotal) * -1;
}
if (property_exists($report_data->invoice_data->{$expenseIndex}, "net_subtotal")) {
$report_data->invoice_data->{$expenseIndex}->net_subtotal = (float)($report_data->invoice_data->$expenseIndex->net_subtotal) * -1;
}
}
}
}
}
return $report_data;
//dump("script completed"); die;
}
/**
* @Route("/administration/resource/edit/{id}", defaults={"id" = null})
*/
public function editResourceAjaxAction(Request $request, Resource $resource)
{
# lets make sure user has access to this page (stronger than super admin rights)
$user = $this->get('security.token_storage')->getToken()->getUser();
$systemParamService = $this->get('core.system_parameter_control');
$access = $systemParamService->getAccessArray('access_resource');
$specialAccess = false;
if (in_array($user->getId(), $access)) {
$specialAccess = true;
}
$em = $this->container->get("doctrine.orm.entity_manager");
$wingSpanCollavoratorId = $resource->getWingSpanCollaboratorId();
if(empty($wingSpanCollavoratorId)) {
$wingSpanService = $this->container->get('resource.wingSpan');
$dataArray = array();
$dataArray['email'] = $resource->getEmail();
$dataArray['firstName'] = $resource->getFirstName();
$dataArray['lastName'] = $resource->getLastName();
$dataArray['memberCompany'] = 'CQ Digital';
$dataArray['memberId'] = (string)$resource->getId();
if (!empty($resource->getWingSpanCollaboratorGroupId())) {
// $response = $wingSpanService->CreateCollaborator($dataArray);
// dd($response);
// $resource->setWingSpanCollaboratorId($response['collaboratorId']);
// $em->persist($resource);
// $em->flush();
// $wingSpanCollaboratorId = $response['collaboratorId'];
//$wingSpanService->pushCollaboratorGroup($response['collaboratorId'], $resource->getWingSpanCollaboratorGroupId());
}
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$i=0;
$envService = $this->container->get("core.get_environment");
//die;
// dd($responseDocIdsArray);
# Variable that turns off client side validation on entire action
$onlyServerSideVal = false;
# Clear Upload Image Session
$session = new Session();
$session->remove("resource_upload_image");
# Create Form Builder Object for "Edit Resource"
/** @var EntityManager $em */
$ClaimTeams = $em->getRepository("ClaimManagementBundle:ClaimTeam")->findBy(['enabled' => true], ['name' => 'ASC']);
$WingSpanGroups = $em->getRepository("CompanyManagementBundle:WingspanGroups")->findBy(['isActive' => 'Y'], ['wingspanGroup' => 'ASC']);
$alreadyNotUsedTeam = $this->getDoctrine()->getRepository('ResourceManagementBundle:TeamsNotUsed')->findBy(array('resourceId' => $resource->getId(),'isActive'=>'Y'));
$alreadyNotUsedTeamArray = array();
if(!empty($alreadyNotUsedTeam)) {
foreach ($alreadyNotUsedTeam as $alreadyNotUsedTeam) {
$alreadyNotUsedTeamArray[$alreadyNotUsedTeam->getTeamId()] = $alreadyNotUsedTeam->getTeamId();
}
}
$mappedWingspanGroups = $this->getDoctrine()->getRepository('ResourceManagementBundle:ResourceWingspanGroupMap')->findBy(array('resourceId' => $resource->getId(),'isActive'=>'Y'));
$alreadyMappedWingspanArray = array();
if(!empty($mappedWingspanGroups)) {
foreach ($mappedWingspanGroups as $mappedWingspanGroups) {
$alreadyMappedWingspanArray[$mappedWingspanGroups->getWingspanGroupId()] = $mappedWingspanGroups->getWingspanGroupId();
}
}
// dd($alreadyMappedWingspanArray);
$niprTracking = $resource->getNiprTracking();
if($niprTracking==1){
$niprNo = $resource->getNiprNumber();
$agentSyncService = $this->container->get('resource.agentSync');
$accessTokenArray = $agentSyncService->getAccessToken();
if (!empty($accessTokenArray['access_token'])){
//$agentSyncDataApi = $agentSyncService->createContactAgentSync($accessTokenArray, $niprNo,$firstName,$LastName,$phone);
$agentSyncContactDataApi = $agentSyncService->getAgentSyncNiprContactData($accessTokenArray, $niprNo);
if($agentSyncContactDataApi['totalSize']>0){
$resource->setAgentSyncResponse($agentSyncContactDataApi['records'][0]['agentsync__AgentSync_Status__c']);
if($agentSyncContactDataApi['records'][0]['agentsync__AgentSync_Status__c']=='nipr_error'){
$is_nipr_tracking = 0;
$resource->setNiprTracking($is_nipr_tracking);
}
$em->persist($resource);
$em->flush();
}else{
$resource->setAgentSyncResponse('NpnNotFoundError');
$em->persist($resource);
$em->flush();
}
}
}
$formFactory = $this->container->get("form.factory");
$kernel = $this->container->get("kernel");
$authChecker = $this->container->get("security.authorization_checker");
$form_helper = new ResourceFormHelper($em, $formFactory, $kernel, $onlyServerSideVal, $authChecker);
$resourceForm = $form_helper->getEditForm($resource);
# Variable that sets active tab
$active = 'resource';
$image_id = "";
$FileManager = $em->getRepository("ResourceManagementBundle:FileManager")->loadByFileIDEntity($resource->getId(), "ResourceSignature");
if ($FileManager) { // if signature file exists for this Resource
# fill variable used to validate is signature file was ever uploaded
$image_id = $FileManager->getId();
}
$currentRole = "ROLE_REGISTERED";
if ($resource->getRoles()) {
$getRole = $resource->getRoles();
if (is_array($getRole) && count($getRole) > 0) {
$currentRole = $getRole[0];
}
}
$Roles = [
"ROLE_SUPER_ADMIN",
"ROLE_ADMIN",
"ROLE_EXAMINER",
"ROLE_TEAM_LEADER",
"ROLE_ADJUSTER",
"ROLE_REGISTERED"
];
// user stats for ICM
$isCarrier = $envService->getIsCarrier();
// check if resource has ever been deployed
$sql = "SELECT count(c.id) as claim_count
FROM claim as c, assignments as cr, resource as r
WHERE c.id = cr.claim_id
AND cr.resource_id = r.id
AND r.id = :resource_id
AND c.loss_state_id != r.state_id
AND IFNULL(cr.next_assignment_id,0) = 0
AND IFNULL(cr.is_current_assignment,0) = 1";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"resource_id" => $resource->getId()
]);
$claim_count = $stmt->fetchAll( \PDO::FETCH_ASSOC );
if( $claim_count[0]['claim_count'] > 0 )
$hasBeenDeployed = true;
else
$hasBeenDeployed = false;
// count of all claims
// check if resource has ever been deployed
$sql = "SELECT COUNT(*) as claim_count
FROM claim c, assignments cr
WHERE c.id = cr.claim_id
AND cr.resource_id = :resource_id
AND IFNULL(cr.next_assignment_id,0) = 0
AND IFNULL(cr.is_current_assignment,0) = 1";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute([
"resource_id" => $resource->getId()
]);
$claim_count = $stmt->fetchAll( \PDO::FETCH_ASSOC );
$resourceClaimCount = $claim_count[0]['claim_count'];
$states = $em->getRepository("ResourceManagementBundle:State")->findBy([],['stateName'=>'ASC']);
$activeForLastYear = 'No';
$strCurrentDate = date('Y-m-d');
$strPreviouYearDate = date('Y-m-d', strtotime("-1 years"));
$dateLastAct = $resource->getLastActivityAt();
if (!empty($dateLastAct)) {
$strResourceLastActDate = $resource->getLastActivityAt()->format('Y-m-d');
if (($strResourceLastActDate >= $strPreviouYearDate) && ($strResourceLastActDate <= $strCurrentDate)){
$activeForLastYear = 'yes';
}else{
$activeForLastYear = 'no';
}
}
# get password change date
if(!empty($resource->getPasswordChangeDate())){
$passChangeDate=$resource->getPasswordChangeDate()->format('m/d/Y H:i:s');
$currentDate = date('Y-m-d H:i:s');
$passwordChangeDate=$resource->getPasswordChangeDate()->format('Y-m-d H:i:s');
$dayDiff = (strtotime($currentDate) - strtotime($passwordChangeDate)) / (60 * 60 * 24);
}else{
$passChangeDate='';
$dayDiff =0;
}
$agentSyncResponse = '';
$agentSyncResponse =$resource->getAgentSyncResponse();
#collect the Adjuster Comment
$sql = "SELECT ac.comment, ac.commentDate, CONCAT(r.first_name, ' ', r.last_name) AS author_name
FROM adjuster_comments ac
LEFT JOIN resource r
ON ac.logged_in_user_id = r.id
WHERE ac.resource_id = :rid
ORDER BY ac.commentDate desc LIMIT 3";
$AdjusterComments = array();
$dataParams['rid'] = $resource->getId();
$stmt = $em->getConnection()->prepare($sql);
//dd($stmt);
$stmt->execute($dataParams);
$AdjusterComments = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($AdjusterComments) < 0) {
$AdjusterComments = array();
}
// dd($AdjusterComments);
return $this->render("ResourceManagementBundle:resources:edit.html.twig", [
"specialAccess" => $specialAccess,
"isTlg" => $resource->GetisTlg(),
"id" => $resource->getId(),
"resource" => $resource,
"useResource" => $resource,
"resourceForm" => $resourceForm->createView(),
"signature" => $resource->getSignature(),
"onlyServerSideVal" => $onlyServerSideVal,
"activeClass" => $active,
"image_id" => $image_id,
"Roles" => $Roles,
"CurrentRole" => $currentRole,
"isCarrier" => $isCarrier,
"hasBeenDeployed" => $hasBeenDeployed,
"resourceClaimCount" => $resourceClaimCount,
"States" => $states,
"activeForLastYear" => $activeForLastYear,
"passChangeDate" => $passChangeDate,
"dayDiff" => round($dayDiff),
"comments" => $AdjusterComments,
'agentSyncResponse' =>$agentSyncResponse,'ClaimTeams'=>$ClaimTeams,'alreadyNotUsedTeamArray'=>$alreadyNotUsedTeamArray,'WingSpanGroups'=>$WingSpanGroups,'alreadyMappedWingspanArray'=>$alreadyMappedWingspanArray
]);
}
/**
* @Route("/administration/resource/make_tmp")
*/
public function createTmpFolder()
{
$kernel = $this->container->get("kernel");
$file_path = $kernel->getRootDir() . "/../../tmp/licenses";
mkdir($file_path, 0775);
die("script completed");
}
/**
* method that checks if Resource has a signature
*
* @Route("/resource/has_signature_view/{id}")
*/
public function hasSignatureImage(Resource $resource)
{
$retVal = true;
if ($resource == null) {
$retVal = false;
}
$file_manager = $this->container->get("app.file_manager");
$retVal = $file_manager->retrieveFilePathByEntity($resource->getId(), "ResourceSignature");
if (!$retVal) {
$retVal = false;
}
if ($retVal == true) {
$json = array(
"error" => false,
"data" => []
);
return new JsonResponse($json);
} else {
$json = array(
"error" => true,
"data" => [],
"messages" => ["This resource does not have a signature"]
);
return new JsonResponse($json);
}
}
/**
* Fetch the blob by invoice id
*
* @Route("/administration/resource/get_blob/item/{invoiceId}")
*/
public function getBlob($invoiceId)
{
$em = $this->container->get("doctrine.orm.entity_manager");
# Push Shreya's Changes
$sql = "SELECT * FROM commission_report WHERE invoice_id = :invoice_id ";
$dataParams['invoice_id'] = $invoiceId;
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute($dataParams);
$resultset = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($resultset as $getItem) {
dump($getItem['report_data']);
}
die;
return new JsonResponse(array());
}
/**
* @Route("/administration/resource/signature_view/{id}/{randomNum}")
*/
public function displaySignatureImage(Resource $resource, $randomNum)
{
if ($resource === null) {
throw new NotFoundHttpException('Could not find this Resource!');
}
$file_manager = $this->container->get("app.file_manager");
$retVal = $file_manager->retrieveFilePathByEntity($resource->getId(), "ResourceSignature", 1);
//return new NonCachableBinaryFileResponse($retVal);
if(isset($retVal) && !empty($retVal))
return new Response($retVal[0], $retVal[1], $retVal[2]);
else
return new Response(1);
}
/**
* @Route("/administration/resource/profile_view/{id}", defaults={"id"=null})
*/
public function displayProfileImage(Resource $resource)
{
if ($resource === null) {
throw new NotFoundHttpException('Could not find this Resource!');
}
$file_manager = $this->container->get("app.file_manager");
$file = $file_manager->retrieveFilePathByEntity($resource->getId(), "ProfilePicture", 1);
if($file){
//return new NonCachableBinaryFileResponse($file);
return new Response($file);
}else{
return "";
}
}
/**
* @Route("/administration/resource/add")
*/
public function addResourceAjaxAction(Request $request)
{
// $this->denyAccessUnlessGranted('add');
# lets make sure user has access to this page (stronger than super admin rights)
$user = $this->get('security.token_storage')->getToken()->getUser();
$systemParamService = $this->get('core.system_parameter_control');
$access = $systemParamService->getAccessArray('access_resource');
$specialAccess = false;
if (in_array($user->getId(), $access)) {
$specialAccess = true;
}
# Variable that turns off client side validation on entire action
$onlyServerSideVal = true;
# Create Form Builder Object for "Add Resource"
$em = $this->container->get("doctrine.orm.entity_manager");
$resource = new Resource();
$resourceForm = $this->createForm(ResourceType::class, $resource, [
'isCarrier' => $this->get('core.get_environment')->getIsCarrier()
]);
# Clear Upload Image Session
$session = new Session();
$session->remove("resource_upload_image");
$Roles = [
"ROLE_SUPER_ADMIN",
"ROLE_ADMIN",
"ROLE_EXAMINER",
"ROLE_TEAM_LEADER",
"ROLE_ADJUSTER",
"ROLE_REGISTERED"
];
$states = $em->getRepository("ResourceManagementBundle:State")->findBy([],['stateName'=>'ASC']);
return $this->render("ResourceManagementBundle:resources:addnew.html.twig", [
"specialAccess" => $specialAccess,
"resourceForm" => $resourceForm->createView(),
"onlyServerSideVal" => $onlyServerSideVal,
"Roles" => $Roles,
"resource" => $user,
"States" => $states
]);
}
/**
* Save Add Resource Action
*
* @Route("/administration/resource/save_add")
*/
public function saveAddResourceAjaxAction(Request $request)
{
$this->denyAccessUnlessGranted('add');
$dispatch = $this->get('event_dispatcher');
# use "Add Resource" Form Object to get submitted form object
$em = $this->container->get("doctrine.orm.entity_manager");
$envService = $this->container->get("core.get_environment");
$resource = new Resource();
$resourceForm = $this->createForm(ResourceType::class, $resource, [
'isCarrier' => $this->get('core.get_environment')->getIsCarrier()
]);
$submittedForm = $request->request->get("resource");
$roles = $request->request->get("roles");
$ssn_ein = isset($submittedForm['ssn_ein']) ? $submittedForm['ssn_ein'] : "";
if(!empty($ssn_ein)){
$ssn_ein1 = str_replace(' ', '', $ssn_ein);
$ssn_ein1 = str_replace('-', '', $ssn_ein1);
}else{
$ssn_ein1 = '';
}
$form_supervisor = isset($submittedForm['supervisor']) ? $submittedForm['supervisor'] : "";
$form_npn_number = isset($submittedForm['niprNumber']) ? trim($submittedForm['niprNumber']) : "";
$is_nipr_tracking = ($request->get('is_nipr_tracking') == 'Yes') ? 1 : 0;
# isW2 isHourly conditions
if(isset($submittedForm['isW2'])){
$formIsW2 = $submittedForm['isW2'];
if($formIsW2 == 1) {
$formIsW2 = true;
$formIsHourly = false;
}
elseif ($formIsW2 == -1) {
$formIsW2 = true;
$formIsHourly = true;
}
elseif ($formIsW2 == 0) {
$formIsW2 = false;
$formIsHourly = false;
}
$resource->setIsW2($formIsW2);
$resource->setIsHourly($formIsHourly);
}
# Set Supervisor
$Supervisor = $em->getRepository("ResourceManagementBundle:Resource")->find($form_supervisor);
$resource->setSupervisor($Supervisor);
# Set NPN Number
if(!empty($form_npn_number)) {
$resource->setNiprNumber($form_npn_number);
}
# Manually submit form
$resourceForm->submit(
$submittedForm
);
$userNoteLog = $this->container->get("app.resource_note_logger");
$user = $this->container->get("security.token_storage")->getToken()->getUser();
if ($resource->getResourceType() instanceof \Globals\ResourceManagementBundle\Entity\ResourceType) {
$resourceTypeText = $resource->getResourceType()->getResourceType();
} else {
/**
* Resource Type id 2 should be field adjuster
* better to search by int rather than string.
*/
$resourceType = $em->getRepository("ResourceManagementBundle:ResourceType")->find(2);
$resourceTypeText = $resourceType->getResourceType();
$resource->setResourceType($resourceType);
}
if ($resource->getId() == $user->getId()) {
$comment = $resource->getFullName() . " added the Resource Type $resourceTypeText.";
} else {
$comment = "The Resource Type $resourceTypeText was added to the user " . $resource->getFullName() . ", by " . $user->getFullName() . ".";
}
# added 11/2018
# This will add the address information (validation will only occur if NON carrier)
$addr_form = $request->request->get('addr_form');
if(!$addr_form['phone'] && !$envService->getIsCarrier())
{
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "form_phone",
'text' => "This field needs a value, it cannot be blank!"
];
return new JsonResponse($response);
}
if(!$addr_form['city'] && !$envService->getIsCarrier())
{
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "form_city",
'text' => "This field needs a value, it cannot be blank!"
];
return new JsonResponse($response);
}
if(!$addr_form['state'] && !$envService->getIsCarrier())
{
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "form_state",
'text' => "This field needs a value, it cannot be blank!"
];
return new JsonResponse($response);
}
if(!$addr_form['zip'] && !$envService->getIsCarrier())
{
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "form_zip",
'text' => "This field needs a value, it cannot be blank!"
];
return new JsonResponse($response);
}
if(!$addr_form['address'] && !$envService->getIsCarrier())
{
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "form_address",
'text' => "This field needs a value, it cannot be blank!"
];
return new JsonResponse($response);
}
if ($resourceForm->isValid()) {
# Validate Password not blank
if ($resource->getPassword() == "") {
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "resource_password",
'text' => "Please enter a password."
];
return new JsonResponse($response);
}
# Validate for duplicate email
$HasEmail = $em->getRepository("ResourceManagementBundle:Resource")->findBy(array("email" => $resource->getEmail()));
if ($HasEmail) { // if duplicate
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "resource_email",
'text' => "This email already exists with a different account."
];
return new JsonResponse($response);
}
# Validate for duplicate username
$HasUser = $em->getRepository("ResourceManagementBundle:Resource")->findBy(array("username" => $resource->getUsername()));
if ($HasUser) { // if duplicate
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "resource_username",
'text' => "This username already exists with a different account."
];
return new JsonResponse($response);
}
if ($resource->getPassword() != "") { // if set password
# encrypt password with md5
$resource->setPassword(md5($resource->getPassword()));
} else {
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "resource_password",
'text' => "Please enter a password."
];
return new JsonResponse($response);
}
if (!$envService->getIsCarrier()) {
if ($resource->getSsnEin()) {
$resource->setSsnEin(md5($resource->getSsnEin()));
} else {
$response = [];
$response['error'] = true;
$response['data']['errors'][] = [
'id' => "resource_ssn_ein",
'text' => "This field is required."
];
return new JsonResponse($response);
}
}
# CUSTOM ADDRESS SAVING
$resource->setCity("");
if ($addr_form['city']) {
$resource->setCity($addr_form['city']);
}
$State = $em->getRepository("ResourceManagementBundle:State")->find(1);
$resource->setState($State);
if (intval($addr_form['state']) > 0) {
$State = $em->getRepository("ResourceManagementBundle:State")->find(intval($addr_form['state']));
$resource->setState($State);
}
$resource->setAddress("");
if ($addr_form['address']) {
$resource->setAddress($addr_form['address']);
}
$resource->setZip("");
if ($addr_form['zip']) {
$resource->setZip($addr_form['zip']);
}
$resource->setPhone("");
if ($addr_form['phone']) {
$resource->setPhone($addr_form['phone']);
}
if ($roles === "0") {
$roles = "ROLE_ADJUSTER";
$resource->setRoles('["ROLE_ADJUSTER"]');
} else {
$resource->setRoles("[" . '"' . $roles . '"' . "]");
}
// For updating payroll id while creating new adjuster start
if($roles=='ROLE_ADJUSTER' || $roles=='ROLE_REGISTERED'){
$payrollService = $this->get('resource.payroll_service');
$length = 4;
$payrollId = $payrollService->randomStr($length);
$resourceWithPayroll = $this->getDoctrine()->getRepository('ResourceManagementBundle:Resource')->findBy(array('payrollId' => $payrollId));
if (!empty($resourceWithPayroll)) {
$payrollId = $payrollService->randomStr($length);
}
$resource->setPayrollId($payrollId);
}
// For updating payroll id while creating new adjuster end
$em->flush();
# Persist to DB using Resource Profile Service method - saveAddResource()
$resource_profile = $this->container->get("app.resource_profile");
$resource_profile->saveAddResource($resource);
$resource->setPasswordChangeDate(new \DateTime());
$resource->setNiprTracking($is_nipr_tracking);
# Persist once more
$em->persist($resource);
# Flush it all down
try {
$em->flush();
} catch (\Exception $e) {
}
// to log the resource type changes
$userNoteLog->logNote($comment, $resource);
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(new ResourceCreatedEvent($resource), ResourceCreatedEvent::RENAME );
$firstName = $resource->getFirstName();
$LastName = $resource->getLastName();
$niprNo = $resource->getNiprNumber();
$phone = $resource->getPhone();
$wingSpanService = $this->container->get('resource.wingSpan');
$dataArray = array();
$dataArray['email'] = $resource->getEmail();
$dataArray['firstName'] = $resource->getFirstName();
$dataArray['lastName'] = $resource->getLastName();;
$dataArray['memberCompany'] = 'CQ Digital';
$dataArray['memberId'] = $resource->getId();
if (!empty($resource->getWingSpanCollaboratorGroupId())) {
//$response = $wingSpanService->CreateCollaborator($dataArray);
// $resource->setWingSpanCollaboratorId($response['collaboratorId']);
// $wingSpanService->pushCollaboratorGroup($response['collaboratorId'], $resource->getWingSpanCollaboratorGroupId());
}
$ssn_ein = $ssn_ein1;
$niprTracking = $resource->getNiprTracking();
if($niprTracking==1){
$agentSyncService = $this->container->get('resource.agentSync');
$accessTokenArray = $agentSyncService->getAccessToken();
if (!empty($accessTokenArray['access_token'])){
$agentSyncContactDataApi = $agentSyncService->getAgentSyncNiprContactData($accessTokenArray, $niprNo,$firstName,$LastName);
if($agentSyncContactDataApi['totalSize']>0){
}else{
$agentSyncService->createContactAgentSync($accessTokenArray, $niprNo,$firstName,$LastName,$phone,$ssn_ein,$resource->getId());
}
}
}
# Return success JSON
$retVal = array(
"result" => "success",
"error_msgs" => [],
"roles" => $resource->getRoles(),
"resource_id" => $resource->getId(),
);
$session = new Session();
$session->remove("resource_upload_image");
return new JsonResponse($retVal);
} else {
$response = [];
$response['error'] = true;
$response['formError'] = (string)$resourceForm->getErrors(true);
foreach($resourceForm as $formField){
$errorString = (string)$formField->getErrors();
if($errorString != ""){
$response['data']['errors'][] = [
'id' => $resourceForm->getName()."_".$formField->getName(),
'text' => $errorString
];
}
}
return new JsonResponse($response);
}
}
/**
* @Route("/administration/fix/claim_report_duplicates")
*/
public function deleteDupClaimReport() {
$em = $this->getDoctrine();
$sql = "SELECT * FROM claim_report cr
WHERE claim_id = :claim_id
AND invoice_id = :invoice_id
AND document_type_id = :document_type_id AND cr.file_title = :file_title
AND document_type_id = 9
AND invoice_id <> 0 ";
$stmt_select_like_reports = $em->getConnection()->prepare($sql);
$sql = "SELECT cr.*
FROM claim_report cr
INNER JOIN claim_report cr2
ON cr.claim_id = cr2.claim_id
AND cr.invoice_id = cr.invoice_id
AND cr.document_type_id = cr2.document_type_id
AND cr.file_title = cr2.file_title
AND cr.id != cr2.id
WHERE cr.document_type_id = 9
AND cr.invoice_id != 0
ORDER BY cr.invoice_id ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($results as $getEach) {
$sql = "SELECT id, claim FROM claim_report cr
WHERE claim_id = :claim_id
AND invoice_id = :invoice_id
AND document_type_id = :document_type_id AND cr.file_title = :file_title
AND document_type_id = 9
AND invoice_id <> 0 ";
$stmt_select_like_reports->execute([
"claim_id" => $getEach['claim_id'],
"invoice_id" => $getEach['invoice_id'],
"document_type_id" => $getEach['document_type_id'],
"file_title" => $getEach['file_title']
]);
$i = 0;
$LikeResults = $stmt_select_like_reports->fetchAll(\PDO::FETCH_ASSOC);
foreach ($LikeResults as $getLike) {
if ($i < count($LikeResults) - 1) {
// delete
/*/
DELETE FROM claim_report where id = :id
$getLike['id']
//*/
}
$i++;
}
}
dump("Script completed"); die;
}
/**
* @Route("/datatables/save/numperpage", methods={"POST"})
*/
public function saveNumberPerPage(Request $request)
{
$numPerPage = $request->request->has("num_per_page") ? $request->request->get("num_per_page") : 10;
$session = new Session();
$session->set("NumPerPage", $numPerPage);
/*$user = $this->container->get("security.token_storage")->getToken()->getUser();
if (!is_scalar($user)) {
$user->setNumPerPage($numPerPage);
}*/
return new JsonResponse([
"error" => false
]);
}
/**
* Save Update Resource Action
*
* @Route("/administration/resource/sendwingspanlink/{id}")
*/
public function sendwingspanlink(Request $request, Resource $resource)
{
$em = $this->container->get("doctrine.orm.entity_manager");
$tokenStorage = $this->container->get('security.token_storage');
$user = $tokenStorage->getToken()->getUser();
$mailer = $this->container->get('mail_management.mailer');
$email_from = $user->getEmail();
//$mailer->replaceParam = array('strImagePath' => "", 'imageUrl' => "");
$mailer->setSendingConfig();
$wingspanlinkObj = $em->getRepository('CoreBundle:SystemControlMetadata')->findOneBy(['cmetaKey' => 'wing_span_link']);
$email_body = "<p><strong>Hello ".$resource->getFirstName()." ".$resource->getLastName().",</strong></p>";
$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>";
$email_body .= "<p>Please click below link for registration on wingspan</p>";
$email_body .= "<p><a href='".$wingspanlinkObj->getCmetaValue()."'>Register</a></p>";
$email_body .= "<p></p><p>You can reach out to recruiting if you have any questions.</p>";
$email_body .= "<br/> Thanks </br/> The Recruiting Department ";
$Mail = new Mail();
# SETTING THE SUBJECT
# ######################################################
$email_to = $resource->getEmail();
# Recipient
$Recipient = new MailRecipient();
$Recipient->setEmail($email_to);
$Recipient->setMail($Mail);
$Recipient->setRecipientId($user->getId());
$entityName = $em->getMetadataFactory()->getMetadataFor(get_class($user))->getName();
$Recipient->setRecipientType($entityName);
# Adds the single recipient (resource);
$Mail->addRecipient($Recipient);
$Mail->setSubject("Wing Span Registration - Notification");
# Finalize the MAIL object
$Mail->setBody($email_body);
$Mail->setSenderName(MailHelper::getMailSenderName($tokenStorage));
$mailer->sendEmail($Mail, $email_from, "");
# Return JSON with Error Messages
$retVal = array(
"result" => "success",
"error_msgs" => 'send',
"error" => false
);
return new JsonResponse($retVal);
}
/**
* Save Update Resource Action
*
* @Route("/administration/resource/save_edit/{id}")
*/
public function saveEditResourceAjaxAction(Request $request, Resource $resource)
{
$this->denyAccessUnlessGranted('edit', $resource);
# "Edit Resource" Form Object, get submitted form object
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$AddressInfo='';
$OldAddressInfo='';
$workType='';
$oldworkType='';
$session = new Session();
$session->remove("ResourceChanged");
$session->remove("ResourceChanges");
$envService = $this->container->get("core.get_environment");
$kernel = $this->container->get("kernel");
$authChecker = $this->container->get("security.authorization_checker");
$onlyServerSideVal = false;
$form_helper = new ResourceFormHelper($em, $formFactory, $kernel, $onlyServerSideVal, $authChecker);
$oldSsnEin = $resource->getSsnEin();
$form = $request->request->get("form");
// if(!empty($wingSpanCollaboratorId)){
// $wingSpanService = $this->container->get('resource.wingSpan');
//$responseDocIdsArray = $wingSpanService->fetchCollaboratorDocumentIDs($wingSpanCollavoratorId);
//foreach($responseDocIdsArray as $keyDocId=>$valueDocId){
/// $clientIdData = $wingSpanService->fetchDocumentDetails($valueDocId);
// $fieldId = $clientIdData['client'];
// $title = $clientIdData['docName'];
// $filecontent = $wingSpanService->downloadFile($fieldId);
// $kernel = $this->container->get("kernel");
// $env = $kernel->getEnvironment();
// $env = str_replace("_dev", "", $env);
// $env = 1000;
// $new_file_path = $kernel->getRootDir() . "/../web/" . $env . "/wingSpanData/".$resource->getId();
// if (!file_exists($new_file_path)) {
// mkdir($new_file_path, 0775);
// }else{
// }
// Then just save it like this
// file_put_contents( $new_file_path.'/'.$title, $filecontent );
// }
// }
//$wingSpanService = $this->container->get('resource.wingSpan');
// $dataArray = array();
//$response = $wingSpanService->CreateCollaborator($dataArray);
$employement_form = $request->request->get("employment_form");
$form_ssn_ein = isset($form['ssn_ein']) ? $form['ssn_ein'] : "";
$xactAddress = ($request->request->has("xactAddress")) ? $request->request->get("xactAddress") : "";
$symbilityAddress = ($request->request->has("symbilityAddress")) ? $request->request->get("symbilityAddress") : "";
$form_supervisor = isset($form['supervisor']) ? $form['supervisor'] : "";
$enabled = isset($form['isActive']) ? $form['isActive'] : "";
$oldSupervisor = $resource->getSupervisor();
if(!empty($form['resource_type']))
$resourceType = $em->getRepository("ResourceManagementBundle:ResourceType")->find($form['resource_type']);
/**
* When disabling a vendor we need to remove all of their percentages so they dont get claims
*/
if ($enabled == 0 && $resource->getResourceType() && $resource->getResourceType()->getId() == 3) {
# only use resource service here so just call the function directly
$this->container->get("resource.service")->removeVendorPercentages($resource);
}
if(isset($form['supervisor'])){
$newSupervisor = $em->getRepository("ResourceManagementBundle:Resource")->find($form['supervisor']);
}else{
$newSupervisor = "";
}
$didSupervisorChange = false;
if($oldSupervisor != $newSupervisor && ($oldSupervisor=="" || $newSupervisor=="")){
$didSupervisorChange = true;
}
# isW2 isHourly conditions
if(isset($employement_form['isW2'])){
$formIsW2 = $employement_form['isW2'];
if($formIsW2 == 1) {
$formIsW2 = true;
$formIsHourly = false;
}
elseif ($formIsW2 == -1) {
$formIsW2 = true;
$formIsHourly = true;
}
elseif ($formIsW2 == 0) {
$formIsW2 = false;
$formIsHourly = false;
}
##
$DbIsW2=intval($resource->getIsW2());
$DbIsHourly=intval($resource->getIsHourly());
$DbRadioValue=0;
if($DbIsW2===1 && $DbIsHourly===0){ $DbRadioValue=1;}
if($DbIsW2===1 && $DbIsHourly===1){ $DbRadioValue= -1;}
if($DbIsW2===0 && $DbIsHourly===0){ $DbRadioValue=0;}
if($DbRadioValue !==intval($employement_form['isW2']) ){
$oldworkType= ($DbRadioValue == 1) ? "Salary" : (($DbRadioValue == -1) ? "Hourly" : "1099");
$workType = (intval($employement_form['isW2']) == 1) ? "Salary" : ((intval($employement_form['isW2']) == -1) ? "Hourly" : "1099");
}
##
$resource->setIsW2($formIsW2);
$resource->setIsHourly($formIsHourly);
if ($xactAddress) {
$resource->setXactAddress($xactAddress);
}
if ($symbilityAddress) {
$resource->setSymbilityAddress($symbilityAddress);
}
}
# Request security role
$role = $request->request->get("role");
$resourceForm = $form_helper->getEditForm($resource);
# this function must be called before $resourceForm->getData()
$password = $request->request->get("changepass");
# Get Days Available Info from Request
$weekDays = array();
# Get Submitted Form Resource Object
$resourceForm->handleRequest($request);
$resource = $resourceForm->getData();
# Check if new Ssn EIn was entered
if ($form_ssn_ein) { // if yes
# md5 the value
$resource->setSsnEin(md5($form_ssn_ein));
} else { // if not
}
// save auth code
$sms_authetication = $request->request->get('sms_authetication');
if ($sms_authetication) {
$resource->setSmsAuthetication($sms_authetication);
}
// save SMS ADJUSTER ACCEPT code
$sms_accept_message = $request->request->get('sms_accept_message');
if ($sms_accept_message) {
$resource->setSmsAcceptMessage($sms_accept_message);
}else{
$resource->setSmsAcceptMessage(0);
}
$alreadyNotUsedTeam = $this->getDoctrine()->getRepository('ResourceManagementBundle:TeamsNotUsed')->findBy(array('resourceId' => $resource->getId()));
if(!empty($alreadyNotUsedTeam)){
foreach($alreadyNotUsedTeam as $alreadyNotUsedTeam){
$alreadyNotUsedTeam->setIsActive('N');
$em->persist($alreadyNotUsedTeam);
}
}
$team_not_used = $request->request->get('team_not_used');
if(!empty($team_not_used)){
foreach($team_not_used as $key=>$value){
$teamNotUsed = new TeamsNotUsed();
$teamNotUsed->setResourceId($resource->getId());
$teamNotUsed->setTeamId($value);
$teamNotUsed->setIsActive('Y');
$teamNotUsed->setCreatedDate(new \DateTime());
$teamNotUsed->setUpdatedDate(new \DateTime());
$em->persist($teamNotUsed);
}
}
# added 11/2018
# This will add the address information (validation will only occur if NON carrier)
# for saving wingspan groups starts
// $alreadymappedWingspanGroups = $this->getDoctrine()->getRepository('ResourceManagementBundle:ResourceWingspanGroupMap')->findBy(array('resourceId' => $resource->getId()));
// if(!empty($alreadymappedWingspanGroups)){
// foreach($alreadymappedWingspanGroups as $alreadymappedWingspanGroups){
// $alreadymappedWingspanGroups->setIsActive('N');
// $em->persist($alreadymappedWingspanGroups);
// }
// }
$wingspan_group_id = $request->request->get('wingspan_group_id');
if(!empty($wingspan_group_id)){
$sent_id = '';
$wingSpanCollavoratorId = $resource->getWingSpanCollaboratorId();
$wingSpanService = $this->container->get('resource.wingSpan');
if(empty($wingSpanCollavoratorId)) {
$dataArray = array();
$dataArray['email'] = $resource->getEmail();
$dataArray['firstName'] = $resource->getFirstName();
$dataArray['lastName'] = $resource->getLastName();
$dataArray['memberCompany'] = 'CQ Digital';
$dataArray['memberId'] = $resource->getId();
// if (!empty($resource->getWingSpanCollaboratorGroupId())) {
$response = $wingSpanService->CreateCollaborator($dataArray);
$resource->setWingSpanCollaboratorId($response['collaboratorId']);
$wingSpanCollaboratorId = $response['collaboratorId'];
// $wingSpanService->pushCollaboratorGroup($response['collaboratorId'], $resource->getWingSpanCollaboratorGroupId());
//}
}
foreach($wingspan_group_id as $key=>$value){
$alreadymappedWingspanGroups = $this->getDoctrine()->getRepository('ResourceManagementBundle:ResourceWingspanGroupMap')->findBy(array('resourceId'=>$resource->getId(),'wingspanGroupId'=>$value));
if(!empty($alreadymappedWingspanGroups)){
}else {
$ResourceWingspanGroupMap = new ResourceWingspanGroupMap();
$ResourceWingspanGroupMap->setResourceId($resource->getId());
$ResourceWingspanGroupMap->setWingspanGroupId($value);
$ResourceWingspanGroupMap->setIsActive('Y');
$ResourceWingspanGroupMap->setPushedWingspan('Y');
$ResourceWingspanGroupMap->setCreatedDate(new \DateTime());
$ResourceWingspanGroupMap->setUpdatedDate(new \DateTime());
$em->persist($ResourceWingspanGroupMap);
$wingSpanService->pushCollaboratorGroup($resource->getWingSpanCollaboratorId(), $value);
if(!empty($sent_id))
$sent_id .= ', '.$value;
else
$sent_id = $value;
}
// tag wingspan group to collaborator
// tag wingspan group to collaborator
}
if(!empty($sent_id)) {
$user = $this->get('security.token_storage')->getToken()->getUser();
$comment = "The resource, " . $resource->getFirstName() . " " . $resource->getLastName() . ", was updated by " . $user . ", with the following changes: added wingspan group $sent_id.";
$UserNote = new UserNote();
$UserNote->setComment($comment);
$UserNote->setCommentDate(new \DateTime());
$UserNote->setCommentByResource($user);
$UserNote->setResource($resource);
$UserNote->setUserNotesTypeId(9);
$UserNote->setEntryDate(new \DateTime());
$em->persist($UserNote);
}
}
# for saving wingspan groups ends
$addr_form = $request->request->get('addr_form');
if(!$addr_form['phone'] && !$envService->getIsCarrier())
{
$nextError['id'] = "phone";
$nextError['text'] = "This field needs a value, it cannot be blank!";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $data['errors'],
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
if(!$addr_form['city'] && !$envService->getIsCarrier())
{
$nextError['id'] = "city";
$nextError['text'] = "This field needs a value, it cannot be blank!";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $data['errors'],
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
if(!$addr_form['state'] && !$envService->getIsCarrier())
{
$nextError['id'] = "state";
$nextError['text'] = "This field needs a value, it cannot be blank!";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $data['errors'],
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
if(!$addr_form['zip'] && !$envService->getIsCarrier())
{
$nextError['id'] = "zip";
$nextError['text'] = "This field needs a value, it cannot be blank!";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $data['errors'],
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
if(!$addr_form['address'] && !$envService->getIsCarrier())
{
$nextError['id'] = "address";
$nextError['text'] = "This field needs a value, it cannot be blank!";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $data['errors'],
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
$resID = null;
if(!empty($resource))
$resID = $resource->getId();
if ($resourceType instanceof \Globals\ResourceManagementBundle\Entity\ResourceType) {
$resource->setResourceType($resourceType);
} else {
/**
* Resource Type id 2 should be field adjuster
* better to search by int rather than string.
*/
$resourceType = $em->getRepository("ResourceManagementBundle:ResourceType")->find(2);
$resource->setResourceType($resourceType);
}
# Compare 2 objects to see if there were any changes made
if ($resourceForm->isValid()) { // if form is valid
# Validate for duplicate email
$HasEmail = $em->getRepository("ResourceManagementBundle:Resource")->checkEmailExists($resource->getEmail(), $resource->getId());
if ($HasEmail) {
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "email";
$nextError['text'] = "This email already exists with a different account.";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
# Validate for duplicate username
$HasUser = $em->getRepository("ResourceManagementBundle:Resource")->checkUsernameExists($resource->getUsername(), $resource->getId());
if ($HasUser) {
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "username";
$nextError['text'] = "This username already exists with a different account.";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
# If password field was updated
if ($password) {
# encrypt submitted password
$resource->setPassword(md5($password));
$resource->setPasswordChangeDate(new \DateTime());
}
# If is being changed to Adjuster and does not have PayCom ID
if ($resource->getResourceType() == "Adjuster") {
if (!$resource->getPayrollId()) {
# Add Paycom ID
$payrollService = $this->get('resource.payroll_service');
$payrollIdExists = true;
do {
$length = 4;
$payrollId = $payrollService->randomStr($length);
$resourceWithPayroll = $this->getDoctrine()->getRepository('ResourceManagementBundle:Resource')->findBy(array('payrollId' => $payrollId));
if (empty($resourceWithPayroll)) {
$payrollIdExists = false;
}
} while ($payrollIdExists === true);
$resource->setPayrollId($payrollId);
}
}
if ($role) { // if role passed
# Set Security Role as Json
$roleArr[] = $role;
$resource->setRoles(json_encode($roleArr));
}
if($didSupervisorChange){
/** @var Resource $user */
$user = $this->get('security.token_storage')->getToken()->getUser();
$oldSupervisor = is_null($oldSupervisor)?"NULL":$oldSupervisor;
$newSupervisor = is_null($newSupervisor)?"NULL":$newSupervisor;
$comment = "The resource, ". $resource->getFirstName()." ".$resource->getLastName().", was updated by " . $user . ", with the following changes: Supervisor was changed from $oldSupervisor to $newSupervisor.";
$UserNote = new UserNote();
$UserNote->setComment($comment);
$UserNote->setCommentDate(new \DateTime());
$UserNote->setCommentByResource($user);
$UserNote->setResource($resource);
$UserNote->setUserNotesTypeId(9);
$UserNote->setEntryDate(new \DateTime());
$em->persist($UserNote);
}
# compare the Db value with post value data
$DbAddress=$resource->getAddress();
$checkAddress = strcmp(trim($addr_form['address']),trim($DbAddress));
if ($checkAddress !=0){
$OldAddressInfo .=$DbAddress.', ';
$AddressInfo .=$addr_form['address'].', ';
}
$DbCity=$resource->getCity();
$checkCity = strcmp(trim($addr_form['city']),trim($DbCity));
if ($checkCity !=0){
$OldAddressInfo .=$DbCity.', ';
$AddressInfo .=$addr_form['city'].', ';
}
$DbState=$resource->getState()->getId();
if (intval($addr_form['state']) != $DbState){
$NewStateName = $em->getRepository("ResourceManagementBundle:State")->find(intval($addr_form['state']));
$OldAddressInfo .=$resource->getState()->getStateName().', ';
$AddressInfo .=$NewStateName->getStateName();
}
$DbZip=$resource->getZip();
$checkZip = strcmp(trim($addr_form['zip']),trim($DbZip));
if ($checkZip !=0){
$OldAddressInfo .=$DbZip.', ';
$AddressInfo .=$addr_form['zip'].', ';
}
$DbPhone=$resource->getPhone();
if ($addr_form['phone'] != $DbPhone){
$OldAddressInfo .=" Phone No: ".$DbPhone;
$AddressInfo .=" Phone No: ". $addr_form['phone'];
}
# compare the Db value with post value data
# 11/2018
# CUSTOM ADDRESS SAVING
$resource->setAddress("");
if($addr_form['address'])
{
$resource->setAddress($addr_form['address']);
}
$resource->setCity("");
if($addr_form['city'])
{
$resource->setCity($addr_form['city']);
}
$State = $em->getRepository("ResourceManagementBundle:State")->find(1);
$resource->setState($State);
if(intval($addr_form['state']) > 0)
{
$State = $em->getRepository("ResourceManagementBundle:State")->find(intval($addr_form['state']));
$resource->setState($State);
}
$resource->setZip("");
if($addr_form['zip'])
{
$resource->setZip($addr_form['zip']);
}
$resource->setPhone("");
if($addr_form['phone'])
{
$resource->setPhone($addr_form['phone']);
}
# Check if Resource Entity Changed (from Resource Event Listener)
$session->remove("ResourceChanged");
$session->remove("ResourceChanges");
# Persist to DB using Resource Profile Service method - saveUpdateResouce()
$resource_profile = $this->container->get("app.resource_profile");
$resource_profile->saveUpdateResource($resource, false);
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(new ResourceUpdatedEvent($resource), ResourceUpdatedEvent::RENAME );
# send mail to Finance team if Profile of resource updated
$FinanceTeamEmail = $em->getRepository('CoreBundle:SystemControlMetadata')->findOneBy(['cmetaKey' => 'fin_team_emails_to_send']);
$tokenStorage = $this->container->get('security.token_storage');
$user = $tokenStorage->getToken()->getUser();
$mailer = $this->container->get('mail_management.mailer');
$email_from = $user->getEmail();
//$mailer->replaceParam = array('strImagePath' => "", 'imageUrl' => "");
$mailer->setSendingConfig();
$addresses = explode(',', $FinanceTeamEmail instanceof SystemControlMetadata ? $FinanceTeamEmail->getCmetaValue() : "");
$email_body ="<p><strong>Hi Team,</strong></p>";
$email_body .="<p>User Profile: ".$resource->getFullName()." has been updated</p>";
if(!empty($AddressInfo) ){
$email_body .="<p><strong>Old Address: </strong>".$OldAddressInfo."</p>";
$email_body .="<p><strong>New Address: </strong>".$AddressInfo."</p><br/>";
}
if(!empty($workType) ){
$email_body .="<p><strong>Old Employee Type: </strong>".$oldworkType."</p>";
$email_body .="<p><strong>New Employee Type: </strong>".$workType."</p><br/>";
}
if(!empty($AddressInfo) || !empty($workType)){
$email_body .="<br/> Thanks </br/> system Admin";
$Mail = new Mail();
foreach ($addresses as $address) {
# SETTING THE SUBJECT
# ######################################################
$email_to = $address;
# Recipient
$Recipient = new MailRecipient();
$Recipient->setEmail($email_to);
$Recipient->setMail($Mail);
$Recipient->setRecipientId($user->getId());
$entityName = $em->getMetadataFactory()->getMetadataFor(get_class($user))->getName();
$Recipient->setRecipientType($entityName);
# Adds the single recipient (resource);
$Mail->addRecipient($Recipient);
$Mail->setSubject("User Profile updated - Notification");
}
# Finalize the MAIL object
$Mail->setBody($email_body);
$Mail->setSenderName(MailHelper::getMailSenderName($tokenStorage));
$mailer->sendEmail($Mail, $email_from, "");
}
# Return JSON Success Object
$retVal = array(
"result" => "success",
"error_msgs" => []
);
return new JsonResponse($retVal);
} else {
$data = [];
# Get Form Errors using Validator Service
$errors = $this->get("validator")->validate($resource);dd($errors);
$errors2 = array();
if (count($errors) > 0) {
$data = [
"errors" => array()
];
foreach ($errors as $error) {
$nextError = array();
$nextError['id'] = $error->getPropertyPath();
$nextError['text'] = $error->getMessage();
$data['errors'][] = $nextError;
}
}
# Return JSON with Error Messages
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
/**
* Handle Upload Signature File Action
* recieves file object and saves to session for later use
*
* @Route("/administration/resource/upload_image")
*/
public function saveUploadImageResourceAjaxAction(Request $request)
{
if (isset($_FILES['files']) && count($_FILES['files']['name']) > 0) { // if file uploaded
$session = new Session();
# Extract File Object from $_FILES object
$useFile = array();
foreach ($_FILES['files'] as $key => $value) {
$useFile[$key] = $value[0];
}
$pathArr = pathinfo(strtolower($useFile['name']));
# Add File Extension to File Object Array
$useFile['file_ext'] = $pathArr['extension'];
# Validate file type
$allowed_file_types = ["jpg", "jpeg", "png", "gif"];
if (!in_array($useFile['file_ext'], $allowed_file_types)) { // if uploaded invalid file type
# pass back validation message of bad file type, instead of file name
$retVal = [
"files" => [
[
"name" => "File type not allowed"
]
]
];
return new JsonResponse($retVal);
}
# create unique hash for filename, without extension
$path = $useFile['tmp_name'];
$get_num = md5(uniqid());
$new_file_name = is_numeric($get_num) ? $this->getRandomLargeNumber() : $get_num;
$new_file_path = "/tmp/" . $new_file_name;
$useFile['new_file_name'] = $new_file_name;
$Log = new SLogger();
$Log->log("new_file_name: " . $new_file_name);
# make note where file came from
$useFile['used_by_module'] = "EditResource";
$orig_file_name = $useFile['name'];
# save to session
$session->set("resource_upload_image", $useFile);
# copy as new file with unique id filename in /tmp folder, since original tmp file will be deleted after page runs
move_uploaded_file($path, $new_file_path);
}
# Return file name back to upload plugin
$retVal = [
"files" => [
[
"name" => $orig_file_name
]
]
];
return new JsonResponse($retVal);
}
/**
* Modify Adjuster Positions Action
*
* @Route("/administration/resource/adjuster_position/edit/{id}")
*/
public function editResourceAdjusterPositionAjaxAction(Resource $resource)
{
# lets make sure user has access to this page (stronger than super admin rights)
$em = $this->container->get("doctrine.orm.entity_manager");
$user = $this->get('security.token_storage')->getToken()->getUser();
$systemParamService = $this->get('core.system_parameter_control');
$access = $systemParamService->getAccessArray('access_resource');
if (in_array($user->getId(), $access)) {
$specialAccess = true;
}
# Create Form Builder Object for "Edit Adjuster Positions"
$formFactory = $this->container->get("form.factory");
$kernel = $this->container->get("kernel");
$authChecker = $this->container->get("security.authorization_checker");
$onlyServerSideVal=false;
$form_helper = new ResourceFormHelper($em, $formFactory, $kernel, $onlyServerSideVal, $authChecker);
$resourcePositionForm = $form_helper->getAdjusterPositionEditForm($resource);
# Get Current Adjuster Positions for this Resource
$adjusterPositions = array();
$adjusterPosIDs = array();
foreach ($resource->getAdjusterPositions() as $adjusterPosition) {
$adjusterPositions[] = $adjusterPosition;
$adjusterPosIDs[] = $adjusterPosition->getId();
}
# Create array that contians whether or not each Adjuster Position exists on db for this Resource
$SelAdjustersLoop = [];
$AllAdjusterPositions = $em->getRepository("ResourceManagementBundle:AdjusterPosition")->findBy(array(),array('positionName' => 'ASC') );
foreach ($AllAdjusterPositions as $getPosition) {
if (in_array($getPosition->getId(), $adjusterPosIDs)) {
$SelAdjustersLoop[] = 1;
} else {
$SelAdjustersLoop[] = 0;
}
}
# Variable that sets active tab
$active = 'adjusterPositions';
$apiEndPointUsers = $systemParamService->getAccessArray('PushNotificaton_tab');
$bShowAPIEndPointTab = false;
if (!empty($apiEndPointUsers) && in_array($user->getId(),$apiEndPointUsers)) {
$bShowAPIEndPointTab = true;
}
return $this->render("ResourceManagementBundle:resources/adjuster_position:edit.html.twig", [
"specialAccess" => isset($specialAccess),
"resourcePositionForm" => $resourcePositionForm->createView(),
"id" => $resource->getId(),
"resource" => $resource,
"useResource" => $resource,
"SelAdjustersLoop" => $SelAdjustersLoop,
"AllAdjusterPositions" => $AllAdjusterPositions,
"activeClass" => $active,
"bShowAPIEndPointTab" => $bShowAPIEndPointTab
]);
}
/**
* Save Adjuster Positions Action
*
* @Route("/administration/resource/adjuster_position/save_edit/{id}")
*/
public function saveEditResourceAdjusterPositionAjaxAction(Request $request, Resource $resource)
{
# use "Edit Adjuster Positsions" Form Object to get submitted form object
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$kernel = $this->container->get("kernel");
$authChecker = $this->container->get("security.authorization_checker");
$onlyServerSideVal = false;
$form_helper = new ResourceFormHelper($em, $formFactory, $kernel, $onlyServerSideVal,$authChecker);
$form = $form_helper->getAdjusterPositionEditForm($resource);
# Log Changes to User Note
$user = $this->container->get("security.token_storage")->getToken()->getUser();
$userNoteLog = $this->container->get("app.resource_note_logger");
# Handle Request
$form->handleRequest($request);
$resource = $form->getData();
#Check the adjuster positions that a user alreday has
$sql = "SELECT adjuster_position_id
FROM resource_adjuster_position
WHERE resource_id = :resource_id ";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute(array("resource_id" => $resource->getId()));
$resourcePositions = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$slog = new SLogger();
$slog->log('$resourcePositions');
$slog->log($resourcePositions);
$existingPositions = array();
foreach ($resourcePositions as $resourcePosition){
$existingPositions[] = $resourcePosition['adjuster_position_id'];
}
$slog->log('$existingPositions');
$slog->log($existingPositions);
## Handle updating of adjuster position checkboxes
# First, Delete all relations between resource and adjuster positions
$sql = "DELETE FROM resource_adjuster_position WHERE resource_id = :resource_id ";
$stmh = $em->getConnection()->prepare($sql);
$stmh->execute(array("resource_id" => $resource->getId()));
# Will then add back adjuster positions that were checked on form
$sql = "INSERT INTO resource_adjuster_position
( resource_id, adjuster_position_id) VALUES
(:resource_id, :adjuster_position_id) ";
$stmh_insert_resource_aduster = $em->getConnection()->prepare($sql);
$positions = $request->request->get("chkPosition");
$slog->log('$positions');
$slog->log($positions);
if ($positions) {
foreach ($positions as $getPosition) {
$positionAdded = true;
$sql = "INSERT INTO resource_adjuster_position
( resource_id, adjuster_position_id) VALUES
(:resource_id, :adjuster_position_id) ";
# add back adjuster positions that were checked on form
$stmh_insert_resource_aduster->execute(array(
"resource_id" => $resource->getId(),
"adjuster_position_id" => $getPosition
));
if($existingPositions) {
if (in_array($getPosition, $existingPositions)) {
$positionAdded = false;
}
}
$AdjusterPosition = $em->getRepository("ResourceManagementBundle:AdjusterPosition")->find($getPosition);
if($positionAdded){
#log the user note
if ($resource->getId() == $user->getId()) {
$comment = $resource->getFullName() . " added the position" . $AdjusterPosition->getPositionName() . " to his profile.";
} else {
$comment = "The position " . $AdjusterPosition->getPositionName() . ", was added to the user " . $resource->getFullName() . ", by " . $user->getFullName() . ".";
}
$userNoteLog->logNote($comment, $resource);
}
}
}
if($existingPositions){
foreach ($existingPositions as $existingPosition){
$positionRemoved = true;
if($positions) {
if (in_array($existingPosition, $positions)) {
$positionRemoved = false;
}
}
$AdjusterPosition = $em->getRepository("ResourceManagementBundle:AdjusterPosition")->find($existingPosition);
if($positionRemoved){
#log the user note
if ($resource->getId() == $user->getId()) {
$comment = $resource->getFullName() . " removed the position" . $AdjusterPosition->getPositionName() . " from his profile.";
} else {
$comment = "The position " . $AdjusterPosition->getPositionName() . ", was removed from the user " . $resource->getFullName() . ", by " . $user->getFullName() . ".";
}
$userNoteLog->logNote($comment, $resource);
}
}
}
# Save Other Resource Fields on Adjuster Positions Form
$em->persist($resource);
$em->flush();
// for saving data of adjuster position tab update start
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(new ResourceUpdatedEvent($resource), ResourceUpdatedEvent::RENAME );
// for saving data of adjuster position tab update end
# Return Success JSON
$retVal = array(
"error" => false,
"error_msgs" => []
);
return new JsonResponse($retVal);
}
/**
* Show Datatable Ajax Data Action (for Old DataBuilders Style)
*
* @Route("/administration/resources2/search")
*/
public function showResources2DataTablesAction(Request $request)
{
$User = $this->container->get("security.token_storage")->getToken()->getUser();
# Array of columns that will be sorted
$columnsArr = array(
"id",
"username",
"first_name",
"last_name",
"city",
"state",
"zip",
"payroll_id",
"show_active"
);
$active = intval($request->query->get("active"));
$dataParams = array();
$sql = "SELECT sr.*, S.stateName state, CASE WHEN ifnull(sr.is_active, 0) = 1 THEN 'Yes' ELSE 'No' END as show_active
FROM resource sr
LEFT JOIN state S
ON sr.state_id = S.id
WHERE roles NOT LIKE '%REGISTERED%' AND roles NOT LIKE '%BRANCH%' AND roles IS NOT NULL ";
if ($active == 1) {
$sql .= "AND sr.is_active = 1 ";
} else if ($active == 0) {
$sql .= "AND sr.is_active = 0 ";
}
$systemParamService = $this->container->get('core.system_parameter_control');
if(in_array('ROLE_TEAM_LEADER',$User->getRoles()) ) {
$sql_recur = "SELECT sr.*, S.stateName state, CASE WHEN ifnull(sr.is_active, 0) = 1 THEN 'Yes' ELSE 'No' END as show_active
FROM resource sr
LEFT JOIN state S
ON sr.state_id = S.id
WHERE isSupervisees(:supervisor_id,sr.id) = 1 OR sr.ID = :supervisor_id_2
AND sr.roles NOT LIKE '%REGISTERED%' AND sr.roles NOT LIKE '%BRANCH%' AND sr.roles IS NOT NULL ";
if ($active == 1) {
$sql_recur .= "AND sr.is_active = 1 ";
} else if ($active == 0) {
$sql_recur .= "AND sr.is_active = 0 ";
}
//$sql .=" AND sr.supervisor_id = :supervisor_id";
$dataParams['supervisor_id'] = $User->getId();
$dataParams['supervisor_id_2'] = $User->getId();
$slog = new SLogger();
$slog->log("$sql_recur");
$slog->log($sql_recur);
$sql = $sql_recur;
}
# if search keyword input was typed
$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) ";
$paginator = $this->container->get("resource.paginator_service");
$retVal = $paginator->getPaginationResults($request, $sql, $dataParams, "sr.first_name ASC", $columnsArr, "", $keyword_filter, "keyword", "", "POST");
# Manipulate the resultset to be recieved by datatable
$Results2 = $retVal['data'];
$Results = array();
foreach ($Results2 as $index => $getResult) {
$getResult2 = $getResult;
$getResult2['is_active'] = $getResult['is_active'] == 1 ? "Yes" : "No";
$rolesArr2 = array();
$rolesArr = json_decode($getResult['roles']);
if (is_array($rolesArr)) {
foreach ($rolesArr as $getRole) {
$rolesArr2[] = ResourceRoleEnum::getTypeName($getRole);
}
} else {
$rolesArr2[] = ResourceRoleEnum::getTypeName($rolesArr);
}
$getResult2['roles'] = implode(", ", $rolesArr2);
unset($getResult2['entryDate']);
$Results[$index] = $getResult2;
}
$retVal['data'] = $Results;
return new JsonResponse($retVal);
}
/**
* @param $sql
* @return array
*
* This creates a paginator from raw sql
*/
public function paginateSQL($sql, $params)
{
$em = $this->container->get("doctrine.orm.entity_manager");
$paginator = new PaginatorSQL($em, $sql, $params);
return $paginator;
}
/**
* @Route("/administration/resource/delete", methods={"POST"})
*/
public function deleteResourceAction(Request $request)
{
if ($this->get('security.authorization_checker')->isGranted('delete') === false) {
$retVal = [
'error' => false,
'error_msgs' => ['You Do Not Have Access To Delete']
];
return new JsonResponse($retVal);
}
$em = $this->getDoctrine()->getManager();
# Request ID to delete
$id = intval($request->request->get("id"));
# Delete Resource
$Resource = $em->getRepository("ResourceManagementBundle:Resource")->find($id);
if (empty($Resource)) {
$retVal = [
'error' => true,
'error_msgs' => ['The resource does not exists']
];
}
$retVal = $this->container->get("resource.service")->isResourceAvailableForDeletion($Resource);
if (!empty($retVal) && isset($retVal['error']) && $retVal['error'] === false ) {
$strResFullName = $Resource->getFullName();
$em->getConnection()->query('SET FOREIGN_KEY_CHECKS=0');
$em->remove($Resource);
$em->flush();
$em->getConnection()->query('SET FOREIGN_KEY_CHECKS=1');
$LoggedInUser = (string)$this->get("security.token_storage")->getToken()->getUser();
$companyNoteService = $this->get('company.note_logger');
$notes = "$strResFullName was deleted by $LoggedInUser.";
$companyNoteService->addCompanyNote($notes);
$retVal = [
'error' => false,
'error_msgs' => [],
'status' => 'success'
];
}
return new JsonResponse($retVal);
}
/**
* @Route("/error/show500")
*/
public function showError()
{
return $this->render("@ResourceManagement/error.html.twig");
}
/**
* @Route("/administration/get_notifications/{resource_id}")
*/
public function getNotifications($resource_id)
{
$notificationFinder = $this->container->get('resource.notification_service');
return new JsonResponse($notificationFinder->getNotificationData($resource_id));
}
/**
* @Route("/administration/test_slog")
*/
public function testSLog()
{
$slog = new SLogger();
$slog->log("did slogger work?");
dump("completed"); die;
}
private function getRandomLargeNumber()
{
return (string)rand(1000000, 2000000) . (string)rand(1000000, 2000000);
}
/**
* @param Request $request
* @param $hash
* @return Response
* @throws \Exception
* Reset Password Action
* shown when user comes from forgot password email
*
* @Route("/administration/user/password/forgot/{hash}")
*/
public function showForgotPasswordAction(Request $request, $hash)
{
# Remove old forgot password sessions
$session = new Session();
$session->remove("hash_user_token");
$session->remove("hash_user_id");
$em = $this->container->get("doctrine.orm.entity_manager");
# Find user token record by hash
$user_tokens = $em->getRepository('ResourceManagementBundle:UserToken')
->createQueryBuilder("u")
->where("u.hash = :hash")
->setParameter("hash", $hash)
->orderBy("u.entryDate", "DESC")
->getQuery()
->getResult();
$user_token = new UserToken();
if (count($user_tokens) > 0) {
$user_token = $user_tokens[0];
} else { // if can't find token
return $this->render("@ResourceManagement/emails/invalid.html.twig");
}
if ($user_token->getAction() != "ForgotPassword") { // if token is not for "Forgot Password"
return $this->render("@ResourceManagement/emails/invalid.html.twig");
}
# Make sure token is still valid (expires after 3 days)
$entryDate = $user_token->getEntryDate();
$curDate = new \DateTime(date("Y-m-d H:i:s"));
$interval = $entryDate->diff($curDate);
$daysDiff = $interval->format('%a');
$resource_profile = $this->container->get("app.resource_profile");
if ($daysDiff >= $resource_profile->daysValid) {
return $this->render("@ResourceManagement/emails/invalid.html.twig");
}
# Get User from token record
$resource = $em->getRepository("ResourceManagementBundle:Resource")->find($user_token->getUserId());
# Save sessions to be used by "Save Reset Password Action"
$session->set("hash_user_token", $hash);
$session->set("hash_user_id", $resource->getId());
# Create Reset Password Form Object
$onlyServerSideVal = false;
$em = $this->container->get("doctrine.orm.entity_manager");
$formFactory = $this->container->get("form.factory");
$kernel = $this->container->get("kernel");
$form_helper = new ResourceFormHelper($em, $formFactory, $kernel, $onlyServerSideVal);
$resourceForm = $form_helper->getUpdatePasswordForm();
# Create Custom CSRF Token
$UserToken = new UserToken();
$js_hash = md5($request->getClientIp() . $UserToken->salt_keyword2 . substr($request->headers->get('User-Agent'), 0, 17));
return $this->render("ResourceManagementBundle:resources/templates:reset_password.html.twig", [
"id" => $resource->getId(),
"resource" => $resource,
"hash" => $js_hash,
"resourceForm" => $resourceForm->createView(),
"onlyServerSideVal" => $onlyServerSideVal
]);
}
/**
* Save Reset Password Action
*
* @Route("/administration/user/password/save_forgot")
*/
public function saveForgotPasswordAction(Request $request)
{
$session = new Session();
$em = $this->container->get("doctrine.orm.entity_manager");
# check if session contains user token information
if (!$session->has("hash_user_token")) { // if session not exists
# send error message
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "password";
$nextError['text'] = "This link has expired.";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
# load user by session from token
$resource = $em->getRepository("ResourceManagementBundle:Resource")->find($session->get("hash_user_id"));
# Validate Custom CSRF Token
$UserToken = new UserToken();
$js_hash = md5($request->getClientIp() . $UserToken->salt_keyword2 . substr($request->headers->get('User-Agent'), 0, 17));
$form_hash = $request->request->get("globals_hash_key");
if ($js_hash != $form_hash) { // if Custom CSRF token is invalid
# send error message
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "password";
$nextError['text'] = "This link has expired.";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
$form = $request->request->get("form");
$password = $form['password'];
if ($password != "") { // if password entered
# Update password
$resource->setPassword(md5($password));
$em->persist($resource);
$em->flush();
$retVal = array(
"result" => "success",
"error_msgs" => []
);
# Remove token used for forgot password
$sql = "DELETE FROM user_token WHERE hash = :hash";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute(array(
"hash" => $session->get("hash_user_token")
));
# remove token session info
$session->remove("hash_user_token");
$session->remove("hash_user_id");
return new JsonResponse($retVal);
} else { // if password is blank
# send error message
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "password";
$nextError['text'] = "You did not enter a password to update.";
$data['errors'][] = $nextError;
$retVal = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
/**
* @Route("/resource/adjuster-comment/{id}")
*/
public function adjusterCommentAction(Request $request)
{
# logged in user
$user = $this->get('security.token_storage')->getToken()->getUser();
//dd($user->getId());
$em = $this->container->get("doctrine.orm.entity_manager");
$response = ['error'=>false, 'data'=>[]];
$comment = $request->request->get('adjustercomment');
$ResourceId = $request->get('id');
# Check for post #
if ($comment) {
$ResourceEdited = $em->getRepository("ResourceManagementBundle:Resource")->find($ResourceId);
$AdjComment = new AdjusterComment();
$AdjComment->setComment($comment);
$AdjComment->setCommentDate(new \DateTime());
$AdjComment->setLoggedInUserId($user->getId());
$AdjComment->setResourceId($ResourceEdited->getId());
$em->persist($AdjComment);
//dd($AdjComment);
$em->flush();
#collect the Adjuster Comment
$sql = "SELECT ac.comment, ac.commentDate, CONCAT(r.first_name, ' ', r.last_name) AS author_name
FROM adjuster_comments ac
LEFT JOIN resource r
ON ac.logged_in_user_id = r.id
WHERE ac.resource_id = :rid
ORDER BY ac.commentDate desc LIMIT 3";
$AdjusterComments = array();
$dataParams['rid'] = $ResourceEdited->getId();
$stmt = $em->getConnection()->prepare($sql);
//dd($stmt);
$stmt->execute($dataParams);
$AdjusterComments = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($AdjusterComments) < 0) {
$AdjusterComments = array();
}else{
$response=['error'=>false, 'data'=>$AdjusterComments];
}
//dd($response);
return new JsonResponse($response);
}else{
return new JsonResponse(['error' => 'Adjuster Comment\'s Cannot Be Blank']);
}
}
/**
* @Route("/resource/all-adjuster-comment/")
*/
public function allAdjusterCommentAction(Request $request)
{
# logged in user
$user = $this->get('security.token_storage')->getToken()->getUser();
//dd($user->getId());
$em = $this->container->get("doctrine.orm.entity_manager");
$response = ['error'=>false, 'data'=>[]];
$ResourceId = $request->request->get('resId');
# Check for post #
if ($ResourceId) {
#collect the Adjuster Comment
$sql = "SELECT ac.comment, ac.commentDate, CONCAT(r.first_name, ' ', r.last_name) AS author_name
FROM adjuster_comments ac
LEFT JOIN resource r
ON ac.logged_in_user_id = r.id
WHERE ac.resource_id = :rid
ORDER BY ac.commentDate desc";
$AdjusterComments = array();
$dataParams['rid'] = $ResourceId;
$stmt = $em->getConnection()->prepare($sql);
//dd($stmt);
$stmt->execute($dataParams);
$AdjusterComments = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (count($AdjusterComments) < 0) {
$AdjusterComments = array();
}
return $this->render('@ResourceManagement/resources/popup-adj-comments.html.twig', [
"AllComments" => $AdjusterComments
]);
}else{
return new JsonResponse(['error' => 'Adjuster Comment\'s Cannot Be Blank']);
}
}
}