<?php
namespace App\Controller;
#use Symfony\Component\HTTPFoundation\Response;
#use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\DialogueAccessLog;
use App\Entity\DialogueNotes;
use App\Entity\Patient;
use App\Entity\Dialogue;
use App\Entity\User;
use App\Entity\Family;
use App\Entity\PredefinedCaseCard;
use Symfony\Component\HttpFoundation\Response;
use App\Form\DialogueCaseCardType;
use App\Entity\DialogueCaseCard;
use App\Entity\PatientInformation;
use App\Entity\PatientInformationDetails;
use App\Entity\PredefinedAttachmentType;
use App\Entity\DialogueAttachmentDetails;
use App\Entity\DialogueAttachments;
use App\Entity\DialogueCasecardMeasure;
use App\Entity\DialogueConsentInfo;
use App\Entity\PredefinedTemplate;
use App\Entity\TravelNeedsDetails;
use App\Entity\Category;
use App\Entity\DialogueCaseCardHistory;
use App\Entity\JoGroup;
use App\Form\JoGroupType;
use App\Entity\JoMasterInformation;
use App\Entity\JoMasterInformationLocation;
use App\Entity\DialogueMultipleAttachment;
use App\Lib\SoapClientDebug;
use App\Entity\PatientSibling;
use App\Entity\JoCaseCardEvent;
use Symfony\Component\HttpClient\HttpClient;
use App\Entity\JoPostMail;
use App\Entity\JoCaseCardHold;
use App\Entity\JoGroupWaitinglist;
use App\Entity\JoCaseComments;
use App\Entity\JoCaseCommentsLog;
use App\Entity\JoNotification;
use App\Entity\JoNotificationLog;
use App\Entity\JoActivitySharing;
use App\Entity\JoActivitySharingParticipant;
use App\Entity\JoParticipantNotification;
use App\Entity\JoParticipantSharingActivity;
use App\Entity\JoCaseMemos;
use App\Entity\JoPatientIsdeceasedLog;
use App\Entity\RbRental;
use App\Entity\JoCaseCardEventBrevActivity;
use App\Entity\User as Relative;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use App\Entity\SepoTunnelliste;
use App\Entity\IstElev;
use App\Entity\IstElevUdv;
use App\Entity\ScalingProgression;
use App\Entity\ScalingGraph;
use App\Entity\CaseCardMeasure;
use App\Entity\JoActivityTemplate;
use App\Entity\PredefinedTravelsType;
use App\Entity\UserCaseLogger;
use App\Entity\UserCaseCardLogger;
use App\Entity\UserCaseActivityLogger;
use App\Entity\SkebelonEbookLog;
use App\Entity\StilInstitution;
use App\Entity\StilPerson;
class DefaultController extends AbstractController {
public function index(Request $request) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
ini_set('memory_limit', '-1');
if($this->get('security.authorization_checker')->isGranted('ROLE_PARENT')) {
$session->set("isCitizenLogin", true);
return $this->redirect($this->generateUrl('parentIndex'));
} else {
$session->set("isCitizenLogin", false);
}
$selectedPatient = $session->get("selectedPatient", null);
$selectedDialogue = $session->get("selectedDialogue", null);
$isCprLookupActive = $this->container->getParameter('isCprLookupActive');
$pagelimit = $this->container->getParameter('pageResultLimit');
$isTestServer = $this->container->getParameter('isTestServer');
$session->set("isTestServer", $isTestServer);
$isJoGroupExist = $session->get("isJoGroupExist", null);
$selectedJoGroup = $session->get("selectedJoGroup", null);
$session->set('waitingListCount',null);
$session->set('postMailCnt',null);
$showRapportUrl = $this->container->getParameter('showRapportUrl');
$session->set('showRapportUrl', $showRapportUrl);
$isCopenhagen = $this->container->getParameter('isCopenhagen');
$session->set('isCopenhagen', $isCopenhagen);
$session->set("komunneName", null);
$session->set("komunneId",null);
$session->set('rentalItemCnt',null);
$isTestServer = $this->container->getParameter('isTestServer');
$this->checkUserAgent($request, $session);
$templateVersion = $session->get('templateVersion');
/*if($templateVersion == "mobile" && $isCopenhagen == "0") {
return $this->render('site/maintenance.html.twig', array(
));
}*/
if ($selectedDialogue) {
$selectedDialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue);
if ($selectedDialogue) {
$selectedPatient = $em->getRepository(Patient::class)->find($selectedDialogue->getPatient()->getId());
}
}
if ($isJoGroupExist) {
$selectedJoGroup = $em->getRepository(JoGroup::class)->find($selectedJoGroup);
}
$isDialogueExist = $session->get("isDialogueExist", false);
$session->set("isDialogueExist", false);
$session->set("selectedPatient", null);
$session->set("selectedDialogue", null);
$session->set("isJoGroupExist", false);
$session->set("selectedJoGroup", null);
$user = $this->get('security.token_storage')->getToken()->getUser();
$isTestUser = $user->getIsTestUser();
$isDummyPatient = $isTestUser ? 1 : 0;
$loginUserCat = $user->getCategory()->getName();
//$loginUserInstitutions
/*$loginUserInstitutionsArray = $em->createQuery("SELECT distinct (sp.institutionId) FROM App\Entity\StilPerson sp
left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser
WHERE ac.user =".$user->getId() )
->getScalarResult();
$loginUserInstitutions = array_map('current', $loginUserInstitutionsArray);
if(count($loginUserInstitutions) == 0){
$loginUserInstitutions[] = 0;
}*/
$loginUserInstitutions = $this->loginUserInstitutions($em, $user);
$currentSelectedInstitution = $session->get('selectedInstitutionId') ? $session->get('selectedInstitutionId') : $loginUserInstitutions[0];
$loginUserGroups = $this->loginUserGroups($em, $user);
//echo $loginUserGroups;die;
//fetch dialogues of matching user role i.e dialogut_type 1->csv : 2->
$dialogueType = $user->hasRole('ROLE_CSV') ? 1 : ($user->hasRole('ROLE_DTS') ? 2 : 0);
$userRoleTypeText = $user->hasRole('ROLE_CSV') ? 'ROLE_CSV' : ($user->hasRole('ROLE_DTS') ? 'ROLE_DTS' : 0);
$indexSearch = trim($request->get('indexSearch'));
$sortBy = trim($request->get('sortBy'));
$orderBy = trim($request->get('orderBy'));
$listType = trim($request->get('listType'));
$searchTerm = trim($request->get('searchTxt'));
$indexCaseCardIds = trim($request->get('indexCaseCardIds'));
$indexAreaIds = trim($request->get('indexAreaIds'));
$indexStatusIds = trim($request->get('indexStatusIds'));
$indexFilterAdUserId = trim($request->get('indexFilterAdUserId'));
$indexSchoolIds = trim($request->get('indexSchoolIds'));
$indexInstIds = trim($request->get('indexInstIds'));
$indexdocumentIds = trim($request->get('indexdocumentIds'));
$isResultWithoutFilter = false;
if($searchTerm !="" || $indexAreaIds !="" || $indexStatusIds !="" || $indexFilterAdUserId != "" || $indexSchoolIds !="" || $indexInstIds !="") {
$isResultWithoutFilter = true;
}
if($searchTerm =="" && $indexAreaIds =="" && $indexStatusIds =="" && $indexFilterAdUserId == "" && $indexSchoolIds =="" && $indexInstIds =="") {
$pagelimit = $this->container->getParameter('pageResultLimit');
}
if ($request->isXmlHttpRequest()) {
$pagelimit = NULL;
if($searchTerm =="" && $indexAreaIds =="" && $indexStatusIds =="" && $indexFilterAdUserId == "" && $indexSchoolIds =="" && $indexInstIds =="") {
$pagelimit = $this->container->getParameter('pageResultLimit');
}
}
if($indexCaseCardIds == ""){
$isResultWithoutFilter = false;
}
//$fetchAllDialogues = $em->getRepository(Dialogue::class)->findBy(array('deleted' => false, 'status' => 1, 'dialogueType' => $dialogueType));
if (strlen($searchTerm) > 6 && $searchTerm[6] == '-') {//when search by cpr number and 7th char is - then replace it and pass the search string
$searchTerm = str_replace('-', '', $searchTerm);
} else {
$searchTerm = $searchTerm;
}
if ($request->isXmlHttpRequest()) {
//No need to reset the paramenter array while doing ajax call
} else {
$parameters = [];
}
$parameters['dialogueType'] = $dialogueType;
$instiId = $session->get('institutionId');
$searchSqlStr = "SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\User u with u.id = p.user
left join App\Entity\DialogueCaseCard dc with d.id = dc.dialogue
left join App\Entity\DialogueCaseCardMeasure dcm with dc.id = dcm.DialogueCaseCard
left join App\Entity\User a with a.id = d.anchor
left join App\Entity\User ar with ar.id = dc.createdBy
left join App\Entity\User arm with arm.id = dcm.responsiblePerson
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\Category c with a.category = c.id
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status = 1 and d.dialogueType= :dialogueType and p.isDummyPatient = ".$isDummyPatient." and sp.institutionId in (".$currentSelectedInstitution.")";
if (strlen($indexCaseCardIds) > 0) {
$searchSqlStr = $searchSqlStr . " and (dc.pCaseCardId in (:caseCardId) ) ";
$parameters['caseCardId'] = explode(",", $indexCaseCardIds);
}
if (strlen($searchTerm) > 0) {
$searchSqlStr = $searchSqlStr . " and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText or u.fullName LIKE :searchText) ";
$parameters['searchText'] = '%' . $searchTerm . '%';
}
if (strlen($indexAreaIds) > 0) {
if($user->hasRole('ROLE_CSV')){
if($indexAreaIds == 'Børnecenter København'){
$searchSqlStr = $searchSqlStr . " and (c.name LIKE :areaTxt) ";
$parameters['areaTxt'] = '%' . $indexAreaIds . '%';
}else{
$areaName = explode(',',$indexAreaIds);
$i = 0;
foreach($areaName as $area){
if($i == 0){
$searchSqlStr = $searchSqlStr . " and ( ";
$searchSqlStr = $searchSqlStr . " (a.area LIKE :areaTxt) ";
}else{
$searchSqlStr = $searchSqlStr . " OR (a.area LIKE :areaTxt) ";
}
$i++;
$parameters['areaTxt'] = '%' . $area . '%';
}
$searchSqlStr = $searchSqlStr . " )";
// $searchSqlStr = $searchSqlStr . " and (a.area LIKE :areaTxt) ";
}
}else{
if($indexAreaIds == 'Børnecenter København'){
$searchSqlStr = $searchSqlStr . " and (c.name LIKE :areaTxt) ";
$parameters['areaTxt'] = '%' . $indexAreaIds . '%';
}else{
$areaName = explode(',',$indexAreaIds);
$i = 0;
foreach($areaName as $area){
if($i == 0){
//$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " and ( ";
$searchSqlStr = $searchSqlStr . " (d.dialogueArea LIKE :areaTxt_$i) ";
}else{
//$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " OR ( d.dialogueArea LIKE :areaTxt_$i) ";
}
$parameters["areaTxt_$i"] = '%' . $area . '%';
$i++;
}
$searchSqlStr = $searchSqlStr . " )";
// $searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt) ";
}
}
}
if (strlen($indexSchoolIds) > 0) {
// $searchSqlStr = $searchSqlStr . " and (pi.citizenSchoolName LIKE :schoolText) ";
// $parameters['schoolText'] = '%' . $indexSchoolIds . '%';
$schoolName = explode(',',$indexSchoolIds);
$i = 0;
foreach($schoolName as $school){
if($i == 0){
//$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " and (pi.citizenSchoolName LIKE :schoolText_$i) ";
}else{
//$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " OR ( pi.citizenSchoolName LIKE :schoolText_$i) ";
}
$parameters["schoolText_$i"] = '%' . $school . '%';
$i++;
}
}
// if (strlen($indexInstIds) > 0) {
// $searchSqlStr = $searchSqlStr . " and (pi.citizenInstitutionName LIKE :instText) and pi.citizenInstitutionToDate IS NULL";
// $parameters['instText'] = '%' . $indexInstIds . '%';
// }
if (strlen($indexInstIds) > 0) {
$InstIds = explode(',', $indexInstIds);
$searchSqlStr = $searchSqlStr ." and (";
$count = 0;
if( count($InstIds) > 0) {
unset($parameters['instText']);;
}
foreach($InstIds as $InstId){
//echo "*".$count.$InstId."*";
if($count){
$searchSqlStr = $searchSqlStr . " or ";
}
$searchSqlStr = $searchSqlStr . " (pi.citizenInstitutionName LIKE :instText_$count) ";
$parameters["instText_$count"] = '%' . $InstId . '%';
$count++;
}
$searchSqlStr = $searchSqlStr ." ) and pi.citizenInstitutionToDate IS NULL";
}
if (strlen($indexdocumentIds) > 0) {
// $searchSqlStr = $searchSqlStr . " and (dad.templateHeading LIKE :templateName)";
// $parameters['templateName'] = '%' . $indexdocumentIds . '%';
$documentName = explode(',',$indexdocumentIds);
$i = 0;
foreach($documentName as $document){
if($i == 0){
//$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " and (dad.templateHeading LIKE :templateName_$i) ";
$searchSqlStr = $searchSqlStr . " and dad.activityType < 5 ";
}else{
//$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " OR ( dad.templateHeading LIKE :templateName_$i) ";
$searchSqlStr = $searchSqlStr . " and dad.activityType < 5 ";
}
$parameters["templateName_$i"] = '%' . $document . '%';
$i++;
}
}
if (strlen($indexStatusIds) > 0) {
$isDraftTempArray = explode(",", $indexStatusIds);
//if (in_array(0, $isDraftTempArray) && (in_array(1, $isDraftTempArray)) && (in_array(2, $isDraftTempArray))) {
if (in_array(0, $isDraftTempArray)) {
//$searchSqlStr = $searchSqlStr . " and dc.toDate IS NULL OR dc.toDate IS NOT NULL ";
$searchSqlStr = $searchSqlStr . " and (dc.isClosed = false OR dc.isClosed = true) ";
//$qb->andWhere('dc.toDate IS NULL OR dc.toDate IS NOT NULL');
//} else if (in_array(1, $isDraftTempArray) && (!in_array(2, $isDraftTempArray))) {
} else if (in_array(1, $isDraftTempArray)) {
//$searchSqlStr = $searchSqlStr . " and dc.toDate IS NULL ";
$searchSqlStr = $searchSqlStr . " and dc.isClosed = false ";
//$qb->andWhere('dc.toDate IS NULL');
//} else if (in_array(2, $isDraftTempArray) && (!in_array(1, $isDraftTempArray))) {
} else if (in_array(2, $isDraftTempArray)) {
//$searchSqlStr = $searchSqlStr . " and dc.toDate IS NOT NULL ";
$searchSqlStr = str_replace(" AND dc.toDate IS NULL ", " ", $searchSqlStr);
$searchSqlStr = $searchSqlStr . " and dc.isClosed = true ";
//$qb->andWhere('dc.toDate IS NOT NULL');
}
}
if(strlen($indexFilterAdUserId)) {
if($user->hasRole('ROLE_CSV')){
$searchSqlStr = $searchSqlStr . " and dcm.responsiblePerson = :indexFilterAdUserId ";
$parameters['indexFilterAdUserId'] = '' . $indexFilterAdUserId . '';
}else{
$searchSqlStr = $searchSqlStr . " and (dcm.responsiblePerson = :indexFilterAdUserId or dc.createdBy = :indexFilterAdUserId)";
$parameters['indexFilterAdUserId'] = '' . $indexFilterAdUserId . '';
}
}
$searchSqlStr = $searchSqlStr . " order by d.latestGrade desc";
//if(($user->getIsTestUser() == "1" || $isTestServer == "1" || count($parameters) > 1) || ($indexSearch != '') ) { //Do not display “Alle sager” in overview.(5th list)
//echo $dialogueType." ".$searchSqlStr;
$fetchAllDialogues = $em->createQuery($searchSqlStr)
->setParameters($parameters) //send multiple paramenters
//->setMaxResults($pagelimit)
->execute();
/*}else{
$fetchAllDialogues = array();
}*/
if ($request->isXmlHttpRequest()) {
//No need to reset the paramenter array while doing ajax call
} else {
$parameters = [];
}
$parameters['dialogueType'] = $dialogueType;
$searchSqlStr = "SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\User u with u.id = p.user
left join App\Entity\DialogueCaseCard dc with d.id = dc.dialogue
left join App\Entity\DialogueCaseCardMeasure dcm with dc.id = dcm.DialogueCaseCard
left join App\Entity\User a with a.id = d.anchor
left join App\Entity\User ar with ar.id = dc.createdBy
left join App\Entity\User arm with arm.id = dcm.responsiblePerson
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\Category c with a.category = c.id
left join App\Entity\DialogueAttachmentDetails dad with dad.dialogue = d.id
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status = 1 and d.dialogueType= :dialogueType and p.isDummyPatient = ".$isDummyPatient." and sp.institutionId in (".$currentSelectedInstitution.")";
if ($request->isXmlHttpRequest()) {
if (strlen($indexCaseCardIds) > 0) {
$searchSqlStr = $searchSqlStr . " and (dc.pCaseCardId in (:caseCardId) ) ";
$parameters['caseCardId'] = explode(",", $indexCaseCardIds);
}
if (strlen($searchTerm) > 0) {
$searchSqlStr = $searchSqlStr . " and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText or u.fullName LIKE :searchText) ";
$parameters['searchText'] = '%' . $searchTerm . '%';
}
if (strlen($indexAreaIds) > 0) {
/*if($indexAreaIds == 'Børnecenter København'){
$searchSqlStr = $searchSqlStr . " and (c.name LIKE :areaTxt) ";
$parameters['areaTxt'] = '%' . $indexAreaIds . '%';
}else{
$searchSqlStr = $searchSqlStr . " and (a.area LIKE :areaTxt) ";
$parameters['areaTxt'] = '%' . $indexAreaIds . '%';
}*/
if($user->hasRole('ROLE_CSV')){
if($indexAreaIds == 'Børnecenter København'){
$searchSqlStr = $searchSqlStr . " and (c.name LIKE :areaTxt) ";
$parameters['areaTxt'] = '%' . $indexAreaIds . '%';
}else{
$areaName = explode(',',$indexAreaIds);
$i = 0;
foreach($areaName as $area){
if($i == 0){
$searchSqlStr = $searchSqlStr . " and ( ";
$searchSqlStr = $searchSqlStr . " (a.area LIKE :areaTxt) ";
}else{
$searchSqlStr = $searchSqlStr . " OR (a.area LIKE :areaTxt) ";
}
$i++;
$parameters['areaTxt'] = '%' . $area . '%';
}
$searchSqlStr = $searchSqlStr . " )";
// $searchSqlStr = $searchSqlStr . " and (a.area LIKE :areaTxt) ";
}
}else{
if($indexAreaIds == 'Børnecenter København'){
$searchSqlStr = $searchSqlStr . " and (c.name LIKE :areaTxt) ";
$parameters['areaTxt'] = '%' . $indexAreaIds . '%';
}else{
$areaName = explode(',',$indexAreaIds);
$i = 0;
foreach($areaName as $area){
if($i == 0){
//$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " and ( ";
$searchSqlStr = $searchSqlStr . " (d.dialogueArea LIKE :areaTxt_$i) ";
}else{
//$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " OR (d.dialogueArea LIKE :areaTxt_$i) ";
}
$parameters["areaTxt_$i"] = '%' . $area . '%';
$i++;
}
$searchSqlStr = $searchSqlStr . " )";
// $searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt) ";
}
}
}
if(strlen($indexFilterAdUserId)) {
//$searchSqlStr = $searchSqlStr . " and d.anchor = :indexFilterAdUserId ";
if($user->hasRole('ROLE_CSV')){
$searchSqlStr = $searchSqlStr . " and dcm.responsiblePerson = :indexFilterAdUserId ";
$parameters['indexFilterAdUserId'] = '' . $indexFilterAdUserId . '';
}else{
$searchSqlStr = $searchSqlStr . " and (dcm.responsiblePerson = :indexFilterAdUserId or dc.createdBy = :indexFilterAdUserId)";
$parameters['indexFilterAdUserId'] = '' . $indexFilterAdUserId . '';
}
}
if (strlen($indexSchoolIds) > 0) {
// $searchSqlStr = $searchSqlStr . " and (pi.citizenSchoolName LIKE :schoolText) ";
// $parameters['schoolText'] = '%' . $indexSchoolIds . '%';
$schoolName = explode(',',$indexSchoolIds);
$i = 0;
foreach($schoolName as $school){
if($i == 0){
//$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " and (pi.citizenSchoolName LIKE :schoolText_$i) ";
}else{
//$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " OR ( pi.citizenSchoolName LIKE :schoolText_$i) ";
}
$parameters["schoolText_$i"] = '%' . $school . '%';
$i++;
}
}
/* if (strlen($indexInstIds) > 0) {
$searchSqlStr = $searchSqlStr . " and (pi.citizenInstitutionName LIKE :instText) and pi.citizenInstitutionToDate IS NULL";
$parameters['instText'] = '%' . $indexInstIds . '%';
}*/
if (strlen($indexInstIds) > 0) {
$InstIds = explode(',', $indexInstIds);
$searchSqlStr = $searchSqlStr ." and (";
$count = 0;
if( count($InstIds) > 0) {
unset($parameters['instText']);;
}
foreach($InstIds as $InstId){
//echo "*".$count.$InstId."*";
if($count){
$searchSqlStr = $searchSqlStr . " or ";
}
$searchSqlStr = $searchSqlStr . " (pi.citizenInstitutionName LIKE :instText_$count) ";
$parameters["instText_$count"] = '%' . $InstId . '%';
$count++;
}
$searchSqlStr = $searchSqlStr ." ) and pi.citizenInstitutionToDate IS NULL";
}
if (strlen($indexdocumentIds) > 0) {
// $searchSqlStr = $searchSqlStr . " and (dad.templateHeading LIKE :templateName)";
// $parameters['templateName'] = '%' . $indexdocumentIds . '%';
$documentName = explode(',',$indexdocumentIds);
$i = 0;
foreach($documentName as $document){
if($i == 0){
//$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " and (dad.templateHeading LIKE :templateName_$i) ";
$searchSqlStr = $searchSqlStr . " and dad.activityType < 5 ";
}else{
//$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
$searchSqlStr = $searchSqlStr . " OR ( dad.templateHeading LIKE :templateName_$i) ";
$searchSqlStr = $searchSqlStr . " and dad.activityType < 5 ";
}
$parameters["templateName_$i"] = '%' . $document . '%';
$i++;
}
}
if (strlen($indexStatusIds) > 0) {
$isDraftTempArray = explode(",", $indexStatusIds);
//if (in_array(0, $isDraftTempArray) && (in_array(1, $isDraftTempArray)) && (in_array(2, $isDraftTempArray))) {
if (in_array(0, $isDraftTempArray)) {
//$searchSqlStr = $searchSqlStr . " and dc.toDate IS NULL OR dc.toDate IS NOT NULL ";
$searchSqlStr = $searchSqlStr . " and (dc.isClosed = false OR dc.isClosed = true) ";
//$qb->andWhere('dc.toDate IS NULL OR dc.toDate IS NOT NULL');
//} else if (in_array(1, $isDraftTempArray) && (!in_array(2, $isDraftTempArray))) {
} else if (in_array(1, $isDraftTempArray)) {
//$searchSqlStr = $searchSqlStr . " and dc.toDate IS NULL ";
$searchSqlStr = $searchSqlStr . " and dc.isClosed = false ";
//$qb->andWhere('dc.toDate IS NULL');
//} else if (in_array(2, $isDraftTempArray) && (!in_array(1, $isDraftTempArray))) {
} else if (in_array(2, $isDraftTempArray)) {
//$searchSqlStr = $searchSqlStr . " and dc.toDate IS NOT NULL ";
$searchSqlStr = str_replace(" AND dc.toDate IS NULL ", " ", $searchSqlStr);
$searchSqlStr = $searchSqlStr . " and dc.isClosed = true ";
//$qb->andWhere('dc.toDate IS NOT NULL');
}
}
}
//if(($user->getIsTestUser() == "1" || $isTestServer == "1" || count($parameters) > 1) || ($indexSearch != '') ) { //Do not display “Alle sager” in overview.(5th list)
$fetchAllDialoguesAll = $em->createQuery($searchSqlStr)
->setParameters($parameters) //send multiple paramenters
//->setMaxResults($pagelimit)
->execute();
/*}else{
$fetchAllDialoguesAll = array();
}*/
$predefinedTemplateAll = $em->createQuery('SELECT pt FROM App\Entity\PredefinedTemplate pt
WHERE pt.parentId NOT IN (0) and pt.userType = :userRoleTypeText')
->setParameter('userRoleTypeText', $userRoleTypeText)
->execute();
foreach($predefinedTemplateAll as $key => $template){
$predefinedTemplate[$key] = $template->getName();
}
$documentsLinkForEachDialgue = array();
if (strlen($indexdocumentIds) > 0) {
$documentName = explode(',',$indexdocumentIds);
foreach($fetchAllDialogues as $dialog){
$dialogDOcuments = $em->createQuery('SELECT dad FROM App\Entity\DialogueAttachmentDetails dad
WHERE dad.deletedBy IS NULL and dad.dialogue = :dialog and dad.pAtttachmentType = 7 and dad.templateHeading IN (:indexdocumentIds) and ((dad.isDraft = 1 and dad.visibleStatus = 1 and dad.user = :user) or (dad.isDraft = 1 and dad.visibleStatus = 0) or (dad.isDraft = 0)) ')
//WHERE dad.deletedBy IS NULL and dad.dialogue = :dialog and dad.pAtttachmentType = 7 and dad.templateHeading IN (:indexdocumentIds) and (dad.visibleStatus = 0 or (dad.visibleStatus = 1 and dad.user = :user)) ')
->setParameter('dialog', $dialog)
->setParameter('user', $user)
->setParameter('indexdocumentIds', $documentName)
->execute();
$dialogDocumentLinks = '';
foreach ($dialogDOcuments as $document){
$link = "<a href='therapist/load-dialogue/".$dialog->getId()."/".$document->getId()."' class='detail-view-link'><u>".$document->getTemplateHeading()."</u></a>, ";
$dialogDocumentLinks = $dialogDocumentLinks.$link;
}
$dialogDocumentLinks = rtrim($dialogDocumentLinks, ', ');
$documentsLinkForEachDialgue[$dialog->getId()] = $dialogDocumentLinks;
}
}
//var_dump($documentsLinkForEachDialgue);
// Fetch dialogues where current user has created case_card or notes or measure (list 3)
if ($user->hasRole('ROLE_CSV')) {
$onlyMyDialogues = $em->getRepository(Dialogue::class)->myActiveCases('ROLE_CSV', $searchTerm, $user, $dialogueType, $pagelimit, $isDummyPatient, 0 );
}else{
$onlyMyDialogues = $em->getRepository(Dialogue::class)->myActiveCases('ROLE_DTS', $searchTerm, $user, $dialogueType, $pagelimit, $isDummyPatient, 0 );
}
if ($user->hasRole('ROLE_CSV')) {
$onlyMyDialoguesRecords = $em->getRepository(Dialogue::class)->myActiveCases('ROLE_CSV', $searchTerm, $user, $dialogueType, $pagelimit, $isDummyPatient, 1 );
}else{
$onlyMyDialoguesRecords = $em->getRepository(Dialogue::class)->myActiveCases('ROLE_DTS', $searchTerm, $user, $dialogueType, $pagelimit, $isDummyPatient, 1 );
}
$onlyMyDialoguesCount = count($onlyMyDialoguesRecords);
//(list 2)
//DTS and CSV: The caes shown here should be the cases last accessed by the user logged in – not last accessed in general by all users.
/*$recentDialogues = $em->createQuery(
'SELECT d FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\DialogueAccessLog c with c.dialogue = d.id
WHERE c.dialogue = d and c.createdBy = :user and d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'
and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText)
group by d.id order by max(c.id) desc'
)
->setParameter('searchText', '%' . $searchTerm . '%')
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
->setMaxResults($pagelimit)
->execute();*/
$today = new \DateTime();
$before30days = $today->modify('-30 day')->format('Y-m-d');
$recentDialogues = $em->createQuery(
'SELECT dal, MAX(dal.id) as id, max(dal.createdAt) as accessed, sig.groupname as groupName FROM App\Entity\DialogueAccessLog dal
LEFT JOIN App\Entity\Dialogue d with dal.dialogue = d.id
LEFT JOIN App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE dal.createdBy = :user AND d.deleted = false and d.status =1 and dal.createdAt >:before30days and d.dialogueType = :dialogueType and (pi.citizenSchoolName LIKE :category or pi.citizenInstitutionName LIKE :category) and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$loginUserInstitutions[0].')
GROUP BY dal.dialogue ORDER BY accessed desc'
)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
->setParameter('category', $loginUserCat)
->setParameter('before30days',$before30days)
->setMaxResults($pagelimit)
->execute();
//}
/*$recentDialoguesCount = $em->createQuery(
'SELECT d FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\DialogueAccessLog c with c.dialogue = d.id
WHERE c.dialogue = d and c.createdBy = :user and d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'
and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText)
group by d.id order by max(c.id) desc'
)
->setParameter('searchText', '%' . $searchTerm . '%')
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
->execute();*/
$recentDialoguesCount = $em->createQuery(
'SELECT dal, MAX(dal.id) as id, max(dal.createdAt) as accessed FROM App\Entity\DialogueAccessLog dal
LEFT JOIN App\Entity\Dialogue d with dal.dialogue = d.id
LEFT JOIN App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE dal.createdBy = :user AND d.deleted = false and d.status =1 and dal.createdAt >:before30days and d.dialogueType = :dialogueType and (pi.citizenSchoolName LIKE :category or pi.citizenInstitutionName LIKE :category) and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$loginUserInstitutions[0].')
GROUP BY dal.dialogue ORDER BY accessed desc'
)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
->setParameter('category', $loginUserCat)
->setParameter('before30days',$before30days)
->execute();
//var_dump($recentDialoguesCount);die;
//$recentDialogues = $em->getRepository(Dialogue::class)->findBy(array('deleted' => false, 'status' => 1, 'dialogueType' => $dialogueType), array('updatedAt' => 'desc'), 10);
//Save post mails as reminder activity
$isSavedAsActivity = false;
$postMailControllerObj = new PostMailController();
//foreach($fetchAllDialogues as $pDialogue) {
//foreach($fetchAllDialoguesAll as $pDialogue) {
//foreach($onlyMyDialogues as $pDialogue) {
foreach($recentDialoguesCount as $pDialogue) {
$dialogue = $pDialogue[0]->getDialogue();
$patient = $dialogue->getPatient();
$getNotSavedAsActivityPostMails = $em->getRepository(JoPostMail::class)->getNotSavedAsActivityPostMails($isSavedAsActivity, $dialogue);
$predefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->getFirstPreCaseCardByUserType($userRoleTypeText);
$postMailControllerObj->createReminderActivityAsPostMail($request, $em, $user, $predefinedCaseCardObj, $patient, $dialogue, $getNotSavedAsActivityPostMails);
}
$mailActivitiesDraft = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('pAtttachmentType' => '9','activityType' => '7', 'isPostMailActivity' => 1));
foreach ($mailActivitiesDraft as $activity){
if($activity->getJoPostMail() != null){
if($activity->getUser()->getId() != $activity->getJoPostMail()->getSender()->getId()){
$activity->setUser($activity->getJoPostMail()->getSender());
$em->persist($activity);
$em->flush();
}
}
}
// get all my notes whose remider date is past today (list 1)
/* $notesPassedReminderDate = $em->createQuery('SELECT n from App\Entity\DialogueAttachmentDetails n where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate <= :cdate')->
setParameter('user', $user)->setParameter('cdate', date("Y-m-d"))->execute(); */
$notesPassedReminderDate = $em->createQuery('
SELECT n,po.isDeleted from App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
inner join App\Entity\Patient p with p.id = n.patient
left join App\Entity\JoPostMail po with po.id = n.joPostMail
where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0
and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText) and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType group by n.id HAVING (po.isDeleted = false or po.isDeleted is null) order by n.reminderDate asc')
->setParameter('searchText', '%' . $searchTerm . '%')
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
//->setParameter('cdate', date("Y-m-d"))
->setMaxResults($pagelimit)
->execute();
//}
$notesPassedReminderDateCount1 = $em->createQuery('
SELECT n.id,po.isDeleted from App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
inner join App\Entity\Patient p with p.id = n.patient
left join App\Entity\JoPostMail po with po.id = n.joPostMail
where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0
and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText) and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType group by n.id HAVING (po.isDeleted = false or po.isDeleted is null)')
->setParameter('searchText', '%' . $searchTerm . '%')
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
//->setParameter('cdate', date("Y-m-d"))
->execute();
$notesPassedReminderDateCount = count($notesPassedReminderDateCount1);
// Fetch dialogues created by other than logged in user or dialogues where current other than login user has created case_card or notes or attachment (list 4)
// $today = new \DateTime();
// $before30days = $today->modify('-30 day')->format('Y-m-d');
$newContentDialogues = $em->getRepository(DialogueAttachmentDetails::class)->newContentInMyActiveCases($searchTerm, $user, $before30days, $onlyMyDialoguesRecords, $dialogueType, $pagelimit, $isDummyPatient, 0 );
$newContentDialoguesCount1 = $em->getRepository(DialogueAttachmentDetails::class)->newContentInMyActiveCases($searchTerm, $user, $before30days, $onlyMyDialoguesRecords, $dialogueType, $pagelimit, $isDummyPatient, 1 );
$newContentDialoguesCount = ($newContentDialoguesCount1[0][1]);
if ($orderBy == 'desc') {
$orderBy = 'asc';
} else {
$orderBy = 'desc';
}
$searchFilter = "ROLE_DTS";
if ($user->hasRole('ROLE_CSV')) {
$searchFilter = "ROLE_CSV";
}
/* for search functionality case card list */
$userCreatedCaseCardsId = $userCreatedDialogueCaseCard = array();
$userCaseCardAll = $em->getRepository(DialogueCaseCard::class)->findBy(array('createdBy' => $user));
foreach ($userCaseCardAll as $userCaseCard) {
$userCreatedCaseCardsId[] = $userCaseCard->getPCaseCardId()->getId();
}
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForIndividual' => 1));
/* for search functionality area list */
$allDefaultUserAreas = array(array('id' => 1, 'area' => 'Amager'), array('id' => 2, 'area' => 'Nørrebro/Bispebjerg'), array('id' => 3, 'area' => 'Indre By/Østerbro'), array('id' => 4, 'area' => 'Brønshøj/Vanløse'), array('id' => 5, 'area' => 'Valby/Vesterbro/Kgs. Enghave'), array('id' => 6, 'area' => 'Børnecenter København'));
$allUserAreas = $em->createQuery(
'select u from App\Entity\User u where u.area is not null GROUP BY u.area'
)->execute();
$userArea = $em->getRepository(User::class)->findOneBy(array('id' => $user));
/* for search functionality school list and institute list */
//$allDefaultUserSchools = array(array('id' => 1, 'citizenSchoolName' => "Bjørn's International School", 'schoolarea' => 'Nørrebro/Bispebjerg' ), array('id' => 2, 'citizenSchoolName' => 'Blågård Skole', 'schoolarea' => 'Nørrebro/Bispebjerg'), array('id' => 3, 'citizenSchoolName' => 'Guldberg Skole', 'schoolarea' => 'Nørrebro/Bispebjerg'), array('id' => 4, 'citizenSchoolName' => 'Sortedamskolen', 'schoolarea' => 'Indre By/Østerbro'), array('id' => 5, 'citizenSchoolName' => 'Sølvgades Skole' , 'schoolarea' => 'Indre By/Østerbro'));
$toDate = "'".date("Y-m-d")."'";
$month20Date = "'".date("Y-m-d",strtotime("-14 month"))."'";
$allDefaultUserSchools= $em->createQuery(
"select pi from App\Entity\PatientInformation pi
left join App\Entity\Patient p with p.id = pi.patient
inner join App\Entity\Dialogue d with p.id = d. patient
where pi.citizenSchoolName is not null and p.isDummyPatient = ".$isDummyPatient." and d.dialogueType= :dialogueType and (pi.citizenSchoolEnd IS NULL OR StrToDate(pi.citizenSchoolEnd,'%d.%m.%Y')> ".$toDate.") and (pi.citizenSchoolEnd IS NULL AND StrToDate(pi.citizenSchoolStart,'%d.%m.%Y')> ".$month20Date.") GROUP BY pi.citizenSchoolName"
)->setParameter('dialogueType', $dialogueType)->execute();
$allUserSchools = $em->createQuery(
'select pi from App\Entity\PatientInformation pi
where pi.citizenSchoolName is not null GROUP BY pi.citizenSchoolName'
)->execute();
/*$userSchools = $em->getRepository(PatientInformation::class)->findOneBy(array('user' => $user));*/
$allInstitute = $em->createQuery(
'select pi from App\Entity\PatientInformation pi
left join App\Entity\Patient p with p.id = pi.patient
inner join App\Entity\Dialogue d with p.id = d. patient
where pi.citizenInstitutionName is not null and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType and (pi.citizenInstitutionToDate IS NULL OR pi.citizenInstitutionToDate> '.$toDate.') GROUP BY pi.citizenInstitutionName'
)->setParameter('dialogueType', $dialogueType)->execute();
if($isTestServer){
$showkopenhagen = ' or k.id =1 ';
}else{
$showkopenhagen = '';
}
$allCasesKommunes = $em->createQuery(
'select k from App\Entity\Dialogue d
inner join App\Entity\Patient p with p.id = d. patient
inner join App\Entity\PredefinedKomunne k with k.komunneId = p.kommuneId
where ((p.kommuneId IS NOT NULL and p.kommuneId != 0 and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType ) '.$showkopenhagen.' ) GROUP BY k.komunneId ORDER BY k.komunneName ASC'
)->setParameter('dialogueType', $dialogueType)
->execute();
$userInfo = $em->getRepository(PatientInformation::class)->findOneBy(array('user' => $user));
// Fetch Foranstaltningstype - should be the text added in the "Foranstaltning"
$dialogueMeasureText = "";
//$joGroup = new JoGroup();
//$joGroupForm = $this->createForm(JoGroupType::class, $joGroup);
$groupPredefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCards($searchFilter);
//$getLatestJoCaseMemosReminder = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($selectedDialogue,$user);
$huskeseddelAllReminder = $em->getRepository(JoCaseMemos::class)->getMemosReminderForUser(null , $user);
$session->set("huskeseddelAllReminderCount", count($huskeseddelAllReminder));
$advisCount = $em->getRepository(JoCaseMemos::class)->fetchLatestAdvisFromJosaCaseMemosUnreadCount(null , $user);
$session->set("advisCount", count($advisCount));
//$loginUserInstitutions
$loginUserData = $em->createQuery("SELECT sp.firstname,sp.familyname,sp.occupation,si.institutionnumber,si.institutionname, si.id FROM App\Entity\StilPerson sp
left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser
left join App\Entity\StilInstitution si with sp.institutionId = si.id
WHERE ac.user =".$user->getId() )
->execute();
$currentSelectedData = $em->getRepository(StilInstitution::class)->findOneBy(array("id" => $currentSelectedInstitution));
if($currentSelectedData){
$currentSelectedPersonData = $em->getRepository(StilPerson::class)->findOneBy(array("institutionId" => $currentSelectedInstitution));
$session->set("occupation", $currentSelectedPersonData->getOccupation());
$session->set("institutionname", $currentSelectedData->getInstitutionname());
$session->set("InstitutionNumber", $currentSelectedData->getInstitutionnumber());
}
if(!strlen($indexFilterAdUserId)) {
$indexFilterAdUserId = '';
}
if(!strlen($indexAreaIds)) {
$indexAreaIds = '';
}
if(!strlen($indexdocumentIds)) {
$indexdocumentIds = '';
}
if ($request->isXmlHttpRequest()) {
return $this->render("default/_search_index.html.twig", array(
'isDialogueExist' => $isDialogueExist,
'fetchAllDialogues' => $fetchAllDialogues,
'user' => $user,
'indexFilterAdUserId' => $indexFilterAdUserId,
'indexAreaIds' => $indexAreaIds,
'indexStatusIds' => $indexStatusIds,
'indexdocumentIds' => $indexdocumentIds,
//'myDialogues' => $myDialogues,
//'myDialoguesCount' => $myDialoguesCount,
'allCaseCardsCount' => count($fetchAllDialoguesAll),
'recentDialogues' => $recentDialogues,
'recentDialoguesCount' => $recentDialoguesCount,
'notesPassedReminderDate' => $notesPassedReminderDate,
'notesPassedReminderDateCount' => $notesPassedReminderDateCount,
'selectedPatient' => $selectedPatient,
'selectedDialogue' => $selectedDialogue,
'newContentDialogues' => $newContentDialogues,
'newContentDialoguesCount' => $newContentDialoguesCount,
'dialogueMeasureText' => $dialogueMeasureText,
'sortBy' => $sortBy,
'orderBy' => $orderBy,
'listType' => $listType,
'cids' => explode(",", $indexCaseCardIds),
'pagelimit' => $pagelimit,
'isResultWithoutFilter' => $isResultWithoutFilter,
'onlyMyDialogues' => $onlyMyDialogues,
'onlyMyDialoguesCount' => $onlyMyDialoguesCount,
'documentsLinkForEachDialgue' => $documentsLinkForEachDialgue,
'predefinedTemplateAll' => $predefinedTemplate,
'isTestServer' => $isTestServer,
'loginUserData' => $loginUserData
)
);
} else {
return $this->render("default/index.html.twig", array(
'isDialogueExist' => $isDialogueExist,
'fetchAllDialogues' => $fetchAllDialogues,
'user' => $user,
'indexFilterAdUserId' => $indexFilterAdUserId,
'indexAreaIds' => $indexAreaIds,
'indexStatusIds' => $indexStatusIds,
'indexdocumentIds' => $indexdocumentIds,
//'myDialogues' => $myDialogues,
//'myDialoguesCount' => $myDialoguesCount,
'allCaseCardsCount' => count($fetchAllDialoguesAll),
'recentDialogues' => $recentDialogues,
'recentDialoguesCount' => $recentDialoguesCount,
'notesPassedReminderDate' => $notesPassedReminderDate,
'notesPassedReminderDateCount' => $notesPassedReminderDateCount,
'selectedPatient' => $selectedPatient,
'selectedDialogue' => $selectedDialogue,
'newContentDialogues' => $newContentDialogues,
'newContentDialoguesCount' => $newContentDialoguesCount,
'dialogueMeasureText' => $dialogueMeasureText,
'sortBy' => $sortBy,
'orderBy' => $orderBy,
'listType' => $listType,
'predefinedCaseCardAll' => $predefinedCaseCardAll,
'userCaseCardAll' => $userCreatedCaseCardsId,
'allDefaultUserAreas' => $allDefaultUserAreas,
'allUserAreas' => $allUserAreas,
'userArea' => $userArea,
'allUserSchools' => $allUserSchools,
'allDefaultUserSchools' => $allDefaultUserSchools,
'userInfo' => $userInfo,
'allInstitute' => $allInstitute,
'allCasesKommunes' => $allCasesKommunes,
'cids' => array(),
'isCprLookupActive' => $isCprLookupActive,
'pagelimit' => $pagelimit,
'isResultWithoutFilter' => $isResultWithoutFilter,
'onlyMyDialogues' => $onlyMyDialogues,
'onlyMyDialoguesCount' => $onlyMyDialoguesCount,
//'joGroupForm' => $joGroupForm->createView(),
'groupPredefinedCaseCardAll' => $groupPredefinedCaseCardAll,
'selectedJoGroup' => $selectedJoGroup,
'documentsLinkForEachDialgue' => $documentsLinkForEachDialgue,
'isJoGroupExist' => $isJoGroupExist,
'isTestServer' => $isTestServer,
'loginUserData' => $loginUserData
)
);
}
}
public function createCase() {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
return $this->render("default/createCase.html.twig");
}
public function createCaseWithExisting(Request $request, $cprNo) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$cprNo = base64_decode($cprNo);
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedDialogue = $session->get("selectedDialogue", null);
if ($selectedDialogue) {
$selectedDialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue);
}
// Symfony 2.5
//$therapist = $this->get('security.context')->getToken()->getUser();
// Symfony 2.6
$user = $this->get('security.token_storage')->getToken()->getUser();
$patientObj = $womenArray = $menArray = $gardianArray = $addedRelations = $childExtraInfo = array();
$gardianExistCnt = 0;
$session = $request->getSession();
//$session->set('isUserCreated', false);
$womenExist = $menExist = $bothExist = $gardianAsWomen = $gardianAsMen = false;
$isExistingPatient = false;
$searchFilter = "ROLE_DTS";
if ($user->hasRole('ROLE_CSV')) {
$searchFilter = "ROLE_CSV";
}
if ($cprNo) {
$cprNo = str_replace('-', '', $cprNo);
$patientObjTemp = $em->getRepository(Patient::class)->findBy(array('cpr' => $cprNo));
$patientObj = $patientObjTemp ? $patientObjTemp[0] : array();
if($patientObj->getId() < 20) {
$isExistingPatient = true;
}
$userObjTemp = $em->getRepository(User::class)->findBy(array('username' => $cprNo));
$userObj = $userObjTemp ? $userObjTemp[0] : array();
//var_dump($userObj);
//Patient family members
$patientFamilyObj = $em->getRepository(Family::class)->findBy(array('patient' => $patientObj));
//Patient info
$patientInfoObjTemp = $em->getRepository(PatientInformation::class)->findBy(array('user' => $patientObj->getUser()));
$patientInfoObj = $patientInfoObjTemp ? $patientInfoObjTemp[0] : array();
//var_dump($patientInfoObj);
$statCprNo = $cprNo;
if($patientInfoObj && $patientInfoObj->getIsMultiple()){
$childExtraInfoTemp = $em->getRepository(PatientInformationDetails::class)->findBy(array('user' => $patientObj->getUser()),array('id' => 'desc','citizen_institution_from_date' =>'desc'));
$childExtraInfo[$statCprNo]['info'] = $childExtraInfoTemp ? $childExtraInfoTemp : array();
// var_dump($childExtraInfo);die;
}
/*if ($statCprNo == '0605045467') {
$childExtraInfo[$statCprNo]['info'][0] = array("citizen_institution_name" => "Fritidscenter Bispebjerg Nord", "citizen_institution_fromdate" => "01.08.2014", "citizen_institution_tilldate" => "30.05.2017", "citizen_school_name" => "", "citizen_school_fromdate" => "", "citizen_school_tilldate" => "");
$childExtraInfo[$statCprNo]['info'][1] = array("citizen_institution_name" => "Fritidsinstitutionen ved Guldberg Skole", "citizen_institution_fromdate" => "01.08.2010", "citizen_institution_tilldate" => "03.06.2014", "citizen_school_name" => "", "citizen_school_fromdate" => "", "citizen_school_tilldate" => "");
}
if ($statCprNo == '1110104359') {
$childExtraInfo[$statCprNo]['info'][0] = array("citizen_institution_name" => "Børnevænget", "citizen_institution_fromdate" => "30.11.2011", "citizen_institution_tilldate" => "14.01.2013", "citizen_school_name" => "", "citizen_school_fromdate" => "", "citizen_school_tilldate" => "");
}
if ($statCprNo == '1102128866') {
$childExtraInfo[$statCprNo]['info'][0] = array("citizen_institution_name" => "", "citizen_institution_fromdate" => "", "citizen_institution_tilldate" => "", "citizen_school_name" => "Blågård Skole", "citizen_school_fromdate" => "10.08.2018", "citizen_school_tilldate" => "08.08.2019");
}*/
$getFullDate = $this->getBirthDate($cprNo);
$bdateYear = date_format($getFullDate, "d.m.Y");
$dateDiff = $this->getUserAge($bdateYear);
foreach ($patientFamilyObj as $patientFamily) {
if ($patientFamily->getRelation() == "1") {
$womenArray = $patientFamily;
$womenExist = true;
}
if ($patientFamily->getRelation() == "2") {
$menArray = $patientFamily;
$menExist = true;
}
if ($patientFamily->getRelation() == "9") {
if($patientFamily->getRelative()->getDeletedBy() == null){
$addedRelations[] = $patientFamily;
}
}
if ($patientFamily->getRelation() == "3") {
$gardianArray[] = $patientFamily;
$gardianExist = true;
$gardianExistCnt = ($gardianExistCnt+1);
}
}
if ($womenExist && $menExist) {
$bothExist = true;
}
if(count($gardianArray) == "1") {
if(!$womenExist) {
$womenArray = $gardianArray ? $gardianArray[0] : array();
$gardianAsWomen = $womenExist = true;
$gardianArray=[];
}
if($womenExist && !$menExist) {
$menArray = $gardianArray ? $gardianArray[0] : array();
$gardianAsMen = $menExist = true;
$gardianArray=[];
}
if($bothExist) {
$gardianArray = $gardianArray;
}
}
//var_dump($gardianAsMen, $menExist); die;
$dialogueObj = $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $patientObj));
$session->set("selectedPatient", $patientObj);
$session->set("selectedDialogue", $dialogueObj);
$dialogueConsentObj = $em->getRepository(DialogueConsentInfo::class)->findOneBy(array('dialogue' => $dialogueObj));
$patientTravelNeedsDetails = $em->getRepository(TravelNeedsDetails::class)->findBy(array('dialogue' => $dialogueObj, 'patient' => $patientObj));
}
$locationText = null;
$patientInstitutionMasterObj = null;
if(!is_array($patientInfoObj)){
$patientInstitutionMasterObj = $em->getRepository(JoMasterInformation::class)->findOneBy(array("inr" => $patientInfoObj->getCitizenInstitutionNumber()));
if($patientInfoObj->getInstitutionLocationId() > 0){
$location = $em->getRepository(JoMasterInformationLocation::class)->find($patientInfoObj->getInstitutionLocationId());
$locationText = $location ? $location->getAdresseWithAlias() : null;
}
}
$groupPredefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCards($searchFilter);
$areaNames = $em->getRepository(JoMasterInformation::class)->getAreaNames();
$komunneIdsArray = array(
'101' => 'København',
'147' => 'Frederiksberg',
'151' => 'Ballerup',
'153' => 'Brøndby',
'155' => 'Dragør',
'157' => 'Gentofte',
'159' => 'Gladsaxe',
'161' => 'Glostrup',
'163' => 'Herlev',
'165' => 'Albertslund',
'167' => 'Hvidovre',
'169' => 'Høje-Taastrup',
'173' => 'Lyngby-Taarbæk',
'175' => 'Rødovre',
'183' => 'Ishøj',
'185' => 'Tårnby',
'187' => 'Vallensbæk',
'190' => 'Furesø',
'201' => 'Allerød',
'210' => 'Fredensborg',
'217' => 'Helsingør',
'219' => 'Hillerød',
'223' => 'Hørsholm',
'230' => 'Rudersdal',
'240' => 'Egedal',
'250' => 'Frederikssund',
'253' => 'Greve',
'259' => 'Køge',
'260' => 'Halsnæs',
'265' => 'Roskilde',
'269' => 'Solrød',
'270' => 'Gribskov',
'306' => 'Odsherred',
'316' => 'Holbæk',
'320' => 'Faxe',
'326' => 'Kalundborg',
'329' => 'Ringsted',
'330' => 'Slagelse',
'336' => 'Stevns',
'340' => 'Sorø',
'350' => 'Lejre',
'360' => 'Lolland',
'370' => 'Næstved',
'376' => 'Guldborgsund',
'390' => 'Vordingborg',
'400' => 'Bornholm',
'410' => 'Middelfart',
'411' => 'Christiansø',
'420' => 'Assens',
'430' => 'Faaborg-Midtfyn',
'440' => 'Kerteminde',
'450' => 'Nyborg',
'461' => 'Odense',
'479' => 'Svendborg',
'480' => 'Nordfyns',
'482' => 'Langeland',
'492' => 'Ærø',
'510' => 'Haderslev',
'530' => 'Billund',
'540' => 'Sønderborg',
'550' => 'Tønder',
'561' => 'Esbjerg',
'563' => 'Fanø',
'573' => 'Varde',
'575' => 'Vejen',
'580' => 'Aabenraa',
'607' => 'Fredericia',
'615' => 'Horsens',
'621' => 'Kolding',
'630' => 'Vejle',
'657' => 'Herning',
'661' => 'Holstebro',
'665' => 'Lemvig',
'671' => 'Struer',
'706' => 'Syddjurs',
'707' => 'Norddjurs',
'710' => 'Favrskov',
'727' => 'Odder',
'730' => 'Randers',
'740' => 'Silkeborg',
'741' => 'Samsø',
'746' => 'Skanderborg',
'751' => 'Aarhus',
'756' => 'Ikast-Brande',
'760' => 'Ringkøbing-Skjern',
'766' => 'Hedensted',
'773' => 'Morsø',
'779' => 'Skive',
'787' => 'Thisted',
'791' => 'Viborg',
'810' => 'Brønderslev',
'813' => 'Frederikshavn',
'820' => 'Vesthimmerlands',
'825' => 'Læsø',
'840' => 'Rebild',
'846' => 'Mariagerfjord',
'849' => 'Jammerbugt',
'851' => 'Aalborg',
'860' => 'Hjørring');
$komunneId = $patientObj->getKommuneId();
if (array_key_exists($komunneId,$komunneIdsArray)) {
$komunneName = $komunneIdsArray[$komunneId];
} else if($patientObj->getIsDummyPatient()) {
$komunneName = "Københavns";
} else {
$komunneName = "";
}
$getLatestJoCaseMemosReminder = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($dialogueObj,$user);
$loginUserData = $em->createQuery("SELECT sp.firstname,sp.familyname,sp.occupation,si.institutionnumber,si.institutionname, si.id FROM App\Entity\StilPerson sp
left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser
left join App\Entity\StilInstitution si with sp.institutionId = si.id
WHERE ac.user =".$user->getId() )
->execute();
return $this->render("default/createCaseWithExisting.html.twig", array(
'patientObj' => $patientObj,
'patientFamilyObj' => $patientFamilyObj,
'patientAge' => $dateDiff,
'womenExist' => $womenExist,
'menExist' => $menExist,
'bothExist' => $bothExist,
'womenArray' => $womenArray,
'menArray' => $menArray,
'addedRelations' => $addedRelations,
'user' => $user,
'patientInfoObj' => $patientInfoObj,
'childExtraInfo' => $childExtraInfo,
'statCprNo' => $statCprNo,
'dialogueObj' => $selectedDialogue,
'dialogueConsentObj' => $dialogueConsentObj,
'patientTravelNeedsDetails' => $patientTravelNeedsDetails,
'dateDiff' => $dateDiff,
'userObj' => $userObj,
'isExistingPatient' => $isExistingPatient,
'groupPredefinedCaseCardAll' => $groupPredefinedCaseCardAll,
'instituteLocations' => $patientInstitutionMasterObj ? $patientInstitutionMasterObj->getJoMasterInformationLocations() : null,
'locationText' => $locationText,
'areaNames' => $areaNames,
'komunneName' => $komunneName,
'komunneId' => $komunneId,
'getLatestJoCaseMemosReminder' => $getLatestJoCaseMemosReminder,
'gardianArray' => $gardianArray,
'gardianExistCnt' => $gardianExistCnt,
'gardianAsWomen' => $gardianAsWomen,
'gardianAsMen' => $gardianAsMen,
'loginUserData' => $loginUserData
));
}
public function caseDetailView(Request $request) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$detailviewId = $request->get("detailviewId");
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$activityId = $session->get("activityDetailUpdated", 0);
$session->set('activityDetailUpdated', NULL); //$session->set('activityDetailUpdated', 0);
//var_dump($selectedPatient->getId(), $selectedDialogue->getId()); die;
if (!$selectedPatient) {
return $this->redirect($this->generateUrl('index'));
}
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$patientDetails = $patient->getId();
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
//$user = $em->getRepository(User::class)->find(1);
$user = $this->get('security.token_storage')->getToken()->getUser();
if (!$dialogue) {
return $this->redirect($this->generateUrl('index'));
}
$patient = $dialogue->getPatient();
$session->set("selectedDialogue", $dialogue);
$session->set("selectedPatient", $patient);
$getLatestJoCaseMemos = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue,$user);
$session->set("caseMemoCount",count($getLatestJoCaseMemos));
$getLatestJoCaseComments = $em->getRepository(JoCaseComments::class)->getLatestJoCaseComments($dialogue,$user);
$session->set("caseCommentsCount", count($getLatestJoCaseComments));
$getLatestJoCaseMemosReminder = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($dialogue,$user);
//Delete DialogueAttachmentDetails activity if no borgerplan is attached to this
$checkActivityNotAttachedToEventsCnt = $em->getRepository(DialogueAttachmentDetails::class)->checkActivityNotAttachedToEventsCnt($dialogue,$user);
if(count($checkActivityNotAttachedToEventsCnt) > 0) {
foreach($checkActivityNotAttachedToEventsCnt as $dialogueAttachmentDetail) {
if($dialogueAttachmentDetail){
$JoCaseCardEventBrevActivityObj = $em->getRepository(JoCaseCardEventBrevActivity::class)->findOneBy(array('attachmentDetails' => $dialogueAttachmentDetail));
if($JoCaseCardEventBrevActivityObj){
$em->remove($JoCaseCardEventBrevActivityObj);
$em->flush();
}
$em->remove($dialogueAttachmentDetail);
$em->flush();
}
}
}
$finishedForm = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'activityType' => '1', 'isPostMailActivity' => 0));
$draftForm = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'activityType' => '2', 'isPostMailActivity' => 0));
$finishedScheme = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'activityType' => '3', 'isPostMailActivity' => 0));
$draftScheme = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'activityType' => '4', 'isPostMailActivity' => 0));
$finishedNote = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'activityType' => '5', 'isPostMailActivity' => 0));
$draftNote = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'activityType' => '6', 'isPostMailActivity' => 0));
$finishedAttachment = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'activityType' => '7', 'isPostMailActivity' => 0));
$draftAttachment = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'activityType' => '8', 'isPostMailActivity' => 0));
$borgerplan = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'pAtttachmentType' => '8', 'isPostMailActivity' => 0));
if(count($finishedForm)){
}
$caseCardTypeListLi = array(
1 => array(
'label' => 'Brev afsluttet', 'meaning' => 'Form/Letter-finished', 'count' => count($finishedForm)),
2 => array(
'label' => 'Brev kladde', 'meaning' => 'Form/Letter-Draft', 'count' => count($draftForm)),
3 => array(
'label' => 'Skabelon afsluttet', 'meaning' => 'Form/Scheme-finished','count' => count($finishedScheme)),
4 => array(
'label' => 'Skabelon kladde', 'meaning' => 'Form/Scheme-Draft','count' => count($draftScheme)),
5 => array(
'label' => 'Note afsluttet', 'meaning' => 'Note-finished','count' => count($finishedNote)),
6 => array('label' => 'Note kladde', 'meaning' => 'Note-Draft','count' => count($draftNote)),
7 => array('label' => 'Vedhæft afsluttet', 'meaning' => 'Attacment-finished','count' => count($finishedAttachment)),
8 => array('label' => 'Vedhæft kladde', 'meaning' => 'Attacment-Draft','count' => count($draftAttachment)),
10 => array('label' => 'Borgerplan afsluttet', 'meaning' => 'Borgerplan','count' => count($borgerplan)),
9 => array('label' => 'Borgerplan kladde', 'meaning' => 'Borgerplan','count' => count($borgerplan)));
//$selectedDialogue = $dialogue;
//$cpr = "111111";
$cpr = $patient->getCpr();
$getFullDate = $this->getBirthDate($cpr);
$bdateYear = date_format($getFullDate, "d.m.Y");
$dateDiff = $this->getUserAge($bdateYear);
$searchFilter = "ROLE_DTS";
if ($user->hasRole('ROLE_CSV')) {
$searchFilter = "ROLE_CSV";
}
$joPredefinedCaseCardObjs = NULL;
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForIndividual' => 1));
$predefinedCaseCardAllIds = array();
$joPredefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'josa_rapport'));
if($joPredefinedCaseCardObj){
$predefinedCaseCardAllIds[] = $joPredefinedCaseCardObj->getId();
}
$joPredefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'Sagsgrundlag'));
if($joPredefinedCaseCardObj){
$predefinedCaseCardAllIds[] = $joPredefinedCaseCardObj->getId();
$joPredefinedCaseCardObjs = $joPredefinedCaseCardObj;
}
$joGroupObj = NULL;
if(($dialogue->getDialogueType() == 3 || $dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_DTS" ) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
//$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCardListByType($searchFilter, $joGroupObj->getJoMasterInformation()->getInfoType(), $joGroupObj->getJoMasterInformation()->getKkorg());
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => '1'));
} else if(($dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_CSV" ) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => 1));
}
//$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findAll();
//$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findById(array(1, 2, 3, 4, 6, 9, 11,12), array('orderBy' => 'asc'));
$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findBy(array('isActivityType' => 1), array('orderBy' => 'asc'));
$dialogueCaseCardAll = $em->getRepository(DialogueCaseCard::class)->findBy(array('dialogue' => $selectedDialogue));
$userCreatedCaseCardsId = $userCreatedDialogueCaseCard = array();
$closedCaseCardCount = 0;
foreach ($dialogueCaseCardAll as $dialogueCaseCard) {
if (!$dialogueCaseCard->getIsClosed()) {
$userCreatedCaseCardsId[] = $dialogueCaseCard->getPCaseCardId()->getId();
$userCreatedDialogueCaseCard[$dialogueCaseCard->getPCaseCardId()->getId()] = $dialogueCaseCard->getId();
}else{
$closedCaseCardCount++;
}
}
/*$predefinedTemplates = $em->getRepository(PredefinedTemplate::class)->findBy(array(), array('orderBy' => 'asc'));
$parentTemplate = $childTemplate = array();
foreach ($predefinedTemplates as $predefinedTemplate) {
if ($predefinedTemplate->getParentId() == "0") {
$parentTemplate[$predefinedTemplate->getId()] = $predefinedTemplate;
} else {
$childTemplate[$predefinedTemplate->getParentId()][] = $predefinedTemplate;
}
}*/
//var_dump($userCreatedCaseCardsId, $userCreatedDialogueCaseCard);
$sortBy = $request->get('sortBy');
$orderBy = $request->get('orderBy');
if ($user->hasRole('ROLE_PARENT')) {
$activitySharing = $em->getRepository(JoActivitySharing::class)->findOneBy(array('dialogue' => $dialogue));
if($activitySharing){
//$dialogueAttachmentDetailIds = $activitySharing->getLoggedInCitizenActivitiesForDialog($user);
$activitySharingParticipant = $em->getRepository(JoActivitySharingParticipant::class)->findOneBy(array('joActivitySharing' => $activitySharing, 'user' => $user));
if($activitySharingParticipant){
$dialogueAttachmentDetailIds = $activitySharingParticipant->getLoggedInCitizenActivitiesForDialog();
}else{
$dialogueAttachmentDetailIds = array();
}
}else{
$dialogueAttachmentDetailIds = array();
}
}else{
$dialogueAttachmentDetailIds = array();
}
$update_skalering = $this->updateSkaleringAttachment($dialogue,$patient,$em);
$dialogueAttachmentFilter = $em->getRepository(DialogueAttachmentDetails::class)->filterDialogueAttachmentDetails($dialogue, $patient, '', '', '', '', '', '', '', '', '','','' ,$dialogueAttachmentDetailIds, 0, $user );
$dialogueAttachmentDetails = $dialogueAttachmentFilter['result'];
$futureActivities = $dialogueAttachmentFilter['futureActivitiesCount'];
//When an event is journalised(black line) the date of the event should be shown instead of the create date in the case activity column dato. 13-06-2020
$isAttachmentDateUpdated = false;
$relatedRecordsDetails= [];
$tunnelshareActivity=array();
$scaleGraphArray=array();
foreach ($dialogueAttachmentDetails as $attachmentDetailObj) {
if ($attachmentDetailObj->getPAtttachmentType()->getId() == 8) {
foreach ($attachmentDetailObj->getJoCaseCardEvents() as $eventObj) {
$eventStartAt = strtotime($eventObj->getStartAt()->format('Y-m-d'));
$currentDate = strtotime("now");
if(strtotime($attachmentDetailObj->getAttachmentDate()->format('Y-m-d')) != strtotime($eventObj->getStartAt()->format('Y-m-d')) ) {
if ($eventStartAt < $currentDate) {
$attachmentDetailObj->setAttachmentDate($eventObj->getStartAt());
$em->persist($attachmentDetailObj);
$em->flush();
$isAttachmentDateUpdated = true;
}else if($dialogue->getDialogueType() == 3 || $dialogue->getDialogueType() == 4){
$attachmentDetailObj->setAttachmentDate($eventObj->getStartAt());
$em->persist($attachmentDetailObj);
$em->flush();
$isAttachmentDateUpdated = true;
}
}
if($attachmentDetailObj->getPatient()->getUser() != NULL && $attachmentDetailObj->getPatient()->getUser()->getId() == $patient->getUser()->getId()){
$relatedRecords = $em->getRepository(JoCaseCardEvent::class)->findChildIndividualDialogEventList($dialogue,$eventObj->getDialogueCaseCard(),$eventObj->getDialogueCaseCardMeasure(),$eventObj->getHeading(),$eventObj->getEventCollection());
if($relatedRecords != '' && (count($relatedRecords) > 0 )){
$relatedRecordsDetails[$attachmentDetailObj->getId()]['index'] = array_search($eventObj, $relatedRecords) + 1;
$relatedRecordsDetails[$attachmentDetailObj->getId()]['count'] = count( $relatedRecords);
$min = $relatedRecords[0];
for ($i = 1; $i < count($relatedRecords); $i++)
if ($relatedRecords[$i]->getId() < $min->getId())
$min = $relatedRecords[$i];
$relatedRecordsDetails[$attachmentDetailObj->getId()]['link_id'] = $min->getId();
}
}
}
}
$tunnelRid= $attachmentDetailObj->getTunnelListId();
if($tunnelRid){
$tunnelDetailsObj = $em->getRepository(SepoTunnelliste::class)->findOneBy(array('rid' => $tunnelRid));
if($tunnelDetailsObj){
$tunnelshareActivity[$tunnelRid]= array('name' => $tunnelDetailsObj->getName());
}
}
//featchScaleGraph detils
$res=$this->featchAllScalingGraphDetails($em,$attachmentDetailObj);
if($res){
$scaleGraphArray[$attachmentDetailObj->getId()] = isset($res['scalingIndividualGraphArray'][$attachmentDetailObj->getId()])?$res['scalingIndividualGraphArray'][$attachmentDetailObj->getId()]:[];
}
//clear activity access older than today (if not cleared)
if($attachmentDetailObj->getIsOpen() == 1){
if(strtotime($attachmentDetailObj->getOpenTime()->format('Y-m-d')) < strtotime((new \DateTime())->format('Y-m-d')) ) {
$attachmentDetailObj->setIsOpen(0);
$attachmentDetailObj->setOpenedBy(null);
$attachmentDetailObj->setOpenTime(null);
$em->persist($attachmentDetailObj);
$em->flush();
}
}
}
if($isAttachmentDateUpdated){
$dialogueAttachmentFilter = $em->getRepository(DialogueAttachmentDetails::class)->filterDialogueAttachmentDetails($dialogue, $patient, '', '', '', '', '', '', '', '', '','','' ,$dialogueAttachmentDetailIds, 0, $user );
$dialogueAttachmentDetails = $dialogueAttachmentFilter['result'];
$futureActivities = $dialogueAttachmentFilter['futureActivitiesCount'];
}
//}
$dialogueAttachments = $em->getRepository(DialogueAttachments::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient));
$dialogueAttachmentFileName = array();
foreach ($dialogueAttachments as $dialogueAttachment) {
$id = $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
$dialogueAttachmentFileName[$id]['files'][] = $dialogueAttachment;
}
$webPath = '/public/uploads/attachments/'; //$this->get('kernel')->getProjectDir() .
//var_dump($dialogueAttachmentFileName); die;
$dialogueNotes = $em->getRepository(DialogueNotes::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient));
$current_year = date('Y');
$range = range($current_year, $current_year - 10);
$last10Years = array_combine($range, $range);
//fetch all DialogueCaseCardMeasure related to ccId
//$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->findBy(array('referenceType' => 'F'));
$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->fetchMeasureTilDate('F',new \DateTime(),$user->getProfession());
//fetch completed casecard activities
$dialogueCompleteAttachmentDetails = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient, 'isDraft' => "0", 'isPostMailActivity' => 0));
$joGroupObj = NULL;
if($dialogue->getDialogueType() > 2 && $dialogue->getDialogueType() < 5) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
}
$groupPredefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCards($searchFilter);
$areaNames = $em->getRepository(JoMasterInformation::class)->getAreaNames();
$holdList = $em->getRepository(JoCaseCardHold::class)->findAll();
//$joGroup = new JoGroup();
//$joGroupForm = $this->createForm(JoGroupType::class, $joGroup);
$isSavedAsActivity = false;
$getNotSavedAsActivityPostMails = $em->getRepository(JoPostMail::class)->getNotSavedAsActivityPostMails($isSavedAsActivity, $dialogue);
$session->set("postMailCnt", count($getNotSavedAsActivityPostMails));
$showFutureActivities = 0;
$isBackendEnabled = $this->container->getParameter('isBackendEnabled');
$komunneId = $patient->getKommuneId();
$session->set("komunneId",$komunneId);
$brevActivityEvent=array();
$checkBrevActivityDetails = $em->getRepository(DialogueAttachmentDetails::class)->checkBrevActivityEvent($dialogue,$patient);
foreach ($checkBrevActivityDetails as $brevActivity) {
$brevActivityEvent[$brevActivity['id']]= array('eventId' => $brevActivity['eventId'],
'heading' => $brevActivity['heading'],
);
}
$loginUserData = $em->createQuery("SELECT sp.firstname,sp.familyname,sp.occupation,si.institutionnumber,si.institutionname, si.id FROM App\Entity\StilPerson sp
left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser
left join App\Entity\StilInstitution si with sp.institutionId = si.id
WHERE ac.user =".$user->getId() )
->execute();
//check count skelering activity
$checkForSkelering = $em->getRepository(DialogueAttachmentDetails::class)->checkSkeleringActivity($dialogue, $patient);
// to display brev and delt sagskter display sent mail/ebook date time
$skebelon_ebook_log = $em->getRepository(SkebelonEbookLog::class)->findBy(array('dialogueId' => $dialogue->getId()));
foreach ($skebelon_ebook_log as $skebelon_ebook_logs) {
// $skebelon_ebook_log_arr[]= $skebelon_ebook_logs['status'];
$id = $skebelon_ebook_logs->getDialogueAttachmentDetailId();
$created_at = date_format($skebelon_ebook_logs->getCreatedAt(), "d.m.Y, h.i");
$status = $skebelon_ebook_logs->getStatus();
$skebelon_ebook_log_arr[$id]= array('created_at' => $created_at,
'status' => $status ,'id'=>$id
);
}
$i = 0;
foreach($dialogueAttachmentDetails as $dialogueAttachment)
{
$noteQuery = $em->createQuery("SELECT dad FROM App\Entity\DialogueAttachmentDetails dad
WHERE dad.parentId =:parentId order by dad.updatedAt DESC")
->setParameter('parentId', $dialogueAttachment->getId());
$noteIds = $noteQuery->execute();
$dialogueAttachmentArray[$dialogueAttachment->getId()] = $noteIds;
$i++;
}
return $this->render("default/caseDetailView.html.twig", array(
'dateDiff' => $dateDiff,
'dialogueNotes' => $dialogueNotes,
'dialogueCaseCardAll' => $dialogueCaseCardAll,
'predefinedCaseCardAll' => $predefinedCaseCardAll,
'userCreatedCaseCardsId' => $userCreatedCaseCardsId,
'patientObj' => $patient,
'user' => $user,
'dialogue' => $dialogue,
'predefinedAttachmentType' => $predefinedAttachmentType,
'dialogueAttachmentDetails' => $dialogueAttachmentDetails,
'holdList' => $holdList,
'dialogueAttachmentFileName' => $dialogueAttachmentFileName,
'webPath' => $webPath,
'sortBy' => $sortBy,
'orderBy' => $orderBy,
'showFutureActivities' => $showFutureActivities,
'futureActivities' => $futureActivities,
'dialogueObj' => $dialogue,
'userCreatedDialogueCaseCard' => $userCreatedDialogueCaseCard,
'caseCardTypeListLi' => $caseCardTypeListLi,
'last10Years' => $last10Years,
'dialogueCaseCardMeasureAll' => $dialogueCaseCardMeasureAll,
'detailviewId' => $detailviewId,
'activityId' => $activityId,
'closedCaseCardCount' => $closedCaseCardCount,
'dialogueCompleteAttachmentDetails' => count($dialogueCompleteAttachmentDetails),
'joGroupObj' => $joGroupObj,
'groupPredefinedCaseCardAll' => $groupPredefinedCaseCardAll,
'relatedRecordsDetails' => $relatedRecordsDetails,
'areaNames' => $areaNames,
'isBackendEnabled' => $isBackendEnabled,
'brevActivityEvent' => $brevActivityEvent,
'getLatestJoCaseMemosReminder' => $getLatestJoCaseMemosReminder,
'tunnelshareActivity' => $tunnelshareActivity,
'patientDetails' => $patientDetails,
'scaleGraphArray' => $scaleGraphArray,
'skeleringCnt' => count($checkForSkelering),
'loginUserData' => $loginUserData,
'joPredefinedCaseCardObjs' => $joPredefinedCaseCardObjs,
'dialogueAttachmentArray' => $dialogueAttachmentArray
//'joGroupForm' => $joGroupForm->createView(),
//'parentTemplate' => $parentTemplate,
//'childTemplate' => $childTemplate,
)
);
}
public function caseDetailOverview(Request $request) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$showNew = $request->get("new");
$openNew = $request->get("open");
$id = $request->get("id");
$holdOpen = $request->get("holdOpen",0);
$dialogueId= $request->get("dialogueId");
$isCprLookupActive = $this->container->getParameter('isCprLookupActive');
$user = $this->get('security.token_storage')->getToken()->getUser();
$session = $request->getSession();
if($dialogueId){
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$dialogue = $em->getRepository(Dialogue::class)->find($dialogueId);
$patient = $em->getRepository(Patient::class)->find($dialogue->getPatient()->getId());
$dialogue->setUpdatedAt(new \DateTime());
$em->persist($dialogue);
$em->flush();
$dal = new DialogueAccessLog();
$dal->createdBy = $this->get('security.token_storage')->getToken()->getUser();
$dal->setCreatedAt(new \DateTime());
$dal->dialogue = $dialogue;
$em->persist($dal);
$em->flush();
$session = $request->getSession();
//$em->detach($patient);
//$em->detach($dialogue);
$selectedPatient = $session->set("selectedPatient", $patient);
$selectedDialogue = $session->set("selectedDialogue", $dialogue);
$selectedPatient = $patient;
$selectedDialogue = $selectedPatient;
if($dialogue->getDialogueType() == 1 || $dialogue->getDialogueType() == 2){
if(!$session->get('waitingListCount',false)){
$measureList = $em->getRepository(DialogueCaseCardMeasure::class)->fetchMeasuresWithStatusAfventer($patient->getId());
$waitingList = $em->getRepository(JoGroupWaitinglist::class)->fetchWaitingListFOrPatient($patient->getId());
$waitingListCount = count($measureList) + count($waitingList);
$session->set('waitingListCount',$waitingListCount,false);
}
$log = $this->checkAccessDialogOfDeceased($dialogue, $user, $patient );
}
//Get rental default listing
$defaultRentalList = $em->getRepository(RbRental::class)->getDefaultRentalList($patient);
$session->set("rentalItemCnt", count($defaultRentalList));
$getLatestJoCaseComments = $em->getRepository(JoCaseComments::class)->getLatestJoCaseComments($dialogue,$user);
$isReadAllComments = 'true';
foreach($getLatestJoCaseComments as $joCaseCommentObj) {
$joCaseCommentsLogObj = $em->getRepository(JoCaseCommentsLog::class)->findOneBy(array('JoCaseComments' => $joCaseCommentObj, 'User' => $user));
if(!$joCaseCommentsLogObj) {
$isReadAllComments = 'false';
break;
}
}
//$session->set("caseCommentsCount", count($getLatestJoCaseComments));
$session->set("isReadAllComments", $isReadAllComments);
if($isReadAllComments === 'false') {
return $this->redirectToRoute('case_comment_overview');
}
$myHuskeseddelReminder = $em->getRepository(JoCaseMemos::class)->getMemosReminderForUser($dialogue , $user);
$session->set("myHuskeseddelReminderCount", count($myHuskeseddelReminder));
$myMemo = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue , $user);
$session->set("myMemoCount", count($myMemo));
}
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$user = $this->get('security.token_storage')->getToken()->getUser();
$womenExist = $menExist = $bothExist = false;
$womenArray = $menArray = $addedRelations = array();
//var_dump($selectedPatient); die;
if (!$selectedPatient) {
return $this->redirect($this->generateUrl('index'));
}
$patientObj = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
$patientFamilyObj = $em->getRepository(Family::class)->findBy(array('patient' => $patientObj));
$cpr = $patientObj->getCpr();
$getFullDate = $this->getBirthDate($cpr);
$bdateYear = date_format($getFullDate, "d.m.Y");
$dateDiff = $this->getUserAge($bdateYear);
$getComments = $em->getRepository(JoCaseComments::class)->getLatestJoCaseComments($dialogue,$user);
$session->set("caseCommentsCount", count($getComments));
$getLatestJoCaseMemos = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue,$user);
$session->set("caseMemoCount",count($getLatestJoCaseMemos));
$getLatestJoCaseMemosReminder = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($dialogue,$user);
//var_dump($selectedDialogue); die;
$searchFilter = "ROLE_DTS";
if ($user->hasRole('ROLE_CSV')) {
$searchFilter = "ROLE_CSV";
}
//if($dialogue->getDialogueType() == 1 || $dialogue->getDialogueType() == 2 ) {
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForIndividual' => 1));
//} else {
//$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => 1));
//}
$joGroupObj = NULL;
if(($dialogue->getDialogueType() == 3 || $dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_DTS" ) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
//$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCardListByType($searchFilter, $joGroupObj->getJoMasterInformation()->getInfoType(), $joGroupObj->getJoMasterInformation()->getKkorg());
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => 1));
} else if(($dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_CSV" ) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => 1));
}
$dialogueCaseCard = new DialogueCaseCard();
$form = $this->createForm(DialogueCaseCardType::class, $dialogueCaseCard);
$dialogueCaseCardAll = $em->getRepository(DialogueCaseCard::class)->findBy(array('dialogue' => $selectedDialogue, 'isClosed' => 0), array('createdAt' => 'desc')); //'toDate' => NULL
//For select case drop down list
$dialogueCaseCardActiveClosed = $em->getRepository(DialogueCaseCard::class)->findBy(array('dialogue' => $selectedDialogue), array('createdAt' => 'desc'));
//Closed case card listing
$dialogueCaseCardClosed = $em->getRepository(DialogueCasecardMeasure::class)->fetchClosedCaseCard($selectedDialogue);
$userCreatedCaseCardsId = array();
$attachmentCnt = $noteCnt = array();
foreach ($dialogueCaseCardActiveClosed as $dialogueCaseCard) {
$userCreatedCaseCardsId[] = $dialogueCaseCard->getPCaseCardId()->getId();
//$allAttachmentRecords = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patientObj, 'pCaseCardId' => $dialogueCaseCard->getPCaseCardId()->getId(), 'user' => $user ));
/* $allAttachmentRecords = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patientObj, 'pCaseCardId' => $dialogueCaseCard->getPCaseCardId()->getId()));
$attachmentCnt[$dialogueCaseCard->getPCaseCardId()->getId()] = count($allAttachmentRecords);
$allNotesRecords = $em->getRepository(DialogueNotes::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patientObj, 'caseCard' => $dialogueCaseCard->getPCaseCardId()->getCaseCardType(), 'user' => $user));
$noteCnt[$dialogueCaseCard->getPCaseCardId()->getId()] = count($allNotesRecords); */
}
$caseCardMeasureCount = [];
// to show count of measures in individual case if gruppe measure is also included
if($dialogue->getdialogueType() == '1' || $dialogue->getdialogueType() == '2'){
foreach ($dialogueCaseCardAll as $caseCard) {
$holds = [];
//$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->findBy(array('DialogueCaseCard' => $caseCard->getId(), 'referenceType' => 'F'), array('searchDate' => 'desc'));
$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->getDialogueMeasuresByProfession($caseCard->getId(),$user->getProfession(),$caseCard->getPCaseCardId()->getId()); // change made for visitation
$queryHoldIds = $em->createQuery(
"SELECT h FROM App\Entity\JoCaseCardHold h
left join App\Entity\DialogueCaseCardMeasure dcm with dcm.id = h.measure
left join App\Entity\DialogueCaseCard dcc with dcm.DialogueCaseCard = dcc.id
WHERE dcc.pCaseCardId = :predefinedCC and h.id IN (SELECT IDENTITY (hr.JoCaseCardHold) FROM App\Entity\HoldResponsiblePerson hr where hr.User = :patientUser and hr.responsibleType = 'GP' )" )
->setParameter('predefinedCC', $caseCard->getPCaseCardId())
->setParameter('patientUser', $patientObj->getUser());
$holdTemps = $queryHoldIds->execute();
foreach($holdTemps as $hold) {
if($hold->getMeasure()->getDialogueCaseCard()->getDialogue()->getFirstJoGroup()){
$holds[] = $hold;
}
}
//var_dump($holdMeasureIds);die;
// $gruppeMeasureIds = [];
// foreach ($holds as $hold){
// if($hold->getMeasure()->getDialogueCaseCard()->getPCaseCardId()->getId() == $caseCard->getPCaseCardId()->getId() ){
// $gruppeMeasureIds[] = $hold->getMeasure()->getId();
// }
// }
// //var_dump($gruppeMeasureIds);die;
//
// $dialogueCaseCardMeasureAllQuery = $em->createQuery(
// "SELECT dcm FROM App\Entity\DialogueCaseCardMeasure dcm
// where ((dcm.DialogueCaseCard = :dialogueCaseCard) or (dcm.id IN (:measureIds))) and dcm.referenceType = 'F' order by dcm.searchDate desc" )
// ->setParameter('dialogueCaseCard', $caseCard->getId())
// ->setParameter('measureIds', $gruppeMeasureIds);
$caseCardMeasureCount[$caseCard->getId()] = count($dialogueCaseCardMeasureAll) + count($holds);
}
}
$caseCardMeasureCountClosed = [];
// to show count of measures in individual case if gruppe measure is also included
if($dialogue->getdialogueType() == '1' || $dialogue->getdialogueType() == '2'){
foreach ($dialogueCaseCardClosed as $caseCard) {
$holds = [];
//$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->findBy(array('DialogueCaseCard' => $caseCard->getId(), 'referenceType' => 'F'), array('searchDate' => 'desc'));
$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->getDialogueMeasuresByProfession($caseCard->getId(),$user->getProfession(),$caseCard->getPCaseCardId()->getId()); // change made for visitation
$queryHoldIds = $em->createQuery(
"SELECT h FROM App\Entity\JoCaseCardHold h
left join App\Entity\DialogueCaseCardMeasure dcm with dcm.id = h.measure
left join App\Entity\DialogueCaseCard dcc with dcm.DialogueCaseCard = dcc.id
WHERE dcc.pCaseCardId = :predefinedCC and h.id IN (SELECT IDENTITY (hr.JoCaseCardHold) FROM App\Entity\HoldResponsiblePerson hr where hr.User = :patientUser and hr.responsibleType = 'GP' )" )
->setParameter('predefinedCC', $caseCard->getPCaseCardId())
->setParameter('patientUser', $patientObj->getUser());
$holdTemps = $queryHoldIds->execute();
foreach($holdTemps as $hold) {
if($hold->getMeasure()->getDialogueCaseCard()->getDialogue()->getFirstJoGroup()){
$holds[] = $hold;
}
}
$caseCardMeasureCountClosed[$caseCard->getId()] = count($dialogueCaseCardMeasureAll) + count($holds);
}
}
//When a case has been created and the create new case card is activated – the case card that is related to the user logged in should be selected as default in the drop down so the user doesn't have to select it them selves.
/* $userDefaultSelectedCC = array();
//&& ( count($userCreatedCaseCardsId) == 0 )
if(!is_null($user->getProfession())){
$userProfession = substr($user->getProfession(), 0 , 3);
$userDefaultSelectedCC = $em->getRepository(PredefinedCaseCard::class)->userDefaultSelectedCC($searchFilter, $userProfession);
} */
$records = $em->getRepository(DialogueAttachmentDetails::class)->getCaseCardRecordCount($selectedDialogue->getId(), $selectedPatient->getId(), $user);
$finalCnt = array();
foreach ($records as $record) {
$pcaseId = $record['pCaseCardId'];
$finalCnt[$pcaseId] = $record['count'];
}
//When you go to a case with no case cards created yet – the add new case card bar should be open as shown here – instead of showing an empty page as it does now
//This should both happen after you have created a new case and after you access a case from the overview with no case card created.
if (count($dialogueCaseCardAll) <= 0) {
$showNew = "true";
}
foreach ($patientFamilyObj as $patientFamily) {
if ($patientFamily->getRelation() == "1" || $patientFamily->getRelation() == "3") {
$womenArray = $patientFamily;
$womenExist = true;
}
if ($patientFamily->getRelation() == "2" || $patientFamily->getRelation() == "4") {
$menArray = $patientFamily;
$menExist = true;
}
if ($patientFamily->getRelation() == "9") {
if($patientFamily->getRelative()->getDeletedBy() == null){
$addedRelations[] = $patientFamily;
}
}
}
if ($womenExist && $menExist) {
$bothExist = true;
}
/*$joGroupObj = NULL;
if(($dialogue->getDialogueType() == 3 || $dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_DTS" ) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCardListByType($searchFilter, $joGroupObj->getJoMasterInformation()->getInfoType(), $joGroupObj->getJoMasterInformation()->getKkorg());
} else if(($dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_CSV" ) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => 1));
} else if(($dialogue->getDialogueType() == 3) && $searchFilter == "ROLE_CSV" ) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
}*/
$groupPredefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCards($searchFilter);
$areaNames = $em->getRepository(JoMasterInformation::class)->getAreaNames();
$komunneId = $patientObj->getKommuneId();
$session->set("komunneId",$komunneId);
$viewData = array(
'predefinedCaseCardAll' => $predefinedCaseCardAll,
'form' => $form->createView(),
'dialogueCaseCardAll' => $dialogueCaseCardAll,
'caseCardMeasureCount' => $caseCardMeasureCount,
'userCreatedCaseCardsId' => $userCreatedCaseCardsId,
'patientObj' => $patientObj,
'user' => $user,
'isCprLookupActive' => $isCprLookupActive,
'showNew' => $showNew,
//'finalCnt' => $finalCnt,
'finalCnt' => $finalCnt,
'dialogueObj' => $dialogue,
'dialogueCaseCardClosed' => $dialogueCaseCardClosed,
'caseCardMeasureCountClosed' => $caseCardMeasureCountClosed,
//'userDefaultSelectedCC' => $userDefaultSelectedCC,
'womenExist' => $womenExist,
'menExist' => $menExist,
'bothExist' => $bothExist,
'womenArray' => $womenArray,
'menArray' => $menArray,
'addedRelations' => $addedRelations,
'openNew' => $openNew,
'id' => $id,
'holdOpen' => $holdOpen,
'dateDiff' => $dateDiff,
'joGroupObj' => $joGroupObj,
'areaNames' => $areaNames,
'groupPredefinedCaseCardAll' => $groupPredefinedCaseCardAll,
'getLatestJoCaseMemosReminder' => $getLatestJoCaseMemosReminder
//'joGroupForm' => $joGroupForm->createView(),
);
//show used matched case card on top for case card and default open casecard in indivisusal case card
if(($dialogue->getDialogueType() == 1 || $dialogue->getDialogueType() == 2)) {
$matchedCaseCardTop=[];$notMatchedCaseCardBelow=[];
foreach ($dialogueCaseCardAll as $caseCard1) {
if(($caseCard1->getPCaseCardId() && $user->getPredefinedCaseCard()) && ($caseCard1->getPCaseCardId()->getId() == $user->getPredefinedCaseCard()->getId())){
$matchedCaseCardTop[]=$caseCard1;
} else {
$notMatchedCaseCardBelow[]=$caseCard1;
}
}
if($openNew == false){
$dialogueCaseCardAll = array_merge($matchedCaseCardTop,$notMatchedCaseCardBelow);
}
if($dialogueCaseCardAll){
$ccId=$dialogueCaseCardAll[0]->getId();
if($ccId !="") {
$dialogueCaseCardObj = $em->getRepository(DialogueCaseCard::class)->find($ccId);
$session->set("dccId", $dialogueCaseCardObj->getId());
$pCaseCardId = $dialogueCaseCardObj->getPCaseCardId()->getId();
$dialogueCaseCardControllerObj = new DialogueCaseCardController();
$dialogueCaseCardData = $dialogueCaseCardControllerObj->defaultContentForCaseCard($request,$em,$user,$ccId);
$dialogueCaseCardMeasureControllerObj = new DialogueCaseCardMeasureController();
$dialogueCaseCardMeasureData = $dialogueCaseCardMeasureControllerObj->getDefaultDialogueCaseCardMeasure($request,$em,$user,$pCaseCardId);
$viewData['dialogueCaseCardObj'] = $dialogueCaseCardObj;
$viewData['ccId'] = $ccId;
$viewData['pCaseCardId'] = $pCaseCardId ;
$viewData['dialogueCaseCardAll'] = $dialogueCaseCardAll;
$viewData['dialogueCaseCardMeasureAll'] = $dialogueCaseCardMeasureData['dialogueCaseCardMeasureAll'];
$viewData['allSkabelonRecords'] = $dialogueCaseCardData['allSkabelonRecords'];
$viewData['recordCount'] = $dialogueCaseCardData['recordCount'];
$viewData['casecardMeasureAll'] = $dialogueCaseCardMeasureData['casecardMeasureAll'];
$viewData['caseCardMeasureTypeAll'] = $dialogueCaseCardMeasureData['caseCardMeasureTypeAll'];
$viewData['casecardMeasureFormAll'] = $dialogueCaseCardMeasureData['casecardMeasureFormAll'];
$viewData['caseCardStatusAll'] = $dialogueCaseCardMeasureData['caseCardStatusAll'];
$viewData['holds'] = $dialogueCaseCardMeasureData['holds'];
$viewData['holdCountList'] = $dialogueCaseCardMeasureData['holdCountList'];
$viewData['patientAge'] = $dateDiff;
$viewData['combo1'] = $dialogueCaseCardMeasureData['combo1'];
$viewData['combo2'] = $dialogueCaseCardMeasureData['combo2'];
$viewData['inactiveHoursArray'] = $dialogueCaseCardMeasureData['inactiveHoursArray'];
$viewData['combo2'] = $dialogueCaseCardMeasureData['combo2'];
$viewData['loginUser'] = $user;
$viewData['isClosedCaseCard'] = $dialogueCaseCardMeasureData['isClosedCaseCard'];
$viewData['orderBy'] = $dialogueCaseCardMeasureData['orderBy'];
}
}
}
//$joGroup = new JoGroup();
//$joGroupForm = $this->createForm(JoGroupType::class, $joGroup);
//for maintain log for case no when click name of patient on index page
if($dialogue->getdialogueType() == 3 || $dialogue->getdialogueType() == 4){
$this->maintaineUserLog($em,$user,$dialogue->getCaseNo(),'','','','','','');
}
return $this->render("default/caseDetailOverview.html.twig", $viewData);
}
public function getBirthDate($cpr) {
$d = intval(substr($cpr, 0, 2));
$m = intval(substr($cpr, 2, 2));
$today_obj = new \DateTime();
$currentYear = $today_obj->format('y');
//$y = intval((intval(substr($this->cpr, 6, 1)) < 5 ? "19" : "20") . substr($this->cpr, 4, 2));
//$y = intval((intval(substr($cpr, 4, 2)) <= $currentYear ? "20" : "19") . substr($cpr, 4, 2));
$digit = intval(substr($cpr, 6, 1));
$digit56 = intval(substr($cpr, 4, 2));
$y = ((($digit >=0 && $digit<=3) || (($digit == 4 || $digit == 9) && ($digit56 > 36))) ? "19" : "20").substr($cpr, 4, 2);
$tstamp = mktime(null, null, null, $m, $d, $y);
return $tstamp == false ? null : new \DateTime('@' . $tstamp);
}
public function getUserAge($bdate) {
//$bday = new \DateTime('02.11.1986'); // Your date of birth d.m.Y
$bday = new \DateTime($bdate); // Your date of birth d.m.Y
$today = new \Datetime(date('m.d.y'));
$diff = $today->diff($bday);
return $diff;
//printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
}
public function addNote(Request $request) {
$em = $this->getDoctrine()->getManager();
$caseCard = $request->get('caseCard');
$headingNote = trim($request->get('headingNote'));
$selectDate = $request->get('selectDateNote');
$reminderDate = $request->get('reminderDate');
$noteText = trim($request->get('noteText'));
$isDraft = $request->get('isDraft');
$visibleStatus = $request->get('visibleStatus');
//$patient = $em->getRepository(Patient::class)->find(1);
//$dialogue = $em->getRepository(Dialogue::class)->find(1);
//$user = $em->getRepository(User::class)->find(1);
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
//$user = $em->getRepository(User::class)->find(1);
$user = $this->get('security.token_storage')->getToken()->getUser();
$dialogueNotes = new DialogueNotes();
$dialogueNotes->setPatient($patient);
$dialogueNotes->setDialogue($dialogue);
if ($selectDate != "") {
$dialogueNotes->setNoteDate(new \DateTime($selectDate));
}
if ($reminderDate != "") {
$dialogueNotes->setReminderDate(new \DateTime($reminderDate));
}
$dialogueNotes->setNoteText($noteText);
$dialogueNotes->setCaseCard($caseCard);
$dialogueNotes->setNoteHeading($headingNote);
$dialogueNotes->setUser($user);
$dialogueNotes->setIsDraft($isDraft);
$dialogueNotes->setVisibleStatus($visibleStatus);
$em->persist($dialogueNotes);
$em->flush();
// return "success";
$responce = "success";
return new Response($responce);
// echo "here";die;
}
public function editView(Request $request) {
$em = $this->getDoctrine()->getManager();
$dataId = $request->get('dataId');
//$grpCreater = $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $dataId));
$grpCreater = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $dataId));
return $this->render("default/editView.html.twig", array('grpCreater' => $grpCreater));
}
public function editTemplateStatusView(Request $request) {
$em = $this->getDoctrine()->getManager();
$dataId = $request->get('dataId');
//$grpCreater = $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $dataId));
$grpCreater = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $dataId));
return $this->render("default/edittemplateStatusView.html.twig", array('grpCreater' => $grpCreater));
}
public function editNote(Request $request) {
$em = $this->getDoctrine()->getManager();
$selectedNote = $request->get('selectedNote');
$caseCard = $request->get('caseCard');
$headingNote = trim($request->get('headingNote'));
$selectDate = $request->get('selectDateNote');
$reminderDate = $request->get('reminderDate');
$noteText = trim($request->get('noteText'));
$isDraft = $request->get('isDraft');
$visibleStatus = $request->get('visibleStatus');
//$patient = $em->getRepository(Patient::class)->find(1);
//$dialogue = $em->getRepository(Dialogue::class)->find(1);
//$user = $em->getRepository(User::class)->find(1);
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
$user = $this->get('security.token_storage')->getToken()->getUser();
$dialogueNotes = $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $selectedNote));
$dialogueNotes->setPatient($patient);
$dialogueNotes->setDialogue($dialogue);
if ($selectDate != "") {
$dialogueNotes->setNoteDate(new \DateTime($selectDate));
}
if ($reminderDate != "") {
$dialogueNotes->setReminderDate(new \DateTime($reminderDate));
}
$dialogueNotes->setNoteText($noteText);
$dialogueNotes->setCaseCard($caseCard);
$dialogueNotes->setNoteHeading($headingNote);
$dialogueNotes->setUser($user);
$dialogueNotes->setIsDraft($isDraft);
$dialogueNotes->setVisibleStatus($visibleStatus);
$em->persist($dialogueNotes);
$em->flush();
$responce = "success";
return new Response($responce);
}
public function createDialogueCaseCard(Request $request) {
$card = new DialogueCaseCard();
$form = $this->createForm(DialogueCaseCardType::class, $card);
$form->handleRequest($request);
$entityManager = $this->getDoctrine()->getManager();
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedDialgoue = $session->get("selectedDialogue", false);
if ($form->isSubmitted() && $form->isValid()) {
$dialogueObj = $em->getRepository(Dialogue::class)->find($selectedDialgoue->getId());
$card->setPatient($dialogueObj->getPatient());
$card->setDialogue($dialogueObj);
$user = $this->get('security.token_storage')->getToken()->getUser();
$card->setCreatedBy($user);
$entityManager->persist($card);
$entityManager->flush();
$dialogueCaseCardControllerObj = new DialogueCaseCardController();
$history = $dialogueCaseCardControllerObj->saveCaseCardHistory($entityManager, $card, 'N',$dialogueObj,null, $user);
$case_detail_overview_url = $this->generateUrl('case_detail_overview', array('open' => 'true'));
return $this->redirect($case_detail_overview_url);
}
}
public function deleteNote(Request $request) {
$em = $this->getDoctrine()->getManager();
$selectedNote = $request->get('selectedNote');
$parentNote = $request->get('parentNote');
$user = $this->get('security.token_storage')->getToken()->getUser();
//$dialogueNotes = $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $selectedNote));
$dialogueNotes = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $selectedNote));
if($dialogueNotes){
foreach ($dialogueNotes->getDialogueAttachmentDetails() as $childNoteObj) {
if ($childNoteObj) {
$childNoteDeleteObj = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $childNoteObj->getId()));
$em->remove($childNoteDeleteObj);
$em->flush();
}
}
}
$em->remove($dialogueNotes);
$em->flush();
// $responce = "success";
// return new Response($responce);
$dialogueAttachmentDetails = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('id' => $parentNote));
$i = 0;
foreach($dialogueAttachmentDetails as $dialogueAttachment)
{
$noteQuery = $em->createQuery("SELECT dad FROM App\Entity\DialogueAttachmentDetails dad
WHERE dad.parentId =:parentId order by dad.updatedAt DESC")
->setParameter('parentId', $dialogueAttachment->getId());
$noteIds = $noteQuery->execute();
$dialogueAttachmentArray[$dialogueAttachment->getId()] = $noteIds;
$i++;
}
return $this->render("default/dialogueNoteAttachmentDetailsUpdated.html.twig", array(
'dialogueAttachmentArray' => $dialogueAttachmentArray,
'dialogueAttachmentDetails' => $dialogueAttachmentDetails,
'user' => $user
));
}
public function loadDialogue(Request $request, $id,$detailviewId) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$isRentalSystemAccessible = $this->container->getParameter('isRentalSystemAccessible');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$user = $this->get('security.token_storage')->getToken()->getUser();
$session->set("isRentalSystemAccessible", $isRentalSystemAccessible ? true : false);
$dialogue = $em->getRepository(Dialogue::class)->find($id);
$postMailControllerObj = new PostMailController();
$userRoleType = $user->hasRole('ROLE_CSV') ? 1 : ($user->hasRole('ROLE_DTS') ? 2 : 0);
$userRoleTypeText = $user->hasRole('ROLE_CSV') ? 'ROLE_CSV' : ($user->hasRole('ROLE_DTS') ? 'ROLE_DTS' : 0);
$patient = $em->getRepository(Patient::class)->find($dialogue->getPatient()->getId());
if($patient->getUserAge() != $patient->getChildAge()){
if($patient->getIsFakeCpr() != '1'){
$patient->setChildAge($patient->getUserAge());
}
$em->persist($patient);
$em->flush();
}
$dialogue->setUpdatedAt(new \DateTime());
$dialougeType = $dialogue->getDialogueType();
if(($dialougeType == 1 or $dialougeType == 2) && ($dialogue->getCaseNo() == NULL || $dialogue->getCaseNo() == '9001000') ) {
$dialogue->setCaseNo($dialogue->getUniqueCaseNumber());
} else if(($dialougeType == 3 or $dialougeType == 4) && ($dialogue->getCaseNo() == NULL) ) {
$dialogue->setCaseNo($dialogue->getUniqueGroupNumber());
}
$em->persist($dialogue);
if($dialougeType == 1 or $dialougeType == 2) {
$dal = new DialogueAccessLog();
$dal->createdBy = $this->get('security.token_storage')->getToken()->getUser();
$dal->setCreatedAt(new \DateTime());
$dal->dialogue = $dialogue;
$em->persist($dal);
$log = $this->checkAccessDialogOfDeceased($dialogue, $user, $patient);
}
//update phone number from nordjurrs
$this->addFlash("updateParentPhone", true);
//for maintain log for case no when click name of patient on index page
$this->maintaineUserLog($em,$user,$dialogue->getCaseNo(),'','','','','','');
//create dialougecase card details
$dialogueCaseCardObj = $this->createDefaultDialougeCaseCard($user,$patient,$dialogue);
$saveMeasure = $this->createMeasureOnLoad($dialogueCaseCardObj,$user);
//create default skelering activity
$checkForSkeleringobjs = $em->getRepository(DialogueAttachmentDetails::class)->checkSkeleringActivity($dialogue, $patient);
//echo count($checkForSkelering)."\n".$dialogue->getId()."".$patient->getId();
//die;
if(count($checkForSkeleringobjs)==0){
$checkForSkelerings = $em->getRepository(DialogueAttachmentDetails::class)->checkSkeleringActivityTrash($dialogue, $patient);
if($checkForSkelerings){
foreach ($checkForSkelerings as $skeleringActivity) {
$dialogueAttachmentDetailsObj = $em->getRepository(DialogueAttachmentDetails::class)->find($skeleringActivity['id']);
foreach ($dialogueAttachmentDetailsObj->getScalingProgressions() as $progressionObj) {
if ($progressionObj) {
$graphObjs = $em->getRepository(ScalingGraph::class)->findBy(array('progression' => $progressionObj->getId()));
foreach($graphObjs as $graphObj){
if($graphObj){
$em->remove($graphObj);
$em->flush();
}
}
$em->remove($progressionObj);
$em->flush();
}
}
$em->remove($dialogueAttachmentDetailsObj);
$em->flush();
}
}
$skeleringObj = $this->createSkelringCaseActivity($user,$patient,$dialogue,$dialogueCaseCardObj);
}
$isSavedAsActivity = false;
$getNotSavedAsActivityPostMails = $em->getRepository(JoPostMail::class)->getNotSavedAsActivityPostMails($isSavedAsActivity, $dialogue);
//$predefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->getFirstPreCaseCardByUserType($userRoleTypeText);
//$postMailControllerObj->createReminderActivityAsPostMail($request, $em, $user, $predefinedCaseCardObj, $patient, $dialogue, $getNotSavedAsActivityPostMails);
$session->set("postMailCnt", count($getNotSavedAsActivityPostMails));
//$getLatestJoCaseCommentsCount = $em->getRepository(JoCaseComments::class)->getLatestJoCaseCommentsCount($dialogue);
//$session->set("caseCommentsCount", $getLatestJoCaseCommentsCount);
$getLatestJoCaseComments = $em->getRepository(JoCaseComments::class)->getLatestJoCaseComments($dialogue,$user);
$isReadAllComments = 'true';
foreach($getLatestJoCaseComments as $joCaseCommentObj) {
$joCaseCommentsLogObj = $em->getRepository(JoCaseCommentsLog::class)->findOneBy(array('JoCaseComments' => $joCaseCommentObj, 'User' => $user));
if(!$joCaseCommentsLogObj) {
$isReadAllComments = 'false';
break;
}
}
$getLatestJoCaseMemos = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue,$user);
$getLatestSentJoCaseMemos = $em->getRepository(JoCaseMemos::class)->getLatestSentJoCaseMemos($dialogue,$user);
$getLatestJoCaseMemosReminder = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($dialogue,$user);
$session->set("caseCommentsCount", count($getLatestJoCaseComments));
$session->set("caseMemoCount",count($getLatestJoCaseMemos));
$session->set("isReadAllComments", $isReadAllComments);
$komunneIdsArray = array(
'101' => 'København',
'147' => 'Frederiksberg',
'151' => 'Ballerup',
'153' => 'Brøndby',
'155' => 'Dragør',
'157' => 'Gentofte',
'159' => 'Gladsaxe',
'161' => 'Glostrup',
'163' => 'Herlev',
'165' => 'Albertslund',
'167' => 'Hvidovre',
'169' => 'Høje-Taastrup',
'173' => 'Lyngby-Taarbæk',
'175' => 'Rødovre',
'183' => 'Ishøj',
'185' => 'Tårnby',
'187' => 'Vallensbæk',
'190' => 'Furesø',
'201' => 'Allerød',
'210' => 'Fredensborg',
'217' => 'Helsingør',
'219' => 'Hillerød',
'223' => 'Hørsholm',
'230' => 'Rudersdal',
'240' => 'Egedal',
'250' => 'Frederikssund',
'253' => 'Greve',
'259' => 'Køge',
'260' => 'Halsnæs',
'265' => 'Roskilde',
'269' => 'Solrød',
'270' => 'Gribskov',
'306' => 'Odsherred',
'316' => 'Holbæk',
'320' => 'Faxe',
'326' => 'Kalundborg',
'329' => 'Ringsted',
'330' => 'Slagelse',
'336' => 'Stevns',
'340' => 'Sorø',
'350' => 'Lejre',
'360' => 'Lolland',
'370' => 'Næstved',
'376' => 'Guldborgsund',
'390' => 'Vordingborg',
'400' => 'Bornholm',
'410' => 'Middelfart',
'411' => 'Christiansø',
'420' => 'Assens',
'430' => 'Faaborg-Midtfyn',
'440' => 'Kerteminde',
'450' => 'Nyborg',
'461' => 'Odense',
'479' => 'Svendborg',
'480' => 'Nordfyns',
'482' => 'Langeland',
'492' => 'Ærø',
'510' => 'Haderslev',
'530' => 'Billund',
'540' => 'Sønderborg',
'550' => 'Tønder',
'561' => 'Esbjerg',
'563' => 'Fanø',
'573' => 'Varde',
'575' => 'Vejen',
'580' => 'Aabenraa',
'607' => 'Fredericia',
'615' => 'Horsens',
'621' => 'Kolding',
'630' => 'Vejle',
'657' => 'Herning',
'661' => 'Holstebro',
'665' => 'Lemvig',
'671' => 'Struer',
'706' => 'Syddjurs',
'707' => 'Norddjurs',
'710' => 'Favrskov',
'727' => 'Odder',
'730' => 'Randers',
'740' => 'Silkeborg',
'741' => 'Samsø',
'746' => 'Skanderborg',
'751' => 'Aarhus',
'756' => 'Ikast-Brande',
'760' => 'Ringkøbing-Skjern',
'766' => 'Hedensted',
'773' => 'Morsø',
'779' => 'Skive',
'787' => 'Thisted',
'791' => 'Viborg',
'810' => 'Brønderslev',
'813' => 'Frederikshavn',
'820' => 'Vesthimmerlands',
'825' => 'Læsø',
'840' => 'Rebild',
'846' => 'Mariagerfjord',
'849' => 'Jammerbugt',
'851' => 'Aalborg',
'860' => 'Hjørring');
$komunneId = $patient->getKommuneId();
//var_dump($komunneId);
if (array_key_exists($komunneId,$komunneIdsArray)) {
$session->set("komunneName", $komunneIdsArray[$komunneId]);
$session->set("komunneId",$komunneId);
}else if($patient->getIsDummyPatient()) {
$session->set("komunneName", "Københavns");
$session->set("komunneId",0);
} else {
$session->set("komunneName", "");
$session->set("komunneId","");
}
//update ALL data in stamdata first time a case is opened on a given day
if($patient && !($patient->getIsDummyPatient()) && !($patient->getIsFakeCpr())) {
$nextStamdataCallDateObj = $patient->getNextStamdataCall();
if(!is_null($nextStamdataCallDateObj)){
$nextStamdataCallDate = $nextStamdataCallDateObj->format('d-m-Y');
}
$todayDate = new \DateTime();
$todayDateFormatted = $todayDate->format('d-m-Y');
$tomorrowDate = new \DateTime('+6 days');
$tomorrowDateFormatted = $tomorrowDate->format('d-m-Y');
//var_dump($nextStamdataCallDate, $todayDateFormatted); die;
//var_dump(is_null($nextStamdataCallDate), strtotime($todayDateFormatted) , strtotime($nextStamdataCallDate) ); die;
if(is_null($nextStamdataCallDateObj) || (strtotime($nextStamdataCallDate) <= strtotime($todayDateFormatted))) {
$userProfession = $user->getProfession();
if($userProfession){ // update user profession in pcascecard field
if (strpos($userProfession, ',') !== false) {
$userProfession = substr($userProfession, 0, strpos($userProfession, ","));
}
if(strlen($userProfession) > 5){
$userProfession = substr($userProfession, 0, -3);
}
$userRole = "ROLE_DTS";
if ($user->hasRole('ROLE_CSV')) {
$userRole = "ROLE_CSV";
}
$userDefaultSelectedCC = $em->getRepository(PredefinedCaseCard::class)->userDefaultSelectedCC($userRole, trim($userProfession));
if($userDefaultSelectedCC){
$user->setPredefinedCaseCard($userDefaultSelectedCC);
$em->persist($user);
$em->flush();
}
}
// $this->updateAllStamdata($patient, $session);
//Update citizen school and institude information from IST_ELEV and IST_ELEV_UDV entity
$this->updateStamdataISTElevData($patient, $session);
//var_Dump($tomorrowDateFormatted, $tomorrowDate); die;
//$patient->setNextStamdataCall($tomorrowDate);
$em->persist($patient);
}
}
$em->flush();
//$type = "1";
//$message = "Amol Is so smart";
//$notificationObj = $this->setNotificationData($em, $dialogue, $user, $type, $message);
//$notificationLogObj = $this->setNotificationLogData($em, $dialogue, $user, $notificationObj);
$em->detach($patient);
$em->detach($dialogue);
$selectedPatient = $session->set("selectedPatient", $patient);
$selectedDialogue = $session->set("selectedDialogue", $dialogue);
$session->set("isJoGroupExist", false);
$session->set("selectedJoGroup", null);
if($dialogue->getDialogueType() == 1 || $dialogue->getDialogueType() == 2){
$measureList = $em->getRepository(DialogueCaseCardMeasure::class)->fetchMeasuresWithStatusAfventer($patient->getId());
$waitingList = $em->getRepository(JoGroupWaitinglist::class)->fetchWaitingListFOrPatient($patient->getId());
$waitingListCount = count($measureList) + count($waitingList);
$session->set('waitingListCount',$waitingListCount,false);
}
//Get rental default listing
$defaultRentalList = $em->getRepository(RbRental::class)->getDefaultRentalList($patient);
$session->set("rentalItemCnt", count($defaultRentalList));
$myHuskeseddelReminder = $em->getRepository(JoCaseMemos::class)->getMemosReminderForUser($dialogue , $user);
$session->set("myHuskeseddelReminderCount", count($myHuskeseddelReminder));
$myMemo = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue , $user);
$session->set("myMemoCount", count($myMemo));
if($isReadAllComments === 'false') {
return $this->redirectToRoute('case_comment_overview');
}
if($detailviewId) {
$isMemo = explode("me_",$detailviewId);
if(count($isMemo) === 2) {
if (strpos($isMemo[1], '_sent') !== false) {
$session->set("openSentMemo", true);
}
return $this->redirectToRoute('case_memo_overview');
}
return $this->redirectToRoute('case_detail_view',['detailviewId' => $detailviewId]);
} else {
return $this->redirectToRoute('case_detail_view');
}
}
public function checkAccessDialogOfDeceased ($dialogue, $user, $patient ){
$em = $this->getDoctrine()->getManager();
$this->addFlash("citizenDeceased", '');
$this->addFlash("parentDeceased", '');
//for Citizen deceased
if($patient->getIsDeceased() == 1){
$JoPatientIsdeceasedLog = $em->getRepository(JoPatientIsdeceasedLog::class)->findBy(array('dialogue' => $dialogue, 'loggedUser' => $user, 'User' => $patient->getUser()));
if(!$JoPatientIsdeceasedLog){
//$session->set("citizenDeceased", $patient->getDeceaseDate()->format('d-m-Y'));
$this->addFlash("citizenDeceased", $patient->getDeceaseDate()->format('d-m-Y'));
$newJoPatientIsdeceasedLog = new JoPatientIsdeceasedLog();
$newJoPatientIsdeceasedLog->setDialogue($dialogue);
$newJoPatientIsdeceasedLog->setLoggedUser($user);
$newJoPatientIsdeceasedLog->setUser($patient->getUser());
$em->persist($newJoPatientIsdeceasedLog);
$em->flush();
}
}
//for Parents deceased
$patientFamilyObj = $em->getRepository(Family::class)->findBy(array('patient' => $patient));
foreach ($patientFamilyObj as $patientFamily) {
if ($patientFamily->getRelation() == "1" || $patientFamily->getRelation() == "2" || $patientFamily->getRelation() == "3" || $patientFamily->getRelation() == "4") {
if($patientFamily->getIsDeceased() == 1){
$JoPatientIsdeceasedLog = $em->getRepository(JoPatientIsdeceasedLog::class)->findBy(array('dialogue' => $dialogue, 'loggedUser' => $user, 'User' => $patientFamily->getRelative()));
if(!$JoPatientIsdeceasedLog){
//$session->set("parentDeceased", $patientFamily->getDeceaseDate()->format('d-m-Y'));
$this->addFlash("parentDeceased", $patientFamily->getDeceaseDate()->format('d-m-Y'));
$newJoPatientIsdeceasedLog = new JoPatientIsdeceasedLog();
$newJoPatientIsdeceasedLog->setDialogue($dialogue);
$newJoPatientIsdeceasedLog->setLoggedUser($user);
$newJoPatientIsdeceasedLog->setUser($patientFamily->getRelative());
$em->persist($newJoPatientIsdeceasedLog);
$em->flush();
break;
}
}
}
}
return true;
}
public function deleteView(Request $request) {
$em = $this->getDoctrine()->getManager();
$dataId = $request->get('dataId');
//$grpCreater = $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $dataId));
$grpCreater = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $dataId));
return $this->render("default/deleteView.html.twig", array('grpCreater' => $grpCreater));
}
public function editStamdataProfile(Request $request, $familyId) {
$em = $this->getDoctrine()->getManager();
$user = $this->get('security.token_storage')->getToken()->getUser();
$session = $request->getSession();
$childRelation = $request->get('childRelation');
$selectedPatient = $session->get("selectedPatient", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$familyDetails = $em->getRepository(Family::class)->find($familyId);
if($this->get('security.authorization_checker')->isGranted('ROLE_PARENT')) {
return $this->render("dialogue/citizen-edit-stamdata-profile.html.twig", array('familyDetails' => $familyDetails, 'patientObj' => $patient, 'childRelation' => $childRelation));
}else{
return $this->render("dialogue/edit-stamdata-profile.html.twig", array('familyDetails' => $familyDetails, 'patientObj' => $patient, 'childRelation' => $childRelation));
}
}
public function saveStamdataProfile(Request $request, $userId) {
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$loginUser = $this->get('security.token_storage')->getToken()->getUser();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$responce = 'fail';
$motherTongue = $request->get('mother_tongue');
$phoneNo1 = $request->get('phoneno1');
$phoneNo2 = $request->get('phoneno2');
$phoneNo3 = $request->get('phoneno3');
$smsOne = $request->get('smsOne');
$smsTwo = $request->get('smsTwo');
$smsThree = $request->get('smsThree');
$needTranslator = $request->get('needTranslator');
$secretAddress = $request->get('secretAddress');
$oralConsentDate = $request->get('oralConsentDate');
$oralConsentText = $request->get('oralConsentText');
$isSecretNumber = $request->get('isSecretNumber',null);
$isSecretNumber2 = $request->get('isSecretNumber2',null);
$dialogue = NULL;
$mobile_1_code = trim($request->get('mobile_1_code'));
if(strlen($mobile_1_code) > 1 && $phoneNo1 !=""){
$phoneNo1 = $mobile_1_code.'-'.$phoneNo1;
}
$mobile_2_code = trim($request->get('mobile_2_code'));
if(strlen($mobile_2_code) > 1 && $phoneNo2 !=""){
$phoneNo2 = $mobile_2_code.'-'.$phoneNo2;
}
//echo $motherTongue.", ".$phoneNo.", ".$needTranslator.", ".$secretAddress.", ";die;
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$userObj = $em->getRepository(User::class)->find($userId);
if($selectedDialogue){
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
}
//var_dump($userObj);die;
if($motherTongue){
$userObj->setNativeLanguage($motherTongue);
}
//if($phoneNo1){
$userObj->setmobileNo($phoneNo1);
//}
// if($phoneNo2){
$userObj->setmobileNo2($phoneNo2);
// }
//if($phoneNo3){
$userObj->setmobileNo3($phoneNo3);
// }
//if($smsOne){
$userObj->setSmsOne($smsOne);
//}
//if($smsTwo){
$userObj->setSmsTwo($smsTwo);
//}
if($smsThree){
$userObj->setSmsThree($smsThree);
}
//if($needTranslator){
$userObj->setTranslate($needTranslator);
//}
//if($secretAddress){
$userObj->setIsSecretAddress($secretAddress);
//}
//if($isSecretNumber){
$userObj->setIsSecretNumber($isSecretNumber);
//}
$userObj->setIsSecretNumber2($isSecretNumber2);
$em->persist($userObj);
$em->flush();
$familyObj = $em->getRepository(Family::class)->findOneBy(array("relative" => $userObj, 'patient' => $patient));
if ($oralConsentDate != '') {
$oralConsentDate = new \DateTime($oralConsentDate);
$familyObj->setOralConsentDate($oralConsentDate);
} else {
$familyObj->setOralConsentDate(null);
}
if ($oralConsentText != '') {
$familyObj->setOralConsentText($oralConsentText);
} else {
$familyObj->setOralConsentText('');
}
//Save oral consent record in dialogue multiple attachement table to send the ebook message
$patientOralConsentText = trim($familyObj->getOralConsentText());
if(isset($dialogue)){
$dialogueAttachmentObj = $em->getRepository(DialogueMultipleAttachment::class)->findOneBy(array('patient' => $patient, 'dialogue' => $dialogue, 'isOralConsent' => true, 'oralConsentGivenBy' => $userObj));
if ((!$dialogueAttachmentObj) && strlen($patientOralConsentText) > 0 && isset($dialogue)) {
$dialogueAttachmentObj = new DialogueMultipleAttachment();
$dialogueAttachmentObj->setPatient($patient);
$dialogueAttachmentObj->setDialogue($dialogue);
$dialogueAttachmentObj->setUser($loginUser);
$dialogueAttachmentObj->setAttachmentName(NULL);
$dialogueAttachmentObj->setOriginalName(NULL);
$dialogueAttachmentObj->setIsDeleted(false);
$dialogueAttachmentObj->setIsDefault(true);
$dialogueAttachmentObj->setSequenceNumber(0);
$dialogueAttachmentObj->setIsOralConsent(1);
$dialogueAttachmentObj->setOralConsentGivenBy($userObj);
$em->persist($dialogueAttachmentObj);
$em->flush();
}
}
//update phone number in nordjurrs
$NotatController = new NotatWorkFlowController();
$updateParentPhone = $NotatController->updateParentPhoneInNorddjurs($em,$patient,$phoneNo1,$phoneNo2,$familyObj->getRelation(),$this->container);
$em->persist($familyObj);
$em->flush();
$this->updatePatientDate($patient);
$patient->setUpdatedBy($loginUser);
$em->persist($patient);
$em->flush();
$responce = 'success';
$response = new Response(json_encode(array('result' => $responce)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function searchCaseOverview(Request $request) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
//var_dump($selectedPatient->getId(), $selectedDialogue->getId()); die;
if (!$selectedPatient) {
return $this->redirect($this->generateUrl('index'));
}
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
//$user = $em->getRepository(User::class)->find(1);
$user = $this->get('security.token_storage')->getToken()->getUser();
$patient = $dialogue->getPatient();
$session->set("selectedDialogue", $dialogue);
$session->set("selectedPatient", $patient);
//Search filter paramenters
$searchByTypeHeading = trim($request->get('searchByTypeHeading'));
$filtercasecardids = trim($request->get('filtercasecardids'));
$filterstatusids = trim($request->get('filterstatusids'));
$filtertypeids = trim($request->get('filtertypeids'));
$filterfromdate = trim($request->get('filterfromdate'));
$filtertodate = trim($request->get('filtertodate'));
$filteruserid = trim($request->get('filteruserid'));
$filterbyyearly = trim($request->get('filterbyyearly'));
$filterByQuarter = trim($request->get('filterByQuarter'));
//$selectedDialogue = $dialogue;
//$cpr = "111111";
$cpr = $patient->getCpr();
$getFullDate = $this->getBirthDate($cpr);
$bdateYear = date_format($getFullDate, "d.m.Y");
$dateDiff = $this->getUserAge($bdateYear);
$sortBy = $request->get('sortBy');
$orderBy = $request->get('orderBy');
$showFutureActivities = $request->get('showFutureActivities');
$searchFilter = "ROLE_DTS";
if ($user->hasRole('ROLE_CSV')) {
$searchFilter = "ROLE_CSV";
}
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForIndividual' => 1));
$predefinedCaseCardAllIds = array();
$joPredefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'josa_rapport'));
if($joPredefinedCaseCardObj){
$predefinedCaseCardAllIds[] = $joPredefinedCaseCardObj->getId();
}
$joPredefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'Sagsgrundlag'));
if($joPredefinedCaseCardObj){
$predefinedCaseCardAllIds[] = $joPredefinedCaseCardObj->getId();
}
$joGroupObj = NULL;
if(($dialogue->getDialogueType() == 3 || $dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_DTS" ) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
//$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCardListByType($searchFilter, $joGroupObj->getJoMasterInformation()->getInfoType(), $joGroupObj->getJoMasterInformation()->getKkorg());
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => '1'));
} else if(($dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_CSV" ) {
$joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => 1));
}
//$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findAll();
//$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findById(array(1, 2, 3, 4, 6, 9, 11,12));
$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findBy(array('isActivityType' => 1), array('orderBy' => 'asc'));
$dialogueCaseCardAll = $em->getRepository(DialogueCaseCard::class)->findBy(array('dialogue' => $selectedDialogue));
$userCreatedCaseCardsId = $userCreatedDialogueCaseCard = array();
foreach ($dialogueCaseCardAll as $dialogueCaseCard) {
$userCreatedCaseCardsId[] = $dialogueCaseCard->getPCaseCardId()->getId();
$userCreatedDialogueCaseCard[$dialogueCaseCard->getPCaseCardId()->getId()] = $dialogueCaseCard->getId();
}
//Delete DialogueAttachmentDetails activity if no borgerplan is attached to this
$checkActivityNotAttachedToEventsCnt = $em->getRepository(DialogueAttachmentDetails::class)->checkActivityNotAttachedToEventsCnt($dialogue, $user);
if(count($checkActivityNotAttachedToEventsCnt) > 0) {
foreach($checkActivityNotAttachedToEventsCnt as $dialogueAttachmentDetail) {
if($dialogueAttachmentDetail){
$JoCaseCardEventBrevActivityObj = $em->getRepository(JoCaseCardEventBrevActivity::class)->findOneBy(array('attachmentDetails' => $dialogueAttachmentDetail));
if($JoCaseCardEventBrevActivityObj){
$em->remove($JoCaseCardEventBrevActivityObj);
$em->flush();
}
$em->remove($dialogueAttachmentDetail);
$em->flush();
}
}
}
if ($user->hasRole('ROLE_PARENT')) {
$activitySharing = $em->getRepository(JoActivitySharing::class)->findOneBy(array('dialogue' => $dialogue));
if($activitySharing){
$loggedInUser = $session->get("loggedInUser");
if($loggedInUser){ // for cpr and cvr users who have multiple entries in user table
$user = $em->getRepository(User::class)->find($loggedInUser->getId());
}
//$dialogueAttachmentDetailIds = $activitySharing->getLoggedInCitizenActivitiesForDialog($user);
$activitySharingParticipant = $em->getRepository(JoActivitySharingParticipant::class)->findOneBy(array('joActivitySharing' => $activitySharing, 'user' => $user));
if($activitySharingParticipant){
$dialogueAttachmentDetailIds = $activitySharingParticipant->getLoggedInCitizenActivitiesForDialog();
}else{
$dialogueAttachmentDetailIds = array();
}
}else{
$dialogueAttachmentDetailIds = array();
}
}else{
$dialogueAttachmentDetailIds = array();
}
$update_skalering = $this->updateSkaleringAttachment($dialogue,$patient,$em);
//$dialogueAttachmentDetails = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient),array('attachmentDate' => 'desc'));
$dialogueAttachmentFilter = $em->getRepository(DialogueAttachmentDetails::class)->filterDialogueAttachmentDetails($dialogue, $patient, $searchByTypeHeading, $filtercasecardids, $filterstatusids, $filtertypeids, $filterfromdate, $filtertodate, $filteruserid, $filterbyyearly, $filterByQuarter,$sortBy,$orderBy ,$dialogueAttachmentDetailIds, $showFutureActivities, $user );
$dialogueAttachmentDetails = $dialogueAttachmentFilter['result'];
$futureActivitiesCount = $dialogueAttachmentFilter['futureActivitiesCount'];
$relatedRecordsDetails = [];
$isAttachmentDateUpdated = false;
$tunnelshareActivity=array();
foreach ($dialogueAttachmentDetails as $attachmentDetailObj) {
if ($sortBy == 'measureName') {
$attachmentDetailObj = $attachmentDetailObj[0];
}
if ($attachmentDetailObj->getPAtttachmentType()->getId() == 8) {
foreach ($attachmentDetailObj->getJoCaseCardEvents() as $eventObj) {
$eventStartAt = strtotime($eventObj->getStartAt()->format('Y-m-d'));
$currentDate = strtotime("now");
if(strtotime($attachmentDetailObj->getAttachmentDate()->format('Y-m-d')) != strtotime($eventObj->getStartAt()->format('Y-m-d')) ) {
if ($eventStartAt < $currentDate) {
$attachmentDetailObj->setAttachmentDate($eventObj->getStartAt());
$em->persist($attachmentDetailObj);
$em->flush();
$isAttachmentDateUpdated = true;
}else if($dialogue->getDialogueType() == 3 || $dialogue->getDialogueType() == 4){
$attachmentDetailObj->setAttachmentDate($eventObj->getStartAt());
$em->persist($attachmentDetailObj);
$em->flush();
$isAttachmentDateUpdated = true;
}
}
if($attachmentDetailObj->getPatient()->getUser() != NULL && $attachmentDetailObj->getPatient()->getUser()->getId() == $patient->getUser()->getId()){
$relatedRecords = $em->getRepository(JoCaseCardEvent::class)->findChildIndividualDialogEventList($dialogue,$eventObj->getDialogueCaseCard(),$eventObj->getDialogueCaseCardMeasure(),$eventObj->getHeading(),$eventObj->getEventCollection());
if(count($relatedRecords) > 0 ){
$relatedRecordsDetails[$attachmentDetailObj->getId()]['index'] = array_search($eventObj, $relatedRecords) + 1;
$relatedRecordsDetails[$attachmentDetailObj->getId()]['count'] = count( $relatedRecords);
$min = $relatedRecords[0];
for ($i = 1; $i < count($relatedRecords); $i++)
if ($relatedRecords[$i]->getId() < $min->getId())
$min = $relatedRecords[$i];
$relatedRecordsDetails[$attachmentDetailObj->getId()]['link_id'] = $min->getId();
}
}
}
}
$tunnelRid= $attachmentDetailObj->getTunnelListId();
if($tunnelRid){
$tunnelDetailsObj = $em->getRepository(SepoTunnelliste::class)->findOneBy(array('rid' => $tunnelRid));
if($tunnelDetailsObj){
$tunnelshareActivity[$tunnelRid]= array('name' => $tunnelDetailsObj->getName());
}
}
}
if($isAttachmentDateUpdated){
$dialogueAttachmentFilter = $em->getRepository(DialogueAttachmentDetails::class)->filterDialogueAttachmentDetails($dialogue, $patient, $searchByTypeHeading, $filtercasecardids, $filterstatusids, $filtertypeids, $filterfromdate, $filtertodate, $filteruserid, $filterbyyearly, $filterByQuarter,$sortBy,$orderBy, $dialogueAttachmentDetailIds, $showFutureActivities, $user );
$dialogueAttachmentDetails = $dialogueAttachmentFilter['result'];
$futureActivitiesCount = $dialogueAttachmentFilter['futureActivitiesCount'];
}
$dialogueAttachments = $em->getRepository(DialogueAttachments::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient));
/*$dialogueAttachments = $em->createQuery(
"SELECT dad FROM App\Entity\DialogueAttachmentDetails dad
where (dad.deletedBy IS NULL) and (dad.dialogue = :dialogue and dad.patient = :patient) and dad.isPostMailActivity = 0
order by dad.$sortBy " . $orderBy)
->setParameter('dialogue', $dialogue)
->setParameter('patient', $patient);*/
$dialogueAttachmentFileName = array();
foreach ($dialogueAttachments as $dialogueAttachment) {
$id = $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
$dialogueAttachmentFileName[$id]['files'][] = $dialogueAttachment;
}
$webPath = '/public/uploads/attachments/'; //$this->get('kernel')->getProjectDir() .
//var_dump($dialogueAttachmentFileName); die;
$dialogueNotes = $em->getRepository(DialogueNotes::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient));
//fetch all DialogueCaseCardMeasure related to ccId
//$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->findBy(array('referenceType' => 'F'));
$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->fetchMeasureTilDate('F',new \DateTime(),$user->getProfession());
$holdList = $em->getRepository(JoCaseCardHold::class)->findAll();
$brevActivityEvent = array();
$checkBrevActivityDetails = $em->getRepository(DialogueAttachmentDetails::class)->checkBrevActivityEvent($dialogue,$patient);
foreach ($checkBrevActivityDetails as $brevActivity) {
$brevActivityEvent[$brevActivity['id']]= array('eventId' => $brevActivity['eventId'],
'heading' => $brevActivity['heading'],
);
}
$i = 0;
foreach($dialogueAttachmentDetails as $dialogueAttachment)
{
$noteQuery = $em->createQuery("SELECT dad FROM App\Entity\DialogueAttachmentDetails dad
WHERE dad.parentId =:parentId order by dad.updatedAt DESC")
->setParameter('parentId', $dialogueAttachment->getId());
$noteIds = $noteQuery->execute();
$dialogueAttachmentArray[$dialogueAttachment->getId()] = $noteIds;
$i++;
}
return $this->render("default/dialogueNoteAttachmentDetails.html.twig", array(
'dateDiff' => $dateDiff,
'dialogueNotes' => $dialogueNotes,
'dialogueCaseCardAll' => $dialogueCaseCardAll,
'predefinedCaseCardAll' => $predefinedCaseCardAll,
'userCreatedCaseCardsId' => $userCreatedCaseCardsId,
'patientObj' => $patient,
'user' => $user,
'dialogue' => $dialogue,
'predefinedAttachmentType' => $predefinedAttachmentType,
'dialogueAttachmentDetails' => $dialogueAttachmentDetails,
'holdList' => $holdList,
'relatedRecordsDetails' => $relatedRecordsDetails,
'dialogueAttachmentFileName' => $dialogueAttachmentFileName,
'webPath' => $webPath,
'dialogueObj' => $dialogue,
'userCreatedDialogueCaseCard' => $userCreatedDialogueCaseCard,
'fromOverview' => 1,
'dialogueCaseCardMeasureAll' => $dialogueCaseCardMeasureAll,
'futureActivitiesCount' => $futureActivitiesCount,
'sortBy' => $sortBy,
'isFromFilter' => true,
'brevActivityEvent' => $brevActivityEvent,
'dialogueAttachmentArray' => $dialogueAttachmentArray
)
);
}
public function editChildProfile(Request $request, $childId) {
//echo 'editChildProfile call';die;
$em = $this->getDoctrine()->getManager();
$user = $this->get('security.token_storage')->getToken()->getUser();
$travelText = array();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$childInfo = $em->getRepository(User::class)->find($childId);
$currentDateTime = strtotime("now");
$patientInfo = $em->getRepository(Patient::class)->findOneBy(array('user' => $childId));
$patientTravelInfo = $em->getRepository(TravelNeedsDetails::class)->findBy(array('patient' => $selectedPatient));
if (count($patientTravelInfo) > 0) {
foreach ($patientTravelInfo as $text) {
$travelText[] = $text->getTravelNeedsText();
}
}
$needTextObj = new TravelNeedsDetails();
$patientTravelNeedsDetails_session = $session->get('needTravelInfo');
// var_dump($patientTravelNeedsDetails_session);die;
if (!is_null($patientTravelNeedsDetails_session)) {
$patientTravelInfo = [];
foreach ($patientTravelNeedsDetails_session as $key => $travelInfo) {
$travelObj = [];
$travelObj['travelNeedId'] = $key;
$travelObj['travelNeedsText'] = $travelInfo['name'];
$travelObj['travelNeedsFromDate'] = new \DateTime($travelInfo['fromDate']);
$travelObj['travelNeedsToDate'] = new \DateTime($travelInfo['toDate']);
array_push($patientTravelInfo, $travelObj);
}
}
$needTextOptions = $needTextObj::$travelNeedStrings;
//var_dump($patientTravelInfo);die;
$patientCoreAreas = $em->getRepository(PredefinedTravelsType::class)->findBy(array('status'=>'1'));
if($this->get('security.authorization_checker')->isGranted('ROLE_PARENT')) {
return $this->render("dialogue/citizen-edit-child-profile.html.twig", array('childInfo' => $childInfo, 'patientInfo' => $patientInfo, 'patientTravelInfo' => $patientTravelInfo, 'needTextOptions' => $needTextOptions, 'travelText' => $travelText, 'currentDateTime' => $currentDateTime,'patientCoreAreas'=>$patientCoreAreas));
}else{
return $this->render("dialogue/edit-child-profile.html.twig", array('childInfo' => $childInfo, 'patientInfo' => $patientInfo, 'patientTravelInfo' => $patientTravelInfo, 'needTextOptions' => $needTextOptions, 'travelText' => $travelText, 'currentDateTime' => $currentDateTime,'patientCoreAreas'=>$patientCoreAreas));
}
}
public function deleteChildProfileOralConsent(Request $request, $childId){
$em = $this->getDoctrine()->getManager();
$userObj = $em->getRepository(User::class)->find($childId);
$patientObj = $em->getRepository(Patient::class)->findOneBy(array('user' => $userObj));
$patientObj->setOralConsentText(NULL);
$patientObj->setOralConsentDate(NULL);
$em->persist($patientObj);
$em->flush();
$responce = 'success';
$response = new Response(json_encode(array('result' => $responce)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function deleteStamdataProfileOralConsent(Request $request, $userId){
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$userObj = $em->getRepository(User::class)->find($userId);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$familyObj = $em->getRepository(Family::class)->findOneBy(array("relative" => $userObj, 'patient' => $patient));
$familyObj->setOralConsentDate(NULL);
$familyObj->setOralConsentText(NULL);
$em->persist($familyObj);
$em->flush();
$responce = 'success';
$response = new Response(json_encode(array('result' => $responce)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function saveChildProfile(Request $request, $childId) {
$responce = 'fail';
$motherTongue = $request->get('mother_tongue');
$phoneNo = $request->get('phoneno');
$phoneNo2 = $request->get('phoneno2');
$phoneNo3 = $request->get('phoneno3');
$smsOne = $request->get('smsOne');
$smsTwo = $request->get('smsTwo');
$smsThree = $request->get('smsThree');
$needTranslator = $request->get('needTranslator');
$secretAddress = $request->get('secretAddress');
$em = $this->getDoctrine()->getManager();
$userObj = $em->getRepository(User::class)->find($childId);
$session = $request->getSession();
$selectedDialogue = $session->get("selectedDialogue", null);
$isSecretNumber = $request->get('isSecretNumber');
$isSecretNumber2 = $request->get('isSecretNumber2');
$needTravelInfo = $request->get('needTravelInfo');
$patientCoreArea = $request->get('patientCoreArea');
$patientCoreSubArea = $request->get('patientCoreSubArea');
$user = $this->get('security.token_storage')->getToken()->getUser();
$mobile_1_code = trim($request->get('mobile_1_code'));
if(strlen($mobile_1_code) > 1 && $phoneNo !=""){
$phoneNo = $mobile_1_code.'-'.$phoneNo;
}
$mobile_2_code = trim($request->get('mobile_2_code'));
if(strlen($mobile_2_code) > 1 && $phoneNo2 !=""){
$phoneNo2 = $mobile_2_code.'-'.$phoneNo2;
}
$tt = $request->get('isSecretNumber');
if ($selectedDialogue) {
$selectedDialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue);
}
$user = $this->get('security.token_storage')->getToken()->getUser();
$patientObj = $em->getRepository(Patient::class)->findOneBy(array('user' => $userObj));
$patient_dialogue = $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $patientObj));
$oralConsentText = trim($request->get('oralConsent'));
$oralConsentDate = $request->get('oralconsentselectdate');
$travelNeedsText = $request->get('travelneedsselecttotext');
$travelNeedsFromDate = $request->get('travelneedsselectfromdate');
$travleNeedsToDate = $request->get('travelneedsselecttodate');
$consentdatechanged = $request->get('oralconsentdatechanged');
$patientObj->setOralConsentText($oralConsentText);
if ($oralConsentDate != "") {
$patientObj->setOralConsentDate(new \DateTime($oralConsentDate));
} else {
$patientObj->setOralConsentDate(NULL);
}
//Save oral consent record in dialogue multiple attachement table to send the ebook message
$patientOralConsentText = trim($patientObj->getOralConsentText());
$dialogueAttachmentObj = $em->getRepository(DialogueMultipleAttachment::class)->findOneBy(array('patient' => $patientObj, 'dialogue' => $selectedDialogue, 'isOralConsent' => true, 'oralConsentGivenBy' => $userObj));
if ((!$dialogueAttachmentObj) && strlen($patientOralConsentText) > 0 && isset($selectedDialogue) ) {
$dialogueAttachmentObj = new DialogueMultipleAttachment();
$dialogueAttachmentObj->setPatient($patientObj);
$dialogueAttachmentObj->setDialogue($selectedDialogue);
$dialogueAttachmentObj->setUser($user);
$dialogueAttachmentObj->setAttachmentName(NULL);
$dialogueAttachmentObj->setOriginalName(NULL);
$dialogueAttachmentObj->setIsDeleted(false);
$dialogueAttachmentObj->setIsDefault(NULL);
$dialogueAttachmentObj->setSequenceNumber(NULL);
$dialogueAttachmentObj->setIsOralConsent(1);
$dialogueAttachmentObj->setOralConsentGivenBy($userObj);
$em->persist($dialogueAttachmentObj);
$em->flush();
}
if ($user->hasRole('ROLE_CSV')) {
$selectedTravelNeeds = $em->getRepository(TravelNeedsDetails::class)->findBy(array('patient' => $patientObj, 'dialogue' => $selectedDialogue));
foreach ($selectedTravelNeeds as $stn) {
$em->remove($stn);
$em->flush();
}
/* $patientObj->setTravelNeedsText($travelNeedsText);
if($travelNeedsFromDate != ""){
$patientObj->setTravelNeedsFromDate(new \DateTime($travelNeedsFromDate));
}
if($travleNeedsToDate != ""){
$patientObj->setTravleNeedsToDate(new \DateTime($travleNeedsToDate));
} */
if($patientCoreArea && $patientCoreSubArea){
$patientCoreAreaObj = $em->getRepository(PredefinedTravelsType::class)->find($patientCoreArea);
$patientCoreSubAreaObj = $em->getRepository(PredefinedTravelsType::class)->find($patientCoreSubArea);
$patientObj->setPatientCoreArea($patientCoreAreaObj);
$patientObj->setPatientSubCoreArea($patientCoreSubAreaObj);
}
$em->persist($patientObj);
$em->flush();
if ($consentdatechanged && $patient_dialogue) {
$dialogueConsentInfo = $em->getRepository(DialogueConsentInfo::class)->findOneBy(array('dialogue' => $patient_dialogue));
if (!$dialogueConsentInfo) {
$dialogueConsentInfo = new DialogueConsentInfo();
}
$dialogueConsentInfo->setDialogue($patient_dialogue);
$dialogueConsentInfo->setUser($user);
$em->persist($dialogueConsentInfo);
$em->flush();
}
$needTravelInfo_session = $session->get('needTravelInfo');
$session->set('needTravelInfo', null);
// var_dump($selectedDialogue->getPatient()->getFirstName());die;
// var_dump($patient_dialogue);die;
if($patient_dialogue){
if (!is_null($needTravelInfo)) {
foreach ($needTravelInfo as $allTravelInfo) {
foreach ($allTravelInfo as $key => $travelInfo) {
$needTextObj = new TravelNeedsDetails();
$needTextObj->setTravelNeedsText($travelInfo['name']);
if ($travelInfo['fromDate'] != "") {
$needTextObj->setTravelNeedsFromDate(new \DateTime($travelInfo['fromDate']));
} else {
$needTextObj->setTravelNeedsFromDate(NULL);
}
if ($travelInfo['toDate'] != "") {
$needTextObj->setTravelNeedsToDate(new \DateTime($travelInfo['toDate']));
} else {
$needTextObj->setTravelNeedsToDate(NULL);
}
$needTextObj->setCreatedBy($user);
$needTextObj->setPatient($patientObj);
$needTextObj->setDialogue($patient_dialogue);
$needTextObj->setTravelNeedId($key);
$em->persist($needTextObj);
$em->flush();
}
}
}
}else{
if($needTravelInfo)
$session->set('needTravelInfo', $needTravelInfo);
if($needTravelInfo_session)
$session->set('needTravelInfo', $needTravelInfo_session);
}
}
$this->updatePatientDate($patientObj);
$patientObj->setUpdatedBy($user);
$em->persist($patientObj);
$em->flush();
//echo $motherTongue.", ".$phoneNo.", ".$needTranslator.", ".$secretAddress.", ";die;
//echo $oralConsentText.", ".$oralConsentDate.", ".$travelNeedsText.", ".$travelNeedsFromDate.", ".$travleNeedsToDate.", ";die;
if($motherTongue){
$userObj->setNativeLanguage($motherTongue);
}
// if($phoneNo){
$userObj->setmobileNo($phoneNo);
// }
// if($phoneNo2){
$userObj->setmobileNo2($phoneNo2);
//}
if($phoneNo3){
$userObj->setmobileNo3($phoneNo3);
}
//if($smsOne){
$userObj->setSmsOne($smsOne);
//}
//if($smsTwo){
$userObj->setSmsTwo($smsTwo);
//}
if($smsThree){
$userObj->setSmsThree($smsThree);
}
//if($needTranslator){
$userObj->setTranslate($needTranslator);
//}
//if($secretAddress){
$userObj->setIsSecretAddress($secretAddress);
//}
//if($isSecretNumber){
$userObj->setIsSecretNumber($isSecretNumber);
//}
//if($isSecretNumber2){
$userObj->setIsSecretNumber2($isSecretNumber2);
//}
$em->persist($userObj);
$em->flush();
$responce = 'success';
$response = new Response(json_encode(array('result' => $responce)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function changeCreationDate(Request $request, $ccId) {
$em = $this->getDoctrine()->getManager();
$dialogueCaseCardObj = $em->getRepository(DialogueCaseCard::class)->find($ccId);
if ('POST' === $request->getMethod()) {
$onSelectCCcreation = $request->get('onSelectCCcreation');
if ($onSelectCCcreation != "") {
$dialogueCaseCardObj->setCreatedAt(new \DateTime($onSelectCCcreation));
$em->persist($dialogueCaseCardObj);
$em->flush();
$dialogueCaseCardHistories = $dialogueCaseCardObj->getDialogueCaseCardHistories();
if($dialogueCaseCardHistories){
if($dialogueCaseCardHistories[0]->getType() == 'C'){
$dialogueCaseCardHistory = $dialogueCaseCardHistories[1];
}else{
$dialogueCaseCardHistory = $dialogueCaseCardHistories[0];
}
$dialogueCaseCardHistory->setCreatedAt(new \DateTime($onSelectCCcreation));
$em->persist($dialogueCaseCardHistory);
$em->flush();
}
}
}
return $this->render("default/changeCreationDate.html.twig", array(
'dialogueCaseCardObj' => $dialogueCaseCardObj,
'ccId' => $ccId
));
}
public function showUserDetails(Request $request, $userId) {
$em = $this->getDoctrine()->getManager();
$userObj= $em->getRepository(User::class)->find($userId);
return $this->render("default/userDetailsPopup.html.twig", array(
'user' => $userObj
));
}
public function showHistoryCasecard(Request $request, $ccId) {
$em = $this->getDoctrine()->getManager();
$dialogueCaseCardObj= $em->getRepository(DialogueCaseCard::class)->find($ccId);
$dialogueCaseCardHistories = $dialogueCaseCardObj->getDialogueCaseCardHistories();
return $this->render("default/showHistoryCasecard.html.twig", array(
'dialogueCaseCardHistories' => $dialogueCaseCardHistories
));
}
public function changeEndDate(Request $request, $ccId) {
$em = $this->getDoctrine()->getManager();
$dialogueCaseCardObj = $em->getRepository(DialogueCaseCard::class)->find($ccId);
if ('POST' === $request->getMethod()) {
$onSelectCCcreation = $request->get('onSelectCCcreation');
if ($onSelectCCcreation != "") {
$dialogueCaseCardObj->setToDate(new \DateTime($onSelectCCcreation));
$em->persist($dialogueCaseCardObj);
$em->flush();
$dialogueCaseCardHistories = $dialogueCaseCardObj->getDialogueCaseCardHistories();
if($dialogueCaseCardHistories){
$dialogueCaseCardHistory = $dialogueCaseCardHistories[0];
$dialogueCaseCardHistory->setCreatedAt(new \DateTime($onSelectCCcreation));
$em->persist($dialogueCaseCardHistory);
$em->flush();
}
}
}
return $this->render("default/changeEndDate.html.twig", array(
'dialogueCaseCardObj' => $dialogueCaseCardObj,
'ccId' => $ccId
));
}
function updatePatientDate($patientObj) {
$em = $this->getDoctrine()->getManager();
$patientObj->setUpdatedAt(new \DateTime());
$em->persist($patientObj);
$em->flush();
}
public function patientTravelInfo(Request $request) {
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$currentDateTime = strtotime("now");
$needValText = $request->get('needVal');
$needVal = $request->get('needVal').'-'.$currentDateTime;
$needText = $request->get('needText').'-'.$currentDateTime;
$needId = $request->get('needId');
$needIdDiff = $request->get('needId').'-'.$currentDateTime;
$selectedDialogue = $session->get("selectedDialogue", null);
$selectedPatient = $session->get("selectedPatient", null);
return $this->render("default/patientTravelInfo.html.twig", array(
'selectedDialogue' => $selectedDialogue,
'selectedPatient' => $selectedPatient,
'needVal' => $needVal,
'needText' => $needText,
'needId' => $needId,
'needValText' => $needValText,
'needIdDiff' => $needIdDiff,
'currentDateTime' => $currentDateTime
));
}
public function viewMoreRecentlyOpen(Request $request){
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$user = $this->get('security.token_storage')->getToken()->getUser();
$listType = $request->get('listType');
$sortBy = $request->get('sortBy');
$orderBy = $request->get('orderBy');
$isTestUser = $user->getIsTestUser();
$isDummyPatient = $isTestUser ? 1 : 0;
$dialogueType = $user->hasRole('ROLE_CSV') ? 1 : ($user->hasRole('ROLE_DTS') ? 2 : 0);
$loginUserCat = $user->getCategory()->getName();
$loginUserInstitutions = $this->loginUserInstitutions($em, $user);
$currentSelectedInstitution = $session->get('selectedInstitutionId') ? $session->get('selectedInstitutionId') : $loginUserInstitutions[0];
$loginUserGroups = $this->loginUserGroups($em, $user);
$today = new \DateTime();
$before30days = $today->modify('-30 day')->format('Y-m-d');
$recentDialoguesQuery = 'SELECT dal, MAX(dal.id) as id, max(dal.createdAt) as accessed, sig.groupname as groupName FROM App\Entity\DialogueAccessLog dal
LEFT JOIN App\Entity\Dialogue d with dal.dialogue = d.id
LEFT JOIN App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE dal.createdBy = :user AND d.deleted = false and d.status =1 and dal.createdAt >:before30days and d.dialogueType = :dialogueType and (pi.citizenSchoolName LIKE :category or pi.citizenInstitutionName LIKE :category) and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.')
GROUP BY dal.dialogue';
if ($sortBy != null && $orderBy != null && $listType == 'recent') {
if ($sortBy == 'createdAt') {
$recentDialoguesQuery .= ' order by d.createdAt ' . $orderBy;
} elseif ($sortBy == 'fullName') {
$recentDialoguesQuery .= ' order by p.firstName ' . $orderBy;
} elseif ($sortBy == 'caseCard') {
$recentDialoguesQuery .= ' ';
} elseif ($sortBy == 'cpr') {
$recentDialoguesQuery .= ' order by p.cpr ' . $orderBy;
} elseif ($sortBy == 'anchorName') {
$recentDialoguesQuery .= ' ';
} elseif ($sortBy == 'updatedAt') {
$recentDialoguesQuery .= ' order by accessed ' . $orderBy;
} elseif ($sortBy == 'age') {
$recentDialoguesQuery .= ' order by p.childAge ' . $orderBy;
} elseif ($sortBy == 'citizenInstitutionStatus') {
$recentDialoguesQuery .= ' order by groupName ' . $orderBy;
} elseif ($sortBy == 'school') {
$recentDialoguesQuery .= ' ';
} elseif ($sortBy == 'gread') {
$recentDialoguesQuery .= ' order by d.latestGrade ' . $orderBy;
}
} else {
$recentDialoguesQuery .= ' ORDER BY accessed desc';
}
$recentDialogues = $em->createQuery($recentDialoguesQuery)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
->setParameter('category', $loginUserCat)
->setParameter('before30days',$before30days)
->execute();
//var_dump($recentDialogues) ;
return $this->render("default/viewMoreRecentlyOpen.html.twig", array('recentDialogues' => $recentDialogues, 'user' => $user));
}
public function viewMoreMyUrgentInfo(Request $request) {
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$user = $this->get('security.token_storage')->getToken()->getUser();
$listType = $request->get('listType');
$sortBy = $request->get('sortBy');
$orderBy = $request->get('orderBy');
$isTestUser = $user->getIsTestUser();
$isDummyPatient = $isTestUser ? 1 : 0;
$dialogueType = $user->hasRole('ROLE_CSV') ? 1 : ($user->hasRole('ROLE_DTS') ? 2 : 0);
// get all my notes whose remider date is past today
if ($sortBy != null && $orderBy != null && $listType == 'urgent') {
if ($sortBy == 'createdAt') {
$notesPassedReminderDate = $em->createQuery(
'SELECT n,po.isDeleted from App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
inner join App\Entity\Patient p with p.id = n.patient
left join App\Entity\JoPostMail po with po.id = n.joPostMail
where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by n.createdAt ' . $orderBy)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
//->setParameter('cdate', date("Y-m-d"))
->execute();
} elseif ($sortBy == 'fullName') {
$notesPassedReminderDate = $em->createQuery(
'SELECT n,po.isDeleted from App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
inner join App\Entity\Patient p with p.id = n.patient
left join App\Entity\JoPostMail po with po.id = n.joPostMail
where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by p.firstName ' . $orderBy)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
//->setParameter('cdate', date("Y-m-d"))
->execute();
} elseif ($sortBy == 'cpr') {
$notesPassedReminderDate = $em->createQuery(
'SELECT n,po.isDeleted from App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
inner join App\Entity\Patient p with p.id = n.patient
left join App\Entity\JoPostMail po with po.id = n.joPostMail
where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by p.cpr ' . $orderBy)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
//->setParameter('cdate', date("Y-m-d"))
->execute();
} elseif ($sortBy == 'age') {
$notesPassedReminderDate = $em->createQuery(
'SELECT n,po.isDeleted from App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
inner join App\Entity\Patient p with p.id = n.patient
left join App\Entity\JoPostMail po with po.id = n.joPostMail
where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by p.childAge ' . $orderBy)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
//->setParameter('cdate', date("Y-m-d"))
->execute();
} elseif ($sortBy == 'heading') {
$notesPassedReminderDate = $em->createQuery(
'SELECT n,po.isDeleted from App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
inner join App\Entity\Patient p with p.id = n.patient
left join App\Entity\JoPostMail po with po.id = n.joPostMail
where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by n.attachmentHeading ' . $orderBy)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
// ->setParameter('cdate', date("Y-m-d"))
->execute();
} elseif ($sortBy == 'reminderDate') {
$notesPassedReminderDate = $em->createQuery(
'SELECT n,po.isDeleted from App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
inner join App\Entity\Patient p with p.id = n.patient
left join App\Entity\JoPostMail po with po.id = n.joPostMail
where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by n.reminderDate ' . $orderBy)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
//->setParameter('cdate', date("Y-m-d"))
->execute();
}
} else {
$notesPassedReminderDate = $em->createQuery('
SELECT n,po.isDeleted from App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
inner join App\Entity\Patient p with p.id = n.patient
left join App\Entity\JoPostMail po with po.id = n.joPostMail
where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'
group by n.id HAVING (po.isDeleted = false or po.isDeleted is null) order by n.reminderDate asc ')
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
//->setParameter('cdate', date("Y-m-d"))
->execute();
}
return $this->render("default/viewMoreMyUrgentInfo.html.twig", array('notesPassedReminderDate' => $notesPassedReminderDate, 'user' => $user));
}
public function viewMoreMyActiveInfo(Request $request) {
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$user = $this->get('security.token_storage')->getToken()->getUser();
$listType = $request->get('listType');
$sortBy = $request->get('sortBy');
$orderBy = $request->get('orderBy');
$isTestUser = $user->getIsTestUser();
$isDummyPatient = $isTestUser ? 1 : 0;
$dialogueType = $user->hasRole('ROLE_CSV') ? 1 : ($user->hasRole('ROLE_DTS') ? 2 : 0);
if ($sortBy != null && $orderBy != null && $listType == 'active') {
// Fetch dialogues created by logged in user or dialogues where current user has created case_card or notes
if ($sortBy == 'createdAt') {
if ($user->hasRole('ROLE_CSV')) {
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ( m.responsiblePerson = :user and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by d.createdAt ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}else{
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by d.createdAt ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}
$myDialogues = $query->execute();
} elseif ($sortBy == 'fullName') {
if ($user->hasRole('ROLE_CSV')) {
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ( m.responsiblePerson = :user and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}else{
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}
$myDialogues = $query->execute();
} elseif ($sortBy == 'age') {
if ($user->hasRole('ROLE_CSV')) {
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ( m.responsiblePerson = :user and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.childAge ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}else{
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.childAge ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}
$myDialogues = $query->execute();
} elseif ($sortBy == 'cpr') {
if ($user->hasRole('ROLE_CSV')) {
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ( m.responsiblePerson = :user and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.cpr ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}else{
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.cpr ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}
$myDialogues = $query->execute();
} elseif ($sortBy == 'updatedAt') {
if ($user->hasRole('ROLE_CSV')) {
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ( m.responsiblePerson = :user and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by d.updatedAt ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}else{
$query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by d.updatedAt ' . $orderBy
)->setParameter('dialogueType', $dialogueType)
->setParameter('user', $user);
}
$myDialogues = $query->execute();
}
} else {
// Fetch dialogues created by logged in user or dialogues where current user has created case_card or notes
/* $query = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueAttachmentDetails n with d.id = n.dialogue
WHERE (d.anchor = :user or c.createdBy = :user or n.user = :user) and d.deleted = false and d.status =1 '
)->setParameter('user', $user);
$myDialogues = $query->execute(); */
if ($user->hasRole('ROLE_CSV')) {
$myDialogues = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ( m.responsiblePerson = :user and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'
order by p.firstName ASC'
)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
->execute();
}else{
$myDialogues = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'
order by p.firstName ASC'
)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
->execute();
}
}
return $this->render("default/viewMoreMyActiveInfo.html.twig", array('myDialogues' => $myDialogues, 'user' => $user));
}
public function viewMoreMyNewInfo(Request $request) {
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$user = $this->get('security.token_storage')->getToken()->getUser();
$listType = $request->get('listType');
$sortBy = $request->get('sortBy');
$orderBy = $request->get('orderBy');
$isTestUser = $user->getIsTestUser();
$isDummyPatient = $isTestUser ? 1 : 0;
$pagelimit = NULL;
$searchTerm = NULL;
$dialogueType = $user->hasRole('ROLE_CSV') ? 1 : ($user->hasRole('ROLE_DTS') ? 2 : 0);
$parameters = [];
$parameters['dialogueType'] = $dialogueType;
/*$searchSqlStr = "SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\User u with u.id = p.user
left join App\Entity\DialogueCaseCard dc with d.id = dc.dialogue
left join App\Entity\User a with a.id = d.anchor
WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType AND dc.isClosed = false and p.isDummyPatient = ".$isDummyPatient;
$fetchAllDialogues = $em->createQuery($searchSqlStr)
->setParameters($parameters) //send multiple paramenters
->execute();*/
$dialogueMeasureText = "";
if ($user->hasRole('ROLE_CSV')) {
/*$myDialogues = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ( m.responsiblePerson = :user and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false
and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ASC'
)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
->execute();*/$myDialogues = $em->getRepository(Dialogue::class)->myActiveCases('ROLE_CSV', $searchTerm, $user, $dialogueType, $pagelimit, $isDummyPatient, 1 );
}else{
/*$myDialogues = $em->createQuery(
'SELECT DISTINCT d FROM App\Entity\Dialogue d
left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
left join App\Entity\Patient p with p.id = d.patient
WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false
and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ASC'
)
->setParameter('user', $user)
->setParameter('dialogueType', $dialogueType)
->execute();*/$myDialogues = $em->getRepository(Dialogue::class)->myActiveCases('ROLE_DTS', $searchTerm, $user, $dialogueType, $pagelimit, $isDummyPatient, 1 );
}
//}
$today = new \DateTime();
$before30days = $today->modify('-30 day')->format('Y-m-d');
//var_dump(($myDialogues));
if ($sortBy != null && $orderBy != null && $listType == 'newContent') {
if ($sortBy == 'createdAt') {
$queryOther = $em->createQuery(
'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
left join App\Entity\Patient p with p.id = n.patient
WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by n.createdAt ' . $orderBy
)
->setParameter('user', $user)
->setParameter('before30days', $before30days)
->setParameter('dialogueId', $myDialogues)
->setParameter('dialogueType', $dialogueType);
$newContentDialogues = $queryOther->execute();
} elseif ($sortBy == 'attachmentDate') {
$queryOther = $em->createQuery(
'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
left join App\Entity\Patient p with p.id = n.patient
WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by n.attachmentDate ' . $orderBy
)
->setParameter('user', $user)
->setParameter('before30days', $before30days)
->setParameter('dialogueId', $myDialogues)
->setParameter('dialogueType', $dialogueType);
$newContentDialogues = $queryOther->execute();
} elseif ($sortBy == 'fullName') {
$queryOther = $em->createQuery(
'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
left join App\Entity\Patient p with p.id = n.patient
WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ' . $orderBy
)
->setParameter('user', $user)
->setParameter('before30days', $before30days)
->setParameter('dialogueId', $myDialogues)
->setParameter('dialogueType', $dialogueType);
$newContentDialogues = $queryOther->execute();
} elseif ($sortBy == 'cpr') {
$queryOther = $em->createQuery(
'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
left join App\Entity\Patient p with p.id = n.patient
WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.cpr ' . $orderBy
)
->setParameter('user', $user)
->setParameter('before30days', $before30days)
->setParameter('dialogueId', $myDialogues)
->setParameter('dialogueType', $dialogueType);
$newContentDialogues = $queryOther->execute();
} elseif ($sortBy == 'heading') {
$queryOther = $em->createQuery(
'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
left join App\Entity\Patient p with p.id = n.patient
WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by n.attachmentHeading ' . $orderBy
)
->setParameter('user', $user)
->setParameter('before30days', $before30days)
->setParameter('dialogueId', $myDialogues)
->setParameter('dialogueType', $dialogueType);
$newContentDialogues = $queryOther->execute();
} elseif ($sortBy == 'userName') {
$queryOther = $em->createQuery(
'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
left join App\Entity\Patient p with p.id = n.patient
left join App\Entity\User u with u.id = n.user
WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by u.fullName ' . $orderBy
)
->setParameter('user', $user)
->setParameter('before30days', $before30days)
->setParameter('dialogueId', $myDialogues)
->setParameter('dialogueType', $dialogueType);
$newContentDialogues = $queryOther->execute();
}
} else {
$newContentDialogues = $em->createQuery(
'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n
left join App\Entity\Dialogue d with d.id = n.dialogue
left join App\Entity\Patient p with p.id = n.patient
WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'
order by n.createdAt desc'
)
->setParameter('user', $user)
->setParameter('before30days', $before30days)
->setParameter('dialogueId', $myDialogues)
->setParameter('dialogueType', $dialogueType)
->execute();
}
return $this->render("default/viewMoreMyNewInfo.html.twig", array('newContentDialogues' => $newContentDialogues, 'dialogueMeasureText' => $dialogueMeasureText, 'user' => $user));
}
public function viewMoreAllInfo(Request $request) {
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$user = $this->get('security.token_storage')->getToken()->getUser();
$listType = $request->get('listType');
$sortBy = $request->get('sortBy');
$orderBy = $request->get('orderBy');
$isTestUser = $user->getIsTestUser();
$isDummyPatient = $isTestUser ? 1 : 0;
$loginUserCat = $user->getCategory()->getName();
$loginUserInstitutions = $this->loginUserInstitutions($em, $user);
$currentSelectedInstitution = $session->get('selectedInstitutionId') ? $session->get('selectedInstitutionId') : $loginUserInstitutions[0];
$loginUserGroups = $this->loginUserGroups($em, $user);
$dialogueType = $user->hasRole('ROLE_CSV') ? 1 : ($user->hasRole('ROLE_DTS') ? 2 : 0);
if ($sortBy != null && $orderBy != null && $listType == 'all') {
if ($sortBy == 'createdAt') {
$query = $em->createQuery(
'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by d.createdAt ' . $orderBy
)->setParameter('dialogueType', $dialogueType);//->setParameter('category', $loginUserCat);
$fetchAllDialogues = $query->execute();
} elseif ($sortBy == 'fullName') {
$query = $em->createQuery(
'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by p.firstName ' . $orderBy
)->setParameter('dialogueType', $dialogueType);//->setParameter('category', $loginUserCat);
$fetchAllDialogues = $query->execute();
} elseif ($sortBy == 'age') {
$query = $em->createQuery(
'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber= p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by p.childAge ' . $orderBy
)->setParameter('dialogueType', $dialogueType);//->setParameter('category', $loginUserCat);
//var_dump($query);
//die;
$fetchAllDialogues = $query->execute();
} elseif ($sortBy == 'citizenInstitutionStatus') {
$query = $em->createQuery(
'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber= p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by groupName ' . $orderBy
)->setParameter('dialogueType', $dialogueType);//->setParameter('category', $loginUserCat);
$fetchAllDialogues = $query->execute();
} elseif ($sortBy == 'gread') {
$query = $em->createQuery(
'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by d.latestGrade ' . $orderBy
)->setParameter('dialogueType', $dialogueType);//->setParameter('category', $loginUserCat);
$fetchAllDialogues = $query->execute();
} elseif ($sortBy == 'cpr') {
$query = $em->createQuery(
'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') or sp.maingroupid in ('.$loginUserGroups.') order by p.cpr ' . $orderBy
)->setParameter('dialogueType', $dialogueType);//->setParameter('category', $loginUserCat);
$fetchAllDialogues = $query->execute();
} elseif ($sortBy == 'updatedAt') {
$query = $em->createQuery(
'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by d.updatedAt ' . $orderBy
)->setParameter('dialogueType', $dialogueType);//->setParameter('category', $loginUserCat);
$fetchAllDialogues = $query->execute();
}
} else {
//$fetchAllDialogues = $em->getRepository(Dialogue::class)->findBy(array('deleted' => false, 'status' => 1, 'dialogueType' => $dialogueType));
//if (strlen($searchTerm) > 6 && $searchTerm[6] == '-') {//when search by cpr number and 7th char is - then replace it and pass the search string
// $searchTerm = str_replace('-', '', $searchTerm);
// } else {
// $searchTerm = $searchTerm;
$parameters = [];
$parameters['dialogueType'] = $dialogueType;
$searchSqlStr = "SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d
left join App\Entity\Patient p with p.id = d.patient
left join App\Entity\User u with u.id = p.user
left join App\Entity\DialogueCaseCard dc with d.id = dc.dialogue
left join App\Entity\User a with a.id = d.anchor
left join App\Entity\PatientInformation pi with p.id = pi.patient
left join App\Entity\Category c with a.category = c.id
left join App\Entity\DialogueAttachmentDetails dad with dad.dialogue = d.id
left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType AND dc.toDate IS NULL and p.isDummyPatient = ".$isDummyPatient." and sp.institutionId in (".$currentSelectedInstitution.") ";
//echo $dialogueType." ".$searchSqlStr;
$fetchAllDialogues = $em->createQuery($searchSqlStr)
->setParameters($parameters) //send multiple paramenters
->execute();
}
$dialogueMeasureText = "";
return $this->render("default/viewMoreAllInfo.html.twig", array('fetchAllDialogues' => $fetchAllDialogues, 'dialogueMeasureText' => $dialogueMeasureText, 'user' => $user));
}
public function loginUserInstitutions($em, $user){
//$loginUserInstitutions
$loginUserInstitutionsArray = $em->createQuery("SELECT distinct (sp.institutionId) FROM App\Entity\StilPerson sp
left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser
WHERE ac.user =".$user->getId() )
->getScalarResult();
$loginUserInstitutions = array_map('current', $loginUserInstitutionsArray);
if(count($loginUserInstitutions) == 0){
$loginUserInstitutions[] = 0;
}
//var_dump($loginUserInstitutions);die;
return $loginUserInstitutions;
}
public function loginUserGroups($em, $user){
//$loginUserGroups
$loginUserGroupsArray = $em->createQuery("SELECT distinct (spg.groupid) FROM App\Entity\StilPerson sp
left join App\Entity\StilPersonGroup spg with sp.id = spg.personId
left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser
WHERE spg.groupid is not NULL and ac.user =".$user->getId() )
->getScalarResult();
$loginUserGroups = array_map('current', $loginUserGroupsArray);
if(count($loginUserGroups) == 0){
$loginUserGroups[] = 0;
}
$comma_list = "'" .implode("', '", $loginUserGroups) . "'";
return $comma_list;
}
public function updatePatientInfo(Request $request){
$em = $this->getDoctrine()->getManager();
$patientId = $request->get('patientId');
$instiStu = trim($request->get('instiStu'));
$instiEmail = trim($request->get('instiEmail'));
$instiTlf = trim($request->get('instiTlf'));
$schoolEmail = trim($request->get('schoolEmail'));
$schoolTlf = trim($request->get('schoolTlf'));
$instiHomepage = trim($request->get('instiHomepage'));
$instiLocation = trim($request->get('instiLocation'));
$patientObj = $em->getRepository(PatientInformation::class)->find($patientId);
$session = $request->getSession();
//if($instiStu != ""){
$patientObj->setCitizenInstitutionStatus($instiStu);
//}
if($instiEmail != ""){
$patientObj->setCitizenInstitutionMail($instiEmail);
}
//if($instiTlf != ""){
$patientObj->setCitizenInstitutionTelephone($instiTlf);
//}
if($schoolEmail != ""){
$patientObj->setCitizenSchoolMail($schoolEmail);
}
//if($schoolTlf != ""){
$patientObj->setCitizenSchoolTelephone($schoolTlf);
//}
//if($instiHomepage != ""){
$patientObj->setHomepage($instiHomepage);
//}
//if($instiLocation != ""){
$patientObj->setCitizenInstitutionLocationName($instiLocation);
//}
$em->persist($patientObj);
$em->flush();
$selectedPatient = $session->get("selectedPatient", false);
$patientObj = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$patientInfoObjTemp = $em->getRepository(PatientInformation::class)->findBy(array('user' => $patientObj->getUser()));
$patientInfoObj = $patientInfoObjTemp ? $patientInfoObjTemp[0] : array();
return $this->render("default/reloadDtsChildInfo.html.twig", array(
'patientObj' => $patientObj,
'patientInfoObj' => $patientInfoObj));
}
public function updateAllStamdata($patient, $session) {
$em = $entityManager = $this->getDoctrine()->getManager();
$dialogueControllerObj = new DialogueController();
if($patient->getIsFakeCpr() == 1 || $patient->getIsDummyPatient() == 1){
return true;
}
if ($patient) {
$newPatient = $patient;
$cprNo = $patient->getCpr();
// Call service 208
$serviceResponse = $this->doSoapRequest(208, $cprNo);
if($serviceResponse){
$patientObject = $serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row[0];
$isPatientDeceased = trim($dialogueControllerObj->getFieldValue($patientObject, 'CNVN_STATUS'));
if(isset($isPatientDeceased) && $isPatientDeceased == 90){
$newPatient->setIsDeceased(1);
$deceasedDateTime = trim($dialogueControllerObj->getFieldValue($patientObject, 'CNVN_STATUSSTARTDATO'));
if(isset($deceasedDateTime)){
//var_dump($deceasedDateTime);
$deceasedDateTemp = substr($deceasedDateTime, 0,8);
//var_dump($deceasedDateTemp);
$deceasedDate = substr($deceasedDateTemp, 0,4).'-'.substr($deceasedDateTemp, 4,2).'-'.substr($deceasedDateTemp, 6,2);
//var_dump($deceasedDate);die;
$newPatient->setDeceaseDate(new \DateTime($deceasedDate));
}
}
//Update patient name
$cprFirstName = trim($this->getFieldValue($patientObject, 'CNVN_FORNVN')).' '. trim($this->getFieldValue($patientObject, 'CNVN_MELNVN'));
$cprLastName = trim($this->getFieldValue($patientObject, 'CNVN_EFTERNVN'));
$newPatient->setLastName($cprFirstName);
$newPatient->setFirstName($cprLastName);
//Update patient address as well as user address
$newPatient->setAddressLine1($dialogueControllerObj->getFieldValue($patientObject, 'STADR'));
$patientAddressObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'PNR_FOEDDATO', $newPatient->getCpr());
if ($patientAddressObject) {
$newPatient->setPostNumber($dialogueControllerObj->getFieldValue($patientAddressObject, 'CPST_POSTNR'));
$newPatient->setCity($dialogueControllerObj->getFieldValue($patientAddressObject, 'CPSN_POSTDISTTXT'));
} else {
$newPatient->setPostNumber($dialogueControllerObj->getFieldValue($patientObject, 'POSTNR'));
$newPatient->setCity($dialogueControllerObj->getFieldValue($patientObject, 'BYNVN'));
}
//Also update the stamdata family members
$this->updateMorFarGardianToStamdata($em, $newPatient, $patientObject, $serviceResponse, $dialogueControllerObj, $session);
$newPatientUserObj = $newPatient->getUser();
$newPatientUserObj->setAddress($newPatient->getAddressLine1());
$newPatientUserObj->setPostNumber($newPatient->getPostNumber());
$newPatientUserObj->setCity($newPatient->getCity());
$newPatientUserObj->setFirstName($cprFirstName);
$newPatientUserObj->setLastName($cprLastName);
$newPatientUserObj->setFullName($cprFirstName." ".$cprLastName);
$entityManager->persist($newPatientUserObj);
//Call to findout siblings if child address match with mor or far then call the with parent cpr and get sublinks
$siblingsArray = $spouseArray = array();
$loopCnt = 0;
foreach ($newPatient->getFamily() as $member) {
if (true || $member->getRelative()->getAddress() == $newPatient->getAddressLine1() && $member->getRelative()->getCity() == $newPatient->getCity() && $member->getRelative()->getPostNumber() == $newPatient->getPostNumber()) {
//$isParentAddressMatch++;
$parentCprNo = $member->getRelative()->getUsername();
if(strlen($parentCprNo)=="10") {
// Call service 208
$parentServiceResponse = $this->doSoapRequest(208, $parentCprNo);
//$parentServiceObject = $parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row;
$patientNameObject = $parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row[0];
$parentFirstName = trim($dialogueControllerObj->getFieldValue($patientNameObject, 'CNVN_FORNVN'));
$parentMiddleName = trim($dialogueControllerObj->getFieldValue($patientNameObject, 'CNVN_MELNVN'));
$parentLastName = trim($dialogueControllerObj->getFieldValue($patientNameObject, 'CNVN_EFTERNVN'));
$isparentDeceased = trim($dialogueControllerObj->getFieldValue($patientNameObject, 'CNVN_STATUS'));
if(isset($isparentDeceased) && $isparentDeceased == 90){
$member->setIsDeceased(1);
$deceasedDateTime = trim($dialogueControllerObj->getFieldValue($patientNameObject, 'CNVN_STATUSSTARTDATO'));
if(isset($deceasedDateTime)){
$deceasedDateTemp = substr($deceasedDateTime, 0,8);
$deceasedDate = substr($deceasedDateTemp, 0,4).'-'.substr($deceasedDateTemp, 4,2).'-'.substr($deceasedDateTemp, 6,2);
$member->setDeceaseDate(new \DateTime($deceasedDate));
}
}
if ($parentFirstName != "" && $parentLastName != "") {
$member->getRelative()->setFirstName($parentFirstName . ' ' . $parentMiddleName);
$member->getRelative()->setLastName($parentLastName);
}
//In stam data we have check box for “Hemmelig adresse”.
//If value found check it - if not it is blank (unchecked). do for parents
$isSecretAddressParent = $dialogueControllerObj->getFieldValue($patientNameObject, 'BESKYT');
$isSecretAddressParentVal = false;
if (!is_null($isSecretAddressParent)) {
$isSecretAddressParentVal = true;
}
//if ($isSecretAddressParentVal) {
$newpatientUserObj = $member->getRelative();
$member->getRelative()->setIsSecretAddress($isSecretAddressParentVal);
//}
$siblingObject = $dialogueControllerObj->getChildMatchingObject($parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Barn');
if ($siblingObject) {
$siblingsArray = $dialogueControllerObj->siblingsArrayData($siblingObject, $newPatient, $siblingsArray);
}
//Spouse - In parent lookup we need to look for FAMMRK "Ægtefælle" too.
//To find who the parent is currently married to. If divorced and remarried a new person will be listed here.
$spouseObject = $dialogueControllerObj->getChildMatchingObject($parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Ægtefælle');
if ($spouseObject) {
$spouseBarnObject = $dialogueControllerObj->getChildMatchingObject($parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Barn');
$siblingsArray = $dialogueControllerObj->siblingsArrayData($spouseBarnObject, $newPatient, $siblingsArray);
}
$entityManager->persist($member);
$entityManager->flush();
}
}
}
//var_dump($siblingsArray); die;
$getPatientFullDate = $dialogueControllerObj->getBirthDate($newPatient->getCpr());
$patientBdateYear = date_format($getPatientFullDate, "d.m.Y");
$patientDateDiff = $dialogueControllerObj->getUserAge($patientBdateYear);
$patientAgeDiff = $patientDateDiff->y;
// remove addressCallForSiblings
/*if ($patientAgeDiff < 18) {
$komk = $post = $hnr = $vejk = $etag = $sido = "";
$komk = trim($dialogueControllerObj->getFieldValue($patientObject, 'KOMKOD'));
$post = trim($dialogueControllerObj->getFieldValue($patientObject, 'POSTNR'));
$hnr = trim($dialogueControllerObj->getFieldValue($patientObject, 'HUSNR'));
$vejk = trim($dialogueControllerObj->getFieldValue($patientObject, 'VEJKOD'));
$etag = trim($dialogueControllerObj->getFieldValue($patientObject, 'ETAGE'));
$sido = trim($dialogueControllerObj->getFieldValue($patientObject, 'SIDEDOER'));
$addressCallForSiblings = $this->addressCallForSiblings($komk, $post, $hnr, $vejk, $etag, $sido);
$addressSiblingsObject = $addressCallForSiblings->Gctp->System->Service->CprData->Rolle->Table->Row;
foreach ($addressSiblingsObject as $addressSibling) {
$childDOB = trim($dialogueControllerObj->getFieldValue($addressSibling, 'CPRS_FOEDDATO'));
$childCpr = trim($dialogueControllerObj->getFieldValue($addressSibling, 'PNR'));
$childTempName = $dialogueControllerObj->getFieldValue($addressSibling, 'CNVN_ADRNVN');
if($childTempName){
$childExploadeName = explode(",", $childTempName);
$childFirstName = $childExploadeName[1];
$childLastName = $childExploadeName[0];
$childFullName = $childFirstName . ' ' . $childLastName;
$cYear = substr($childDOB, 0, 4);
$cMonth = substr($childDOB, 4, 2);
$cDate = substr($childDOB, 6, 2);
$bdateYear = $cDate . "." . $cMonth . "." . $cYear;
$dateDiff = $dialogueControllerObj->getUserAge($bdateYear);
$childAge = $dateDiff->y;
if ($childCpr != $newPatient->getCpr()) {
$childAddress = '';
$childPostNo = '';
$childCity = '';
if ($childAge < 18) {
$url_in_array = in_array($childCpr, array_column($siblingsArray, 'cprNo'));
if (!$url_in_array) {
$siblingsArray[$loopCnt]['cprNo'] = $childCpr;
$siblingsArray[$loopCnt]['fullName'] = $childFullName;
$siblingsArray[$loopCnt]['address'] = $childAddress;
$siblingsArray[$loopCnt]['postNo'] = $childPostNo;
$siblingsArray[$loopCnt]['city'] = $childCity;
if ($childAge) {
$siblingsArray[$loopCnt]['age'] = $childAge;
} else {
$siblingsArray[$loopCnt]['age'] = 0;
}
$loopCnt = ($loopCnt + 1);
}
}
}
}
}
}*/
//var_dump($siblingsArray, $addressSiblingsObject); die;
$newPatient->siblings = $siblingsArray;
$komunneIdsArray = array(
'0101' => 'København',
'0147' => 'Frederiksberg',
'0151' => 'Ballerup',
'0153' => 'Brøndby',
'0155' => 'Dragør',
'0157' => 'Gentofte',
'0159' => 'Gladsaxe',
'0161' => 'Glostrup',
'0163' => 'Herlev',
'0165' => 'Albertslund',
'0167' => 'Hvidovre',
'0169' => 'Høje-Taastrup',
'0173' => 'Lyngby-Taarbæk',
'0175' => 'Rødovre',
'0183' => 'Ishøj',
'0185' => 'Tårnby',
'0187' => 'Vallensbæk',
'0190' => 'Furesø',
'0201' => 'Allerød',
'0210' => 'Fredensborg',
'0217' => 'Helsingør',
'0219' => 'Hillerød',
'0223' => 'Hørsholm',
'0230' => 'Rudersdal',
'0240' => 'Egedal',
'0250' => 'Frederikssund',
'0253' => 'Greve',
'0259' => 'Køge',
'0260' => 'Halsnæs',
'0265' => 'Roskilde',
'0269' => 'Solrød',
'0270' => 'Gribskov',
'0306' => 'Odsherred',
'0316' => 'Holbæk',
'0320' => 'Faxe',
'0326' => 'Kalundborg',
'0329' => 'Ringsted',
'0330' => 'Slagelse',
'0336' => 'Stevns',
'0340' => 'Sorø',
'0350' => 'Lejre',
'0360' => 'Lolland',
'0370' => 'Næstved',
'0376' => 'Guldborgsund',
'0390' => 'Vordingborg',
'0400' => 'Bornholm',
'0410' => 'Middelfart',
'0411' => 'Christiansø',
'0420' => 'Assens',
'0430' => 'Faaborg-Midtfyn',
'0440' => 'Kerteminde',
'0450' => 'Nyborg',
'0461' => 'Odense',
'0479' => 'Svendborg',
'0480' => 'Nordfyns',
'0482' => 'Langeland',
'0492' => 'Ærø',
'0510' => 'Haderslev',
'0530' => 'Billund',
'0540' => 'Sønderborg',
'0550' => 'Tønder',
'0561' => 'Esbjerg',
'0563' => 'Fanø',
'0573' => 'Varde',
'0575' => 'Vejen',
'0580' => 'Aabenraa',
'0607' => 'Fredericia',
'0615' => 'Horsens',
'0621' => 'Kolding',
'0630' => 'Vejle',
'0657' => 'Herning',
'0661' => 'Holstebro',
'0665' => 'Lemvig',
'0671' => 'Struer',
'0706' => 'Syddjurs',
'0707' => 'Norddjurs',
'0710' => 'Favrskov',
'0727' => 'Odder',
'0730' => 'Randers',
'0740' => 'Silkeborg',
'0741' => 'Samsø',
'0746' => 'Skanderborg',
'0751' => 'Aarhus',
'0756' => 'Ikast-Brande',
'0760' => 'Ringkøbing-Skjern',
'0766' => 'Hedensted',
'0773' => 'Morsø',
'0779' => 'Skive',
'0787' => 'Thisted',
'0791' => 'Viborg',
'0810' => 'Brønderslev',
'0813' => 'Frederikshavn',
'0820' => 'Vesthimmerlands',
'0825' => 'Læsø',
'0840' => 'Rebild',
'0846' => 'Mariagerfjord',
'0849' => 'Jammerbugt',
'0851' => 'Aalborg',
'0860' => 'Hjørring');
$komunneId = trim($dialogueControllerObj->getFieldValue($patientObject, 'KOMKOD'));
if (array_key_exists($komunneId, $komunneIdsArray)) {
$komunneName = $komunneIdsArray[$komunneId];
$session->set("komunneName", $komunneIdsArray[$komunneId]);
$session->set("komunneId",$komunneId);
} else if($newPatient->getIsDummyPatient()) {
$komunneName = "Københavns";
$session->set("komunneName", "Københavns");
$session->set("komunneId",0);
} else {
$komunneName = "Københavns";
$session->set("komunneName", "");
$session->set("komunneId","");
}
$newPatient->setKommuneId($komunneId? $komunneId:null);
//var_dump($komunneName); die;
//Save patient
$getFullDate = $dialogueControllerObj->getBirthDate($newPatient->getCpr());
$bdateYear = date_format($getFullDate, "d.m.Y");
$dateDiff = $dialogueControllerObj->getUserAge($bdateYear);
if($newPatient->getIsFakeCpr() != '1'){
$newPatient->setChildAge($dateDiff->y);
}
if (count($newPatient->siblings) > 0) {
foreach ($newPatient->siblings as $sibling) {
$patientSiblingObj = $em->getRepository(PatientSibling::class)->findOneBy(array( 'patient' => $newPatient, 'cpr' => $sibling['cprNo']));
if(!$patientSiblingObj){
$patientSiblingObj = new PatientSibling();
$patientSiblingObj->setPatient($newPatient);
$patientSiblingObj->setCpr($sibling['cprNo']);
$patientSiblingObj->setFullName($sibling['fullName']);
$patientSiblingObj->setAddress($sibling['address']);
$patientSiblingObj->setPostNo($sibling['postNo']);
$patientSiblingObj->setCity($sibling['city']);
$patientSiblingObj->setAge($sibling['age']);
$entityManager->persist($patientSiblingObj);
$entityManager->flush();
}else{
$patientSiblingUpdateObj = $em->getRepository(PatientSibling::class)->findBy(array('patient' => $newPatient));
foreach ($patientSiblingUpdateObj as $siblingUpdateObj) {
if(($siblingUpdateObj && $patientSiblingObj) && ($siblingUpdateObj->getId() == $patientSiblingObj->getId())){
$siblingUpdateObj->setIsDeleted(false);
$siblingUpdateObj->setAddress($sibling['address']);
$siblingUpdateObj->setPostNo($sibling['postNo']);
$siblingUpdateObj->setCity($sibling['city']);
$siblingUpdateObj->setAge($sibling['age']);
$entityManager->persist($siblingUpdateObj);
$entityManager->flush();
}else{
$siblingUpdateObj->setIsDeleted(true);
$entityManager->persist($siblingUpdateObj);
$entityManager->flush();
}
}
}
}
}else{
$patientSiblingUpdateObj = $em->getRepository(PatientSibling::class)->findBy(array('patient' => $newPatient));
foreach ($patientSiblingUpdateObj as $siblingUpdateObj) {
$siblingUpdateObj->setIsDeleted(true);
$entityManager->persist($siblingUpdateObj);
$entityManager->flush();
}
}
//In stam data we have check box for “Hemmelig adresse”.
//If value found check it - if not it is blank (unchecked).
$isSecretAddress = $dialogueControllerObj->getFieldValue($patientObject, 'BESKYT');
$isSecretAddressVal = false;
if (!is_null($isSecretAddress)) {
$isSecretAddressVal = true;
}
//if ($isSecretAddressVal) {
$newpatientUserObj = $newPatient->getUser();
$newpatientUserObj->setIsSecretAddress($isSecretAddressVal);
$entityManager->persist($newpatientUserObj);
$entityManager->flush();
//}
//var_dump($isSecretAddressVal,$isSecretAddress); die;
if (!$newPatient->isPatientMajor()) {
$newPatient->patientInformationObject = $this->getUserProfileI2Calls($newPatient->getCpr());
$sessionPatientInformationObject = $session->set('sessionPatientInformationObject', $newPatient->patientInformationObject);
$newPatient->patientInformationObject = $session->get('sessionPatientInformationObject');
if (count($newPatient->patientInformationObject) > 0) {
$loopIndex = 0;
foreach ($newPatient->patientInformationObject as $patientInformation) {
//If only one record found in patientInformationObject then we have to
//Stored data only in PatientInformation entity
//If more than one records are exist then we have to stored first record
//in PatientInformation entity and setIsMultiple record = true and then other all
//entries are stored in PatientInformationDetails entity
if ($loopIndex == 0) {
//$patientInformationObj = $em->getRepository(PatientInformation::class)->findOneBy(array("patient" => $newPatient, "bookingId" => $patientInformation['bookingId']));
$patientInformationObj = $em->getRepository(PatientInformation::class)->findOneBy(array("patient" => $newPatient));
if (!$patientInformationObj) {
$patientInformationObj = new PatientInformation();
}
if (count($newPatient->patientInformationObject) > 1) {
$patientInformationObj->setIsMultiple(true);
} else {
$patientInformationObj->setIsMultiple(false);
}
$shortName = $patientInformation['institutionShortName'];
if ($shortName != "") {
$institudeResponce = $this->getI2InstitudeDataCalls($shortName);
if ($institudeResponce) {
/* $patientInformationObj->setCitizenInstitutionKKInstitutionType($institudeResponce['institution']['careType']);
$patientInformationObj->setCitizenInstitutionOwner($institudeResponce['institution']['dayCareType']); */
$careAndDayCareTypeArray = array('careTypeKey' => $institudeResponce['institution']['careType'], 'dayCareTypeKey' => $institudeResponce['institution']['dayCareType']);
$i2InstitutionValue = $dialogueControllerObj->getInstitutionValueI2Call($careAndDayCareTypeArray);
$patientInformationObj->setCitizenInstitutionKKInstitutionType($i2InstitutionValue['citizenInstitutionKkinstitutionType']);
$patientInformationObj->setCitizenInstitutionOwner($i2InstitutionValue['citizenInstitutionOwner']);
}
}
//enhedstrae call
//Get institute master information
if (array_key_exists("institutionShortName", $patientInformation)) {
$citizenInstitutionNumber = trim($patientInformation['institutionShortName']);
$patientInstitutionMasterObj = $em->getRepository(JoMasterInformation::class)->findOneBy(array("inr" => $citizenInstitutionNumber));
if ($patientInstitutionMasterObj) {
//Page 5 JOSA Elev call and enhedstrae call mapping 30 Apl 2020.pdf
$patientInformationObj->setCitizenInstitutionMail($patientInstitutionMasterObj->getMail());
$patientInformationObj->setCitizenInstitutionTelephone($patientInstitutionMasterObj->getTelefon());
$patientInformationObj->setCitizenInstitutionArea($patientInstitutionMasterObj->getDistrikt());
$patientInformationObj->setCitizenInstitutionManager($patientInstitutionMasterObj->getNavn());
//Page 6 JOSA Elev call and enhedstrae call mapping 30 Apl 2020.pdf
$patientInformationObj->setCitizenInstitutionKKInstitutionType($patientInstitutionMasterObj->getOrganisationstype());
$patientInformationObj->setHomepage($patientInstitutionMasterObj->getWww());
$patientInformationObj->setCitizenInstitutionAddress($patientInstitutionMasterObj->getAdresse());
$patientInformationObj->setCitizenInstitutionTownArea($patientInstitutionMasterObj->getBydel());
$patientInformationObj->setDepartment($patientInstitutionMasterObj->getLokationsnavn());
$patientInformationObj->setCitizenInstitutionLocationType($patientInstitutionMasterObj->getIType());
$patientUserObj = $newPatient->getUser();
$patientUserObj->setCvrNo($patientInstitutionMasterObj->getCvr());
$entityManager->persist($patientUserObj);
$entityManager->flush();
}
}
} else {
$patientInformationObj = $em->getRepository(PatientInformationDetails::class)->findOneBy(array("patient" => $newPatient));
if (!$patientInformationObj) {
$patientInformationObj = new PatientInformationDetails();
}
}
$patientInformationObj->setUser($newPatient->getUser());
$patientInformationObj->setPatient($newPatient);
if (array_key_exists("bookingId", $patientInformation)) {
$patientInformationObj->setBookingId($patientInformation['bookingId']);
}
if (array_key_exists("institutionName", $patientInformation)) {
$patientInformationObj->setCitizenInstitutionName(trim($patientInformation['institutionName']));
}
if (array_key_exists("institutionShortName", $patientInformation)) {
$patientInformationObj->setCitizenInstitutionNumber(trim($patientInformation['institutionShortName']));
}
if (array_key_exists("startDate", $patientInformation)) {
$patientInformationObj->setCitizen_institution_from_date(new \Datetime(date('Y-m-d', strtotime($patientInformation['startDate']))));
}
if (array_key_exists("endDate", $patientInformation)) {
$patientInformationObj->setCitizenInstitutionToDate(new \Datetime(date('Y-m-d', strtotime($patientInformation['endDate']))));
}
if (array_key_exists("module", $patientInformation)) {
if (array_key_exists("description", $patientInformation['module'])) {
$patientInformationObj->setInstitutionType($patientInformation['module']['description']);
}
if (array_key_exists("name", $patientInformation['module'])) {
$patientInformationObj->setCitizenInstitutionModul($patientInformation['module']['name']);
}
}
if (array_key_exists("room", $patientInformation)) {
$patientInformationObj->setCitizenInstitutionStatus($patientInformation['room']);
}
$entityManager->persist($patientInformationObj);
$entityManager->flush();
$loopIndex = ($loopIndex + 1);
}
}
$newPatient->patientSchoolObject = $this->getI2ElevSchoolCalls($newPatient->getCpr());
$sessionPatientSchoolObject = $session->set('sessionPatientSchoolObject', $newPatient->patientSchoolObject);
$newPatient->patientSchoolObject = $session->get('sessionPatientSchoolObject');
if (count($newPatient->patientSchoolObject) > 0) {
$schoolLoopIndex = 0;
$lastLoopIndex = 0;
$isMultipleRecords = false;
if (array_key_exists('historik', $newPatient->patientSchoolObject)) {
$lastLoopIndex = (count($newPatient->patientSchoolObject['historik']) - 1);
$isMultipleRecords = true;
}
$patientSchoolInformation = $newPatient->patientSchoolObject;
$patientInformationObj = $em->getRepository(PatientInformation::class)->findOneBy(array("patient" => $newPatient));
if (!$patientInformationObj) {
$patientInformationObj = new PatientInformation();
}
if ($isMultipleRecords && count($newPatient->patientSchoolObject['historik']) > 1) {
$patientInformationObj->setIsMultiple(true);
} else {
$patientInformationObj->setIsMultiple(false);
}
$patientInformationObj->setUser($newPatient->getUser());
$patientInformationObj->setPatient($newPatient);
if (array_key_exists("skolenavn", $patientSchoolInformation)) {
$patientInformationObj->setCitizenSchoolName($patientSchoolInformation['skolenavn']);
}
if (array_key_exists("klassetrin", $patientSchoolInformation)) {
$patientInformationObj->setCitizenSchoolLevel($patientSchoolInformation['klassetrin']);
}
if (array_key_exists("klassebetegnelse", $patientSchoolInformation)) {
$patientInformationObj->setCitizenSchoolClass($patientSchoolInformation['klassebetegnelse']);
}
if (array_key_exists("skolenr", $patientSchoolInformation)) {
$patientInformationObj->setCitizenSchoolNumber($patientSchoolInformation['skolenr']);
}
if (array_key_exists("skoletype", $patientSchoolInformation)) {
$patientInformationObj->setCitizenSchoolType($patientSchoolInformation['skoletype']);
}
if (array_key_exists("grunddistrSkolenavn", $patientSchoolInformation)) {
$patientInformationObj->setCitizenSchoolDistrict($patientSchoolInformation['grunddistrSkolenavn']);
}
if (array_key_exists("elevartTxt", $patientSchoolInformation)) {
$patientInformationObj->setCitizenPupilCat($patientSchoolInformation['elevartTxt']);
}
if (array_key_exists("klasselaererNavn", $patientSchoolInformation)) {
$patientInformationObj->setCitizenSchoolTeacher($patientSchoolInformation['klasselaererNavn']);
}
if (array_key_exists("klasseartTxt", $patientSchoolInformation)) {
$patientInformationObj->setCitizenClasseCat($patientSchoolInformation['klasseartTxt']);
}
if (array_key_exists("klassetypeTxt", $patientSchoolInformation)) {
$patientInformationObj->setCitizenClasseType($patientSchoolInformation['klassetypeTxt']);
}
if (array_key_exists("historik", $patientSchoolInformation)) {
if (array_key_exists("klasselaererInit", $patientSchoolInformation['historik'][$lastLoopIndex])) {
$patientInformationObj->setCitizenSchoolTeacherIntials($patientSchoolInformation['historik'][$lastLoopIndex]['klasselaererInit']);
}
if (array_key_exists("skoleklasseFraDato", $patientSchoolInformation['historik'][$lastLoopIndex])) {
$patientInformationObj->setCitizenSchoolYear(substr($patientSchoolInformation['historik'][$lastLoopIndex]['skoleklasseFraDato'], 6, 9) . "/" . date("Y"));
}
if (array_key_exists("skoleklasseFraDato", $patientSchoolInformation['historik'][0])) {
$patientInformationObj->setCitizenSchoolStart(str_replace("/", ".", $patientSchoolInformation['historik'][0]['skoleklasseFraDato']));
}
if (array_key_exists("skoleklasseTilDato", $patientSchoolInformation['historik'][0])) {
$patientInformationObj->setCitizenSchoolEnd($patientSchoolInformation['historik'][0]['skoleklasseTilDato']);
}
}
if (array_key_exists("primaerFagansvarlig", $patientSchoolInformation)) {
if (array_key_exists("medarbejdernavn", $patientSchoolInformation['primaerFagansvarlig'])) {
$adkode = "";
if (array_key_exists("adkode", $patientSchoolInformation['primaerFagansvarlig'])) {
$adkode = ", ".$patientSchoolInformation['primaerFagansvarlig']['adkode'];
}
$patientInformationObj->setCitizenSchoolNurse($patientSchoolInformation['primaerFagansvarlig']['medarbejdernavn'].$adkode);
}
}
if (array_key_exists("modersmaal", $patientSchoolInformation)) {
$nativeLanguage = $patientSchoolInformation['modersmaal'];
$newPatientUserObj = $newPatient->getUser();
if (strlen($nativeLanguage) > 0) {
$newPatientUserObj->setNativeLanguage($nativeLanguage);
}
}
//enhedstrae call
//Get school master information
if (array_key_exists("skolenr", $patientSchoolInformation)) {
$citizenSchoolNumber = $patientSchoolInformation['skolenr'];
$patientSchoolMasterObj = $em->getRepository(JoMasterInformation::class)->findOneBy(array("skolenr" => $citizenSchoolNumber));
if ($patientSchoolMasterObj) {
//Page 1 JOSA Elev call and enhedstrae call mapping 30 Apl 2020.pdf
$patientInformationObj->setCitizenSchoolMail($patientSchoolMasterObj->getEmail());
$patientInformationObj->setCitizenSchoolTelephone($patientSchoolMasterObj->getTelephone());
$patientInformationObj->setCitizenSchoolArea($patientSchoolMasterObj->getDistrikt());
if (trim($patientInformationObj->getCitizenSchoolManager()) == "") {
$patientInformationObj->setCitizenSchoolManager($patientSchoolMasterObj->getSkoleleder());
}
//Page 2 JOSA Elev call and enhedstrae call mapping 30 Apl 2020.pdf
$patientInformationObj->setCitizenSchoolTownArea($patientSchoolMasterObj->getBydel());
$patientInformationObj->setCitizenSchoolOwner($patientSchoolMasterObj->getEjerforhold());
if ($patientInformationObj->getCitizenSchoolAdress() == "") {
$patientInformationObj->setCitizenSchoolAdress($patientSchoolMasterObj->getAdresse() . ", " . $patientSchoolMasterObj->getPostnr() . " " . $patientSchoolMasterObj->getSBy());
}
}
}
$entityManager->persist($patientInformationObj);
$entityManager->flush();
if ($isMultipleRecords && count($newPatient->patientSchoolObject['historik']) > 1) {
$historyLoopIndex = 0;
foreach ($newPatient->patientSchoolObject['historik'] as $patientSchoolInformationHistory) {
//if($historyLoopIndex > 0) {
$patientInformationObj = $em->getRepository(PatientInformationDetails::class)->findOneBy(array("patient" => $newPatient));
if(!$patientInformationObj) {
$patientInformationObj = new PatientInformationDetails();
}
$patientInformationObj->setUser($newPatient->getUser());
$patientInformationObj->setPatient($newPatient);
if (array_key_exists("klasselaererInit", $newPatient->patientSchoolObject['historik'][$lastLoopIndex])) {
$patientInformationObj->setCitizenSchoolTeacherIntials($newPatient->patientSchoolObject['historik'][$lastLoopIndex]['klasselaererInit']);
}
if (array_key_exists("skoleklasseFraDato", $newPatient->patientSchoolObject['historik'][$lastLoopIndex])) {
$patientInformationObj->setCitizenSchoolYear($newPatient->patientSchoolObject['historik'][$lastLoopIndex]['skoleklasseFraDato']);
}
if (array_key_exists("skoleklasseFraDato", $patientSchoolInformationHistory)) {
$patientInformationObj->setCitizenSchoolStart(str_replace("/", ".", $patientSchoolInformationHistory['skoleklasseFraDato']));
}
if (array_key_exists("skoleklasseTilDato", $patientSchoolInformationHistory)) {
$patientInformationObj->setCitizenSchoolEnd(str_replace("/", ".", $patientSchoolInformationHistory['skoleklasseTilDato']));
}
if (array_key_exists("skolenavn", $patientSchoolInformationHistory)) {
$patientInformationObj->setCitizenSchoolName($patientSchoolInformationHistory['skolenavn']);
}
if (array_key_exists("klasse", $patientSchoolInformationHistory)) {
$patientInformationObj->setCitizenSchoolClass($patientSchoolInformationHistory['klasse']);
}
if (array_key_exists("skoletrin", $patientSchoolInformationHistory)) {
$patientInformationObj->setCitizenSchoolLevel($patientSchoolInformationHistory['skoletrin']);
}
if (array_key_exists("klasseart", $patientSchoolInformationHistory)) {
$patientInformationObj->setCitizenClasseCat($patientSchoolInformationHistory['klasseart']);
}
$entityManager->persist($patientInformationObj);
$entityManager->flush();
//}
$historyLoopIndex = ($historyLoopIndex + 1);
}
}
$schoolLoopIndex = ($schoolLoopIndex + 1);
//}
}
}
$newPatient->setUpdatedAt(new \DateTime());
$entityManager->persist($newPatient);
$entityManager->flush();
}
}
return true;
}
private function doSoapRequest($service, $cprNo) {
$par = '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="Familie+"> <CprServiceHeader r="Familie+"> <Key> <Field r="PNR" v="' . $cprNo . '"/> </Key> </CprServiceHeader> </Service> </System> </Gctp> ]]>';
$_cdata = new \SoapVar($par, XSD_ANYXML);
$gctpMessage = new \SoapParam(new \SoapVar($par, XSD_ANYXML), 'gctpMessage');
$wsdl = $this->get('kernel')->getRootDir() . '/cprservice/CprLookupService.wsdl';
$endpoint = 'https://prod.serviceplatformen.dk/service/CPRLookup/CPRLookup/2';
$certificate = $this->get('kernel')->getRootDir() . '/cprservice/cert/alldialogue_16mar.cert.key.pem';
$password = 'Werner1978';
$options = array(
'location' => $endpoint,
'keep_alive' => true,
'trace' => 1,
'local_cert' => $certificate,
'passphrase' => $password,
'cache_wsdl' => WSDL_CACHE_NONE
);
try {
$parametros[] = new \SoapParam(new \SoapVar(1067, XSD_STRING, null, null, 'InvocationContext', 'urn'), 'InvocationContext');
$parametros[] = new \SoapParam(new \SoapVar('site', XSD_STRING, null, null, 'canalVenda', 'urn'), 'canalVenda');
$parametros[] = new \SoapParam(1067, 'operacaoparceiro');
$parametros[] = new \SoapParam(new \SoapVar($par, XSD_ANYXML), 'InvocationContext');
$soapClient = new SoapClientDebug($wsdl, $options);
$reqData = array('callGCTPCheckServiceRequest' => array('InvocationContext' => array(
'ServiceAgreementUUID' => '24ed133a-ad35-4b59-8ef5-f7cfcc058a40', //serviceaftale UUID for josaFaxe (Familie+)
'UserSystemUUID' => 'ffa2ea04-bc05-461f-8e8e-59833045eef8', //System UUID same for all
'UserUUID' => '6a4a5130-d96c-4ddd-a2df-d095bc40a813', //KOMMUNE UUID for josaFaxe
'ServiceUUID' => 'a34cf599-26e4-4609-bfbd-2490d3d1c3ab'))); //Familie+ UUID
$reqData['callGCTPCheckServiceRequest']['gctpMessage'] = ($par);
$data = ($soapClient->__call('callGctpService', $reqData));
} catch (Exception $e) {
$code = $e->getCode();
return false;
}
//print_r($data->result); die;
//file_put_contents("D:/test/".$cprNo.".xml", $data->result);
$xml = simplexml_load_string($data->result);
return $xml;
}
public function addressCallForSiblings($komk,$post,$hnr,$vejk,$etag,$sido) {
//var_dump($komk,$post,$hnr,$vejk,$etag,$sido);//die('ff');
$eTagString ='<Field r="ETAG" v="'.$etag.'"/>';
$sideDoerString = '<Field r="SIDO" v="'.$sido.'"/>';
$parString = '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/><Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
if($etag !="" && $sido == "") {
$parString = '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/>'.$eTagString.'<Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
}
if($etag == "" && $sido !="") {
$parString = '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/>'.$sideDoerString.'<Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
}
if($etag != "" && $sido !="") {
$parString = '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/>'.$eTagString.$sideDoerString.'<Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
}
$par = $parString;
//$par = '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/><Field r="ETAG" v="'.$etag.'"/><Field r="SIDO" v="'.$sido.'"/><Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
//var_dump($par); //die;
$_cdata = new \SoapVar($par, XSD_ANYXML);
$gctpMessage = new \SoapParam(new \SoapVar($par, XSD_ANYXML), 'gctpMessage');
//$wsdl = 'G:/liveprojects/cprservice/CprLookupService.wsdl';
//$certificate = 'G:/liveprojects/cprservice/cert/alldialogue_16mar.cert.key.pem';
$wsdl = $this->get('kernel')->getRootDir() . '/cprservice/CprLookupService.wsdl';
$endpoint = 'https://prod.serviceplatformen.dk/service/CPRLookup/CPRLookup/2';
$certificate = $this->get('kernel')->getRootDir() . '/cprservice/cert/alldialogue_16mar.cert.key.pem';
$password = 'Werner1978';
$options = array(
'location' => $endpoint,
'keep_alive' => true,
'trace' => 1,
'local_cert' => $certificate,
'passphrase' => $password,
'cache_wsdl' => WSDL_CACHE_NONE
);
try {
$soapClient = new SoapClientDebug($wsdl, $options);
$reqData = array('callGCTPCheckServiceRequest' => array('InvocationContext' => array(
'ServiceAgreementUUID' => '1ea87a27-1f9f-4985-94f3-723cbc950d29', //serviceaftale UUID for josaFaxe (ADRSOG1)
'UserSystemUUID' => 'ffa2ea04-bc05-461f-8e8e-59833045eef8', //System UUID same for all
'UserUUID' => '6a4a5130-d96c-4ddd-a2df-d095bc40a813', //KOMMUNE UUID for josaFaxe
'ServiceUUID' => '6538f113-b1e6-4b21-8fe1-28b7bf78a1bd'))); //ADRSOG1 UUID
$reqData['callGCTPCheckServiceRequest']['gctpMessage'] = ($par);
$data = ($soapClient->__call('callGctpService', $reqData));
//print_r($data->result); die;
} catch (Exception $e) {
var_dump($e);
}
$xml = simplexml_load_string($data->result);
return $xml;
}
public function getUserProfileI2Calls($username) {
$I2HostURL = $this->container->getParameter('I2HostURL');
$I2SubscriptionKey = $this->container->getParameter('I2InstSubscriptionKey');
$isCopenhagen = $this->container->getParameter('isCopenhagen');
$callId = $isCopenhagen ? 101 : 320; //101 for København : 320 for faxe
try {
// this header is added to all requests made by this client
$client = HttpClient::create(['headers' => [
//'Accept' => 'text/plain',
'Ocp-Apim-Subscription-Key' => $I2SubscriptionKey,
'Content-Type' => 'application/json',
]]);
$getRequestUrl = "https://$I2HostURL/ww/api/v1/municipalities/$callId/enrollments/forchild";
$response = $client->request('POST', $getRequestUrl, [
// defining data using an array of parameters
//'body' => '1204075502',
'body' => "'".$username."'",
]);
$statusCode = $response->getStatusCode();
// $statusCode = 200
if($statusCode == 200){
$contentType = $response->getHeaders()['content-type'][0];
// $contentType = 'application/json'
$content = $response->getContent();
$isJSON = $this->isJSON($content);
//var_dump($isJSON); die;
if($isJSON) {
// $content = '{"id":521583, "name":"symfony-docs", ...}'
$content = $response->toArray();
// $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
//var_dump($content); die("end");
return $content;
} else {
return array();
}
} else {
//throw new \Exception('Error code:'.$statusCode);
//return array('Error code' => $statusCode);
return array();
}
} catch (TransportException $e) {
//var_dump($e->getMessage());
//die;
return array();
} catch(Exception $p){return array();}
return $content;
}
public function isJSON($string){
return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE) && strlen($string) > 3 ? true : false;
}
private function getI2InstitudeDataCalls($shortName) {
$I2HostURL = $this->container->getParameter('I2HostURL');
$I2InstSubscriptionKey = $this->container->getParameter('I2InstSubscriptionKey');
$isCopenhagen = $this->container->getParameter('isCopenhagen');
$callId = $isCopenhagen ? 101 : 320; //101 for København : 320 for faxe
//var_dump($I2HostURL, $I2InstSubscriptionKey, $shortName); die;
try{
// this header is added to all requests made by this client
$client = HttpClient::create(['headers' => [
//'Accept' => 'text/plain',
'Ocp-Apim-Subscription-Key' => $I2InstSubscriptionKey,
'Content-Type' => 'application/json',
]]);
$getRequestUrl = "https://$I2HostURL/ww/api/v1/municipalities/$callId/institutions/byShortName/$shortName/details";
$response = $client->request('GET', $getRequestUrl, [
// defining data using an array of parameters
//'body' => '1204075502',
//'body' => "'".$username."'",
]);
$statusCode = $response->getStatusCode();
// $statusCode = 200
if($statusCode == 200){
$contentType = $response->getHeaders()['content-type'][0];
// $contentType = 'application/json'
$content = $response->getContent();
$isJSON = $this->isJSON($content);
//var_dump($isJSON); die;
if($isJSON) {
// $content = '{"id":521583, "name":"symfony-docs", ...}'
$content = $response->toArray();
// $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
//var_dump($content); die("end");
return $content;
} else {
return array();
}
} else {
//throw new \Exception('Error code:'.$statusCode);
//return array('Error code' => $statusCode);
return array();
}
} catch (TransportException $e) {
//var_dump($e->getMessage());
//die;
return array();
} catch(Exception $p){return array();}
return $content;
}
private function getI2ElevSchoolCalls($username) {
/*$stresponce = file_get_contents('C:/projects/josa/josa/2106065678.json');
if($stresponce) {
$content = json_decode($stresponce, true);
//var_Dump($content);die;
return $content;
}*/
$profileAuthentication = $this->container->getParameter('profileAuthentication');
$profileBaseUrl = $this->container->getParameter('profileBaseUrl');
$profileToken = $this->container->getParameter('profileToken');
try {
// this header is added to all requests made by this client
$client = HttpClient::create(['verify_host'=>false,'headers' => [
//'Accept' => 'text/plain',
'Authorization' => $profileAuthentication,
'Ocp-Apim-Subscription-Key' => $profileToken,
'Accept' => 'text/plain',
]]);
$getRequestUrl = "https://$profileBaseUrl/josa/v1/elev";
$response = $client->request('GET', $getRequestUrl, [
// defining data using an array of parameters
//'body' => '2106065678',
//'cprNr' => "'".$username."'",
'query' => [
'cprNr' => "$username",
],
]);
$statusCode = $response->getStatusCode();
// $statusCode = 200
if($statusCode == 200){
$contentType = $response->getHeaders()['content-type'][0];
// $contentType = 'application/json'
$content = $response->getContent();
$isJSON = $this->isJSON($content);
//var_dump($isJSON, $content); die;
if($isJSON) {
// $content = '{"id":521583, "name":"symfony-docs", ...}'
$content = $response->toArray();
// $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
//var_dump($content); die("end");
return $content;
} else {
return array();
}
} else {
//throw new \Exception('Error code:'.$statusCode);
//return array('Error code' => $statusCode);
return array();
}
} catch (TransportException $e) {
//var_dump($e->getMessage());
//die;
return array();
} catch(Exception $p){return array();}
return $content;
}
public function setNotificationData($em, $dialogue, $user, $type, $message) {
//$em = $this->getDoctrine()->getManager();
$notificationObj = new JoNotification();
$notificationObj->setDialogue($dialogue);
$notificationObj->setUser($user);
$notificationObj->setType($type);
$notificationObj->setMessage($message);
$notificationObj->setCreatedAt(new \DateTime());
$notificationObj->setUpdatedAt(new \DateTime());
$em->persist($notificationObj);
$em->flush();
return $notificationObj;
}
public function setNotificationLogData($em, $dialogue, $user, $notificationObj) {
$notificationLogObj = $em->getRepository(JoNotificationLog::class)->findOneBy(array('dialogue' => $dialogue, 'user' => $user, 'notification' => $notificationObj));
if (!$notificationLogObj) {
$notificationLogObj = new JoNotificationLog();
if ($notificationLogObj) {
$notificationLogObj->setDialogue($dialogue);
$notificationLogObj->setUser($user);
$notificationLogObj->setNotification($notificationObj);
$notificationLogObj->setCreatedAt(new \DateTime());
$em->persist($notificationLogObj);
$em->flush();
return $notificationLogObj;
}
}
}
public function getDialogueCaseCardHoldsMeasure(Request $request, $dccId) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
$user = $this->get('security.token_storage')->getToken()->getUser();
$dialogueCaseCardObj = $em->getRepository(DialogueCaseCard::class)->find($dccId);
$today = new \DateTime();
$holds = [];
if ($dialogue->getdialogueType() == '1' || $dialogue->getdialogueType() == '2') {
$queryHoldIds = $em->createQuery(
"SELECT h FROM App\Entity\JoCaseCardHold h
left join App\Entity\DialogueCaseCardMeasure dcm with dcm.id = h.measure
left join App\Entity\DialogueCaseCard dcc with dcm.DialogueCaseCard = dcc.id
WHERE dcc.pCaseCardId = :predefinedCC and h.id IN (SELECT IDENTITY (hr.JoCaseCardHold) FROM App\Entity\HoldResponsiblePerson hr where hr.User = :patientUser and hr.responsibleType = 'GP' ) and (dcm.toDate >=:today or dcm.toDate IS NULL ) ")
->setParameter('predefinedCC', $dialogueCaseCardObj->getPCaseCardId())
->setParameter('patientUser', $patient->getUser())
->setParameter("today", $today->format('Y-m-d'));
$holdTemps = $queryHoldIds->execute();
foreach ($holdTemps as $hold) {
if ($hold->getMeasure()->getDialogueCaseCard()->getDialogue()->getFirstJoGroup()) {
$holds[] = $hold;
}
}
}
return $this->render("default/getDialogueCaseCardHoldsMeasure.html.twig", array(
'holds' => $holds,
));
}
public function shareActivity(Request $request) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
$user = $this->get('security.token_storage')->getToken()->getUser();
$shareListIds = $request->get('shareListIds');
$skalering_content = $request->get('skaleringContent');
$activityListQuery = $em->createQuery(
"SELECT dad FROM App\Entity\DialogueAttachmentDetails dad
WHERE dad.id IN (:shareListIds) order by dad.attachmentDate DESC")
->setParameter('shareListIds', explode(',', $shareListIds));
$activityList = $activityListQuery->execute();
$listId = explode(',', $shareListIds);
$fileCount= array();
foreach ($listId as $id){
$query = $em->createQuery(
"SELECT IDENTITY(da.dialogueAttachmentDetailId) as attachId, count(da) as filesCount from App\Entity\DialogueAttachments da WHERE da.dialogueAttachmentDetailId = :shareListIds")
->setParameter('shareListIds', $id);
$fileResult = $query->execute();
foreach($fileResult as $list){
$fileCount[$list['attachId']]['id'] = $list['filesCount'];
$fileCount[$list['attachId']]['size'] = $this->getFilesSize($user,$em,$list['attachId'],'unit');
}
}
$shareUsers = array();
//if($patient->getChildAge() < 18){
$patientFamilyObj = $em->getRepository(Family::class)->findBy(array('patient' => $patient));
foreach ($patientFamilyObj as $family){
if($family->getIsDeceased()!=1){
if($family->getCustodySince() != ''){
$shareUsers[] = $family;
}
if ($family->getRelation() == "9" && $family->getRelative()->getCprNo() != null && $family->getRelative()->getDeletedBy() == null) {
$shareUsers[] = $family;
}
}
}
//}
$shareUsersExternal = array();
$JoActivitySharing = $em->getRepository(JoActivitySharing::class)->findOneBy(array('dialogue' => $dialogue));
if($JoActivitySharing){
$participants = $JoActivitySharing->getJoActivitySharingParticipants();
foreach ($participants as $participant){
if($participant->getUserType() != 8 && $participant->getUserType() != null){
if(count($participant->getJoConsentApproveStatuses())){
if($participant->getReversedArrayStatuses()[0]->getApprovedStatus() == 1){
$shareUsersExternal[] = $participant;
}
}
}
}
}
//$patientInfoObjTemp = $em->getRepository(PatientInformation::class)->findBy(array('patient' => $patient));
//$patientInfoObj = $patientInfoObjTemp ? $patientInfoObjTemp[0] : array();
$isTestServer = $this->container->getParameter('isTestServer');
return $this->render("dialogueAttachment/_shareActivity.html.twig", array(
'activityList' => $activityList,
'shareListIds' => $shareListIds,
'skalering_content' => $skalering_content,
'patient' => $patient,
'shareUsers' => $shareUsers,
'shareUsersExternal' => $shareUsersExternal,
'isTestServer' => $isTestServer,
'fileCount' => $fileCount
//'patientInfoObj' => $patientInfoObj,
));
}
public function saveShareActivity(Request $request) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
$user = $this->get('security.token_storage')->getToken()->getUser();
$sharetype = $request->get('sharetype');
$shareListIds = $request->get('shareListIds');
$shareListIdArr = explode(',', $shareListIds);
$shareListIdArr = array_unique($shareListIdArr);
$participantUserIds = $request->get('participant_user_id');
$participantRelations = $request->get('participant_relation');
$participantCategories = $request->get('participant_category');
$participantMessages = $request->get('participant_message');
$external_recipient_texts = $request->get('external_recipient_text');
$participantEmails = $request->get('participant_email');
$cprNoList = ['0301782721','30598539'];
$isTestServer = $this->container->getParameter('isTestServer');
$shareTemplateSelectType = $request->get('share_template_select_type');
$participantRapportPdfs = $request->get('participant_rapport_pdf');
$participantFolgebrevPdfs = $request->get('participant_folgebrev_pdf');
if($sharetype == 'pdf'){
$sharingType = 0;
}elseif($sharetype == 'via_josa'){
$sharingType = 1;
}
$sendEbookEmail=1;
//var_dump($participantMessage); var_dump($participantRelation); var_dump($participantUserId);die;
//var_dump($shareListIdArr);die;
if($participantUserIds !="" && count($participantUserIds) > 0) {
//add in JoActivitySharing
if($sharingType == 1){
$JoActivitySharing = $em->getRepository(JoActivitySharing::class)->findOneBy(array('dialogue' => $dialogue));
if(!$JoActivitySharing){
$JoActivitySharing = new JoActivitySharing();
$JoActivitySharing->setDialogue($dialogue);
$JoActivitySharing->setSharingType($sharingType);
$JoActivitySharing->setCreatedAt(new \DateTime());
$JoActivitySharing->setUpdatedAt(new \DateTime());
}
$JoActivitySharing->setCreatedBy($user);
$em->persist($JoActivitySharing);
$em->flush();
$index = 0;
//add new notification for citizen
$type = 3;
$message = 5;
$notificationObj = $this->setNotificationData($em, $dialogue, $user, $type, $message);
$newParticipantCount = 0;
foreach ($participantUserIds as $participantUserId){
$participantUser = $em->getRepository(User::class)->find($participantUserId);
$userEmail = $participantUser->getEmail();
$isNewParticipant = false;
$JoActivitySharingParticipant = $em->getRepository(JoActivitySharingParticipant::class)->findOneBy(array('user' => $participantUserId, 'joActivitySharing' => $JoActivitySharing));
if(!$JoActivitySharingParticipant){
$JoActivitySharingParticipant = new JoActivitySharingParticipant();
$JoActivitySharingParticipant->setJoActivitySharing($JoActivitySharing);
$JoActivitySharingParticipant->setUser($participantUser);
//$JoActivitySharingParticipant->setActivity($activity);
$JoActivitySharingParticipant->setRelationText($participantRelations[$index]);
$JoActivitySharingParticipant->setSupplementsText($participantMessages[$index]);
$JoActivitySharingParticipant->setCreatedAt(new \DateTime());
$JoActivitySharingParticipant->setUpdatedAt(new \DateTime());
if($participantCategories){
$JoActivitySharingParticipant->setUserType(9);
}else{
$JoActivitySharingParticipant->setUserType(8);
}
$JoActivitySharingParticipant->setCreatedBy($user);
$newParticipantCount++;
$isNewParticipant = true;
}
//$JoActivitySharingParticipant->setSharingType($sharingType);
$em->persist($JoActivitySharingParticipant);
$em->flush();
foreach ($shareListIdArr as $shareListId){
//add in JOactivitysharingParticipant
$activity = $em->getRepository(DialogueAttachmentDetails::class)->find($shareListId);
$JoParticipantSharingActivity = $em->getRepository(JoParticipantSharingActivity::class)->findOneBy(array('JoActivitySharingParticipant' => $JoActivitySharingParticipant, 'Activity' => $activity));
if(!$JoParticipantSharingActivity){
$JoParticipantSharingActivity = new JoParticipantSharingActivity();
$JoParticipantSharingActivity->setJoActivitySharingParticipant($JoActivitySharingParticipant);
$JoParticipantSharingActivity->setActivity($activity);
}
$JoParticipantSharingActivity->setSharingType($sharingType);
$em->persist($JoParticipantSharingActivity);
$em->flush();
}
if($isNewParticipant){
$JoParticipantNotification1 = new JoParticipantNotification();
$JoParticipantNotification1->setJoActivitySharingParticipant($JoActivitySharingParticipant);
$JoParticipantNotification1->setJoNotification($notificationObj);
$JoParticipantNotification1->setCreatedAt(new \DateTime());
$em->persist($JoParticipantNotification1);
$em->flush();
}
if((($participantUser->hasRole('ROLE_EXTERN') || $user->getCategory()->getId() == 2) && $isTestServer == 1 && $userEmail == 'lsh@alldialogue.com') || (($participantUser->hasRole('ROLE_EXTERN') || $user->getCategory()->getId() == 2) && $isTestServer == 0)){
$participantMessage = $participantMessages[$index];
$container = $this->container;
$mailSubject = $dialogue->getSharedInvitationTitle()." - Delte dokumenter";
$messageTextConsent = $this->get('templating')->render('message/shared_josa_case_activity.html.twig', array(
'invitationTitle' => $dialogue->getSharedInvitationTitle(),
'participantMessage' => $participantMessage,
'userObj' => $participantUser,
'patient' => $patient,
'dialogue' => $dialogue,
'loginUserObj' => $user
));
$dialogueAttachmentControllerObj = new DialogueAttachmentController();
$responce = $dialogueAttachmentControllerObj->sendEmailMessage($em,$user,$container,'share_josa_case_activity_email',$mailSubject,$messageTextConsent,$userEmail,'post@jo-sa.dk','','','','');
//var_dump($responce);
//die;
if($responce || $responce == 0){
$fromUserId = $user->getId();
$toUserId = $participantUser->getId();
$dialogueId = $dialogue->getId();
$logFileName = '';
$logType = 'share_josa_case_activity_email';
$saveLogData = $dialogueAttachmentControllerObj->saveSkebelonLog($em,$responce,$fromUserId,$toUserId,$logType,$dialogueId,$logFileName,'','');
}
}
$index++;
}
if($newParticipantCount == 0){
$em->remove($notificationObj);
$em->flush();
}
}else{
$caseActivityId='';
$index = 0;
$participantMessage='';
$tunnelUserObj = $participantUser ='';
foreach ($participantUserIds as $participantUserId){
$participantMessage = $participantMessages[$index];
if($shareTemplateSelectType == 1){
$participantUserArr = explode("_",$participantUserId);
$participantUser= isset($participantUserArr[0])? $participantUserArr[0]:$participantUserId;
$tunnelUserObj = $em->getRepository(SepoTunnelliste::class)->findOneBy(array("rid" => $participantUser));
}else{
$participantUser = $em->getRepository(User::class)->find($participantUserId);
}
$predefinedType = $em->getRepository(PredefinedAttachmentType::class)->findOneBy(array('attachmentType' =>'Rapport'));
$predefinedAttachmentTypeObj = $em->getRepository(PredefinedAttachmentType::class)->find($predefinedType->getId());
$joPredefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'josa_rapport'));
$heading = 'Notater delt med aktør';
$selectedDateAttachment = '';
$isDraft = 0;
$dialogueAttachmentDetailObj = new DialogueAttachmentDetails();
$dialogueAttachmentDetailObj->setPCaseCardId($joPredefinedCaseCardObj);
$dialogueAttachmentDetailObj->setPatient($patient);
$dialogueAttachmentDetailObj->setDialogue($dialogue);
$dialogueAttachmentDetailObj->setDialogueCaseCard(NULL);
$dialogueAttachmentDetailObj->setDialogueCaseCardMeasureId(NULL);
$dialogueAttachmentDetailObj->setMeasureId(NULL);
$dialogueAttachmentDetailObj->setUser($user);
$dialogueAttachmentDetailObj->setPAtttachmentType($predefinedAttachmentTypeObj);
$selectedDate = new \DateTime($selectedDateAttachment);
$time_now = new \DateTime();
$merge = new \DateTime($selectedDate->format('Y-m-d') . ' ' . $time_now->format('H:i:s'));
$setSelectedDate = $merge->format('Y-m-d H:i:s');
$dialogueAttachmentDetailObj->setAttachmentDate(new \DateTime($setSelectedDate));
$dialogueAttachmentDetailObj->setTypeHeading($predefinedAttachmentTypeObj->getAttachmentType());
$dialogueAttachmentDetailObj->setIsDraft($isDraft);
$dialogueAttachmentDetailObj->setVisibleStatus(0);
$dialogueAttachmentDetailObj->setActivityType(12);
$dialogueAttachmentDetailObj->setAttachmentHeading($heading);
if($shareTemplateSelectType == 1){
$dialogueAttachmentDetailObj->setTunnelListId($tunnelUserObj->getRid());
$dialogueAttachmentDetailObj->setLetterRecevierName($tunnelUserObj->getName());
$relations = $participantEmails[$index];
$dialogueAttachmentDetailObj->setLetterRecevierUnit($relations);
}else if($shareTemplateSelectType == 2 || $shareTemplateSelectType == 3){
$dialogueAttachmentDetailObj->setLetterRecevier($participantUser);
$relations = $participantRelations[$index].", ".$participantEmails[$index];
$dialogueAttachmentDetailObj->setLetterRecevierUnit($relations);
}else{
$dialogueAttachmentDetailObj->setLetterRecevier($participantUser);
$patientFamilyObj = $em->getRepository(Family::class)->findOneBy(array('relative' => $participantUser));
$dialogueAttachmentDetailObj->setLetterRecevierUnit('Borger');
if($patientFamilyObj){
if($patientFamilyObj->getCustodySince() != ''){
if($patientFamilyObj->getRelation() == 1){
$dialogueAttachmentDetailObj->setLetterRecevierUnit('Forældre 1');
}
if($patientFamilyObj->getRelation() == 2){
$dialogueAttachmentDetailObj->setLetterRecevierUnit('Forældre 2');
}
}
if($patientFamilyObj->getRelation() == 9){
$dialogueAttachmentDetailObj->setLetterRecevierUnit($patientFamilyObj->getRelative()->getStamdataLabel());
}
}
}
$dialogueAttachmentDetailObj->setSahreTemplateType($shareTemplateSelectType);
if($shareTemplateSelectType == 1 || $shareTemplateSelectType == 2 || $shareTemplateSelectType == 0 || $shareTemplateSelectType == 3){
$dialogueAttachmentDetailObj->setExternalParticipantText($external_recipient_texts[$index]);
}
$em->persist($dialogueAttachmentDetailObj);
$em->flush();
$session->set('activityDetailUpdated', $dialogueAttachmentDetailObj->getId());
$newFilePath = '';
$webPath = $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
$fileName = pathinfo($participantRapportPdfs[$index], PATHINFO_FILENAME).".pdf";
$selectedFile = $webPath.$participantRapportPdfs[$index];
//File upload code for new records
if (file_exists($selectedFile) && $sharetype == 'pdf') {
$ext = pathinfo($selectedFile, PATHINFO_EXTENSION);
$onlyFileName = pathinfo($selectedFile, PATHINFO_FILENAME);
$newFilename = $onlyFileName."." . $ext;
$newFilePath = $webPath . $newFilename;
$originalFileName = 'Delte notater'. "." . $ext;
$dialogueAttachmentRapportObj = new DialogueAttachments();
$dialogueAttachmentRapportObj->setPatient($patient);
$dialogueAttachmentRapportObj->setDialogue($dialogue);
$dialogueAttachmentRapportObj->setUser($user);
$dialogueAttachmentRapportObj->setDialogueAttachmentDetailId($dialogueAttachmentDetailObj);
$dialogueAttachmentRapportObj->setAttachmentName($newFilename);
$dialogueAttachmentRapportObj->setOriginalName($originalFileName);
$dialogueAttachmentRapportObj->setIsDeleted(false);
$em->persist($dialogueAttachmentRapportObj);
$em->flush();
}
if (file_exists($selectedFile) && $sharetype == 'pdf') {
if($shareTemplateSelectType == 1 || $shareTemplateSelectType == 3){
$fromUserId = $user->getId();
if($shareTemplateSelectType == 1){
$toUserId = $tunnelUserObj->getRid();
$toEmail = $participantEmails[$index];//$tunnelUserObj->getEmail();
$receiver = $tunnelUserObj->getName()."_".$participantEmails[$index];//$tunnelUserObj->getEmail();
}else{
$toUserId = $participantUser->getId();
$toEmail = $participantUser->getEmail();
$receiver = $participantUser->getfullName()."_".$participantUser->getEmail();
}
$dialogueId = $dialogue->getId();
$mailSubject = "Delte dokumenter ";//$dialogue->getSharedExternalTitle();
$displayFileName = "Rapport sagsakter";
$logType = 'share_activity_brev_email';
$message='';
//$toEmail = $tunnelUserObj->getEmail();
$logFileName = $newFilename;
//$receiver = $tunnelUserObj->getName()."_".$tunnelUserObj->getEmail();
if($isTestServer == 1 && $toEmail == 'lsh@alldialogue.com' || $isTestServer == 0){
$citizenAddressFilePath = $webPath.$participantFolgebrevPdfs[$index];
if($citizenAddressFilePath){
$ext = pathinfo($citizenAddressFilePath, PATHINFO_EXTENSION);
$onlyFileName = pathinfo($citizenAddressFilePath, PATHINFO_FILENAME);
$newFilename = $onlyFileName."." . $ext;
$originlName = "Følgebrev.PDF";
$dialogueAttachmentFolbrevObj = new DialogueAttachments();
$dialogueAttachmentFolbrevObj->setPatient($patient);
$dialogueAttachmentFolbrevObj->setDialogue($dialogue);
$dialogueAttachmentFolbrevObj->setUser($user);
$dialogueAttachmentFolbrevObj->setDialogueAttachmentDetailId($dialogueAttachmentDetailObj);
$dialogueAttachmentFolbrevObj->setAttachmentName($newFilename);
$dialogueAttachmentFolbrevObj->setOriginalName($originlName);
$dialogueAttachmentFolbrevObj->setIsDeleted(false);
$em->persist($dialogueAttachmentFolbrevObj);
$em->flush();
}
$messageTextConsentForEmail = $this->get('templating')->render('message/share_activity-external-tunnel-dialogue-citizen.html.twig', array(
'participantMessage' => $participantMessage,
'userObj' => $tunnelUserObj,
'participantUser' => $participantUser,
'patient' => $patient,
'dialogueObj' => $dialogue,
'loginUserObj' => $user,
'shareTemplateSelectType' => $shareTemplateSelectType
));
$dialogueAttachmentControllerObj = new DialogueAttachmentController();
$responce = $dialogueAttachmentControllerObj->sendEmailMessage($em,$user,$this->container,"share_activity_brev_email",$mailSubject,$messageTextConsentForEmail,$toEmail,'post@jo-sa.dk', $displayFileName,$newFilePath,$shareListIdArr,'');
if($responce || $responce == 0){
$dialogueAttachmentControllerObj->saveSkebelonLog($em,$responce,$fromUserId,$toUserId,$logType,$dialogueId,$logFileName,$receiver,$dialogueAttachmentDetailObj->getId());
}else{
$sendEbookEmail=0;
//remove rapport
$em->remove($dialogueAttachmentRapportObj);
$em->flush();
//remove Følgebrev pdf
$em->remove($dialogueAttachmentFolbrevObj);
$em->flush();
//remove activity because email was not sent
$em->remove($dialogueAttachmentDetailObj);
$em->flush();
}
}
}else{
$fromUserId = $user->getId();
$toUserId = $participantUser->getId();
$dialogueId = $dialogue->getId();
$logFileName = $fileName;
$newFilePath = $selectedFile;
$mailSubject = $dialogue->getKommuneName();
$logType = 'case_activity_ebook';
$username = $participantUser->getUsername();
$userCpr = $participantUser->getCprNo();
$cprNo='';
if ($participantUser->hasRole('ROLE_TUNNEL_EXTERN')) {
$username = $participantUser->getCvrNo();
if(strlen($username) == 8) {
$cprNo = is_numeric($username)? $username : '0';
}
}else{
$username = $participantUser->getUsername();
if(strlen($username) >= 9 && strlen($username) <= 11) {
$cprNo = is_numeric($username)? $username : '0';
}else{
$cprNo = is_numeric($userCpr)? $userCpr : '0';
}
}
$folgebrevPdf = $webPath.$participantFolgebrevPdfs[$index];
if(($isTestServer == 1 && in_array($cprNo, $cprNoList) && $cprNo) || ($isTestServer == 0 && $cprNo)){
$container = $this->container;
$dialogueAttachmentControllerObj = new DialogueAttachmentController();
$responce = $dialogueAttachmentControllerObj->sendDoc2MailDialogueMessage($em,$user,$container,$newFilePath,$cprNo, $participantUser,$mailSubject, $dialogue,$dialogueAttachmentDetailObj,$dialogueAttachmentRapportObj,$shareListIdArr,'','',$participantMessage,$folgebrevPdf);
if($responce || $responce == 0){
$saveLogData = $dialogueAttachmentControllerObj->saveSkebelonLog($em,$responce,$fromUserId,$toUserId,$logType,$dialogueId,$logFileName,'',$dialogueAttachmentDetailObj->getId());
}
}
}
}
$index++;
}
}
}
$responce = 'success';
$response = new Response(json_encode(array('result' => $responce,'sharetype' => $sharetype,'send' => $sendEbookEmail)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function checkUserAgent($request, $session) {
$userAgent = strtolower($request->headers->get('user-agent'));
//var_dump($userAgent); die;
//strpos($userAgent,"ipad") === false &&
if ( preg_match('/(alcatel|amoi|android|ipad|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|
iemobile|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|
philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|
up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $userAgent
)
) {
//$request->setRequestFormat('mobile', 'text/html');
$session->set('templateVersion', 'mobile');
} else {
//$request->setRequestFormat('html', 'text/html');
$session->set('templateVersion', 'web');
}
}
/**
* @Route("/therapist/changeUserCategory/{category_id}", name="change_user_category", methods={"GET", "POST"})
*/
public function changeUserCategory(Request $request, $category_id){
$em = $this->getDoctrine()->getManager();
$response = new Response();
$response->headers->set('Content-Type', 'application/json');
/** TODO: Make this array using a config template; then render; then getContent() on rendered output */
$user_array = [];
$user_array[59996] = ["host"=>["nbg2-1-dev1.jo-sa.dk"], "categories"=>[45,48], "groups"=>[45=>"FAGGRUPPE_FAMILIEHUSET", 48=>"FAGGRUPPE_PPR"]];
$user_array[1648] = ["host"=>["holbaek.jo-sa.dk"], "categories"=>[53,64], "groups"=>[53=>"FAGGRUPPE_FAMILIEHUSET", 64=>"FAGGRUPPE_PPR"]];
$user = $this->get('security.token_storage')->getToken()->getUser();
if(!isset($user_array[$user->getId()])){
$response->setContent(json_encode(["result"=>"failed: user not allowed to change category"]));
return $response;
}
if(!in_array($_SERVER['HTTP_HOST'], $user_array[$user->getId()]["host"]) ){
$response->setContent(json_encode(["result"=>"failed: user not allowed to change category on this site"]));
return $response;
}
if(!in_array($category_id, $user_array[$user->getId()]["categories"]) ){
$response->setContent(json_encode(["result"=>"failed: user not allowed to change to that category"]));
return $response;
}
$category = $em->getRepository(Category::class)->findOneBy(["id"=>$category_id]);
$user->setCategory($category);
$em->persist($user);
$em->flush();
$stmt = $em->getConnection()->prepare("select roles from jo_user where id = ".$user->getId());
$stmt->execute();
$row = $stmt->fetch();
$roles = unserialize($row["roles"]);
$new_roles = [];
foreach($roles as $role){
if(!preg_match("/FAGGRUPPE_/", $role)){
$new_roles[] = $role;
}
}
$new_roles[] = $user_array[$user->getId()]["groups"][$category_id];
$stmt = $em->getConnection()->prepare("update jo_user set roles='".serialize($new_roles)."' where id = ".$user->getId());
$stmt->execute();
$response->setContent(json_encode(["result"=>"success"]));
return $response;
}
public function updateMorFarGardianToStamdata($em, $newPatient, $patientObject, $serviceResponse, $dialogueControllerObj, $session) {
$motherObject = $fatherObject = $guardianObject = null;
$parentCategory = $em->getRepository(Category::class)->findOneBy(array("id" => 1));
$userFullName = strlen($dialogueControllerObj->getFieldValue($patientObject, 'CNVN_FORNVN'));
if ($userFullName > 0) {
//This is normal code
$patientAddressObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'PNR_FOEDDATO', $newPatient->getCpr());
$newPatient->setLastName(trim($dialogueControllerObj->getFieldValue($patientObject, 'CNVN_EFTERNVN')));
$newPatient->setFirstName($dialogueControllerObj->getFieldValue($patientObject, 'CNVN_FORNVN') . ' ' . trim($dialogueControllerObj->getFieldValue($patientObject, 'CNVN_MELNVN')));
$newPatient->setAddressLine1($dialogueControllerObj->getFieldValue($patientObject, 'STADR'));
$isPatientDeceased = trim($dialogueControllerObj->getFieldValue($patientObject, 'CNVN_STATUS'));
if (isset($isPatientDeceased) && $isPatientDeceased == 90) {
$newPatient->setIsDeceased(1);
$deceasedDateTime = trim($dialogueControllerObj->getFieldValue($patientObject, 'CNVN_STATUSSTARTDATO'));
if (isset($deceasedDateTime)) {
//var_dump($deceasedDateTime);
$deceasedDateTemp = substr($deceasedDateTime, 0, 8);
//var_dump($deceasedDateTemp);
$deceasedDate = substr($deceasedDateTemp, 0, 4) . '-' . substr($deceasedDateTemp, 4, 2) . '-' . substr($deceasedDateTemp, 6, 2);
//var_dump($deceasedDate);die;
$newPatient->setDeceaseDate(new \DateTime($deceasedDate));
}
}
if ($patientAddressObject) {
$newPatient->setPostNumber($dialogueControllerObj->getFieldValue($patientAddressObject, 'CPST_POSTNR'));
$newPatient->setCity($dialogueControllerObj->getFieldValue($patientAddressObject, 'CPSN_POSTDISTTXT'));
} else {
$newPatient->setPostNumber($dialogueControllerObj->getFieldValue($patientObject, 'POSTNR'));
$newPatient->setCity($dialogueControllerObj->getFieldValue($patientObject, 'BYNVN'));
}
$session->set('cpr_naname', false);
} else {
//This code for child has no name i.e. untitled
//In that case set Mor Last name + Mor Address must be set to match MOTHER info with child.
$isMotherListed = false;
foreach (array('CFMY_RELTYPA', 'CFMY_RELTYPB', 'CFMY_RELTYPC') as $v) {
$rType = $dialogueControllerObj->getFieldValue($patientObject, $v);
if ($rType == '00003') {
$isMotherListed = true;
break;
}
}
if ($isMotherListed) {
$motherObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Mor');
if ($motherObject) {
$tmpMother = $this->createRelative($motherObject);
$newPatient->setFirstName("Unavngivet");
$newPatient->setLastName($tmpMother->getLastName());
$newPatient->setAddressLine1($tmpMother->getAddress());
$newPatient->setPostNumber($tmpMother->getPostNumber());
$newPatient->setCity($tmpMother->getCity());
$session->set('cpr_naname', true);
}
}
}
if (!$newPatient->isPatientMajor()) {
$rTypes = array();
$rTypesText = array('00003' => 'Mor', '00004' => 'Far', '00005' => 'Værge');
$whoIsHavingCustody = array();
$relationNumber = 0;
$custodyDates = array();
foreach (array('CFMY_RELTYPA' => 'CFMY_STARTDATOA', 'CFMY_RELTYPB' => 'CFMY_STARTDATOB', 'CFMY_RELTYPC' => 'CFMY_STARTDATOC') as $k => $v) {
$rType = $dialogueControllerObj->getFieldValue($patientObject, $k);
if ($rType) {
$rTypes[] = $rType;
$custodyDates[$rType] = $dialogueControllerObj->getFieldValue($patientObject, $v);
}
}
foreach ($rTypes as $relation) {
if ($relation == '00003') {
$motherObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Mor');
} else if ($relation == '00004') {
$fatherObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Far');
}if ($relation == '00005') {
$guardianObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Værge');
}if ($relation == '00006') {
$guardianObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Værge');
}
if(!in_array($relation, $whoIsHavingCustody)) {
array_push($whoIsHavingCustody,$relation);
}
}
//var_dump($guardianObject, $whoIsHavingCustody); die("ddd");
if (isset($motherObject) && $motherObject) {
$mothercprNo = $dialogueControllerObj->getFieldValue($motherObject, 'PNR_FOEDDATO');
$u = $em->getRepository(User::class)->findOneBy(array('username' => $mothercprNo));
$mother = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if (!$mother) {
$mother = new Family();
$u = $this->createRelative($motherObject);
if (!$u->hasRole('ROLE_PARENT')) {
$u->addRole('ROLE_PARENT');
$u->setCategory($parentCategory);
$u->setEnabled(true);
}
} else {
$u = $this->createRelative($motherObject);
$mother->setRelation(Family::REL_MOTHER);
}
if (trim($u->getStamdataLabel()) == "-") {
$u->setStamdataLabel(NULL);
}
$mother->setHasCustody(false);
$mother->setCustodySince(NULL);
$mother->setRelative($u);
if (isset($custodyDates['00003'])) {
$mother->setHasCustody(true);
$mother->setCustodySince(new \DateTime($custodyDates['00003']));
$relationNumber = 1;
$stamdataLabel = ((($mothercprNo % 10) % 2) == 0)? "Forælder $relationNumber (KVINDE)" : "Forælder $relationNumber (MAND)";
if($u){
$u->setStamdataLabel($stamdataLabel);
$u->setAddress($this->getFieldValue($motherObject, 'STADR'));
$u->setPostNumber($this->getFieldValue($motherObject, 'CPST_POSTNR'));
$u->setCity($this->getFieldValue($motherObject, 'CPSN_POSTDISTTXT'));
}
}
$newPatient->setMother($mother);
} else {
$motherObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Mor');
if($motherObject) {
$mothercprNo = $dialogueControllerObj->getFieldValue($motherObject, 'PNR_FOEDDATO');
$u = $em->getRepository(User::class)->findOneBy(array('username' => $mothercprNo));
$mother = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if($motherObject) {
$relationNumber = 1;
}
$stamdataLabel = ((($mothercprNo % 10) % 2) == 0)? "Forælder $relationNumber (KVINDE)" : "Forælder $relationNumber (MAND)";
if($u){
$u->setStamdataLabel($stamdataLabel);
$u->setAddress($this->getFieldValue($motherObject, 'STADR'));
$u->setPostNumber($this->getFieldValue($motherObject, 'CPST_POSTNR'));
$u->setCity($this->getFieldValue($motherObject, 'CPSN_POSTDISTTXT'));
}
if((!(isset($custodyDates['00003']))) && $mother){
$mother->setHasCustody(false);
$mother->setCustodySince(NULL);
}
}
}
if (isset($fatherObject) && $fatherObject) {
$fathercprNo = $dialogueControllerObj->getFieldValue($fatherObject, 'PNR_FOEDDATO');
$u = $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
$father = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if (!$father) {
$father = new Family();
$u = $this->createRelative($fatherObject);
if (!$u->hasRole('ROLE_PARENT')) {
$u->addRole('ROLE_PARENT');
$u->setCategory($parentCategory);
$u->setEnabled(true);
}
} else {
$u = $this->createRelative($fatherObject);
$father->setRelation(Family::REL_FATHER);
}
if (trim($u->getStamdataLabel()) == "-") {
$u->setStamdataLabel(NULL);
}
$father->setHasCustody(false);
$father->setCustodySince(NULL);
$father->setRelative($u);
if (isset($custodyDates['00004'])) {
$father->setHasCustody(true);
$father->setCustodySince(new \DateTime($custodyDates['00004']));
if (isset($custodyDates['00003'])){
$relationNumber = 2;
} else {
$relationNumber = 1;
}
$stamdataLabel = ((($fathercprNo % 10) % 2) == 0)? "Forælder $relationNumber (KVINDE)" : "Forælder $relationNumber (MAND)";
if($u){
$u->setStamdataLabel($stamdataLabel);
$u->setAddress($this->getFieldValue($fatherObject, 'STADR'));
$u->setPostNumber($this->getFieldValue($fatherObject, 'CPST_POSTNR'));
$u->setCity($this->getFieldValue($fatherObject, 'CPSN_POSTDISTTXT'));
}
}
$newPatient->setFather($father);
} else {
$motherObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Mor');
$fatherObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Far');
if($fatherObject) {
$fathercprNo = $dialogueControllerObj->getFieldValue($fatherObject, 'PNR_FOEDDATO');
$u = $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
$father = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if($motherObject) {
$relationNumber = 2;
} else {
$relationNumber = 1;
}
$stamdataLabel = ((($fathercprNo % 10) % 2) == 0)? "Forælder $relationNumber (KVINDE)" : "Forælder $relationNumber (MAND)";
if($u){
$u->setStamdataLabel($stamdataLabel);
$u->setAddress($this->getFieldValue($fatherObject, 'STADR'));
$u->setPostNumber($this->getFieldValue($fatherObject, 'CPST_POSTNR'));
$u->setCity($this->getFieldValue($fatherObject, 'CPSN_POSTDISTTXT'));
}
if((!(isset($custodyDates['00004']))) && $father){
$father->setHasCustody(false);
$father->setCustodySince(NULL);
}
}
}
if (isset($guardianObject) && $guardianObject) {
$guardiancprNo = $dialogueControllerObj->getFieldValue($guardianObject, 'PNR_FOEDDATO');
$u = $em->getRepository(User::class)->findOneBy(array('username' => $guardiancprNo));
$guardian = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if (!$guardian) {
$guardian = new Family();
$u = $this->createRelative($guardianObject);
if (!$u->hasRole('ROLE_PARENT')) {
$u->addRole('ROLE_PARENT');
$u->setCategory($parentCategory);
$u->setEnabled(true);
}
} else {
$u = $this->createRelative($guardianObject);
$guardian->setRelation(Family::REL_GUARDIAN);
}
if (trim($u->getStamdataLabel()) == "-") {
$u->setStamdataLabel(NULL);
}
$guardian->setHasCustody(false);
$guardian->setCustodySince(NULL);
$guardian->setRelative($u);
if (isset($custodyDates['00005'])) {
$guardian->setHasCustody(true);
$guardian->setCustodySince(new \DateTime($custodyDates['00005']));
}
$newPatient->setGuardian($guardian);
} else {
$guardianObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Værge');
if($guardianObject) {
$guardiancprNo = $dialogueControllerObj->getFieldValue($guardianObject, 'PNR_FOEDDATO');
$u = $em->getRepository(User::class)->findOneBy(array('username' => $guardiancprNo));
$guardian = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if((!(isset($custodyDates['00005']))) && $guardian){
$guardian->setHasCustody(false);
$guardian->setCustodySince(NULL);
} else if((!(isset($custodyDates['00006']))) && $guardian){
$guardian->setHasCustody(false);
$guardian->setCustodySince(NULL);
}
} else {
//JOSA custody update.pdf
if (in_array('00005', $whoIsHavingCustody)) {
$custodyFarSinceDate = trim($dialogueControllerObj->getFieldValue($patientObject, 'CFMY_STARTDATOA'));
$custodyFatherCprNo = trim($dialogueControllerObj->getFieldValue($patientObject, 'FORAELDRE_MYN_PNRA'));
$fatherUserObj = $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
if (($fathercprNo === $custodyFatherCprNo) && $father) {
if (isset($custodyFarSinceDate) && strlen($custodyFarSinceDate) > 0) {
$father->setHasCustody(true);
$father->setCustodySince(new \DateTime($custodyFarSinceDate));
}
}
} else if (in_array('00006', $whoIsHavingCustody)) {
$custodyMorSinceDate = trim($dialogueControllerObj->getFieldValue($patientObject, 'CFMY_STARTDATOB'));
$custodyMotherCprNo = trim($dialogueControllerObj->getFieldValue($patientObject, 'FORAELDRE_MYN_PNRB'));
$motherUserObj = $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
if (($mothercprNo === $custodyMotherCprNo) && $mother) {
if (isset($custodyMorSinceDate) && strlen($custodyMorSinceDate) > 0) {
$mother->setHasCustody(true);
$mother->setCustodySince(new \DateTime($custodyMorSinceDate));
}
}
}
}
}
}
if (is_null($motherObject) && is_null($fatherObject) && is_null($guardianObject) && (!$newPatient->isPatientMajor())) {
/* 21-11-2017 New code for new cpr functionality * */
$motherObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Mor');
$fatherObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Far');
$guardianObject = $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row, 'FAMMRK', 'Værge');
$childrenCPR = $dialogueControllerObj->getFieldValue($patientObject, 'PNR');
$getFullDate = $this->getFullDateFromCPR($childrenCPR);
if (isset($motherObject) && $motherObject) {
$mothercprNo = $dialogueControllerObj->getFieldValue($motherObject, 'PNR_FOEDDATO');
$u = $em->getRepository(User::class)->findOneBy(array('username' => $mothercprNo));
$mother = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if (!$mother) {
$mother = new Family();
$u = $this->createRelative($motherObject);
if (!$u->hasRole('ROLE_PARENT')) {
$u->addRole('ROLE_PARENT');
$u->setCategory($parentCategory);
$u->setEnabled(true);
}
} else {
$u = $this->createRelative($motherObject);
$mother->setRelation(Family::REL_MOTHER);
}
if (trim($u->getStamdataLabel()) == "-") {
$u->setStamdataLabel(NULL);
}
$mother->setHasCustody(false);
$mother->setCustodySince(NULL);
$mother->setIsParticipant(false);
$mother->setRelative($u);
if (isset($custodyDates['00003'])) {
$mother->setHasCustody(true);
$mother->setCustodySince(new \DateTime($custodyDates['00003']));
} else {
$needToUpdateCustody = true;
//$mother->setCustodySince(new \DateTime($getFullDate));
}
$newPatient->setMother($mother);
}
if (isset($fatherObject) && $fatherObject) {
$fathercprNo = $dialogueControllerObj->getFieldValue($fatherObject, 'PNR_FOEDDATO');
$u = $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
$father = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if (!$father) {
$father = new Family();
$u = $this->createRelative($fatherObject);
if (!$u->hasRole('ROLE_PARENT')) {
$u->addRole('ROLE_PARENT');
$u->setCategory($parentCategory);
$u->setEnabled(true);
}
} else {
$u = $this->createRelative($fatherObject);
$father->setRelation(Family::REL_FATHER);
}
if (trim($u->getStamdataLabel()) == "-") {
$u->setStamdataLabel(NULL);
}
$father->setHasCustody(false);
$father->setCustodySince(NULL);
$father->setIsParticipant(false);
$father->setRelative($u);
if (isset($custodyDates['00004'])) {
$father->setHasCustody(true);
$father->setCustodySince(new \DateTime($custodyDates['00004']));
} else {
$needToUpdateCustody = true;
//$father->setCustodySince(new \DateTime($getFullDate));
}
$newPatient->setFather($father);
}
if (isset($guardianObject) && $guardianObject) {
$guardiancprNo = $dialogueControllerObj->getFieldValue($guardianObject, 'PNR_FOEDDATO');
$u = $em->getRepository(User::class)->findOneBy(array('username' => $guardiancprNo));
$guardian = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if (!$guardian) {
$guardian = new Family();
$u = $this->createRelative($guardianObject);
if (!$u->hasRole('ROLE_PARENT')) {
$u->addRole('ROLE_PARENT');
$u->setCategory($parentCategory);
$u->setEnabled(true);
}
} else {
$u = $this->createRelative($guardianObject);
$guardian->setRelation(Family::REL_GUARDIAN);
}
if (trim($u->getStamdataLabel()) == "-") {
$u->setStamdataLabel(NULL);
}
$guardian->setHasCustody(false);
$guardian->setCustodySince(NULL);
$guardian->setIsParticipant(false);
$guardian->setRelative($u);
if (isset($custodyDates['00005'])) {
$guardian->setHasCustody(true);
$guardian->setCustodySince(new \DateTime($custodyDates['00005']));
} else {
$needToUpdateCustody = true;
//$guardian->setCustodySince(new \DateTime($getFullDate));
}
$newPatient->setGuardian($guardian);
}
//$form = $this->createForm(new PatientType(), $newPatient);
/* 21-11-2017 New code for new cpr functionality * */
if (is_null($guardianObject) && (isset($custodyDates['00005']) || isset($custodyDates['00006']) ) && (!$newPatient->isPatientMajor())) {
//die("you need to do code here");
$userLabelText = "Værge 1";
$userAddress = $userPostno = $userCity = $guardianCustodySince = NULL;
$guardianHasCustody = false;
$guardiancprNo = ($dialogueControllerObj->getFieldValue($patientObject, 'FORAELDRE_MYN_PNRA'));
$getGuardianIsShowAddress = ($dialogueControllerObj->getFieldValue($patientObject, 'MYN_BESKYTA'));
$guardianFullName = ($dialogueControllerObj->getFieldValue($patientObject, 'NAVNA'));
$guardianIsShowAddress = ($getGuardianIsShowAddress == "00001") ? true : false;
if(isset($custodyDates['00005'])) {
$userLabelText = "Værge 1";
$guardianHasCustody = true;
$guardianCustodySince = (new \DateTime($custodyDates['00005']));
$guardian = $this->createPatientGardian($em, $newPatient, $parentCategory, $userLabelText, $guardianHasCustody, $guardianCustodySince, $guardiancprNo, $guardianFullName, $guardianIsShowAddress, $userAddress, $userPostno, $userCity);
$newPatient->setGuardian($guardian);
}
if(isset($custodyDates['00006']) && !isset($custodyDates['00005']) ) {
$userLabelText = "Værge 1";
$guardianHasCustody = true;
$guardianCustodySince = (new \DateTime($custodyDates['00006']));
$guardian = $this->createPatientGardian($em, $newPatient, $parentCategory, $userLabelText, $guardianHasCustody, $guardianCustodySince, $guardiancprNo, $guardianFullName, $guardianIsShowAddress, $userAddress, $userPostno, $userCity);
$newPatient->setGuardian($guardian);
}
if(isset($custodyDates['00006']) && isset($custodyDates['00005']) ) {
$userLabelText = "Værge 2";
$guardianHasCustody = true;
$guardianCustodySince = (new \DateTime($custodyDates['00006']));
$guardiancprNo = ($dialogueControllerObj->getFieldValue($patientObject, 'FORAELDRE_MYN_PNRB'));
$guardianFullName = ($dialogueControllerObj->getFieldValue($patientObject, 'NAVNB'));
$guardian = $this->createPatientGardian($em, $newPatient, $parentCategory, $userLabelText, $guardianHasCustody, $guardianCustodySince, $guardiancprNo, $guardianFullName, $guardianIsShowAddress, $userAddress, $userPostno, $userCity);
$newPatient->setGuardian($guardian);
}
//createGardianRelative($usercpr, $userFirstname, $userLastname, $userAddress=NULL, $userPostno=NULL, $userCity=NULL);
}
//die("Final");
//$errorMsg = "Ingen oplysninger om forældremyndighed for dette CPR-nummer. Dialog kan ikke oprettes. Kontakt evt. Statsforvaltningen.";
//$cprLookupform->get('cpr')->addError(new FormError($errorMsg));
}
}
public function createRelative($relativeObject) {
$serviceResponse = $this->doSoapRequest(208, $this->getFieldValue($relativeObject, 'PNR_FOEDDATO'));
$parentObject = $serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row[0];
//Check this user is already exist or not
$em = $this->getDoctrine()->getManager();
$cprNo = $this->getFieldValue($relativeObject, 'PNR_FOEDDATO');
$user = $em->getRepository(User::class)->findBy(array('username' => $cprNo));
if($user) {
$user = $user ? $user[0] : NULL;
} else {
$user = new Relative();
}
$user->setLastName(trim($this->getFieldValue($parentObject, 'CNVN_EFTERNVN')));
$user->setFirstName($this->getFieldValue($parentObject, 'CNVN_FORNVN'). ' '.trim($this->getFieldValue($parentObject, 'CNVN_MELNVN')));
$user->setUsername($this->getFieldValue($relativeObject, 'PNR_FOEDDATO'));
$user->setAddress($this->getFieldValue($relativeObject, 'STADR'));
//$user->setAddressLine2('');
$user->setPostNumber($this->getFieldValue($relativeObject, 'CPST_POSTNR'));
$user->setCity($this->getFieldValue($relativeObject, 'CPSN_POSTDISTTXT'));
return $user;
}
public function getFieldValue($x, $id) {
if(!is_null($x)){
foreach ($x as $e) {
if ($e['r'] == $id) {
return (string) $e['v'];
}
}
}
return null;
}
/* 21-11-2017 New code for new cpr functionality **/
private function getFullDateFromCPR($date) {
$datebegin = substr($date, 0, 6);
$dateOnly = substr($date, 0, 2);
$monthOnly = substr($date, 2, 2);
$dateend = substr($datebegin, 4, 2);
$yn = date("y");
if ($dateend > $yn && $dateend < 100) {
$year2 = 19;
} else if ($dateend <= $yn) {
$year2 = 20;
}
$date = $dateOnly . "-" . $monthOnly . "-" . $year2 . $dateend;
return $date;
}
public function generateShareActivityPdf(Request $request) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
$user = $this->get('security.token_storage')->getToken()->getUser();
$shareListIds = $request->get('shareListIds');
$skeleringFormContentHtmlData= $request->get('skeleringFormContentHtmlData');
$exploded = explode(',', $shareListIds);
$exploded = array_unique($exploded);
$participantUserIds = $request->get('participant_user_id');
$generatedPDFFile = $this->processShareActivityPdfWithoutUser($em,$this->container,$dialogue,$patient,$user,$exploded,'view_pdf',$skeleringFormContentHtmlData);
/*$caseActivityId='';
foreach ($exploded as $shareListId) {
$caseActivityId .= "_".$shareListId;
}*/
$fileName = "CaseActivityTemplate.pdf";
return $this->file($generatedPDFFile, $fileName, ResponseHeaderBag::DISPOSITION_INLINE);
}
public function processShareActivityPdf($em,$container,$dialogue,$patient,$user,$participantUserIds,$exploded,$type,$skeleringFormContentHtmlData){
$imageData = $this->container->getParameter('image_data');
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')
$url = "https://";
else
$url = "http://";
$url.= $_SERVER['HTTP_HOST'];
//$url = $this->get('kernel')->getProjectDir().'/public';
$activityListQuery = $em->createQuery(
"SELECT dad FROM App\Entity\DialogueAttachmentDetails dad
WHERE dad.id IN (:shareListIds) order by dad.attachmentDate DESC")
->setParameter('shareListIds', $exploded);
$activityList = $activityListQuery->execute();
$activityCount = count($activityList);
foreach ($participantUserIds as $participantUserId){
$participantUserObj = $em->getRepository(User::class)->find($participantUserId);
$cnt=0;$messageText=$caseActivityId='';
$shareActivityArray = array();
foreach ($activityList as $activityObj) {
$attachmentDate = $activityObj->getAttachmentDate()->format('d-m-Y');
//$activityObj = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array('id' => $shareListId));
$tunnelshareActivity=array();
$tunnelRid= $activityObj->getTunnelListId();
if($tunnelRid){
$tunnelDetailsObj = $em->getRepository(SepoTunnelliste::class)->findOneBy(array('rid' => $tunnelRid));
if($tunnelDetailsObj){
$tunnelshareActivity[$tunnelRid]= array('name' => $tunnelDetailsObj->getName());
}
}
$dialogueAttachments = $em->getRepository(DialogueAttachments::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient));
$dialogueAttachmentFileName = array();
foreach ($dialogueAttachments as $dialogueAttachment) {
$id = $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
$dialogueAttachmentFileName[$id]['files'][] = $dialogueAttachment;
$fileIsImported = false;
$isSharedJournal = false;
if(isset($dialogueAttachment) && !empty($dialogueAttachment)) {
$fileIsImported = $dialogueAttachment->getIsImported();
$isSharedJournal = $dialogueAttachment->getIsSharedJournal();
}
if($isSharedJournal) {
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/attachmentsJournal/';
} else if($fileIsImported) {
/*if($user->hasRole('ROLE_CSV')){
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/kingo_src/';
}else{*/
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/kingo/';
//}
} else {
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/attachments/';
}
if(file_exists($webPath.$dialogueAttachment->getAttachmentName())){
$filesize = filesize($webPath.$dialogueAttachment->getAttachmentName());
$dialogueAttachmentFileName[$id]['size'][] = $this->formatSizeUnits($filesize);
}else{
$dialogueAttachmentFileName[$id]['size'][] = '';
}
}
$noteDetails=[];
if($activityObj->getPAtttachmentType()->getId() == 5){
$noteDetails = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('parentId' => $activityObj->getId()),array('id' => 'DESC'));
}
//featchScaleGraph detils
$res=$this->featchAllScalingGraphDetails($em,$activityObj);
if($res){
$scaleGraphArray[$activityObj->getId()] = isset($res['scalingIndividualGraphArray'][$activityObj->getId()])?$res['scalingIndividualGraphArray'][$activityObj->getId()]:[];
}
$array = json_decode($imageData, true);
$skelelonText = $container->get('templating')->render('message/case_activity-success.html.twig', array('dialogueObj'=>$dialogue,'userObj'=> $user, 'participantUserObj'=>$participantUserObj,'activityObj' => $activityObj,'dialogueAttachmentFileName' => $dialogueAttachmentFileName,'cnt'=>$cnt,'schemeAndHost'=>$url,'imageData'=>$array,'patient'=>$patient,'tunnelshareActivity'=>$tunnelshareActivity,'activityList'=>$activityList,'skeleringFormContentHtmlData'=>$skeleringFormContentHtmlData,'scaleGraphArray'=>$scaleGraphArray,'noteDetails'=> $noteDetails, 'attachmentDate'=>$attachmentDate, 'activityCount' => $activityCount));
if($activityObj->getPAtttachmentType()->getAttachmentType() == 'Skabelon'){
$skelelonText = str_replace('class="h70"','class="h70 hide"',$skelelonText);
$skelelonText = str_replace('section_area','section_area'.$cnt,$skelelonText);
$skelelonText = str_replace('header_area','header_area'.$cnt." hide",$skelelonText);
$skelelonText = str_replace('footer_area','footer_area'.$cnt." hide",$skelelonText);
$skelelonText = str_replace('sarea_1','sarea_1'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_2','sarea_2'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_3','sarea_3'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_4','sarea_4'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_5','sarea_5'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_6','sarea_6'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_7','sarea_7'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_8','sarea_8'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_9','sarea_9'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_10','sarea_10'.$cnt,$skelelonText);
$skelelonText = str_replace('sopt_1','sopt_1'.$cnt,$skelelonText);
$skelelonText = str_replace('sopt_2','sopt_2'.$cnt,$skelelonText);
$skelelonText = str_replace('nbr_sections','nbr_sections'.$cnt,$skelelonText);
$skelelonText = str_replace('<span class="editable_div" contenteditable="true" data-text="Skriv her…"></span>','<span class="editable_div" contenteditable="true" data-text="Skriv her…">-</span>',$skelelonText);
$skelelonText = str_replace('<span class="editable_div limit_length w259" max-length="35" contenteditable="true" data-text="Skriv her…"></span>','<span class="editable_div limit_length w259" max-length="35" contenteditable="true" data-text="Skriv her…">-</span>',$skelelonText);
$skelelonText = str_replace('<span class="editable_div limit_length w122" contenteditable="true" max-length="14" data-text="Skriv her…"></span>','<span class="editable_div limit_length w122" contenteditable="true" max-length="14" data-text="Skriv her…">-</span>',$skelelonText);
}
$dialogueAttachmentControllerObj = new DialogueAttachmentController();
$skelelonText = $dialogueAttachmentControllerObj->replaceMessageTextForPdf(true,$container,$skelelonText,'',$attachmentDate);
$messageText .= $skelelonText;
$caseActivityId .= "_".$participantUserId;
$cnt++;
}
}
$messageText = str_replace('Skriv note her...','',$messageText);
$messageText= str_replace('<img class="content-img" src="../template/res/cfk-header-543x703.jpg" alt="">','',$messageText);
$html1 = $messageText;
//echo $html1;
//die;
$webPathDoc_2_mail = $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
//if($type != 'view_pdf'){
$caseActivityId = "_".uniqid('', true);
//}
$htmlFileName = "CaseActivityTemplate".$caseActivityId. ".html";
$pdfFileName = "CaseActivityTemplate".$caseActivityId. ".pdf";
$generatedHtmlFile= $webPathDoc_2_mail . $htmlFileName;
$generatedPDFFile= $webPathDoc_2_mail . $pdfFileName;
$data = file_put_contents($generatedHtmlFile, $html1);
$filePath = $generatedPDFFile;
$html = $webPathDoc_2_mail."CaseActivityTemplate".$caseActivityId. ".html ";
$fileName = "CaseActivityTemplate".$caseActivityId. ".pdf ";
$outputFilePath = $webPathDoc_2_mail.$fileName;
if (file_exists($filePath)) {
unlink($filePath);
}
if (!file_exists($generatedPDFFile)) {
$dialogueAttachmentControllerObj = new DialogueAttachmentController();
$res = $dialogueAttachmentControllerObj->createTemplatePdf($html,$fileName,$outputFilePath);
//var_dump($res);
//die;
if (file_exists($generatedHtmlFile)) {
unlink($generatedHtmlFile);
}
}
return $generatedPDFFile;
}
public function processShareActivityPdfWithoutUser($em,$container,$dialogue,$patient,$user,$exploded,$type,$skeleringFormContentHtmlData){
$imageData = $this->container->getParameter('image_data');
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')
$url = "https://";
else
$url = "http://";
$url.= $_SERVER['HTTP_HOST'];
//$url = $this->get('kernel')->getProjectDir().'/public';
$activityListQuery = $em->createQuery(
"SELECT dad FROM App\Entity\DialogueAttachmentDetails dad
WHERE dad.id IN (:shareListIds) order by dad.attachmentDate DESC")
->setParameter('shareListIds', $exploded);
$activityList = $activityListQuery->execute();
//foreach ($participantUserIds as $participantUserId){
//$participantUserObj = $em->getRepository(User::class)->find($participantUserId);
$cnt=0;$messageText=$caseActivityId='';
$shareActivityArray = $scaleGraphArray = array();
$activityCount = count($activityList);
foreach ($activityList as $activityObj) {
$attachmentDate = $activityObj->getAttachmentDate()->format('d-m-Y');
//$activityObj = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array('id' => $shareListId));
$tunnelshareActivity=array();
$tunnelRid= $activityObj->getTunnelListId();
if($tunnelRid){
$tunnelDetailsObj = $em->getRepository(SepoTunnelliste::class)->findOneBy(array('rid' => $tunnelRid));
if($tunnelDetailsObj){
$tunnelshareActivity[$tunnelRid]= array('name' => $tunnelDetailsObj->getName());
}
}
$dialogueAttachments = $em->getRepository(DialogueAttachments::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient));
$dialogueAttachmentFileName = array();
foreach ($dialogueAttachments as $dialogueAttachment) {
$id = $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
$dialogueAttachmentFileName[$id]['files'][] = $dialogueAttachment;
$fileIsImported = false;
$isSharedJournal = false;
if(isset($dialogueAttachment) && !empty($dialogueAttachment)) {
$fileIsImported = $dialogueAttachment->getIsImported();
$isSharedJournal = $dialogueAttachment->getIsSharedJournal();
}
if($isSharedJournal) {
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/attachmentsJournal/';
} else if($fileIsImported) {
/*if($user->hasRole('ROLE_CSV')){
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/kingo_src/';
}else{*/
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/kingo/';
//}
} else {
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/attachments/';
}
if(file_exists($webPath.$dialogueAttachment->getAttachmentName())){
$filesize = filesize($webPath.$dialogueAttachment->getAttachmentName());
$dialogueAttachmentFileName[$id]['size'][] = $this->formatSizeUnits($filesize);
}else{
$dialogueAttachmentFileName[$id]['size'][] = '';
}
}
$noteDetails=[];
if($activityObj->getPAtttachmentType()->getId() == 5){
$noteDetails = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('parentId' => $activityObj->getId()),array('id' => 'DESC'));
}
//featchScaleGraph detils
$res=$this->featchAllScalingGraphDetails($em,$activityObj);
if($res){
$scaleGraphArray[$activityObj->getId()] = isset($res['scalingIndividualGraphArray'][$activityObj->getId()])?$res['scalingIndividualGraphArray'][$activityObj->getId()]:[];
}
$array = json_decode($imageData, true);
$skelelonText = $container->get('templating')->render('message/case_activity-success.html.twig', array('dialogueObj'=>$dialogue,'userObj'=> $user, 'participantUserObj'=>'','activityObj' => $activityObj,'dialogueAttachmentFileName' => $dialogueAttachmentFileName,'cnt'=>$cnt,'schemeAndHost'=>$url,'imageData'=>$array,'patient'=>$patient,'tunnelshareActivity'=>$tunnelshareActivity,'activityList'=>$activityList,'skeleringFormContentHtmlData'=>$skeleringFormContentHtmlData,'scaleGraphArray'=>$scaleGraphArray,'noteDetails'=> $noteDetails, 'attachmentDate'=>$attachmentDate, 'activityCount' => $activityCount));
if($activityObj->getPAtttachmentType()->getAttachmentType() == 'Skabelon'){
$skelelonText = str_replace('class="h70"','class="h70 hide"',$skelelonText);
$skelelonText = str_replace('section_area','section_area'.$cnt,$skelelonText);
$skelelonText = str_replace('header_area','header_area'.$cnt." hide",$skelelonText);
$skelelonText = str_replace('footer_area','footer_area'.$cnt." hide",$skelelonText);
$skelelonText = str_replace('sarea_1','sarea_1'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_2','sarea_2'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_3','sarea_3'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_4','sarea_4'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_5','sarea_5'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_6','sarea_6'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_7','sarea_7'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_8','sarea_8'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_9','sarea_9'.$cnt,$skelelonText);
$skelelonText = str_replace('sarea_10','sarea_10'.$cnt,$skelelonText);
$skelelonText = str_replace('sopt_1','sopt_1'.$cnt,$skelelonText);
$skelelonText = str_replace('sopt_2','sopt_2'.$cnt,$skelelonText);
$skelelonText = str_replace('nbr_sections','nbr_sections'.$cnt,$skelelonText);
$skelelonText = str_replace('<span class="editable_div" contenteditable="true" data-text="Skriv her…"></span>','<span class="editable_div" contenteditable="true" data-text="Skriv her…">-</span>',$skelelonText);
$skelelonText = str_replace('<span class="editable_div limit_length w259" max-length="35" contenteditable="true" data-text="Skriv her…"></span>','<span class="editable_div limit_length w259" max-length="35" contenteditable="true" data-text="Skriv her…">-</span>',$skelelonText);
$skelelonText = str_replace('<span class="editable_div limit_length w122" contenteditable="true" max-length="14" data-text="Skriv her…"></span>','<span class="editable_div limit_length w122" contenteditable="true" max-length="14" data-text="Skriv her…">-</span>',$skelelonText);
}
$dialogueAttachmentControllerObj = new DialogueAttachmentController();
$skelelonText = $dialogueAttachmentControllerObj->replaceMessageTextForPdf(true,$container,$skelelonText,'',$attachmentDate);
$messageText .= $skelelonText;
//$caseActivityId .= "_".$participantUserId;
$cnt++;
}
//}
$messageText = str_replace('Skriv note her...','',$messageText);
$messageText= str_replace('<img class="content-img" src="../template/res/cfk-header-543x703.jpg" alt="">','',$messageText);
$html1 = $messageText;
//echo $html1;
//die;
$webPathDoc_2_mail = $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
//if($type != 'view_pdf'){
$caseActivityId = "_".uniqid('', true);
//}
$htmlFileName = "CaseActivityTemplate".$caseActivityId. ".html";
$pdfFileName = "CaseActivityTemplate".$caseActivityId. ".pdf";
$generatedHtmlFile= $webPathDoc_2_mail . $htmlFileName;
$generatedPDFFile= $webPathDoc_2_mail . $pdfFileName;
$data = file_put_contents($generatedHtmlFile, $html1);
$filePath = $generatedPDFFile;
$html = $webPathDoc_2_mail."CaseActivityTemplate".$caseActivityId. ".html ";
$fileName = "CaseActivityTemplate".$caseActivityId. ".pdf ";
$outputFilePath = $webPathDoc_2_mail.$fileName;
if (file_exists($filePath)) {
unlink($filePath);
}
if (!file_exists($generatedPDFFile)) {
$dialogueAttachmentControllerObj = new DialogueAttachmentController();
$res = $dialogueAttachmentControllerObj->createTemplatePdf($html,$fileName,$outputFilePath);
//var_dump($res);
//die;
if (file_exists($generatedHtmlFile)) {
unlink($generatedHtmlFile);
}
}
return $generatedPDFFile;
}
public function checkSessionTimeout(Request $request) {
$responce = 'success';
$user = $this->get('security.token_storage')->getToken()->getUser();
//if (!($user)) {
if (!is_object($user)) {
$responce = 'fail';
}
//var_dump($user, $responce); die;
$response = new Response(json_encode(array('result' => $responce)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function updateStamdataISTElevData($patient, $session) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $entityManager = $this->getDoctrine()->getManager();
if ($patient) {
$cprNumber = $patient->getCpr();
$isMultipleRecords = false;
$fetchPatientIstElevData = $em->getRepository(IstElev::class)->findOneByCpr($cprNumber);
$fetchPatientLastSchoolIstElevUdvData = $em->getRepository(IstElevUdv::class)->findLastSchoolByCpr($cprNumber);
$fetchPatientAllIstElevUdvData = $em->getRepository(IstElevUdv::class)->findAllByCpr($cprNumber);
//var_dump($fetchPatientLastSchoolIstElevUdvData);
//die;
//var_dump($cprNumber, $fetchPatientIstElevData);
if ($fetchPatientIstElevData) {
$skolekode = $fetchPatientLastSchoolIstElevUdvData ? $fetchPatientLastSchoolIstElevUdvData->getSkolekode() : $fetchPatientIstElevData->getSkolekode();
$skolenavn = $fetchPatientLastSchoolIstElevUdvData ? $fetchPatientLastSchoolIstElevUdvData->getSkolenavn() : $fetchPatientIstElevData->getSkolenavn();
$skoletype = $fetchPatientLastSchoolIstElevUdvData ? $fetchPatientLastSchoolIstElevUdvData->getSkoletype() : NULL;
$klassetype = $fetchPatientLastSchoolIstElevUdvData ? $fetchPatientLastSchoolIstElevUdvData->getKlassetype() : $fetchPatientIstElevData->getKlassetype();
$elevklassetrin = $fetchPatientLastSchoolIstElevUdvData ? $fetchPatientLastSchoolIstElevUdvData->getElevklassetrin() : NULL;
$klassebetegnelse = $fetchPatientLastSchoolIstElevUdvData ? $fetchPatientLastSchoolIstElevUdvData->getKlassebetegnelse() : NULL;
$fradato = $fetchPatientLastSchoolIstElevUdvData ? $fetchPatientLastSchoolIstElevUdvData->getFradato() : NULL;
$tildato = $fetchPatientLastSchoolIstElevUdvData ? $fetchPatientLastSchoolIstElevUdvData->getTildato() : NULL;
$schoolStartDate = $schoolEndDate = NULL;
$patientInformationObj = $em->getRepository(PatientInformation::class)->findOneBy(array("patient" => $patient));
if (!$patientInformationObj) {
$patientInformationObj = new PatientInformation();
}
if (count($fetchPatientAllIstElevUdvData) > 0) {
$isMultipleRecords = true;
$patientInformationObj->setIsMultiple(true);
} else {
$patientInformationObj->setIsMultiple(false);
}
$patientInformationObj->setUser($patient->getUser());
$patientInformationObj->setPatient($patient);
if (strlen($skolenavn) > 0 && strlen($patientInformationObj->getCitizenSchoolName()) >= 0) {
$patientInformationObj->setCitizenSchoolName($skolenavn);
}
if (strlen($skolekode) > 0 && strlen($patientInformationObj->getCitizenSchoolNumber()) >= 0) {
$patientInformationObj->setCitizenSchoolNumber($skolekode);
}
if (strlen($skoletype) > 0 && strlen($patientInformationObj->getCitizenSchoolType()) >= 0) {
$patientInformationObj->setCitizenSchoolType($skoletype);
}
if (strlen($fradato) > 0) {
$schoolStartDate = date("d.m.Y", strtotime($fradato));
}
if (strlen($tildato) > 0) {
$schoolEndDate = date("d.m.Y", strtotime($tildato));
}
if (strlen($schoolStartDate) > 0) {
$patientInformationObj->setCitizenSchoolStart($schoolStartDate);
}
if (strlen($schoolEndDate) > 0) {
$patientInformationObj->setCitizenSchoolEnd($schoolEndDate);
}
if (strlen($klassetype) > 0 && strlen($patientInformationObj->getCitizenClasseType()) >= 0) {
$patientInformationObj->setCitizenClasseType($klassetype);
}
if (strlen($klassebetegnelse) > 0 && strlen($patientInformationObj->getCitizenSchoolClass()) >= 0) {
$patientInformationObj->setCitizenSchoolClass($klassebetegnelse);
}
if (strlen($elevklassetrin) > 0 && strlen($patientInformationObj->getCitizenSchoolLevel()) >= 0) {
$patientInformationObj->setCitizenSchoolLevel($elevklassetrin);
}
$entityManager->persist($patientInformationObj);
}
//To store school history
if ($fetchPatientAllIstElevUdvData) {
//$allBlankSchoolPatientInformationObj = $em->createQuery('SELECT pd FROM App\Entity\PatientInformationDetails pd WHERE pd.patient = :patient and pd.skoleRef IS NULL')
$allBlankSchoolPatientInformationObj = $em->createQuery('SELECT pd FROM App\Entity\PatientInformationDetails pd WHERE pd.patient = :patient')
->setParameter('patient', $patient)
->execute();
if(count($allBlankSchoolPatientInformationObj) > 0) {
foreach($allBlankSchoolPatientInformationObj as $blankSchoolPatientInformationObj) {
$entityManager->remove($blankSchoolPatientInformationObj);
}
$entityManager->flush();
}
//var_dump($fetchPatientAllIstElevUdvData); die;
foreach ($fetchPatientAllIstElevUdvData as $fetchPatientIstElevUdvDataT) {
$fetchPatientIstElevUdvData = $fetchPatientIstElevUdvDataT[0];
//var_dump($fetchPatientIstElevUdvData);
$schoolStartDate = $schoolEndDate = NULL;
$schoolIstElevUdvRef = $fetchPatientIstElevUdvData->getid();
$patientInformationObj = $em->getRepository(PatientInformationDetails::class)->findOneBy(array("patient" => $patient, "skoleRef" => $schoolIstElevUdvRef));
if (!$patientInformationObj) {
$patientInformationObj = new PatientInformationDetails();
}
$patientInformationObj->setUser($patient->getUser());
$patientInformationObj->setPatient($patient);
$Skoletype = $fetchPatientIstElevUdvData ? $fetchPatientIstElevUdvData->getSkoletype() : NULL;
$skolenavn = $fetchPatientIstElevUdvData ? $fetchPatientIstElevUdvData->getSkolenavn() : NULL;
$klassebetegnelse = $fetchPatientIstElevUdvData ? $fetchPatientIstElevUdvData->getKlassebetegnelse() : NULL;
$elevklassetrin = $fetchPatientIstElevUdvData ? $fetchPatientIstElevUdvData->getElevklassetrin() : NULL;
$fradato = $fetchPatientIstElevUdvData ? $fetchPatientIstElevUdvData->getFradato() : NULL;
$tildato = $fetchPatientIstElevUdvData ? $fetchPatientIstElevUdvData->getTildato() : NULL;
if (strlen($skolenavn) > 0 && strlen($patientInformationObj->getCitizenSchoolName()) == 0) {
$patientInformationObj->setCitizenSchoolName($skolenavn);
}
if (strlen($fradato) > 0) {
$schoolStartDate = date("d.m.Y", strtotime($fradato));
}
if (strlen($tildato) > 0) {
$schoolEndDate = date("d.m.Y", strtotime($tildato));
}
if (strlen($schoolStartDate) > 0) {
$patientInformationObj->setCitizenSchoolStart($schoolStartDate);
}
if (strlen($schoolEndDate) > 0) {
$patientInformationObj->setCitizenSchoolEnd($schoolEndDate);
}
if (strlen($klassebetegnelse) > 0 && strlen($patientInformationObj->getCitizenSchoolClass()) == 0) {
$patientInformationObj->setCitizenSchoolClass($klassebetegnelse);
}
if (strlen($elevklassetrin) > 0 && strlen($patientInformationObj->getCitizenSchoolLevel()) == 0) {
$patientInformationObj->setCitizenSchoolLevel($elevklassetrin);
}
$patientInformationObj->setSkoleRef($schoolIstElevUdvRef);
$entityManager->persist($patientInformationObj);
}
}
$entityManager->flush();
//die("Success");
}
}
public function josaCheckEnvironment(Request $request) {
$responce = "Success";
$APP_DEBUG = ( isset($_SERVER['APP_DEBUG']) && $_SERVER['APP_DEBUG']) ? "True" : "False";
$isCprLookupActiveVal = ( isset($_SERVER['isCprLookupActiveVal']) && $_SERVER['isCprLookupActiveVal']) ? "True" : "False";
$showRapportUrl = ( isset($_SERVER['showRapportUrl']) && $_SERVER['showRapportUrl']) ? "True" : "False";
$isCopenhagen = ( isset($_SERVER['isCopenhagen']) && $_SERVER['isCopenhagen']) ? "True" : "False";
$isBackendEnabled = ( isset($_SERVER['isBackendEnabled']) && $_SERVER['isBackendEnabled']) ? "True" : "False";
$isTestServer = ( isset($_SERVER['isTestServer']) && $_SERVER['isTestServer']) ? "True" : "False";
$pageResultLimit = ( isset($_SERVER['pageResultLimit']) && $_SERVER['pageResultLimit']) ? $_SERVER['pageResultLimit'] : "False";
$indexPageSearchLimit = ( isset($_SERVER['indexPageSearchLimit']) && $_SERVER['indexPageSearchLimit']) ? $_SERVER['indexPageSearchLimit'] : "False";
$isBorgerPlanLetterEnabled = ( isset($_SERVER['isBorgerPlanLetterEnabled']) && $_SERVER['isBorgerPlanLetterEnabled']) ? "True" : "False";
$image_data = ( isset($_SERVER['image_data']) && $_SERVER['image_data']) ? $_SERVER['image_data'] : "False";
$image_data_cubf = ( isset($_SERVER['image_data_cubf']) && $_SERVER['image_data_cubf']) ? $_SERVER['image_data_cubf'] : "False";
$image_data_rfc = ( isset($_SERVER['image_data_rfc']) && $_SERVER['image_data_rfc']) ? $_SERVER['image_data_rfc'] : "False";
$isBorgerPlanLetterEnabled = ( isset($_SERVER['isBorgerPlanLetterEnabled']) && $_SERVER['isBorgerPlanLetterEnabled']) ? "True" : "False";
$isActivityAccessSet = ( isset($_SERVER['isActivityAccessSet']) && $_SERVER['isActivityAccessSet']) ? "True" : "False";
$cssStyle = "<style>
table { width='600px';text-align: left;width: 950px;border-collapse: collapse;padding: 10px;}
table th { width: 40%; border: 1px solid black; padding: 10px;}
table td { width: 60%; border: 1px solid black; padding: 10px;}
</style>";
echo $cssStyle . "<table>"
. "<tr><th>APP_DEBUG</th><td>$APP_DEBUG</td></tr>"
. "<tr><th>isCprLookupActiveVal</th><td>$isCprLookupActiveVal</td></tr>"
. "<tr><th>showRapportUrl</th><td>$showRapportUrl</td></tr>"
. "<tr><th>isCopenhagen</th><td>$isCopenhagen</td></tr>"
. "<tr><th>isBackendEnabled</th><td>$isBackendEnabled</td></tr>"
. "<tr><th>isTestServer</th><td>$isTestServer</td></tr>"
. "<tr><th>pageResultLimit listing 5 section</th><td>$pageResultLimit</td></tr>"
. "<tr><th>indexPageSearchLimit</th><td>$indexPageSearchLimit</td></tr>"
. "<tr><th>isBorgerPlanLetterEnabled</th><td>$isBorgerPlanLetterEnabled</td></tr>"
. "<tr><th>image_data</th><td>$image_data</td></tr>"
. "<tr><th>image_data_cubf</th><td>$image_data_cubf</td></tr>"
. "<tr><th>image_data_rfc</th><td>$image_data_rfc</td></tr>"
. "<tr><th>isActivityAccessSet</th><td>$isActivityAccessSet</td></tr>"
. "</table>";
die("\n" . $responce);
}
public function getRapportPdf(Request $request) {
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
$user = $this->get('security.token_storage')->getToken()->getUser();
$webPath = $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
$shareListIds = $request->get('shareListIds');
$shareListIdArr = explode(',', $shareListIds);
$shareListIdArr = array_unique($shareListIdArr);
$participantUserIds = $request->get('participantUserIds');
$participantMessages = $request->get('participant_message');
$shareTemplateSelectType = $request->get('share_template_select_type');
$skeleringFormContentHtmlData= $request->get('skaleringContent');
//$sharetype = $request->get('shareType');
$container = $this->container;
$caseActivityId = '';
$profession = $user->getProfession();
//$dialogueAttachmentObj = new DialogueAttachmentController();
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')
$url = "https://";
else
$url = "http://";
$url.= $_SERVER['HTTP_HOST'];
//for sagsakter pdf
$generatedPDFFile = $this->processShareActivityPdf($em,$container,$dialogue,$patient,$user,$participantUserIds,$shareListIdArr,'',$skeleringFormContentHtmlData);
$selectedFile = $generatedPDFFile;
//$selectedFile = "CaseActivityTemplate_61c314511b7ab8.46814130.pdf";
$ext = pathinfo($selectedFile, PATHINFO_EXTENSION);
$onlyFileName = pathinfo($selectedFile, PATHINFO_FILENAME);
$newFilename = $onlyFileName."." . $ext;
$rapportSagsakPdf = $newFilename;
$folgebrevFiles = array();
$index = 0;
foreach ($participantUserIds as $participantUserId){
$participantMessage = $participantMessages[$index];
$tunnelUserObj=$participantUser=$fileNameNew='';
if($shareTemplateSelectType == 1){
$tunnelUserObj = $em->getRepository(SepoTunnelliste::class)->findOneBy(array("rid" => $participantUserId));
}else{
$participantUser = $em->getRepository(User::class)->find($participantUserId);
}
$dialogueAttachmentControllerObj = new DialogueAttachmentController();
if($shareTemplateSelectType == 1 || $shareTemplateSelectType == 3){
$mailSubject = "Delte dokumenter";//$dialogue->getSharedExternalTitle($user);
$messageTextConsentForPdf = $this->get('templating')->render('message/share_activity-external-tunnel-dialogue-citizen-pdf.html.twig', array(
'participantMessage' => $participantMessage,
'userObj' => $tunnelUserObj,
'participantUser' => $participantUser,
'patient' => $patient,
'dialogueObj' => $dialogue,
'loginUserObj' => $user,
'subject' => $mailSubject,
'shareTemplateSelectType' => $shareTemplateSelectType
));
$citizenAddressFilePath = $dialogueAttachmentControllerObj->getTunnelExternlCitizenAddress($container,$dialogue,$user,$tunnelUserObj,$participantUser,$messageTextConsentForPdf,'',$shareTemplateSelectType);
}else{
$citizenAddressFilePath = $dialogueAttachmentControllerObj->getRapportCitizenAddress($container,$dialogue,$user,$participantUser,$shareListIdArr,$participantMessage,'');
}
$selectedFolgebrevFile = $citizenAddressFilePath;
//$selectedFolgebrevFile = "RapportPageOneTemplate_61c314896af429.09612605_89.pdf ";
$ext2 = pathinfo($selectedFolgebrevFile, PATHINFO_EXTENSION);
$fileName = pathinfo($selectedFolgebrevFile, PATHINFO_FILENAME);
$fileNameNew = $fileName."." . $ext2;
$folgebrevFiles[$participantUserId] ['folgebrevFilePath'] = $fileNameNew;
$index++;
}
$listId = explode(',', $shareListIds);
$totalSize = 0;
foreach ($listId as $id){
$fileSize = $this->getFilesSize($user,$em,$id,'');
$totalSize += $fileSize;
}
$totalSize += filesize($webPath.$newFilename) + filesize($webPath.$fileNameNew);
$responce = 'success';
$response = new Response(json_encode(array('result' => $responce, 'rapportSagsakPdf' => $rapportSagsakPdf, 'folgebrevFiles' => $folgebrevFiles,'fileSizes' => $totalSize)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function getDeleteRapportPdf(Request $request) {
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", false);
$selectedDialogue = $session->get("selectedDialogue", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
$user = $this->get('security.token_storage')->getToken()->getUser();
$webPath = $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
$participantPdfs = $request->get('participantPdfs');
$folgebrevPdfs = $request->get('folgebrevPdfs');
//delete participantPdfs
foreach ($participantPdfs as $participantPdf){
$ext2 = pathinfo($participantPdf, PATHINFO_EXTENSION);
$fileName = pathinfo($participantPdf, PATHINFO_FILENAME);
$fileNameNew = $fileName."." . $ext2;
$filePath = $webPath . $fileNameNew;
if (file_exists($filePath)) {
unlink($filePath);
}
}
//delete folgebrevPdfs
foreach ($folgebrevPdfs as $folgebrevPdf){
$ext21 = pathinfo($folgebrevPdf, PATHINFO_EXTENSION);
$fileName1 = pathinfo($folgebrevPdf, PATHINFO_FILENAME);
$fileNameNew1 = $fileName1."." . $ext21;
$filePath1 = $webPath . $fileNameNew1;
if (file_exists($filePath1)) {
unlink($filePath1);
}
}
$responce = 'success';
$response = new Response(json_encode(array('result' => $responce)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' KB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
public function createPatientGardian($em, $newPatient, $parentCategory, $userLabelText, $guardianHasCustody, $guardianCustodySince, $guardiancprNo, $guardianFullname, $guardianIsShowAddress, $userAddress, $userPostno, $userCity) {
$u = $em->getRepository(User::class)->findOneBy(array('username' => $guardiancprNo));
$guardian = $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient, 'relative' => $u));
if (!$guardian) {
$guardian = new Family();
//$u = $this->createRelative($guardianObject);
$u = $this->createGardianRelative($em, $guardiancprNo, $guardianFullname, $guardianIsShowAddress, $userAddress, $userPostno, $userCity);
if (!$u->hasRole('ROLE_PARENT')) {
$u->addRole('ROLE_PARENT');
$u->setCategory($parentCategory);
$u->setEnabled(true);
}
} else {
//$u = $this->createRelative($guardianObject);
$u = $this->createGardianRelative($em, $guardiancprNo, $guardianFullname, $guardianIsShowAddress, $userAddress, $userPostno, $userCity);
$guardian->setRelation(Family::REL_GUARDIAN);
}
if (trim($u->getStamdataLabel()) == "-") {
$u->setStamdataLabel(NULL);
} else {
$u->setStamdataLabel($userLabelText);
}
$guardian->setHasCustody($guardianHasCustody);
$guardian->setCustodySince($guardianCustodySince);
$guardian->setIsParticipant(false);
$guardian->setRelative($u);
return $guardian;
}
public function createGardianRelative($em, $usercpr, $userFullname, $guardianIsShowAddress, $userAddress=NULL, $userPostno=NULL, $userCity=NULL) {
//$serviceResponse = $this->doSoapRequest(208, $this->getFieldValue($relativeObject, 'PNR_FOEDDATO'));
//$parentObject = $serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row[0];
//Check this user is already exist or not
//$em = $this->getDoctrine()->getManager();
//$cprNo = $this->getFieldValue($relativeObject, 'PNR_FOEDDATO');
$user = $em->getRepository(User::class)->findOneBy(array('username' => $usercpr));
$isNew = false;
if($user) {
$user = $user ? $user : NULL;
} else {
$user = new Relative();
$isNew = true;
}
if(strlen($userFullname) > 0 && $user) {
$sname = explode(' ', addslashes(trim($userFullname)), 2);
$userFirstname = ($sname[0]);
$userLastname = (isset($sname[1]) ? $sname[1] : '-');
$user->setFirstName($userFirstname);
$user->setLastName($userLastname);
$user->setUsername($usercpr);
if(!$guardianIsShowAddress) { //!="00001"
$user->setAddress($userAddress);
//$user->setAddressLine2('');
$user->setPostNumber($userPostno);
$user->setCity($userCity);
}
if($isNew) {
$em->persist($user);
$em->flush();
}
return $user;
}
}
//create dialougecase card details
public function createDefaultDialougeCaseCard($user,$patient,$dialogue) {
$em = $this->getDoctrine()->getManager();
$predefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->findOneBy(array('caseCardType' => 'Notat'));
$dialougeCaseCardObj = $em->getRepository(DialogueCaseCard::class)->findOneBy(array('dialogue' => $dialogue,'pCaseCardId'=>$predefinedCaseCardObj->getId()));
if($predefinedCaseCardObj && !$dialougeCaseCardObj){
$card = new DialogueCaseCard();
$card->setPatient($patient);
$card->setDialogue($dialogue);
$card->setPCaseCardId($predefinedCaseCardObj);
$card->setCreatedBy($user);
$em->persist($card);
$em->flush();
$dialogueCaseCardControllerObj = new DialogueCaseCardController();
$history = $dialogueCaseCardControllerObj->saveCaseCardHistory($em, $card, 'N',$dialogue,null, $user);
return $card;
}
return $dialougeCaseCardObj;
}
public function featchAllScalingGraphDetails($em,$dialogueAttachmentDetailObj){
//Get scaling progression records
$shortMonthArray = array('01' => "Jan", '02' => "Feb", '03' => "Mar", '04' => "Apr", '05' => "Maj",
'06' => "Jun", '07' => "Jul", '08' => "Aug", '09' => "Sep", '10' => "Okt", '11' => "Nov", '12' => "Dec");
$scalingProgressionObj = $em->getRepository(ScalingProgression::class)->findBy(array('dialogueAttachmentDetail' => $dialogueAttachmentDetailObj, 'isDeleted' => false));
$scalingProgressionArray = array();
$scalingIndividualGraphArray = array();
foreach ($scalingProgressionObj as $scalingProgression) {
$scalingProgressionObjId = $scalingProgression->getId();
$scalingGraph = $em->getRepository(ScalingGraph::class)->getAllScalingRecordByProgression($scalingProgressionObjId);
$totalUserCount = count($scalingGraph);
$userGrade = $avgUserGrade = 0;
$userNameNGrade = "";
foreach ($scalingGraph as $spRecord) {
$userGrade = ($userGrade + $spRecord->getGrade());
$userCurrentGrade = $spRecord->getGrade();
$userNameNGrade = $userNameNGrade.$spRecord->getUser()->getFullName()."($userCurrentGrade)_";
//Participants individual graph records
$indiStartDate = $spRecord->getCreatedAt();
$indiYear = $indiStartDate->format('Y');
$indiMonth = $shortMonthArray[$indiStartDate->format('m')];
//$scalingIndividualGraphArray['userId'] = $spRecord->getUser()->getId();
$scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['id'] = $spRecord->getId();
$scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['user'] = $spRecord->getUser();
$scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['progression'] = $spRecord->getProgression();
$scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['grade'] = $spRecord->getGrade();
$scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['displayYear'] = $indiYear;
$scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['displayMonth'] = strtoupper($indiMonth);
$scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['createdAt'] = $spRecord->getCreatedAt();
$scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['updatedAt'] = $spRecord->getUpdatedAt();
}
//var_dump($userNameNGrade); die;
if ($totalUserCount > 0) {
$avgUserGrade = ($userGrade / $totalUserCount);
}
$startDate = $scalingProgression->getStartDate();
$year = $startDate->format('Y');
$month = $shortMonthArray[$startDate->format('m')];
$scalingProgressionArray[$scalingProgression->getId()]['id'] = $scalingProgression->getId();
$scalingProgressionArray[$scalingProgression->getId()]['avg_cnt'] = (int) round($avgUserGrade);
$scalingProgressionArray[$scalingProgression->getId()]['totalUserCount'] = $totalUserCount;
$scalingProgressionArray[$scalingProgression->getId()]['start_by'] = $scalingProgression->getStartBy();
$scalingProgressionArray[$scalingProgression->getId()]['dialogue'] = $scalingProgression->getDialogue();
$scalingProgressionArray[$scalingProgression->getId()]['start_date'] = $scalingProgression->getStartDate();
$scalingProgressionArray[$scalingProgression->getId()]['displayYear'] = $year;
$scalingProgressionArray[$scalingProgression->getId()]['displayMonth'] = strtoupper($month);
$scalingProgressionArray[$scalingProgression->getId()]['end_date'] = $scalingProgression->getEndDate();
$scalingProgressionArray[$scalingProgression->getId()]['userParticipant'] = $scalingGraph;
$scalingProgressionArray[$scalingProgression->getId()]['toolTipUserList'] = $userNameNGrade;
}
return array('scalingProgressionArray'=>$scalingProgressionArray,'scalingIndividualGraphArray'=>$scalingIndividualGraphArray);
}
public function createMeasureOnLoad($dialogueCaseCardObj,$user){
$em = $this->getDoctrine()->getManager();
$ccId = 38;
$todaysDate = date("Y-m-d");
$caseCardMeasure = $em->getRepository(CaseCardMeasure::class)->findBy(array('pCaseCard'=> $ccId,'referenceType' => 'F'));
foreach($caseCardMeasure as $measure){
$dialogueCaseCardMeasureObj = $em->getRepository(DialogueCaseCardMeasure::class)->findOneBy(array('DialogueCaseCard' => $dialogueCaseCardObj, 'measure' => $measure));
if(!$dialogueCaseCardMeasureObj){
$dialogueCaseCardMeasure = new DialogueCaseCardMeasure();
$dialogueCaseCardMeasure->setCreatedBy($user);
$dialogueCaseCardMeasure->setDialogueCaseCard($dialogueCaseCardObj);
$dialogueCaseCardMeasure->setMeasure($measure);
$dialogueCaseCardMeasure->setReferenceType('F');
$dialogueCaseCardMeasure->setFromDate(new \DateTime($todaysDate));
$dialogueCaseCardMeasure->setResponsiblePerson($user);
$em->persist($dialogueCaseCardMeasure);
$em->flush();
}
}
return true;
}
public function saveSkabelonDate(Request $request,$skId){
$em = $this->getDoctrine()->getManager();
$skabelonDate = $request->get('skabelonDate');
$dialogueAttachmentDetailObj = $em->getRepository(DialogueAttachmentDetails::class)->find($skId);
//var_dump($dialogueAttachmentDetailObj);die;
if ($skabelonDate != "") {
$selectedDate = new \DateTime($skabelonDate);
$time_now = new \DateTime();
$merge = new \DateTime($selectedDate->format('Y-m-d') . ' ' . $time_now->format('H:i:s'));
$setSelectedDate = $merge->format('Y-m-d H:i:s');
$dialogueAttachmentDetailObj->setAttachmentDate(new \DateTime($setSelectedDate));
}
$em->persist($dialogueAttachmentDetailObj);
$em->flush();
$response = "success";
$response = new Response(json_encode(array('data' => $response)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function createSkelringCaseActivity($user,$patient,$dialogue,$dialogueCaseCardObj){
$em = $this->getDoctrine()->getManager();
//$session = $request->getSession();
$response = "fail";
$lastInsertedNoteId='';
$topic = 'Trivselsvurdering';
$selectedDateAttachment = '';
$reminderDateAttachment = '';
$isDraft = 1;
$isAttachmentPrivate = '';
$attachmentText = '';
$dialogueCaseCardMeasureId = '';
$measureId = '';
$holdId = '';
$today1 = new \DateTime();
$after14days = $today1->modify('+14 day');
$predefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->findOneBy(array('caseCardType' => 'Notat'));
$predefinedAttachmentTypeObj = $em->getRepository(PredefinedAttachmentType::class)->findOneBy(array('attachmentType' => 'Skalering'));
$predefinedCaseCard = $predefinedCaseCardObj->getId();
$predefinedTypeId = $predefinedAttachmentTypeObj->getId();
$selectedPatientObj = $em->getRepository(Patient::class)->find($patient->getId());
$selectedDialogueObj = $em->getRepository(Dialogue::class)->find($dialogue->getId());
if ($predefinedCaseCard != "0" && $predefinedTypeId != "0") {
$dialogueAttachmentDetailsObj = new DialogueAttachmentDetails();
$dialogueAttachmentDetailsObj->setPatient($selectedPatientObj);
$dialogueAttachmentDetailsObj->setDialogue($selectedDialogueObj);
if($dialogueCaseCardObj){
$dialogueAttachmentDetailsObj->setDialogueCaseCard($dialogueCaseCardObj);
}
$dialogueAttachmentDetailsObj->setUser($user);
$dialogueAttachmentDetailsObj->setPCaseCardId($predefinedCaseCardObj);
$dialogueAttachmentDetailsObj->setPAtttachmentType($predefinedAttachmentTypeObj);
$dialogueAttachmentDetailsObj->setTypeHeading($predefinedAttachmentTypeObj->getAttachmentType());
$dialogueAttachmentDetailsObj->setAttachmentHeading($topic);
$dialogueAttachmentDetailsObj->setIsDraft($isDraft);
if($isDraft == 0){
$today = new \DateTime();
$tomorrow = $today->modify('+1 day');
$dialogueAttachmentDetailsObj->setPostJournaliseDate($tomorrow);
}
//if ($selectedDateAttachment != "") {
$selectedDate = new \DateTime($selectedDateAttachment);
$time_now = new \DateTime();
$merge = new \DateTime($selectedDate->format('Y-m-d') . ' ' . $time_now->format('H:i:s'));
$setSelectedDate = $merge->format('Y-m-d H:i:s');
$dialogueAttachmentDetailsObj->setAttachmentDate(new \DateTime($setSelectedDate));
//}
if ($reminderDateAttachment != "") {
$dialogueAttachmentDetailsObj->setReminderDate(new \DateTime($reminderDateAttachment));
}
if ($attachmentText != "") {
$dialogueAttachmentDetailsObj->setAttachmentText($attachmentText);
}
$dialogueAttachmentDetailsObj->setVisibleStatus($isAttachmentPrivate);
if($dialogueCaseCardMeasureId == "0") {
$dialogueAttachmentDetailsObj->setDialogueCaseCardMeasureId(NULL);
$dialogueAttachmentDetailsObj->setMeasureId(NULL);
} else {
$dialogueCaseCardMeasureObj = $em->getRepository(DialogueCaseCardMeasure::class)->find($dialogueCaseCardMeasureId);
$dialogueAttachmentDetailsObj->setDialogueCaseCardMeasureId($dialogueCaseCardMeasureObj);
$caseCardMeasureObj = $em->getRepository(CasecardMeasure::class)->find($measureId);
$dialogueAttachmentDetailsObj->setMeasureId($caseCardMeasureObj);
}
if(($holdId == "0") || $holdId == NULL ){
$dialogueAttachmentDetailsObj->setHold(NULL);
} else {
$holdObj = $em->getRepository(JoCaseCardHold::class)->find($holdId);
$dialogueAttachmentDetailsObj->setHold($holdObj);
}
$activityTypeVal = 0;
if($predefinedTypeId == '5' && $isDraft == "1") {
$activityTypeVal = 6;
} else if($predefinedTypeId == '5' && $isDraft == "0") {
$activityTypeVal = 5;
} else if($predefinedTypeId <> '5' && $isDraft == "1") {
$activityTypeVal = 8;
} else if($predefinedTypeId <> '5' && $isDraft == "0") {
$activityTypeVal = 7;
}
$dialogueAttachmentDetailsObj->setActivityType($activityTypeVal);
$dialogueAttachmentDetailsObj->setScaleGrade(0);
$em->persist($dialogueAttachmentDetailsObj);
$em->flush();
/***********************************scaling progression*********************************/
$scalingProgressionObj = new ScalingProgression();
$scalingProgressionObj->setStartBy($user);
$scalingProgressionObj->setPatient($selectedPatientObj);
$scalingProgressionObj->setDialogue($selectedDialogueObj);
$scalingProgressionObj->setDialogueAttachmentDetail($dialogueAttachmentDetailsObj);
$scalingProgressionObj->setIsDeleted(false);
$scalingProgressionObj->setStartDate(new \DateTime());
$scalingProgressionObj->setEndDate($after14days);
//$scalingProgressionObj->setCreatedAt(new \DateTime());
//$scalingProgressionObj->setUpdatedAt(new \DateTime());
$em->persist($scalingProgressionObj);
$em->flush();
/***********************************scaling Graph***************************************/
$scalingGraphObj = new ScalingGraph();
$scalingGraphObj->setUser($user);
$scalingGraphObj->setPatient($selectedPatientObj);
$scalingGraphObj->setDialogue($selectedDialogueObj);
$scalingGraphObj->setProgression($scalingProgressionObj);
$scalingGraphObj->setGrade(0);
//$scalingGraphObj->setCreatedAt(new \DateTime());
//$scalingGraphObj->setUpdatedAt(new \DateTime());
$em->persist($scalingGraphObj);
$em->flush();
if($dialogueCaseCardMeasureId){
$this->addFlash('openDialogueCaseCardMeasureId',$dialogueCaseCardMeasureId);
}
//$session->set('activityDetailUpdated', $dialogueAttachmentDetailsObj->getId());
//File upload code for new records
$response = "success";
//$lastInsertedNoteId = $dialogueAttachmentDetailsObj->getId();
}
return $response;
}
public function getFilesSize($user,$em,$attachId,$type){
$totalSize = 0;
$dialogueAttachments = $em->getRepository(DialogueAttachments::class)->findBy(array('dialogueAttachmentDetailId' => $attachId));
foreach ($dialogueAttachments as $dialogueAttachment) {
$id = $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
$fileIsImported = false;
$isSharedJournal = false;
if(isset($dialogueAttachment) && !empty($dialogueAttachment)) {
$fileIsImported = $dialogueAttachment->getIsImported();
$isSharedJournal = $dialogueAttachment->getIsSharedJournal();
}
if($isSharedJournal) {
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/attachmentsJournal/';
} else if($fileIsImported) {
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/kingo/';
} else {
$webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/attachments/';
}
if(file_exists($webPath.$dialogueAttachment->getAttachmentName())){
$fileSize = filesize($webPath.$dialogueAttachment->getAttachmentName());
$totalSize += $fileSize;
}
}
if($type){
return $this->formatSizeUnits($totalSize);
}else{
return $totalSize;
}
}
public function updateSkaleringAttachment($dialogue,$patient,$em){
$dialogueAttachmentDetailsSkalering = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array('dialogue' => $dialogue,'patient'=>$patient,'pAtttachmentType'=>34));
$dialogueAttachmentDetailsSkalering->setAttachmentDate(new \DateTime());
$dialogueAttachmentDetailsSkalering->setUpdatedAt(new \DateTime());
$em->persist($dialogueAttachmentDetailsSkalering);
$em->flush();
}
public function maintaineUserLog($em,$user,$case_no,$case_card_id,$activity_id,$activity,$forslatling_id,$pccId,$dialogue_case_card_measure)
{
if($case_no != ''){
$user_case_log = new UserCaseLogger();
$user_case_log->setUser($user);
$user_case_log->setCreatedAt(new \DateTime());
$user_case_log->setUpdatedAt(new \DateTime());
$user_case_log->setCaseNo($case_no);
$em->persist($user_case_log);
$em->flush();
}
// for maitain log for UserCaseActivity when click on activity arrow
if($activity_id != ''){
$user_case_activity_log = new UserCaseActivityLogger();
$user_case_activity_log->setUser($user);
$user_case_activity_log->setCreatedAt(new \DateTime());
$user_case_activity_log->setUpdatedAt(new \DateTime());
if($activity->getMeasureId() != ''){
$user_case_activity_log->setForslatlingId($activity->getMeasureId()->getId());
}else{
$user_case_activity_log->setForslatlingId(NULL);
}
$user_case_activity_log->setActivityId($activity_id);
$user_case_activity_log->setCaseNo($activity->getDialogue()->getCaseNo());
$user_case_activity_log->setCaseCardId($activity->getCaseCard()->getId());
if($activity->getDialogue()->getdialogueType() == 3 || $activity->getDialogue()->getdialogueType() == 4){
$user_case_activity_log->setDialogueCaseCardMeasureId($dialogue_case_card_measure ? $dialogue_case_card_measure : NULL);
}
$em->persist($user_case_activity_log);
$em->flush();
}
//for maitaine logger for case no and case card when click on index sagskort
if($case_card_id !=''){
// $user_case_log = new UserCaseLogger();
// $user_case_log->setUser($user);
// $user_case_log->setCreatedAt(new \DateTime());
// $user_case_log->setUpdatedAt(new \DateTime());
// $user_case_log->setCaseNo($case_card_id->getDialogue()->getCaseNo());
// $em->persist($user_case_log);
// $em->flush();
$user_case_card_log = new UserCaseCardLogger();
$user_case_card_log->setUser($user);
$user_case_card_log->setCreatedAt(new \DateTime());
$user_case_card_log->setUpdatedAt(new \DateTime());
$user_case_card_log->setCaseCardId($case_card_id->getPCaseCardId()->getId());
$user_case_card_log->setCaseNo($case_card_id->getDialogue()->getCaseNo());
$em->persist($user_case_card_log);
$em->flush();
}
// for maitain log for UserCaseActivity click on count of activity on opened sagskort
if($forslatling_id != ''){
// var_dump($dialogue_case_card_measure);die;
$user_case_activity_log = new UserCaseActivityLogger();
$user_case_activity_log->setUser($user);
$user_case_activity_log->setCreatedAt(new \DateTime());
$user_case_activity_log->setUpdatedAt(new \DateTime());
$user_case_activity_log->setForslatlingId($forslatling_id);
$user_case_activity_log->setCaseNo($activity->getCaseNo());
$user_case_activity_log->setActivityId(NULL);
$user_case_activity_log->setCaseCardId($pccId);
if($activity->getdialogueType() == 3 || $activity->getdialogueType() == 4){
$user_case_activity_log->setDialogueCaseCardMeasureId($dialogue_case_card_measure ? $dialogue_case_card_measure : NULL);
}
$em->persist($user_case_activity_log);
$em->flush();
}
}
public function callStamdataUpdate(Request $request) {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
//$patientInfo = trim($request->get('patientInfo'));
//$patient = $em->getRepository(Patient::class)->find($patientInfo);
$selectedPatient = $session->get("selectedPatient", false);
$patient = $em->getRepository(Patient::class)->find($selectedPatient->getId());
$cprEncode = $patient->getUserCprEncode();
if($patient && !($patient->getIsDummyPatient()) && !($patient->getIsFakeCpr())) {
$this->updateAllStamdata($patient, $session);
}
return $this->redirectToRoute('create_case_with_existing',['cprNo' => $cprEncode]);
}
public function changeInstitution(Request $request){
$session = $request->getSession();
$institutionId = $request->get('institutionId');
$institutionName = $request->get('institutionName');
$session->set('institutionName',$institutionName);
$session->set('selectedInstitutionId',$institutionId);
$response = "success";
$response = new Response(json_encode(array('data' => $response)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function checkCurrentCase(Request $request) {
$user = $this->get('security.token_storage')->getToken()->getUser();
$dialogueId = $patientName = $patientId = '';
//if (!($user)) {
if (!is_object($user)) {
$patientId = -1;
}else{
//$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$selectedPatient = $session->get("selectedPatient", null);
$selectedDialogue = $session->get("selectedDialogue", null);
if($selectedDialogue){
$dialogue = $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
$patientName = $dialogue->getPatient()->getFullName();
$patientId = $dialogue->getPatient()->getId();
$dialogueId = $dialogue->getId();
}
}
$responce = 'success';
$response = new Response(json_encode(array('dialogueId' => $dialogueId, 'patientId' => $patientId, 'patientName' => $patientName)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}