<?php
namespace Globals\ClaimManagementBundle\Controller;
use Doctrine\ORM\EntityManager;
use Globals\ClaimManagementBundle\DependencyInjection\CompareHelpers\DisbursementCompareHelper;
use Globals\ClaimManagementBundle\DependencyInjection\ExpensesHelper;
use Globals\ClaimManagementBundle\Entity\Claim;
use Globals\ClaimManagementBundle\Entity\ClaimNoteMedia;
use Globals\ClaimManagementBundle\Entity\DiaryEntry;
use Globals\ClaimManagementBundle\Entity\DiaryOtherResource;
use Globals\ClaimManagementBundle\Event\ClaimDiaryAssignedEvent;
use Globals\ClaimManagementBundle\Event\ClaimDiaryCompleteEvent;
use Globals\ClaimManagementBundle\Form\Coverage;
use Globals\ClaimManagementBundle\Form\Deductible;
use Globals\ClaimManagementBundle\Form\DiaryFormType;
use Globals\ClaimManagementBundle\Form\DisbursementTimeLogType;
use Globals\CoreBundle\Helpers\MailHelper;
use Globals\CustomerManagementBundle\DependencyInjection\DisbursementHelper;
use Globals\MailManagementBundle\Entity\Mail;
use Globals\MailManagementBundle\Entity\MailRecipient;
use Globals\ResourceManagementBundle\Entity\Resource;
use Globals\ResourceManagementBundle\Service\SLogger;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Globals\ClaimManagementBundle\Entity\Coverage as CoverageEntity;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Globals\InvoiceManagementBundle\Entity\Disbursement;
use Globals\ClaimManagementBundle\Event\ClaimDuplicatedEvent;
use DateTime;
/**
* @Route("/administration/claims/api")
*/
class ClaimFlowCrudController extends Controller
{
/**
* @Route("/clone/{id}")
* @Method("POST")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function cloneExistingClaim(Claim $claim)
{
if($claim){
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/update/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function updateClaimFlowAction(Claim $claim)
{
/** @var Claim $claim */
return new JsonResponse(['claim_number'=>$claim->getClaimNumber()]);
}
/**
* @Route("/create/deductible")
*/
public function createDeductibleAction(Request $request)
{
# 1) If we are POST-ing *only*
if($request->getMethod() == "POST"){
$deductibleData = $request->request->get('newDeductible');
$deductibleData['name'] = 'Deductible';
$form = $this->createForm(Deductible::class, new \Globals\ClaimManagementBundle\Entity\Deductible());
$form->submit($deductibleData);
if($form->isValid()){
$newDeductible = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($newDeductible);
$em->flush();
# Add Claim Note that Deductible was added
$ClaimNote = $this->container->get("claim.note_provider");
//Status note = 68 Claim Deductible
$ClaimNote->addClaimNote($newDeductible->getClaim(), "Claim Deductible was added.", false, 68);
return new JsonResponse(['error'=>false]);
}else{
$errors = [];
foreach($form as $formField){
if((string)$formField->getErrors(true)){
$errors[] = [
'id'=>$formField->getName(),
'text'=>(string)$formField->getErrors(true)
];
}
}
return new JsonResponse(['error'=>true, 'data' => ['errors' => $errors]]);
}
}else{
return new JsonResponse(['error'=>true]);
}
}
/**
* @Route("/create/coverage")
*/
public function createCoverageAction(Request $request)
{
# 1) If we are POST-ing *only*
if($request->getMethod() == "POST"){
$coverageData = $request->request->get('newCoverage');
$form = $this->createForm(Coverage::class, new CoverageEntity());
$form->submit($coverageData);
if($form->isValid()){
$newCoverage = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($newCoverage);
$em->flush();
return new JsonResponse(['error'=>false]);
}else{
$errors = [];
foreach($form as $formField){
if((string)$formField->getErrors(true)){
$errors[] = [
'id'=>$formField->getName(),
'text'=>(string)$formField->getErrors(true)
];
}
}
return new JsonResponse(['error'=>true, 'data' => ['errors' => $errors]]);
}
}else{
return new JsonResponse(['error'=>true]);
}
}
/**
* @Route("/update/set-inspection-date/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function setInspectionDate(Claim $claim, Request $request)
{
# logged in user
$user = $this->get('security.token_storage')->getToken()->getUser();
$response = ['error'=>false, 'data'=>[]];
if($claim){
$incoming_date = $request->request->get('date');
$incoming_time = $request->request->get('time');
$incoming_note = $request->request->get('note');
$needs_inspection = $request->request->get('needs_inspection');
$needs_inspection = $needs_inspection == 0 ? false:true;
# combine date and time
$Date = new \DateTime($incoming_date);
if(($needs_inspection) && (empty($incoming_time) || is_null($incoming_time) || $incoming_time == '00:00 AM'))
{
$response = ['error'=>true, 'data'=>['message'=>'Time inspected is missing.']];
return new JsonResponse($response);
}
if ($needs_inspection){
$Time = DateTime::createFromFormat('Y-m-d H:i A',$Date->format('Y-m-d')." ".$incoming_time); //new \DateTime($incoming_time);
$mergeDateTime = $Time->format( 'Y-m-d H:i' );
} else {
$mergeDateTime = "";
}
$claim->setNeedsInspection($needs_inspection);
$em = $this->getDoctrine()->getManager();
$em->persist($claim);
$em->flush();
if( $this->get('claim.status_update')->setInspectionDate( $claim, $mergeDateTime, $incoming_note ) ){
# create our note
$inspectionDate = new DateTime($incoming_date);
$inspectionNote = "" . $user->getUsername() . sprintf(" has inspected the claim: %s, note: %s", $inspectionDate->format('m/d/Y h:i A'), $incoming_note);
if ($claim->getTransactionId() && $claim->getTransactionId() != "") {
# send our xml to xact
$xactService = $this->get('integration.xact.outbound');
$xactService->exportAddNotes(
[
'transactionId' => $claim->getTransactionId(),
'userName' => $user->getFullName(),
'dateTime' => $inspectionDate->getTimeStamp(),
'noteType' => 'Inspected',
'notes' => $inspectionNote
]
);
}
if($claim->getAssignmentId()){
$symService = $this->get('integration.symbility.outbound');
$symService->pushInspectionDate($inspectionDate->format('m/d/Y'), $claim->getClaimNumber(), $claim->getAssignmentId());
}
} else {
$response = ['error'=>true, 'data'=>['message'=>'Could not set inspection date. Please try again.']];
}
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/update/set-planned-inspection-date/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function setPlannedInspectionDate(Claim $claim, Request $request)
{
# logged in user
$user = $this->get('security.token_storage')->getToken()->getUser();
$response = ['error'=>false, 'data'=>[]];
if($claim){
$incoming_date = $request->request->get('date');
$incoming_time = $request->request->get('time');
// Ensure $incoming_date is a valid date string before creating DateTime object
$Date = new \DateTime($incoming_date);
// Format the DateTime object to string
$formattedDate = $Date->format('Y-m-d');
// Combine the formatted date string with the incoming time and convert it to a timestamp
$combinedDT = date('Y-m-d H:i', strtotime("$formattedDate $incoming_time"));
$dt = new \DateTime($combinedDT);
$claim->setPlannedInspectionDate($dt);
$em = $this->getDoctrine()->getManager();
$em->persist($claim);
$em->flush();
$ClaimNote = $this->container->get("claim.note_provider");
//Status note = 69 Claim Disbursement
$ClaimNote->addClaimNote($claim, "Planned Inspection date has been changed to " .$incoming_date, false, 69);
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/update/set-first-contact-date/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function setFirstContactDate(Claim $claim, Request $request)
{
# logged in user
$user = $this->get('security.token_storage')->getToken()->getUser();
$response = ['error'=>false, 'data'=>[]];
if($claim){
$incoming_date = $request->request->get('date');
$incoming_time = $request->request->get('time');
$incoming_note = $request->request->get('note');
# combine date and time
$Date = new \DateTime($incoming_date);
$Time = new \DateTime($incoming_time);
$mergeDateTime = $Date->format('Y-m-d') . ' ' . $Time->format('H:i:s');
# create our note
$contactDate = new DateTime($incoming_date);
$contactDateTime = new \DateTime($mergeDateTime);
if( $contactDateTime < $claim->getDateReceived()){
$response['error'] = true;
$response['data']['errors'][] = 'Date contacted cannot be before date received!';
return new JsonResponse($response);
}
$contactNote = "" . $user->getUsername() . sprintf(" has made First Contact: %s, note: %s", $contactDate->format('m/d/Y'), $incoming_note);
if($incoming_date){
$note = "";
if($incoming_note){
$note = $incoming_note;
}
# export to xact to let them know first contact has been made
if( $this->get('claim.status_update')->setFirstContactDate($claim, $mergeDateTime, $note) ){
# If Xact claim, lets do export
if ($claim->getTransactionId()) {
$xactService = $this->get('integration.xact.outbound');
$xactService->exportAddNotes(
[
'transactionId' => $claim->getTransactionId(),
'userName' => $user->getFullName(),
'dateTime' => $contactDate->getTimeStamp(),
'noteType' => 'Contacted',
'notes' => $contactNote
]
);
}
if($claim->getAssignmentId()){
// commented as we not need to send first contact dateto symbility
// $symService = $this->get('integration.symbility.outbound');
// $symService->pushFirstContactDate($contactDate->format('m/d/Y'.' '. $Time->format('H:i:s')), $claim->getClaimNumber(), $claim->getAssignmentId());
}
} else {
$response['error'] = true;
$response['data']['errors'][] = 'The date cannot be set in the future!';
}
}else{
$response['error'] = true;
$response['data']['errors'][] = 'You are missing the date!';
}
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/update/set-review-date/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function setReadyForReviewDate(Claim $claim, Request $request)
{
$response = ['error'=>false, 'data'=>[]];
if($claim){
$em = $this->getDoctrine()->getManager();
$currentDate = new \DateTime();
$result = $this->get('claim.status_update')->setReadyForReviewDate($claim, $currentDate->format("m/d/Y h:i A"));
if($result) {
$slog = new SLogger();
$claim->setReportPDFStacking(1);
$em->persist($claim);
$em->flush();
$slog->log($claim->getReportPDFStacking());
if($claim->getAssignmentId()){
$symService = $this->get('integration.symbility.outbound');
$symService->pushReadyForReview($claim->getClaimNumber(), $claim->getAssignmentId());
}
}
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/update/undo-ready-review/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function setUndoReadyReview(Claim $claim, Request $request)
{
$response = ['error'=>false, 'data'=>[]];
if($claim){
$this->get('claim.status_update')->undoReadyForReview($claim);
if($claim->getIsLocked()){
$this->get('claim.status_update')->unlockClaim($claim);
}
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/update/reopen-claim/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function reopenClaim(Claim $claim, Request $request)
{
$reason = $request->request->get("reason");
$settlement_type_reopen = $request->request->get("settlement_type_reopen");
$cwop_reason_reopen = $request->request->get("cwop_reason_reopen");
$denial_description_line_reopen = $request->request->get("denial_description_line_reopen");
$response = ['error'=>false, 'data'=>[]];
$strCWOPReason ='';
if($claim){
$this->get('claim.status_update')->reopenClaim($claim, $reason);
if (!empty($claim->getCustomer()->isTpaUi())) {
$em = $this->container->get("doctrine.orm.entity_manager");
if (!empty($cwop_reason_reopen)) {
$objCwopReason = $em->getRepository("ClaimManagementBundle:CwopReason")->findOneBy(['id' => $cwop_reason_reopen]);
if (!empty($objCwopReason)) {
$claim->setReopenCwopRsn($objCwopReason);
$claim->setReopenDenialDescriptionLine($denial_description_line_reopen);
$strCWOPReason = $objCwopReason->getDescription();
}
}
$objSettlementType = $em->getRepository("ClaimManagementBundle:SettlementType")->find($settlement_type_reopen);
if (!empty($objSettlementType)) {
$claim->setReopenSettlementType($objSettlementType);
}
$em->persist($claim);
$em->flush();
$ClaimNote = $this->container->get("claim.note_provider");
if(!empty($strCWOPReason)){
$ClaimNote->addClaimNote($claim, "Reopen CWOP Reason ($strCWOPReason) added to the claim with Denial Description as ($denial_description_line_reopen).", false);
}
}
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/update/reinspect-claim/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function reInspectClaim(Claim $claim, Request $request)
{
$reason = $request->request->get("reason");
$response = ['error'=>false, 'data'=>[]];
if($claim){
$this->get('claim.status_update')->reInspectClaim($claim, $reason);
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/update/set-in-progress/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function setInProgress(Claim $claim, Request $request)
{
$response = ['error'=>false, 'data'=>[]];
if($claim){
$this->get('claim.status_update')->setInProgress($claim);
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/create/claim-note/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function addClaimNote(Claim $claim, Request $request)
{
# logged in user
$user = $this->get('security.token_storage')->getToken()->getUser();
$response = ['error'=>false, 'data'=>[]];
$comment = $request->request->get('comment');
$outbound = $request->request->get('outbound');
$send = false;
if( $outbound != "" ){
$send = $outbound == 1;
}
# Check for post #
if ($comment) {
if ($claim) {
/**
* @var $file UploadedFile
*/
$file = $request->files->all()['media'] ?? null;
$claimNoteMediaService = $this->get('claim_note.media');
$newFilename = uniqid();
if ($file instanceof UploadedFile) {
$mediaValid = $claimNoteMediaService->validateClaimNoteMedia($file);
if ($mediaValid['error']) {
return new JsonResponse(['error' => $mediaValid['message']]);
}
$copyMedia = $claimNoteMediaService->copyClaimNoteMedia($file, $newFilename, $claim->getId());
if ($copyMedia !== true) {
return new JsonResponse(['error' => (is_bool($copyMedia) ? "Failed to copy the uploaded media" : $copyMedia)]);
}
}
$em = $this->getDoctrine()->getManager();
$claimNote = $this->get('claim.note_provider')->addClaimNote($claim, $comment);
$em->refresh($claimNote);
if ($file instanceof UploadedFile) {
try {
$em->getRepository(ClaimNoteMedia::class)->createClaimNoteMedia(
$claim->getId(),
$claimNote->getId(),
$file->getClientOriginalExtension(),
$file->getClientOriginalName(),
sprintf("%s.%s", $newFilename, $file->getClientOriginalExtension()),
$file->getClientMimeType()
);
} catch (\Exception $exception) {
$em->remove($claimNote);
return new JsonResponse([
'error' => sprintf("Failed to store ClaimNoteMedia Error: %s", $exception->getMessage())
]);
}
}
# log note to xact
if($send && $claim->getTransactionId()){
$xactService = $this->get('integration.xact.outbound');
$xactService->exportAddNotes(
[
'transactionId' => $claim->getTransactionId(),
'userName' => $user->getFullName(),
'dateTime' => time(),
'notes' => $comment
]
);
}
if($send && $claim->getAssignmentId()){
$symService = $this->get('integration.symbility.outbound');
$symService->addNotes(
[
'transactionId' => $claim->getClaimNumber(),
'userName' => $user->getFullName(),
'dateTime' => time(),
'assignmentID' =>$claim->getAssignmentId(),
'notes' => $comment
]
);
}
return new JsonResponse($response);
} else {
throw new NotFoundHttpException("Couldn't find this claim!");
}
}else{
return new JsonResponse(['error' => 'File Note\'s Cannot Be Blank']);
}
}
/**
* @Route("/update/lock/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function lockClaim(Claim $claim)
{
$this->get('claim.assignment')->assignCurrentUserAsExaminer($claim);
$this->get('claim.status_update')->lockClaim($claim);
return new JsonResponse(['error'=>false]);
}
/**
* @Route("/update/unlock/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function unlockClaim(Claim $claim)
{
$this->get('claim.status_update')->unlockClaim($claim);
return new JsonResponse(['error'=>false]);
}
/**
* @Route("/update/in-progress/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function markInExaminerProgress(Claim $claim)
{
$this->get('claim.status_update')->markInProgressExaminer($claim);
return new JsonResponse(['error'=>false]);
}
/**
* @Route("/update/claim-status/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function updateClaimStatus(Claim $claim, Request $request)
{
$status_id = $request->request->get('status_id');
if($status_id==97){
$status_id=30;
$em = $this->container->get("doctrine.orm.entity_manager");
$stmt = $em->getConnection()->prepare("UPDATE claim SET date_closed = NOW(), updated_at = NOW() WHERE id = ? ");
$stmt->execute([$claim->getId()]);
}//Claim Tech closing
$this->get('claim.status_update')->changeStatus($claim,$status_id);
return new JsonResponse(['error'=>false]);
}
/**
* @Route("/update/examiner-hold/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function markInExaminerHold(Claim $claim)
{
$this->get('claim.status_update')->markInHoldExaminer($claim);
return new JsonResponse(['error'=>false]);
}
/**
* @Route("/update/qa-approved/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function markQaApproved($claim)
{
$resource = $this->get('security.token_storage')->getToken()->getUser();
$currentDate = new \DateTime();
$this->get('claim.status_update')->markQaApproved( $claim, $resource, $currentDate->format("m/d/Y h:i A") );
return new JsonResponse(['error'=>false]);
}
/**
* @Route("/update/qa-rejected/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function markQaRejected($claim, Request $request)
{
$resource = $this->get('security.token_storage')->getToken()->getUser();
$reason = $request->request->get('reason');
$reasonCodeIds = $request->request->get('reason_code');
$ReasonCodeIds = array();
if (strpos($reasonCodeIds, ',') !== false) {
$ReasonCodeIds = explode(",", $reasonCodeIds);
}else{
$ReasonCodeIds[0]= $reasonCodeIds;
}
$em = $this->getDoctrine()->getManager();
$currentDate = new \DateTime();
$ClaimReportRepo = $em->getRepository("ClaimManagementBundle:XactClaimReport");
$ClaimReport = $ClaimReportRepo->findOneBy(['claimNumber' => $claim->getClaimNumber()]);
if (!empty($ClaimReport)) {
$ClaimReport->setReturnedDate($currentDate);
$em->persist($ClaimReport);
$em->flush();
}
$this->get('claim.status_update')->markQaRejected( $claim, $resource,$reason, $ReasonCodeIds, $currentDate->format("m/d/Y h:i A") );
return new JsonResponse(['error'=>false]);
}
/**
* @Route("/claim-diary/complete/{diary_id}", defaults={"diary_id" = null})
*/
public function diaryComplete($diary_id)
{
$dispatch = $this->get('event_dispatcher');
$diaryEntry = $this->getDoctrine()->getRepository('ClaimManagementBundle:DiaryEntry')->find($diary_id);
$diaryEntry->setStatus(1);
$em = $this->getDoctrine()->getManager();
$em->persist($diaryEntry);
$em->flush();
/**
* @date 08/11/2017
*
* Implementing service to push a note to the Claim
*
*/
$NoteService = $this->get('claim.note_provider');
// Todo ClaimDiaryAssignedEvent listener for this event
$dispatch->dispatch(ClaimDiaryCompleteEvent::NAME, new ClaimDiaryCompleteEvent($diaryEntry));
$NoteService->addClaimNote( $diaryEntry->getClaim(), "Diary entry '" . $diaryEntry->getDescription() . "' was completed!", false,70 );
return new JsonResponse(['diary'=> $diaryEntry->getId()]);
}
/**
* @Route("/create/claim-diary/{claim_id}/{diary_id}", defaults={"diary_id" = null})
*/
public function addNewDiaryEntry($claim_id, $diary_id, Request $request)
{
$dispatch = $this->get('event_dispatcher');
// This is the EM we'll use
$em = $this->getDoctrine()->getManager();
$LoggedInUser = $this->container->get("security.token_storage")->getToken()->getUser();
if($claim_id){
$claim = $this->getDoctrine()->getRepository('ClaimManagementBundle:Claim')->find($claim_id);
$diaryFormData = $request->request->get('diary_form');
$isUpdate = false;
if ($diary_id) {
$isUpdate = true;
$diary = $this->getDoctrine()->getRepository('ClaimManagementBundle:DiaryEntry')->find($diary_id);
} else {
$diary = new DiaryEntry();
}
$diaryForm = $this->createForm( DiaryFormType::class, $diary, ['claim_id' => $claim_id]);
$diaryForm->submit( $diaryFormData );
if($diaryForm->isValid()){
/** @var DiaryEntry $DiaryEntry */
$DiaryEntry = $diaryForm->getData();
$DiaryEntry->setClaim($claim);
$DiaryEntry->setAuthor($LoggedInUser);
$DiaryEntry->setStatus(0);
$DiaryEntry->setDateCreated( new \DateTime() );
/**
* @date 08/11/2017
*
* Implementing service to push a note to the Claim
*
*/
$NoteService = $this->get('claim.note_provider');
// Todo ClaimDiaryAssignedEvent listener for this event
if ($isUpdate == false) {
$dispatch->dispatch(ClaimDiaryAssignedEvent::NAME, new ClaimDiaryAssignedEvent($diary));
$NoteService->addClaimNote($DiaryEntry->getClaim(), "Diary entry '" . $DiaryEntry->getDescription() . "' was created!", false, 70);
} else {
$NoteService->addClaimNote($DiaryEntry->getClaim(), "Diary entry '" . $DiaryEntry->getDescription() . "' was updated!", false, 70);
}
/**
* @date 08/31/2017
*
* Implementing multiple diary resources (if they exist)
*
*/
$other_resources = $request->request->get('extra-diary-resources');
if($other_resources && !empty($other_resources)){
foreach($other_resources as $resource_id){
$ActualResource = $em->find("ResourceManagementBundle:Resource", $resource_id);
$DiaryResource = new DiaryOtherResource();
$DiaryResource->setDateAdded( new \DateTime() );
$DiaryResource->setDiaryEntry( $DiaryEntry );
$DiaryResource->setResource( $ActualResource );
$em->persist($DiaryResource);
}
}
$em->persist($DiaryEntry);
$em->flush();
$response['error'] = false;
}else{
$response = [];
$response['error'] = true;
$response['formError'] = (string)$diaryForm->getErrors(true);
foreach($diaryForm as $formField){
$errorString = (string)$formField->getErrors();
if($errorString != ""){
$response['data']['errors'][] = [
'id' => $diaryForm->getName()."_".$formField->getName(),
'text' => $errorString
];
}
}
}
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/create/auto_disbursement")
*/
public function addNewAutoDisbursement(Request $request)
{
// This is the EM we'll use
$em = $this->getDoctrine()->getManager();
$claimId = $request->request->get('claim');
$lastIdentifier = $request->request->get('lastIdentifier');
# JsonResponseObj
$rtnVal = [
'error' => false,
'errors' => [],
'data' => []
];
$nHasQty = 0;
for($i = 0; $i < $lastIdentifier; $i++) {
$autoExpense = $request->request->get('auto-expense-' . $i);
if(!$autoExpense) {
# if section of form doesnt exist, stop
return new JsonResponse($rtnVal);
} else if ($autoExpense['qty'] == "") {
# if quantity was not set, do not submit
$rtnVal['error'] = true;
$rtnVal['errors'][] = "Must set a quantity!";
} else {
$nHasQty++;
# set values
$cost = floatval(ltrim($autoExpense['amount'], '$'));
$description = $autoExpense['description'];
$qty = $autoExpense['qty'];
$customerExpense = $autoExpense['customerExpense'];
$expense = $autoExpense['expense'];
$resource = $this->get('security.token_storage')->getToken()->getUser()->getId();
# prepared statement for fast entries
/*$sql = "INSERT INTO disbursement
(claim_id, invoice_id, resource_id, expense_id, customer_expense_id, quantity, cost, description, dateCreated)
VALUES
('" . $claimId . "', NULL,'" . $resource . "','" . $expense . "', '" . $customerExpense . "', '" . $qty . "', '" . $cost . "', '" . $description . "', NOW())";
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();*/
$disbursement = new Disbursement();
$disbursement->setClaim( $em->find("ClaimManagementBundle:Claim", $claimId) );
$disbursement->setResource( $em->find("ResourceManagementBundle:Resource", $resource) );
$disbursement->setExpense( $em->find("CompanyManagementBundle:Expense", $expense) );
$disbursement->setCustomerExpense( $em->find("InvoiceManagementBundle:CustomerExpense", $customerExpense) );
$disbursement->setQuantity($qty);
$disbursement->setCost($cost);
$disbursement->setDescription( $description );
$disbursement->setDateCreated( new \DateTime() );
$em->persist($disbursement);
$em->flush();
}
}
//Give Error only if none of expenses have Qty
if (!empty($nHasQty)) {
$rtnVal = [
'error' => false,
'errors' => [],
'data' => []
];
}
//Give Error only if none of expenses have Qty
return new JsonResponse($rtnVal);
}
/**
* @Route("/create/expense/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function createClaimExpenseAction($claim, Request $request)
{
// This is the EM we'll use
$em = $this->getDoctrine()->getManager();
// This extract gets submitted through the form builder
$time_log = $request->request->get('disbursement_time_log');
// This extract gets used only if the form submitted fully (to complete adding a new disbursement)
$time_log_extras = $request->request->get('disbursement_other');
if ($time_log['expense'] < 1) {
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "choose-expense";
$nextError['text'] = "Please choose an expense.";
$data['errors'][] = $nextError;
# return json error objects
$retVal = array(
"status" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
# validate the resource on expense model with resource which assignments
$resourceId = $time_log['resource'];
/** @var \PDO $pdo */
$pdo = $em->getConnection();
$chkAdjusterAssinged = $pdo->prepare("SELECT resource_id, assignment_party_id, is_primary_adjuster FROM assignments WHERE claim_id = ? AND resource_id = ? AND is_current_assignment = 1;");
$chkAdjusterAssinged->execute([$claim->getId(), $resourceId]);
if ($chkAdjusterAssinged->rowCount() == 0) {
# return json error objects
$nextError = array();
$nextError['id'] = "resource";
$nextError['text'] = "Resource set for expense is not assinged to claim.";
$data['errors'][] = $nextError;
$retVal = array(
"status" => "fail",
"error_msgs" => array(),
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
// Create the form
$form = $this->createForm(DisbursementTimeLogType::class, new Disbursement(), array('claim_id' => $claim->getId()));
/**
* @date 8/14/2017
*
* Fix to pre-select a date even if one has'nt been chosen in the front end.
* We always default to today's date.
*/
/*$today = new \DateTime();
$time_log['dateCreated'] = $today->format("Y-m-d");*/
$form->submit($time_log);
if($form->isValid()){ // if form is valid
/** @var Disbursement $Disbursement */
$Disbursement = $form->getData();
$Disbursement->setClaim($claim);
if( $time_log_extras['customerExpense'] > 0 ){
$CustomerExpense = $em->find('InvoiceManagementBundle:CustomerExpense', intval($time_log_extras['customerExpense']));
$Disbursement->setCustomerExpense($CustomerExpense);
}
$Disbursement->setCost($time_log['cost']);
$Disbursement->setExcludeInvoicing($Disbursement->getExpense()->getExcludeInvoicing());// for excluding when expense default rate is 100
$em->persist($Disbursement);
$em->flush();
if (!$Disbursement->getExpense()->getExcludeInvoicing()) {
# Update the Discount Amounts on the Disbursements, such as DiscountQty and MaxAmounts
$invoiceService = $this->container->get("app.invoice_helper");
$invoiceService->updateDisbursementDiscounts($claim);
}
$ClaimNote = $this->container->get("claim.note_provider");
//Status note = 69 Claim Disbursement
$ClaimNote->addClaimNote($claim, "Disbursement " . $Disbursement->getExpense()->getExpenseName() . " was added on Claim.", false, 69);
# pass json response success
$retVal = array(
"status" => "success",
"error_msgs" => []
);
return new JsonResponse($retVal);
}else{ // if form has errors
$data = array();
$errors2 = array();
$errorsArr = array();
# Get Error Messages
$error_str = (string)$form->getErrors(true, false);
$slog = new SLogger();
$slog->log("error_str at 2: ");
$slog->log($error_str);
$errorsArr2 = explode("\n", $error_str);
foreach ($errorsArr2 as $getError) {
if (trim($getError) != "") {
$errorsArr[] = trim($getError);
}
}
$i = 1;
if (count($errorsArr) > 0) {
$data = [
"errors" => array()
];
foreach ($errorsArr as $getItem) {
if ($i == 1) {
$nextError = array();
$nextError['id'] = substr($getItem, 0, strlen($getItem) - 1);
} else {
$nextError['text'] = $getItem;
$data['errors'][] = $nextError;
}
if ($i < 2) {
$i++;
} else {
$i = 1;
}
}
}
# return json error objects
$retVal = array(
"status" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
/**
* @Route("/update/expense/{claimId}/{disbursementId}")
*/
public function updateClaimExpenseAction(Request $request, $claimId, $disbursementId)
{
// This is the EM we'll use
$em = $this->getDoctrine()->getManager();
$claim = $em->getRepository("ClaimManagementBundle:Claim")->find($claimId);
$disbursement = $em->getRepository("InvoiceManagementBundle:Disbursement")->find($disbursementId);
## Code checks if changes were made to Claim Object ##
# Get Current Resource on DB
$disbursement_compare = new DisbursementCompareHelper($em);
# this function must be called before $form->getData()
$disbursement_compare->setCurDisbursement($disbursement);
// This extract gets submitted through the form builder
$time_log = $request->request->get('disbursement_time_log');
// This extract gets used only if the form submitted fully (to complete adding a new disbursement)
$time_log_extras = $request->request->get('disbursement_other');
// This extract gets used only if the expense cost is not editable
$editable = $request->request->get('is_editable');
// Create the form
$form = $this->createForm( DisbursementTimeLogType::class, $disbursement, array('claim_id' => $claimId));
$form->submit($time_log);
// backend validation to validate cost cant be changed
if ($editable != 1) {
$cost = $time_log['cost'];
if ($cost != $disbursement->getCost()) {
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "not-editable";
$nextError['text'] = "The cost is not editable for this claim.";
$data['errors'][] = $nextError;
# return json error objects
$retVal = array(
"status" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
}
if ($time_log['expense'] < 1) {
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "choose-expense";
$nextError['text'] = "Please choose an expense.";
$data['errors'][] = $nextError;
# return json error objects
$retVal = array(
"status" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($retVal);
}
if($form->isValid()){ // if form is valid
/** @var Disbursement $Disbursement */
$Disbursement = $form->getData();
if( $time_log_extras['customerExpense'] > 0 ){
$CustomerExpense = $em->find('InvoiceManagementBundle:CustomerExpense', intval($time_log_extras['customerExpense']));
$Disbursement->setCustomerExpense($CustomerExpense);
}
if( $time_log['expense'] > 0 ){
$Expense = $em->find("CompanyManagementBundle:Expense", intval($time_log['expense']));
$Disbursement->setExpense($Expense);
}
$Disbursement->setExcludeInvoicing($Disbursement->getExpense()->getExcludeInvoicing());// for excluding when expense default rate is 100
# Get Submitted Form Claim Object
$disbursement_compare->setNewDisbursement($Disbursement);
# Compare 2 objects to see if there were any changes made
$hasChanges = $disbursement_compare->compareObjects();
if ($hasChanges) {
$em->persist($Disbursement);
$em->flush();
$ClaimNote = $this->container->get("claim.note_provider");
//Status note = 69 Claim Disbursement
$ClaimNote->addClaimNote($claim, "Disbursement " . $Disbursement->getExpense()->getExpenseName() . " was updated on Claim. " . implode(" ", $disbursement_compare->changeLog), false, 69);
}
if (!$Disbursement->getExpense()->getExcludeInvoicing()) {
# Update the Discount Amounts on the Disbursements, such as DiscountQty and MaxAmounts
$invoiceService = $this->container->get("app.invoice_helper");
$invoiceService->updateDisbursementDiscounts($claim);
}
# pass json response success
$retVal = array(
"status" => "success",
"error" => false
);
return new JsonResponse($retVal);
}else{ // if form has errors
# Catch errors in a array
$response = [];
$response['error'] = true;
$response['formError'] = (string)$form->getErrors(true);
# foreach through each field for validation
foreach($form as $formField){
$errorString = (string)$formField->getErrors();
if($errorString != ""){
$response['data']['errors'][] = [
'id' => $form->getName()."_".$formField->getName(),
'text' => $errorString
];
}
}
return new JsonResponse($response);
}
}
/**
* @Route("/make/document_templates")
*/
public function makeGlobalDocumentTemplates()
{
$kernel = $this->container->get("kernel");
$file_path = $kernel->getRootDir() . "/Resources/doc_library";
$finder = new Finder();
$finder->files()->in($file_path);
$fileArr = array();
foreach ($finder as $file) {
$file_name = $file->getRelativePathname();
$file_path = $file->getRealPath();
$fileNameArr = explode("-", $file_name);
$index = $fileNameArr[0];
$fileArr[$index] = [
"name" => $fileNameArr[1],
"path" => $file_path
];
}
ksort($fileArr);
$idsArr = [
"1" => 638,
"2" => 639,
"3" => 640,
"4" => 641,
"5" => 642,
"6" => 643,
"7" => 644
];
$file_manager = $this->container->get("app.file_manager");
foreach ($fileArr as $index => $getFile) {
$fh = fopen($getFile['path'], 'r');
$content = fread($fh, filesize($getFile['path']));
fclose($fh);
# Convert HTML Content to PDF file in /tmp folder
$get_num = md5(uniqid());
$new_file_name = $get_num;
$new_file_path = "/tmp/" . $new_file_name;
$fh1 = fopen($new_file_path, 'w');
fwrite($fh1, $content);
fclose($fh1);
# Create file from temp file using file manager service
$useFile['new_file_name'] = $new_file_name;
$useFile['used_by_module'] = "DocumentLibraryGlobal";
$useFile['name'] = $new_file_name;
$useFile['type'] = "text/html";
$useFile['error'] = 0;
$useFile['size'] = filesize($new_file_path);
$useFile['file_ext'] = "twig";
# Save file by passing file object, id, and entity name
$file_manager->saveFile($useFile, $idsArr[$index], "DocumentLibraryGlobal");
}
dump("Script completed");
die;
}
/**
* @Route("/make/document_templates2")
*/
public function makeGlobalDocumentTemplates2()
{
$kernel = $this->container->get("kernel");
$file_path = $kernel->getRootDir() . "/Resources/doc_library2";
$finder = new Finder();
$finder->files()->in($file_path);
$fileArr = array();
foreach ($finder as $file) {
$file_name = $file->getRelativePathname();
$file_path = $file->getRealPath();
$fileNameArr = explode("-", $file_name);
$index = $fileNameArr[0];
$fileArr[$index] = [
"name" => $fileNameArr[1],
"path" => $file_path
];
}
ksort($fileArr);
$idsArr = [
"8" => 645,
"9" => 646,
"10" => 647
];
$file_manager = $this->container->get("app.file_manager");
foreach ($fileArr as $index => $getFile) {
$fh = fopen($getFile['path'], 'r');
$content = fread($fh, filesize($getFile['path']));
fclose($fh);
# Convert HTML Content to PDF file in /tmp folder
$get_num = md5(uniqid());
$new_file_name = $get_num;
$new_file_path = "/tmp/" . $new_file_name;
$fh1 = fopen($new_file_path, 'w');
fwrite($fh1, $content);
fclose($fh1);
# Create file from temp file using file manager service
$useFile['new_file_name'] = $new_file_name;
$useFile['used_by_module'] = "DocumentLibraryGlobal";
$useFile['name'] = $new_file_name;
$useFile['type'] = "text/html";
$useFile['error'] = 0;
$useFile['size'] = filesize($new_file_path);
$useFile['file_ext'] = "twig";
# Save file by passing file object, id, and entity name
$file_manager->saveFile($useFile, $idsArr[$index], "DocumentLibraryGlobal");
}
dump("Script completed");
die;
}
/**
* @Route("/share/claim-resources/{id}")
* @Method(methods={"POST"})
* @deprecated
*/
public function completeShareResource(Request $request, Claim $claim)
{
$em = $this->container->get("doctrine.orm.entity_manager");
if ($claim == null) {
throw $this->createNotFoundException("Claim does not exist");
}
# Request Adjuster Info
$roles = $request->request->get("roles");
$AdjustersArr = $roles;
# Check if duplicate adjusters have been passed
$hasDuplicates = false;
$allAdjusters = array();
$duplicateAdjusterType = "";
foreach ($AdjustersArr as $adjusterType => $adjusterIds) {
foreach ($adjusterIds as $adjusterId) {
if (in_array($adjusterId, $allAdjusters)) {
$hasDuplicates = true;
$duplicateAdjusterType = $adjusterType;
break;
}
$allAdjusters[] = $adjusterId;
}
}
if ($hasDuplicates) { // if duplicate adjusters were sent
# Send Back Error
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = $duplicateAdjusterType;
$nextError['text'] = "You cannot assign the same Adjuster more than once on this Claim.";
$data['errors'][] = $nextError;
$response = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($response);
} else {
# First Validate that all adjusters can be added
$allErrors = array();
foreach ($AdjustersArr as $adjusterType => $adjusterIds) {
$getAdjustertype = $adjusterType;
$role = $em->getRepository("ClaimManagementBundle:ClaimResourceRole")->findOneBy([
"role" => $getAdjustertype
]);
foreach ($adjusterIds as $adjusterId) {
if ($getAdjustertype == "Field Adjuster" || $getAdjustertype == "Desk Adjuster") { // if field or desk
$adjusters = $em->getRepository("ClaimManagementBundle:ClaimResource")->getAdjustersByClaim($claim);
if (count($adjusters) == 0) { // if no adjusters
# Set Primary
$isPrimary = true;
} else {
if ($getAdjustertype == "Field Adjuster") { // if current type is field adjuster
$fieldAdjustersCount = 0;
foreach ($adjusters as $getAdjuster) {
if ($getAdjuster->getResource->getRole()->getRole() == "Field Adjuster") {
$fieldAdjustersCount++;
}
}
if ($fieldAdjustersCount == 0) { // if there are no other field adjusters
# Set Primary
$isPrimary = true;
} else {
$isPrimary = false;
}
} else {
$isPrimary = false;
}
}
} else {
$isPrimary = false;
}
$currentResource = $em->getRepository("ResourceManagementBundle:Resource")->find($adjusterId);
# Attempt assigning the RESOURCE to the CLAIM
$retVal = $this->get('claim.assignment')->validateAssignResourceToClaim(
$claim,
$currentResource,
$role,
new \DateTime(),
$isPrimary,
$currentResource->getPayrollId()
);
$errors = $this->get('claim.assignment')->getErrors();
$allErrors = $errors;
if ($retVal == false) { // if adding some of the adjusters returned errors
# Send Error Messages
if (!empty($allErrors)) {
$errors2 = array();
$data = [
"errors" => array()
];
$nextError = array();
$nextError['id'] = "";
$nextError['text'] = implode("\n", $allErrors);
$data['errors'][] = $nextError;
$response = array(
"result" => "fail",
"error_msgs" => $errors2,
"error" => true,
"data" => $data
);
return new JsonResponse($response);
exit;
}
}
}
}
# If all adjusters can be added, go ahead and assign them
foreach ($AdjustersArr as $adjusterType => $adjusterIds) {
$getAdjustertype = $adjusterType;
$role = $em->getRepository("ClaimManagementBundle:ClaimResourceRole")->findOneBy([
"role" => $getAdjustertype
]);
foreach ($adjusterIds as $adjusterId) {
if ($getAdjustertype == "Field Adjuster" || $getAdjustertype == "Desk Adjuster") { // if field or desk
$adjusters = $em->getRepository("ClaimManagementBundle:ClaimResource")->getAdjustersByClaim($claim);
if (count($adjusters) == 0) { // if no adjusters
# Set Primary
$isPrimary = true;
} else {
if ($getAdjustertype == "Field Adjuster") { // if current type is field adjuster
$fieldAdjustersCount = 0;
foreach ($adjusters as $getAdjuster) {
if ($getAdjuster->getRole()->getRole() == "Field Adjuster") {
$fieldAdjustersCount++;
}
}
if ($fieldAdjustersCount == 0) { // if there are no other field adjusters
# Set Primary
$isPrimary = true;
} else {
$isPrimary = false;
}
} else {
$isPrimary = false;
}
}
} else {
$isPrimary = false;
}
$currentResource = $em->getRepository("ResourceManagementBundle:Resource")->find($adjusterId);
$this->get('claim.assignment')->assignResourceToClaim(
$claim,
$currentResource,
$role,
new \DateTime(),
$isPrimary,
$currentResource->getPayrollId()
);
}
}
# Return success JSON
$response = array(
"result" => "success",
"error_msgs" => []
);
return new JsonResponse($response);
}
}
/**
* @Route("/verify/claim-resource")
*/
public function verifyShareResource(Request $request)
{
// We want to know what RESOURCE is going into WHAT role, and WHAT claim.. so.
if($request && $request->get('claim') && $request->get('resource')){
# Load the IDs from the GET request
$claim_id = $request->get('claim');
$resource_id = $request->get('resource');
$role_name = $request->get('role');
# Load them now into the ENTITIES
$em = $this->getDoctrine()->getManager();
# Entity mapping
$Claim = $em->find("ClaimManagementBundle:Claim", $claim_id);
$Role = $em->getRepository('ClaimManagementBundle:ClaimResourceRole')->findOneBy(['role'=>$role_name]);
$Resource = $em->find("ResourceManagementBundle:Resource", $resource_id);
# Service to call
$claimService = $this->get('claim.assignment');
# Create the JSON response
$json_response = [
'result' => false,
'messages' => []
];
# Now, we verify if this Resource can be shared onto this Claim.. or if not.
if($claimService->canAssignResourceToClaim($Claim, $Resource, $Role)){
// Send a result saying that it can be assigned, allow it
$json_response['result'] = true;
}else{
// Send a result saying that for some reason this guy can't be added
$json_response['messages'] = $claimService->getErrors();
$json_response['messages'][] = 'Claim could not be assigned.';
}
return new JsonResponse($json_response);
}else{
throw new BadRequestHttpException('Please submit a CLAIM, ROLE and RESOURCE with your request');
}
}
public function slugify($text)
{
$delimiter = "_";
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
return strtolower(preg_replace('/[^A-Za-z0-9-]+/', $delimiter, $text));
}
/**
* @Route("ack-letter/send/{id}")
*/
public function sendAckLetterEmail(Claim $claim, Request $request)
{
$em = $this->container->get('doctrine')->getManager();
$tokenStorage = $this->container->get('security.token_storage');
$user = $tokenStorage->getToken()->getUser();
$incoming_internal_rep = $request->request->get('intRepEmail');
$incoming_addresses = $request->request->get('otherEmail');
$incoming_body = $request->request->get('body');
$kernel = $this->container->get('kernel');
$env = $kernel->getEnvironment();
$strImagePath = $this->generateUrl('globals_companymanagement_company_getcompanylogo', array('id'=>$claim->getId()));
$strImagePathTmp = '';
if ($claim->getCustomer()) {
$ClaimCustomer = $claim->getCustomer();
if ($ClaimCustomer->getSubCompany()) { // if has a Company ID on the Claim Team
# Use that Sub Company ID
$company_id = $ClaimCustomer->getSubCompany()->getId();
$Company = $em->getRepository("CompanyManagementBundle:Company")->findById($company_id);
if ($Company) {
$entity = 'CompanyLogo';
$FileManager = $em->getRepository("ResourceManagementBundle:FileManager")->loadByFileIDEntity($company_id, $entity);
$fileName = $this->slugify($Company[0]->getName());
$strImagePathTmp = $request->server->get('DOCUMENT_ROOT'). "/" . $kernel->getEnvironment() . "/" . $entity . "/" . $fileName . "." . $FileManager->getExt();
}
}
}
$imageUrl = $request->server->get('DOCUMENT_ROOT')."/img/$env.jpg";
if(!empty($strImagePathTmp)){
$imageUrl = $strImagePathTmp;
}
if($incoming_addresses && $incoming_internal_rep){
$incoming_addresses .= ";$incoming_internal_rep";
}else{
$incoming_addresses .= $incoming_internal_rep;
}
if ($incoming_addresses && $claim->getClientEmail()) {
$clientEmail = $claim->getClientEmail();
$incoming_addresses .= ";$clientEmail";
}
$addresses = explode(';', $incoming_addresses);
$email_from = $user->getEmail();
$subject = "Acknowledgment Letter";
$email_body = $incoming_body;
$mailer = $this->container->get('mail_management.mailer');
$mailer->replaceParam = array('strImagePath' => $strImagePath, 'imageUrl' => $imageUrl);
$Mail = new Mail();
$mailer->setSendingConfig();
foreach ($addresses as $address) {
//Validate Emails
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
return new JsonResponse(['error'=>true, 'data' => ['errors' => "Wrong email format"]]);
}
$slog = new SLogger();
$slog->log('address: '.$address);
$email_to = $address;
# Recipient
$Recipient = new MailRecipient();
$Recipient->setEmail($email_to);
$Recipient->setMail($Mail);
$Recipient->setRecipientId($claim->getCustomer()->getId());
$entityName = $em->getMetadataFactory()->getMetadataFor(get_class($claim->getCustomer()))->getName();
$Recipient->setRecipientType($entityName);
//$em->persist( $Recipient );
//$em->flush();
# Adds the single recipient (resource);
$Mail->addRecipient($Recipient);
$Mail->setSubject($subject);
# SETTING THE EXCEPTIONS
# ######################################################
$catcrew_exceptions = false;
$great_american_exception = false;
if($claim->getCustomer()->getId() == 5624)
{
$great_american_exception = true;;
}
if($claim->getCustomer()->getId() == 5727)
{
$catcrew_exceptions = true;
}
}
# SETTING THE SUBJECT
# ######################################################
// $Mail->setSubject("Claim Assigned");
$Mail->setSubject("Claim has been assigned - Claim Assigned Notification");
if($great_american_exception)
{
$SubjectClaim = str_replace("-","",$claim->getClaimNumber());
$Mail->setSubject($SubjectClaim.";Documents;Other;Acknowledgement Davies;;;;Financial Institution Services;;;;;;;Spec Gen;;;;;N;;;");
}
if($catcrew_exceptions)
{
$Mail->setSubject("Acknowledgement for Claim #" . $claim->getClaimNumber());
}
# Finalize the MAIL object
$Mail->setBody($email_body);
$Mail->setSenderName(MailHelper::getMailSenderName($tokenStorage));
$mailer->sendEmail($Mail, $email_from, "");
/*
* Create a Claim Note in the FileNotes
*/
// status note = 71 Ack. Letter
$this->container->get('claim.note_provider')->addClaimNote($claim, "Ack. Letter sent to " . $incoming_addresses . " by " . $email_from , true, 71);
/*
* Call function that converts to PDF and attach to Attachments List
*/
$slog = new SLogger();
$slog->log("123 789");
$this->convertToAttachmentsAckLetter($incoming_body, $claim->getId(), $user->getId());
//Update the claim table with pdfstatus in progress pdf stacking
$update_claim_sql = "UPDATE claim
SET pdfstatus = :pdfstatus,
updated_at = NOW()
WHERE id = :claim_id";
$dataParams = array();
$dataParams['claim_id'] = $claim->getId();
$dataParams['pdfstatus'] = 1;
$stmt = $em->getConnection()->prepare($update_claim_sql);
try{
$stmt->execute($dataParams);
}catch (\PDOException $e){
return new Response("Exception occurred while Updating");
}
return new JsonResponse(['success' => true]);
}
/**
* Function to Convert to PDF and Append to Attachments
*/
public function convertToAttachmentsAckLetter($htmlBody, $claimId, $resourceId){
$em = $this->container->get("doctrine.orm.entity_manager");
$fileManager = $this->container->get("app.file_manager");
$kernel = $this->container->get("kernel");
/*
* Create Path and File name
*/
$new_file_name = md5(uniqid());
$new_file_path = "/tmp/" . $new_file_name;
$this->container->get("knp_snappy.pdf")->setTimeout(600);
$slog = new SLogger();
$slog->log("htmlBody at 712: " . $htmlBody);
$slog->log("new_file_path: $new_file_path");
$rootDir = $kernel->getRootDir();
$rootDir = str_replace("/app", "", $rootDir);
$htmlBody = str_replace("/" . $kernel->getEnvironment() . "/CompanyLogo/", $rootDir . "/web/" . $kernel->getEnvironment() . "/CompanyLogo/", $htmlBody);
$slog->log("htmlBody after at 717: " . $htmlBody);
$this->container->get("knp_snappy.pdf")->generateFromHtml($htmlBody, $new_file_path);
$useFile['new_file_name'] = basename($new_file_path);
$useFile['used_by_module'] = "ClaimReport";
$useFile['name'] = basename($new_file_path);
$useFile['type'] = "application/pdf";
$useFile['error'] = 0;
// echo "<pre>";
// echo $new_file_path;
//
// echo $htmlBody;
// echo "</pre>";
try {
$useFile['size'] = filesize($new_file_path);
} catch (Exception $e) {
return new JsonResponse(['error' => $e->getMessage()]);
}
/*
* Insert into claim_report
*/
$useFile['file_ext'] = "pdf";
$sql = "INSERT INTO
claim_report(file_title,file_size,ext,created_on,claim_id,document_type_id,adjuster_id,invoice_id,status)
VALUES (:file_title, :file_size, :ext, :created_on, :claim_id, :document_type_id, :adjuster_id, :invoice_id, :status_id)";
$dataParams = array();
$dataParams['file_title'] = 'Acknowledgment Letter';
$dataParams['file_size'] = $useFile['size'];
$dataParams['ext'] = 'pdf';
$dataParams['created_on'] = date('Y-m-d');
$dataParams['claim_id'] = $claimId;
$dataParams['document_type_id'] = 10;
$dataParams['adjuster_id'] = $resourceId;
$dataParams['invoice_id'] = 0;
$dataParams['status_id'] = 1;
$stmt = $em->getConnection()->prepare($sql);
try {
$stmt->execute($dataParams);
$fileId = $em->getConnection()->lastInsertId();
} catch (Exception $e) {
return new JsonResponse(['error' => $e->getMessage()]);
}
/*
* Wasabi Save File
*/
if ($fileId) {
//$fileId = $result['id'];
$fileSave = $fileManager->saveFile($useFile, $fileId, "ClaimReport");
if ($fileSave) {
# Return success JSON
$response = array(
"result" => "success",
"error_msgs" => [$fileSave]
);
}else{
#if the file is not saved on wasabi delete it from claim report
$sql = "DELETE FROM claim_report WHERE id = :id";
$dataParams = array();
$dataParams['id'] = $fileId;
$stmt = $em->getConnection()->prepare($sql);
try {
$stmt->execute($dataParams);
} catch (Exception $e) {
return new JsonResponse(['error' => "Error deleting from claim report"]);
}
# Return wrong JSON
$response = array(
"result" => "error FileSave",
"error" => true,
"error_msgs" => [$fileSave]
);
}
}else{
# Return wrong JSON
$response = array(
"result" => "error fileId",
"error" => true,
"error_msgs" => [$fileId]
);
}
return new JsonResponse($response);
}
/**
* @Route("/update/duplicate-claim/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function duplicateClaim(Claim $claim, Request $request)
{
$response = ['error'=>false, 'data'=>[]];
$em = $this->container->get("doctrine.orm.entity_manager");
if($claim){
$sql = "INSERT INTO claim
(claim_number,
severity,
date_received,
status_id,
claim_rep_id,
customer_id,
loss_date,
loss_street,
loss_city,
loss_state_id,
loss_zip,
peril_id,
sub_peril_id,
inspection_note,
policy_id,
policy_number,
policy_type,
policy_start_date,
policy_end_date,
loss_description,
loss_amount,
coinsurance,
mortgage,
form_numbers,
form_numbers_set,
report_due_date,
special_notes,
agent_id,
minor_bday,
parent,
date_created)
SELECT
claim_number,
severity,
date_received,
5,
claim_rep_id,
customer_id,
loss_date,
loss_street,
loss_city,
loss_state_id,
loss_zip,
peril_id,
sub_peril_id,
inspection_note,
policy_id,
policy_number,
policy_type,
policy_start_date,
policy_end_date,
loss_description,
loss_amount,
coinsurance,
mortgage,
form_numbers,
form_numbers_set,
report_due_date,
special_notes,
agent_id,
minor_bday,
id,
NOW()
FROM claim
WHERE id = :claim_id";
$dataParams = array();
$dataParams['claim_id'] = $claim->getId();
$stmt = $em->getConnection()->prepare($sql);
try {
$stmt->execute($dataParams);
$newClaimId = $em->getConnection()->lastInsertId();
} catch (Exception $e) {
return new JsonResponse(['error' => true,'error_msg' => $e->getMessage()]);
}
#Copy the claim insured
$sql = "INSERT INTO claims_insured(claim_id, claim_insured_type_id, file_no, insured_id, is_primary, minor_dob, minor_involved )
SELECT :new_claim_id, claim_insured_type_id, :new_claim_id, insured_id, is_primary, minor_dob, minor_involved
FROM claims_insured
WHERE claim_id = :claim_id";
$dataParams = array();
$dataParams['claim_id'] = $claim->getId();
$dataParams['new_claim_id'] = $newClaimId;
$stmt = $em->getConnection()->prepare($sql);
try {
$stmt->execute($dataParams);
} catch (Exception $e) {
return new JsonResponse(['error' => true,'error_msg' => $e->getMessage()]);
}
#Copy the claim coverages
$sql = "INSERT INTO coverage(claim_id, name, amount, reserve, coverage_type_id, user_changed_id, dateChanged, reasonChanged)
SELECT :new_claim_id, name, amount, reserve, coverage_type_id, user_changed_id, dateChanged, reasonChanged
FROM coverage
WHERE claim_id = :claim_id";
$dataParams = array();
$dataParams['claim_id'] = $claim->getId();
$dataParams['new_claim_id'] = $newClaimId;
$stmt = $em->getConnection()->prepare($sql);
try {
$stmt->execute($dataParams);
} catch (Exception $e) {
return new JsonResponse(['error' => true,'error_msg' => $e->getMessage()]);
}
#Copy the claim deductibles
$sql = "INSERT INTO deductible(claim_id, name, amount, deductible_name_id)
SELECT :new_claim_id, name, amount, deductible_name_id
FROM deductible
WHERE claim_id = :claim_id";
$dataParams = array();
$dataParams['claim_id'] = $claim->getId();
$dataParams['new_claim_id'] = $newClaimId;
$stmt = $em->getConnection()->prepare($sql);
try {
$stmt->execute($dataParams);
} catch (Exception $e) {
return new JsonResponse(['error' => true,'error_msg' => $e->getMessage()]);
}
$newClaim = $this->getDoctrine()->getRepository('ClaimManagementBundle:Claim')->find($newClaimId);
$response['data'] = $newClaimId;
# logged in user
$user = $this->get('security.token_storage')->getToken()->getUser();
$NoteService = $this->get('claim.note_provider');
$strComment = "New claim (copy claim) was duplicated from claim with FILE ID # ".$claim->getId()." by ".$user->getFullName(). " on ". date('m/d/Y h:i A');
$NoteService->addClaimNote( $newClaim, $strComment, false,13 );
// Notify event Claim is created
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(new ClaimDuplicatedEvent($newClaim), ClaimDuplicatedEvent::NAME );
return new JsonResponse($response);
}else{
throw new NotFoundHttpException("Couldn't find this claim!");
}
}
/**
* @Route("/update/claim-cwop-reason/{id}")
* @ParamConverter("claim", class="ClaimManagementBundle:Claim")
*/
public function updateClaimCwopReasonAction(Claim $claim, Request $request)
{
$cwop_reason = $request->request->get('cwop_reason');
$em = $this->container->get("doctrine.orm.entity_manager");
$denial_description_line = $request->request->get('denial_description_line');
$objCwopReason = $em->getRepository("ClaimManagementBundle:CwopReason")->findOneBy(['id' => $cwop_reason]);
if(empty($objCwopReason)){
return new JsonResponse(['error'=>true, 'msg' => 'CWOP Reason not found']);
}
try{
$ReopenDate = $claim->getDateReopened();
$strReopen = "";
if (!empty($ReopenDate)) {
$claim->setReopenCwopRsn($objCwopReason);
$claim->setReopenDenialDescriptionLine($denial_description_line);
$strReopen = "Reopen";
}else{
$claim->setCwopReason($objCwopReason);
$claim->setDenialDescriptionLine($denial_description_line);
}
$em->persist($claim);
$em->flush();
$ClaimNote = $this->container->get("claim.note_provider");
$strCWOPReason = $objCwopReason->getDescription();
$ClaimNote->addClaimNote($claim, "$strReopen CWOP Reason ($strCWOPReason) added to the claim with Denial Description as ($denial_description_line).", false);
}catch(Exception $e){
return new JsonResponse(['error'=>true, 'msg' => $e->getMessage()]);
}
return new JsonResponse(['error'=>false]);
}
}