· 6 years ago · Dec 05, 2019, 03:56 PM
1<?php
2
3
4/**
5 * dp actions.
6 *
7 * @package dp - Disciplinary Process
8 * @subpackage dp
9 * @author Karla Rivas
10 * @version SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
11 *
12 */
13class dpActions extends sfActions
14{
15
16
17 /**
18 * Executes index action
19 *
20 * @param sfRequest $request A request object
21 */
22 public function executeIndex(sfWebRequest $request)
23 {
24 //$this->forward('default', 'module');
25 $this->redirect('dp/followup');
26 }
27
28
29 public function executeUpdateIrRelatedDP(sfWebRequest $request)
30 {
31 $data = array();
32 $data['message_list'] = array();
33
34 $usrId = $this->getUser()->getAttribute('id');
35 $dateFull = date('Y-m-d H:i:s', time());
36
37 $dpId = intval($request->getParameter('dpId'));
38 $irRelatedId = $request->getParameter('irRelId');
39 $irId = split('IR', $irRelatedId);
40 $irId = intval($irId[1]);
41
42 if (($dpId > 0) && ($irId > 0))
43 {
44
45 $oIncidentRep = new IdtIncidentReport;
46 $oIncidentRep = Doctrine_Core::getTable("IdtIncidentReport")->findOneByIreIdAndIreValidAndIreActive($irId, 1, 1);
47
48 if ($oIncidentRep)
49 { // si el ir existe, es valido y esta activo
50 // validar si esta relacionado a otro dp
51 $dpNumberExist = 0;
52
53 $oIdtDpRelatedIr = Doctrine_Core::getTable("IdtDpRelatedIr")->findOneByDriIrIdAndDriActive($irId, 1);
54 if ($oIdtDpRelatedIr)
55 {
56 $dpNumberExist = $oIdtDpRelatedIr->getDriDpId();
57 }
58
59 if (($dpNumberExist != $dpId) && ($dpNumberExist > 0))
60 {
61 // el Ir es de otro dp -----------
62 array_push($data['message_list'], __('This IR Number is related to other Hints Processes!'));
63 } else
64 {
65 // el dp esta no esta relacionado ----------
66
67 /* * ********************UPDATE DATA************************ */
68 $oIrDpRelatedIr = new IdtDpRelatedIr;
69 $oIrDpRelatedIr = Doctrine_Core::getTable("IdtDpRelatedIr")->findOneByDriDpId($dpId);
70 if ($oIrDpRelatedIr)
71 { // update
72 $oIrDpRelatedIr->setDriUpdatedBy($usrId);
73 $oIrDpRelatedIr->setDriUpdatedAt($dateFull);
74
75 // save changes
76 try {
77
78 $oIrDpRelatedIr->setDriIrId($irId);
79 $oIrDpRelatedIr->setDriActive(1);
80
81 $oIrDpRelatedIr->save();
82 } catch (Exception $exc) {
83 array_push($data['message_list'], $exc->getMessage());
84 }
85 } else
86 { // new
87 $oIrDpRelatedIr = new IdtDpRelatedIr;
88
89 $oIrDpRelatedIr->setDriDpId($dpId);
90 $oIrDpRelatedIr->setDriActive(1);
91 $oIrDpRelatedIr->setDriCreatedBy($usrId);
92 $oIrDpRelatedIr->setDriCreatedAt($dateFull);
93
94 // save changes
95 try {
96
97 $oIrDpRelatedIr->setDriIrId($irId);
98
99 $oIrDpRelatedIr->save();
100 } catch (Exception $exc) {
101 array_push($data['message_list'], $exc->getMessage());
102 }
103 }
104
105 $oIrDpRelatedIr = null; // free obj
106 } // else-if
107 } else
108 {
109 array_push($data['message_list'], __("The IR Number provided not exist, is not valid or not is active!"));
110 } // else if
111
112 $oIncidentRep = null; // free obj
113 } else
114 {
115 array_push($data['message_list'], __('Incorrect IR Number or Hint related, please try again!'));
116 }
117
118 $encoded = json_encode($data);
119 $this->getResponse()->setContent($encoded);
120 return sfView::NONE;
121 }
122
123
124 /**
125 * Executes userinfo
126 * First step - retrieve user information
127 *
128 *
129 * @param sfRequest $request A request object
130 */
131 public function executeCreate(sfWebRequest $request)
132 {
133 /* Check if this user has permissions for creating disciplinary process
134 * otherwise redirect them to access deny web page */
135
136 $oRolesManager = new RolesManager();
137 $aEntities = $oRolesManager->getUserRolesUnits($this->getUser()->getAttribute('id'));
138
139 $aCreateDpPermissions = Doctrine_Core::getTable('IdtDisciplinaryProcessPermissions')
140 ->createQuery('p')
141 ->where('dpe_active =? AND dpe_start =?', array(1, 1))
142 ->andWhereIn('dpe_rol_id', $aEntities['roles'])
143 ->fetchArray();
144
145 if (count($aCreateDpPermissions) > 0)
146 {
147 $this->picture_width = sfConfig::get('irdp_user_pictures_width');
148 $this->picture_height = sfConfig::get('irdp_user_pictures_height');
149 } else
150 {
151 $this->forward('default', 'secure');
152 }
153
154 /* Get the form assigned poer sanction */
155 $this->aFormSanction = Doctrine_Core::getTable('IdtFormSanction')
156 ->createQuery('s')
157 ->innerJoin('s.IdtDisciplinaryMatrixSanctions m ON m.dms_id = s.fsa_dms_id')
158 ->innerJoin('s.IdtForm f ON f.frm_id = s.fsa_form_id')
159 ->where('s.fsa_active =?', array(1))
160 ->fetchArray();
161 }
162
163
164 /**
165 * Executes getuser
166 * Returns some values of a user profile *
167 *
168 * @param sfRequest $request A request object
169 */
170 public function executeGetuser(sfWebRequest $request)
171 {
172 /* Variables */
173 $error = false;
174 $error_msg = '';
175 $data = array();
176 $profile = array();
177 $bOpenProcesses = false;
178 $allowed = false;
179
180
181 if ($request->isMethod(sfRequest::POST))
182 {
183 //Try to retrieve user data
184 $empid = $request->getParameter('empid');
185
186 $user = new UserManager();
187 $profile = $user->getUserProfile($empid);
188
189 if (!$profile['error'])
190 {
191 $positionUnitType = Doctrine_Query::create()
192 ->select('p.pos_unit_type')
193 ->from('IdtPositions p')
194 ->where('p.pos_id = ?', array($profile['profile']['usr_position_id']))
195 ->fetchArray();
196 $empPositionType = $positionUnitType[0]['pos_unit_type'];
197
198 /* Check if you are allowed to visualize this user information */
199 $oRolesManager = new RolesManager();
200 $aUserRolesUnits = $oRolesManager->getUserRolesUnits($this->getUser()->getAttribute('id'));
201
202 /* Get the list of roles that can open a request */
203 $aRoles = Doctrine_Core::getTable('IdtDisciplinaryProcessPermissions')
204 ->createQuery('p')
205 ->innerJoin('p.IdtRoles r ON r.rol_id = p.dpe_rol_id')
206 ->whereIn('r.rol_id', $aUserRolesUnits['roles'])
207 ->fetchArray();
208
209 $aValidRoles = array();
210
211 foreach ($aRoles as $cp)
212 {
213 $aValidRoles[] = array($cp['dpe_rol_id'], $cp['IdtRoles']['rol_rvp_id']);
214 }
215
216 foreach ($aValidRoles as $vp)
217 {
218 switch ($vp[1])
219 {
220 case 1:
221 if ($profile['profile']['usr_supervisor_id'] == $this->getUser()->getAttribute('id'))
222 {
223 $allowed = true;
224 }
225 break;
226
227 case 2:
228 if (in_array($profile['profile']['usr_department_id'], $aUserRolesUnits['units']) === true)
229 {
230 $allowed = true;
231 }
232 break;
233 case 3:
234 if (in_array($profile['profile']['usr_department_id'], $aUserRolesUnits['multiple_units']) === true)
235 {
236 $allowed = true;
237 }
238 break;
239 case 4:
240 $allowed = true;
241 break;
242 case 5:
243 /* Second level manager - Get the list of my subordinates */
244 $aSubordinates = Doctrine_Core::getTable('IdtUsers')
245 ->createQuery('u')
246 ->where('usr_supervisor =? AND usr_active =?', array($this->getUser()->getAttribute('id'), 1))
247 ->fetchArray();
248
249 $aPossibleSups = array();
250
251 foreach ($aSubordinates as $sub)
252 {
253 $aPossibleSups[] = $sub['usr_empid'];
254 }
255
256 /* Be aware that this user is an idirect subordinate */
257 foreach ($aPossibleSups as $sup)
258 {
259 if ($profile['profile']['usr_supervisor_id'] == $sup)
260 {
261 $allowed = true;
262 }
263 }
264 break;
265 }
266 }
267
268 if ($allowed)
269 {
270 $data['name'] = $profile['profile']['usr_name'];
271 $data['supervisor'] = $profile['profile']['usr_supervisor_name'];
272 $data['position'] = $profile['profile']['usr_position_name'];
273 $data['unit'] = $profile['profile']['usr_department_name'];
274 $data['unit_id'] = $profile['profile']['usr_department_id'];
275 $data['active'] = $profile['profile']['usr_active'];
276 $data['location'] = $profile['profile']['usr_location_name'];
277 $data['picture'] = sfConfig::get('irdp_user_pictures_path') . $profile['profile']['usr_picture'];
278 $data['emp_pos_unit_type'] = $empPositionType;
279
280 /* Check if the picture location is valid */
281 $loadimage = @file_get_contents($data['picture']);
282 //$loadimage = 0 ;
283 if (!$loadimage)
284 {
285 $data['picture'] = '';
286 }
287
288 /* Active value indicates if a user is still a member of the company
289 * But, the method returns a number, in order to make this value understandable
290 * for the user we check it before print it
291 */
292 if ($data['active'] == '1')
293 {
294 $data['active'] = __("Yes");
295 } else
296 {
297 $data['active'] = __("No");
298 }
299
300 /* Check if this user has an active process. In that case you won't be able to
301 * create a new process
302 */
303 $aActiveDisciplinaryProcess = Doctrine_Core::getTable('IdtDisciplinaryProcess')
304 ->createQuery('p')
305 ->where('p.dpc_active =? AND p.dpc_dgs_status =? AND p.dpc_usr_empid =?', array(1, 1, $empid))
306 ->fetchArray();
307
308 if (count($aActiveDisciplinaryProcess) > 0)
309 {
310 $bOpenProcesses = true;
311 $error_msg = __("This user has a process open.");
312 }
313 } else
314 {
315 $error = true;
316 $error_msg = __("You aren't allowed to see user's information.");
317 }
318 } else
319 {
320 $error = true;
321 $error_msg = $profile['error_msg'];
322 }
323 }
324 $encoded = json_encode(array('error' => $error, 'error_msg' => $error_msg, 'data' => $data, 'open_processes' => $bOpenProcesses));
325 $this->getResponse()->setContent($encoded);
326 return sfView::NONE;
327 }
328
329
330 /**
331 * Executes getArticles
332 * Returns the list of valid articles based on the users's unit
333 *
334 * @param sfRequest $request A request object
335 */
336 public function executeGetarticles(sfWebRequest $request)
337 {
338 $error = false;
339 $error_msg = '';
340 $aData = array();
341 $aCategories = array();
342 $iTotalCat = 0;
343
344 if ($request->isMethod(sfRequest::POST))
345 {
346
347 if ($request->getParameter('unit') != null)
348 {
349 $unit_id = $request->getParameter('unit');
350 $type_position = $request->getParameter('unit_type');
351
352 $sql = "SELECT dmc_id, dmc_name, dma_id, dma_desc, dma_art_id, dcf_type_pos
353 FROM idt_disciplinary_matrix_configuration_units
354 INNER JOIN idt_disciplinary_matrix_configurations ON dcf_id = dcu_dcf_id
355 INNER JOIN idt_disciplinary_matrix_articles_sanctions ON das_dcf_id = dcf_id
356 INNER JOIN idt_disciplinary_matrix_articles ON das_dma_id = dma_id AND dma_active = 1
357 INNER JOIN idt_disciplinary_matrix_categories ON dma_dmc_id = dmc_id
358 WHERE dcu_uni_id = " . $unit_id . " AND dma_active = 1 AND dcf_active = 1 AND dcf_type_pos = " . $type_position . "
359 GROUP BY dma_id
360 HAVING dcf_type_pos = ". $type_position ."
361 ORDER BY dmc_id, dma_id;";
362 /*$sql = "SELECT
363 dmc.dmc_id, dmc.dmc_name, dma.dma_id, dma.dma_desc, dma.dma_art_id
364 FROM
365 idt_disciplinary_matrix_configurations dcf
366 INNER JOIN
367 idt_disciplinary_matrix_articles_sanctions das ON das.das_dcf_id = dcf.dcf_id
368 INNER JOIN
369 idt_disciplinary_matrix_articles dma ON das.das_dma_id = dma.dma_id AND dma.dma_active = 1
370 INNER JOIN
371 idt_disciplinary_matrix_categories dmc ON dma.dma_dmc_id = dmc.dmc_id
372 WHERE
373 dma.dma_active = 1 AND dcf.dcf_active = 1
374 GROUP BY dma.dma_id
375 HAVING dcf.dcf_type_pos = ". $type_position ."
376 ORDER BY dmc.dmc_id, dma.dma_id;";*/
377 // echo $sql;die();
378 $raw_articles = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql);
379
380 if (count($raw_articles) > 0)
381 {
382 foreach ($raw_articles as $a)
383 {
384 /* Remove any special character */
385 $sArticleDescription = $a['dma_desc'];
386 $sArticleCategory = $a['dmc_name'];
387
388 $aData[] = array(
389 'id' => $a['dma_id'],
390 'category' => $sArticleCategory,
391 'article' => $sArticleDescription,
392 'article_id' => $a['dma_art_id']
393 );
394
395 if (!in_array($a['dmc_name'], $aCategories))
396 {
397 $aCategories[] = $a['dmc_name'];
398 }
399 }
400
401 $aCategories = array_unique($aCategories);
402 $iTotalCat = count($aCategories);
403 } else
404 {
405 $error = true;
406 $error_msg = __("No articles were found");
407 }
408 } else
409 {
410 $error = true;
411 $error_msg = __("Unit value cannot be null");
412 }
413 } else
414 {
415 $error = true;
416 $error_msg = __("Error on submit");
417 }
418
419 error_reporting(0);
420 $encoded = json_encode(array('error' => $error, 'error_msg' => $error_msg, 'categories' => $aCategories, 'totalcategories' => $iTotalCat, 'data' => $aData));
421 $this->getResponse()->setContent($encoded);
422
423 return(sfView::NONE);
424 }
425
426
427 /**
428 * Executes save articles
429 * Store the list of articles infringed by the user
430 *
431 * @param sfRequest $request A request object
432 */
433 public function executeGetinfringementhistory(sfWebRequest $request)
434 {
435 /* Variables */
436 $error = false;
437 $error_msg = '';
438 $comment = '';
439 $infringements = array();
440 $aSanctions = array();
441 $aForms = array();
442 $aSuggestedSaction = array();
443
444 if ($request->isMethod(sfRequest::POST))
445 {
446 $empid = $request->getParameter('empid');
447 $aArticles = $request->getParameter('articles');
448 /* Get the configuration id for user's unit */
449 $sql = "SELECT *
450 FROM idt_users u
451 INNER JOIN idt_disciplinary_matrix_configuration_units c ON c.dcu_uni_id = u.usr_currdept
452 WHERE dcu_active = 1 AND u.usr_empid = " . $empid;
453 $sql = "SELECT *
454 FROM
455 idt_users u
456 INNER JOIN
457 idt_positions p ON p.pos_id = u.usr_currposition
458 INNER JOIN
459 idt_disciplinary_matrix_configurations dcf ON (dcf.dcf_type_pos = p.pos_unit_type AND dcf.dcf_active = 1)
460 INNER JOIN
461 idt_disciplinary_matrix_configuration_units c ON (c.dcu_dcf_id = dcf.dcf_id AND c.dcu_uni_id = u.usr_currdept AND c.dcu_active = 1)
462 WHERE
463 u.usr_empid = ".$empid;
464 $aConfiguration = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql)->fetchAll();
465
466 /* Get the list of articles that this user has infringed so far */
467 $sql = "SELECT SUM(TBL.OCURRENCES) AS OCURRENCES, ID, ART_ID, ARTICLE, LAST_INCIDENT
468 FROM (
469 SELECT COUNT(a1.dma_id) AS OCURRENCES, a1.dma_id AS ID, a1.dma_art_id AS ART_ID, a1.dma_desc AS ARTICLE, IFNULL(MAX(p.dpc_incident_date), 'N/A') AS LAST_INCIDENT
470 FROM idt_disciplinary_process p
471 INNER JOIN idt_disciplinary_process_infringements i ON i.dpi_dpc_id = p.dpc_id
472 INNER JOIN idt_disciplinary_matrix_articles a1 ON a1.dma_id = i.dpi_dma_id
473 WHERE dpc_usr_empid = " . $empid . " AND p.dpc_dgs_status NOT IN(3)
474 GROUP BY a1.dma_id
475 UNION
476 SELECT 1 AS OCURRENCES, a2.dma_id AS ID, a2.dma_art_id AS ART_ID, a2.dma_desc AS ARTICLE, 'N/A' AS LAST_INCIDENT
477 FROM idt_disciplinary_matrix_articles a2
478 WHERE a2.dma_id IN(" . implode(',', $aArticles) . ")
479 ) AS TBL
480 GROUP BY TBL.ARTICLE
481 ORDER BY TBL.OCURRENCES DESC;";
482
483 $infringements = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql)->fetchAll();
484
485 if (count($infringements) > 0)
486 {
487 /* The list of suggested santions will be selected in base at the following
488 * criteria. Fisrt the unit's configuration, second the articles selected
489 * and third the amount of times that this article has been infringed
490 * (aka occurrence)
491 */
492 if (count($aConfiguration) > 0)
493 {
494 $sql = "SELECT TBL.ART_ID, TBL.OCURRENCES, s.das_dms_id AS SAN_ID, n.dms_position AS SAN_POSITION, n.dms_name AS SANCTION, s.das_dcf_id AS CONFIGURATION
495 FROM (
496 SELECT SUM(TBLRAW.OCURRENCES) AS OCURRENCES, TBLRAW.ART_ID AS ART_ID
497 FROM (
498 SELECT COUNT(i.dpi_dma_id) AS OCURRENCES, i.dpi_dma_id AS ART_ID, i.dpi_creation_date AS CREATION_DATE
499 FROM idt_disciplinary_process p
500 INNER JOIN idt_disciplinary_process_infringements i ON i.dpi_dpc_id = p.dpc_id AND i.dpi_dma_id IN(" . implode(',', $aArticles) . ")
501 WHERE p.dpc_usr_empid = " . $empid . " AND p.dpc_dgs_status NOT IN(3) AND IF(p.dpc_dma_expiration > 0, IF(ADDDATE(p.dpc_emission_date, INTERVAL p.dpc_dma_expiration MONTH) > CURDATE(), 1, 0), 1) = 1
502 GROUP BY i.dpi_dma_id
503 UNION
504 SELECT 1 AS OCURRENCES, a2.dma_id AS ART_ID, a2.dma_creation_date AS CREATION_DATE
505 FROM idt_disciplinary_matrix_articles a2
506 WHERE a2.dma_id IN(" . implode(',', $aArticles) . ")
507 ) AS TBLRAW
508 GROUP BY TBLRAW.ART_ID
509 ) AS TBL
510 INNER JOIN idt_disciplinary_matrix_articles_sanctions s ON s.das_dma_id = TBL.ART_ID
511 INNER JOIN idt_disciplinary_matrix_sanctions n ON n.dms_id = s.das_dms_id
512 WHERE s.das_active = 1 AND s.das_dcf_id = " . $aConfiguration[0]['dcu_dcf_id'] . " AND TBL.OCURRENCES = s.das_ocurrence
513 ORDER BY n.dms_position DESC, TBL.OCURRENCES DESC
514 LIMIT 1";
515 $aSuggestedSanctions = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql)->fetchAll();
516
517 /* If no suggested santion was returned then take the highest sanction
518 */
519 if (count($aSuggestedSanctions) <= 0)
520 {
521 $aSuggestedSanctions = Doctrine_Query::create()
522 ->select('a.das_dma_id AS ART_ID, a.das_ocurrence AS OCURRENCES, a.das_dms_id AS SAN_ID, n.dms_position AS SAN_POSITION, n.dms_name AS SANCTION, a.das_dcf_id AS CONFIGURATION')
523 ->from('IdtDisciplinaryMatrixArticlesSanctions a')
524 ->innerJoin('a.IdtDisciplinaryMatrixSanctions n ON n.dms_id = a.das_dms_id')
525 ->whereIn('a.das_dma_id', $aArticles)
526 ->orderBy('n.dms_position DESC, a.das_ocurrence DESC')
527 ->limit(1)
528 ->fetchArray();
529 }
530
531 /* Now get the catalog of sanctions */
532 /* List of possible sanctions */
533 $sanctions_available = Doctrine_Query::create()
534 ->select('dms.dms_id, dms.dms_name, das.das_id')
535 ->from('IdtDisciplinaryMatrixArticlesSanctions das')
536 ->innerJoin('das.IdtDisciplinaryMatrixSanctions dms ON dms.dms_id = das.das_dms_id')
537 ->whereIn('das.das_dma_id', $aArticles)
538 ->andWhere('das.das_active = ?', array(1))
539 ->groupBy('dms.dms_id')
540 ->orderBy('dms.dms_name')
541 ->fetchArray();
542 /*$sanctions_available = Doctrine_Core::getTable('IdtDisciplinaryMatrixSanctions')
543 ->createQuery('s')
544 ->where('s.dms_active =?', array(1))
545 ->orderBy('s.dms_position ASC')
546 ->fetchArray();*/
547
548 foreach ($sanctions_available as $s)
549 {
550 $aSanctions[] = array('id' => $s['IdtDisciplinaryMatrixSanctions']['dms_id'], 'name' => $s['IdtDisciplinaryMatrixSanctions']['dms_name']);
551 }
552 /* Select the catalog of forms */
553 $forms = Doctrine_Core::getTable('IdtForm')
554 ->createQuery('f')
555 ->InnerJoin('f.IdtFormSanction s ON s.fsa_form_id = f.frm_id AND s.fsa_active =1 AND s.fsa_dms_id =' . $aSuggestedSanctions[0]['SAN_ID'])
556 ->where('f.frm_active =? AND frm_enabled =?', array(1, 1))
557 ->orderBy('f.frm_name')
558 ->fetchArray();
559
560 foreach ($forms as $f)
561 {
562 $aForms[] = array('id' => $f['frm_id'], 'name' => $f['frm_name']);
563 }
564 } else
565 {
566 $error = __("There's no Hints Guide associated to user's account");
567 }
568 } else
569 {
570 $comment = __("User doesn't have any Hints Processes yet.");
571 }
572 }
573
574 /* Fix date format */
575 $oDateFormater = new DateFormater();
576 foreach ($infringements as $key => $value)
577 {
578 if ($value['LAST_INCIDENT'] != 'N/A')
579 {
580 $infringements[$key]['LAST_INCIDENT'] = $oDateFormater->formatDate($value['LAST_INCIDENT']);
581 }
582 }
583
584 $encoded = json_encode(array('error' => $error,
585 'error_msg' => $error_msg,
586 'comment' => $comment,
587 'suggested_sanction_name' => $aSuggestedSanctions[0]['SANCTION'],
588 'suggested_sanction_id' => $aSuggestedSanctions[0]['SAN_ID'],
589 'infringements' => $infringements,
590 'forms' => $aForms,
591 'sanctions' => $aSanctions,
592 'article' => $aSuggestedSanctions[0]['ART_ID'],
593 'configuration' => $aSuggestedSanctions[0]['CONFIGURATION'],
594 ));
595
596 $this->getResponse()->setContent($encoded);
597 return sfView::NONE;
598 }
599
600
601 /**
602 * Executes set sanction
603 * Store the sanction and form selected
604 *
605 * @param sfRequest $request A request object
606 */
607 public function executeSetsanction(sfWebRequest $request){
608 /* Variables */
609 $error = false;
610 $error_msg = '';
611 $sErrorDetail = '';
612 $iFormId = 0;
613 $iSanction = 0;
614 $iEmpid = 0;
615 $iSuggestedSanction = 0;
616 $aArticles = array();
617 $iVoidDmApproval = 0;
618
619 $userEmail = $this->getUser()->getAttribute('email');
620 $creatorUserId = $this->getUser()->getAttribute('id');
621
622 //$oMailNotification = new MailNotification();
623
624 if ($request->isMethod(sfRequest::POST)){
625 $iEmpid = $request->getParameter('empid');
626 $iFormId = $request->getParameter('sel_form');
627 $iSanction = $request->getParameter('sel_sanction');
628 $aArticles = $request->getParameter('articles');
629 $iArticle = $request->getParameter('suggested_article_id');
630 $iSuggestedSanction = $request->getParameter('suggested_sanction_id');
631 $iConfiguration = $request->getParameter('configuration_id');
632 $iVdmApproval = $request->getParameter('vdm_approval');
633 $iReasonOverrideFrm = $request->getParameter('reason_override_frm');
634 $iVoidDmApproval = 0;
635 $iVoidDmApprovalRole = 0;
636 $iDpId = 0;
637 $iExpirationTime = 1;
638 $sql_string = '';
639 /* Before to create the disciplinary process, check if the current configuration
640 * needs to be approved in case the sanction applied is not the suggested
641 * one
642 */
643 $this->logMessage("DP (referer -> dp/setsanction): Start creation of DP");
644 $aConfiguration = Doctrine_Core::getTable('IdtDisciplinaryMatrixConfigurations')
645 ->createQuery('c')
646 ->where('c.dcf_id =? AND c.dcf_active =?', array($iConfiguration, 1))
647 ->fetchArray();
648
649 if (count($aConfiguration) > 0){
650
651 if ($iSanction != $iSuggestedSanction && $aConfiguration[0]['dcf_vdm_auth'] == 1){
652 $iVoidDmApproval = 1;
653 $iVoidDmApprovalRole = $aConfiguration[0]['dcf_vdm_role'];
654 }
655
656
657
658 /* Get user profile */
659 $oUserManager = new UserManager();
660 $aUserInformation = $oUserManager->getUserProfile($iEmpid);
661
662 if (count($aUserInformation) > 0){
663 /* Get sanction expiration */
664 $aSanction = Doctrine_Core::getTable('IdtDisciplinaryMatrixArticlesSanctions')
665 ->createQuery('s')
666 ->where('s.das_dma_id =? AND s.das_dcf_id =? AND das_dms_id =? AND das_active =?', array($iArticle, $iConfiguration, $iSanction, 1))
667 ->fetchArray();
668
669 $q = Doctrine_Core::getTable('IdtDisciplinaryMatrixArticlesSanctions')
670 ->createQuery('s')
671 ->where('s.das_dma_id =? AND s.das_dcf_id =? AND das_dms_id =? AND das_active =?', array($iArticle, $iConfiguration, $iSanction, 1))
672 ->getSqlQuery();
673
674 if (count($aSanction) > 0){
675 $iExpirationTime = $aSanction[0]['das_expiration'];
676
677 // ajuste si la variable expiration_forced_for_termination_type esta habilitada
678 if ((sfConfig::get('irdp_expiration_forced_for_termination_type') == 1) && ($iSanction > 0) && ($iArticle > 0)){ // forzar expiracion para termination a 6 meses
679 $oDisMatrixArt = Doctrine_Core::getTable("IdtDisciplinaryMatrixArticles")->findOneByDmaId($iArticle);
680 if ($oDisMatrixArt){
681 $dataType = $oDisMatrixArt->getDmaAscId();
682 $iExpirationTime = $dataType == 8 ? 6 : $iExpirationTime; // ajuste para tipo (8) - termination
683 }
684 } // end --> ajuste expiration_forced_for_termination_type
685 // ajuste si variable expiration_forced_for_high_type esta habilitada
686 if ((sfConfig::get('irdp_expiration_forced_for_high_type') == 1) && ($iSanction > 0) && ($iArticle > 0)){ // forzar expiracion para high a 6 meses
687 $oDisMatrixArt = Doctrine_Core::getTable("IdtDisciplinaryMatrixArticles")->findOneByDmaId($iArticle);
688 if ($oDisMatrixArt){
689 $dataType = $oDisMatrixArt->getDmaAscId();
690 $iExpirationTime = $dataType == 6 ? 6 : $iExpirationTime; // ajuste para tipo (6) - high
691 }
692 } // end --> ajuste expiration_forced_for_high_type
693 } else{
694 $aSanction = Doctrine_Core::getTable('IdtDisciplinaryMatrixArticles')
695 ->createQuery('a')
696 ->where('a.dma_id =? AND a.dma_active =?', array($iArticle, 1))
697 ->fetchArray();
698
699 $dataType = $aSanction[0]['dma_asc_id'];
700 $iExpirationTime = $aSanction[0]['dma_expiration'];
701
702 // ajuste si variable expiration_forced_for_termination_type esta habilitada
703 if (sfConfig::get('irdp_expiration_forced_for_termination_type') == 1){ // forzar expiracion para termination a 6 meses
704 $iExpirationTime = $dataType == 8 ? 6 : $iExpirationTime; // ajuste para tipo (8) - termination
705 }
706 // end --> ajuste expiration_forced_for_termination_type
707 // ajuste si variable expiration_forced_for_high_type esta habilitada
708 if (sfConfig::get('irdp_expiration_forced_for_high_type') == 1){ // forzar expiracion para termination a 6 meses
709 $iExpirationTime = $dataType == 6 ? 6 : $iExpirationTime; // ajuste para tipo (6) - high
710 }
711 // end --> ajuste expiration_forced_for_high_type
712 }
713
714 if (count($aSanction) > 0){
715 /* Get form selected fisrt state */
716 $aState = Doctrine_Core::getTable('IdtForm')
717 ->createQuery('f')
718 ->innerJoin('f.IdtDisciplinaryProcessProcesses p ON p.dpr_id = f.frm_proc_id')
719 ->innerJoin('p.IdtDisciplinaryProcessStatesCatalog s ON s.dst_dpr_id = p.dpr_id AND s.dst_sta_cat = 1 AND s.dst_active = 1')
720 ->where('f.frm_id =?', array($iFormId))
721 ->limit(1)
722 ->fetchArray();
723
724 if (count($aState) > 0){
725 /* Open disciplinary process */
726 if($iVoidDmApproval == 1 && ($iReasonOverrideFrm=='' || !isset($iReasonOverrideFrm))){
727 $error=true;
728 $error_msg = __("Required Override Reason ");
729 }else{
730 $noti_uni_dpc = $aUserInformation['profile']['usr_department_id'];
731 $oDisciplinaryProcess = new IdtDisciplinaryProcess ();
732 $oDisciplinaryProcess->setDpcUsrEmpid($iEmpid);
733 $oDisciplinaryProcess->setDpcPosId($aUserInformation['profile']['usr_position_id']);
734 $oDisciplinaryProcess->setDpcUniId($aUserInformation['profile']['usr_department_id']);
735 $oDisciplinaryProcess->setDpcSupId($aUserInformation['profile']['usr_supervisor_id']);
736 $oDisciplinaryProcess->setDpcDmsId($iSanction);
737 $oDisciplinaryProcess->setDpcDmaExpiration($iExpirationTime);
738 $oDisciplinaryProcess->setDpcCurrState($aState[0]['IdtDisciplinaryProcessProcesses']['IdtDisciplinaryProcessStatesCatalog'][0]['dst_id']);
739 $oDisciplinaryProcess->setDpcFormId($iFormId);
740 $oDisciplinaryProcess->setDpcDgsStatus(1);
741 $oDisciplinaryProcess->setDpcVdmRequired($iVoidDmApproval);
742 $oDisciplinaryProcess->setDpcCreatedBy($this->getUser()->getAttribute('id'));
743 $oDisciplinaryProcess->setDpcCreationDate(date('Y-m-d H:i:s', time()));
744 $oDisciplinaryProcess->setDpcActive(1);
745 $oDisciplinaryProcess->setDpcReasonOverride($iReasonOverrideFrm);
746
747 if (is_int($aUserInformation['profile']['usr_seclevelsup_id']) === TRUE){
748 $oDisciplinaryProcess->setDpcSeclevSupId($aUserInformation['profile']['usr_seclevelsup_id']);
749 }
750
751 try {
752 $oDisciplinaryProcess->save(); //TEST *****
753
754 $iDpId = $oDisciplinaryProcess->getDpcId();
755
756 /* Articles infringed */
757 foreach ($aArticles as $art){
758 $oInfringement = new IdtDisciplinaryProcessInfringements();
759 $oInfringement->setDpiUsrEmpid($iEmpid);
760 $oInfringement->setDpiDpcId($iDpId);
761 $oInfringement->setDpiDmaId($art);
762 $oInfringement->setDpiCreatedBy($this->getUser()->getAttribute('id'));
763 $oInfringement->setDpiCreationDate(date('Y-m-d H:i:s', time()));
764 $oInfringement->setDpiActive(1);
765 $oInfringement->save(); //TEST *****
766 }
767
768 /* --------------------------------------------------------------------- */
769 /* Store the suggested sanctions */
770 $oSuggestedSanction = new IdtDisciplinaryProcessSuggestedSanctions();
771 $oSuggestedSanction->setDpsUsrEmpid($iEmpid);
772 $oSuggestedSanction->setDpsDmsId($iSuggestedSanction);
773 $oSuggestedSanction->setDpsDpcId($iDpId);
774 $oSuggestedSanction->setDpsPriority(1);
775 $oSuggestedSanction->setDpsCreatedBy($this->getUser()->getAttribute('id'));
776 $oSuggestedSanction->setDpsCreationDate(date('Y-m-d H:i:s', time()));
777 $oSuggestedSanction->setDpsActive(1);
778 $oSuggestedSanction->save(); //TEST *****
779
780 /* --------------------------------------------------------------------- */
781 /* Store the fisrt step - created in the history table */
782 $oDpHistory = new IdtDisciplinaryProcessStateHistory();
783 $oDpHistory->setDphDpcId($iDpId);
784 $oDpHistory->setDphDstId($aState[0]['IdtDisciplinaryProcessProcesses']['IdtDisciplinaryProcessStatesCatalog'][0]['dst_id']);
785 $oDpHistory->setDphCreatedBy($this->getUser()->getAttribute('id'));
786 $oDpHistory->setDphCreationDate(date('Y-m-d H:i:s'), time());
787 $oDpHistory->setDphActive(1);
788 $oDpHistory->save(); //TEST *****
789
790 /* --------------------------------------------------------------------- */
791 /* Finally create the historical record that will be used for reporting purposes */
792 $sSuggested_Sanction_Name = '';
793 $sImposed_Sanction_Name = '';
794 $sArticle_Details = '';
795
796 /* 1- Get the names of sanctions */
797 $aSanctionsDetail = Doctrine_Core::getTable('IdtDisciplinaryMatrixSanctions')
798 ->createQuery('s')
799 ->where('s.dms_active =?', array(1))
800 ->whereIn('s.dms_id', array($iSuggestedSanction, $iSanction))
801 ->fetchArray();
802
803 foreach ($aSanctionsDetail as $d){
804 if ($d['dms_id'] == $iSuggestedSanction){
805 $sSuggested_Sanction_Name = $d['dms_name'];
806 }
807
808 if ($d['dms_id'] == $iSanction){
809 $sImposed_Sanction_Name = $d['dms_name'];
810 }
811 }
812
813 /* 2- Get the details of articles */
814 $aArticleDetail = Doctrine_Query::create()
815 ->select("GROUP_CONCAT(a.dma_art_id,' - ', a.dma_desc, '<br>') AS ARTICLES")
816 ->from('IdtDisciplinaryMatrixArticles a')
817 ->where('a.dma_active =?', array(1))
818 ->whereIn('a.dma_id', $aArticles)
819 ->fetchArray();
820
821 foreach ($aArticleDetail as $a){
822 $sArticle_Details = $a['ARTICLES'];
823 }
824
825 /* 3- Now, store values in the report table */
826 $oDpReportRecord = new IdtHistoryDisciplinaryProcess();
827
828 $oDpReportRecord->setHdpDpcId($iDpId);
829 $oDpReportRecord->setHdpUsrEmpid($iEmpid);
830 $oDpReportRecord->setHdpPosId($aUserInformation['profile']['usr_position_id']);
831 $oDpReportRecord->setHdpUniId($aUserInformation['profile']['usr_department_id']);
832 $oDpReportRecord->setHdpSupId($aUserInformation['profile']['usr_supervisor_id']);
833 $oDpReportRecord->setHdpSeclevSupId($aUserInformation['profile']['usr_seclevelsup_id']);
834 $oDpReportRecord->setHdpDmaExpiration($iExpirationTime);
835 $oDpReportRecord->setHdpDgsStatus(1);
836
837 $oDpReportRecord->setHdpUsrFullName($aUserInformation['profile']['usr_name']);
838 $oDpReportRecord->setHdpPosName($aUserInformation['profile']['usr_position_name']);
839 $oDpReportRecord->setHdpUniName($aUserInformation['profile']['usr_department_name']);
840 $oDpReportRecord->setHdpSupName($aUserInformation['profile']['usr_supervisor_name']);
841 $oDpReportRecord->setHdpSeclevSupName($aUserInformation['profile']['usr_seclevelsup_name']);
842
843 $oDpReportRecord->setHdpSugSanctionId($iSuggestedSanction);
844 $oDpReportRecord->setHdpAppliedSanctionId($iSanction);
845 $oDpReportRecord->setHdpSugSanctionName($sSuggested_Sanction_Name);
846 $oDpReportRecord->setHdpAppliedSanctionName($sImposed_Sanction_Name);
847 $oDpReportRecord->setHdpArticlesInfringed($sArticle_Details);
848
849 $oDpReportRecord->setHdpCreatedBy($this->getUser()->getAttribute('id'));
850 $oDpReportRecord->setHdpCreationDate(date('Y-m-d H:i:s', time()));
851 $oDpReportRecord->setHdpActive(1);
852 $oDpReportRecord->save(); //TEST *****
853
854 $error_msg = __("The Hint has been applied.");
855 if (!$iReasonOverrideFrm) {
856 $error_msg = __("The Hint has been applied.");
857 }else{
858 $error_msg = __("The override Hint request has been sent.");
859 }
860 $this->logMessage("DP (referer -> dp/setsanction): DP id " . $iDpId . " was created");
861
862 /* Send Notifications */
863 //Set message
864 $iDpIdNum = str_pad($iDpId, 4, "0", STR_PAD_LEFT);
865
866 $sMailContent = sfConfig::get('irdp_notification_dp_create_main_content');
867 $sMailContent = str_replace("[%DP Id%]", $iDpIdNum, $sMailContent);
868 $sMailContent = str_replace("[%VHUR%]", $iEmpid, $sMailContent);
869 $sMailContent = str_replace("[%Name%]", $aUserInformation['profile']['usr_name'], $sMailContent);
870 $sMailContent = str_replace("[%Unit%]", $aUserInformation['profile']['usr_department_name'], $sMailContent);
871 $sMailContent = str_replace("[%Position%]", $aUserInformation['profile']['usr_position_name'], $sMailContent);
872 $sMailContent = str_replace("[%Supervisor%]", $aUserInformation['profile']['usr_supervisor_name'], $sMailContent);
873 $sMailContent = str_replace("[%Articles%]", $sArticle_Details, $sMailContent);
874 $sMailContent = str_replace("[%Sanction Sug%]", $sSuggested_Sanction_Name, $sMailContent);
875 $sMailContent = str_replace("[%Sanction Imp%]", $sImposed_Sanction_Name, $sMailContent);
876
877
878 // Sending notification email when a new hint is created (New Module)
879 $mailHint = new PhpMailerNotif();
880 //Getting employee information
881 $emp_info = Doctrine_Query::create()
882 ->select('u.usr_empid, CONCAT(u.usr_fname, " ", u.usr_mname, " ", u.usr_lname, " ", u.usr_sname) employee_name, u.usr_location, s.sit_name, un.uni_name, p.pos_name, p.pos_name_es, u.usr_email, CONCAT(su.usr_fname, " ", su.usr_mname, " ", su.usr_lname, " ", su.usr_sname) supervisor_name')
883 ->from('IdtUsers u')
884 ->innerJoin('u.IdtSites s ON s.sit_id = u.usr_location')
885 ->innerJoin('u.IdtPositions p ON p.pos_id = u.usr_currposition')
886 ->innerJoin('u.IdtUnits un ON un.uni_id = u.usr_currdept')
887 ->innerJoin('u.IdtUsers su ON su.usr_empid = u.usr_supervisor')
888 ->where('u.usr_empid = ?', array($iEmpid))
889 ->fetchArray();
890 $message = '<html><body>';
891 $message .= "<span style='font-size:14pt;font-family:Arial;color:rgb(73,22,109);background-color:transparent;font-weight:700;vertical-align:baseline;white-space:pre-wrap'>Hints for Success Tracker </span><br><br>";
892 $message .= "<span style='font-size:10pt;font-family:Arial;color:rgb(102,102,102);background-color:transparent;vertical-align:baseline;white-space:pre-wrap'><br>The following Hint has been created.<br></span><br>";
893 $message .= '<table rules="all" width="75%" style="border-color: #8c68a6;" cellpadding="10">';
894 $message .= "<tr style='background: #72CF0C; color:#FFF;'><td style='width:25%;'><strong>Hint Number:</strong> </td><td>".$iDpIdNum."</td></tr>";
895 $message .= "<tr style='color:#666666;'><td><strong>Employee ID:</strong> </td><td>".$emp_info[0]['usr_empid']."</td></tr>";
896 $message .= "<tr style='color:#666666;'><td><strong>Employee Name:</strong> </td><td>".$emp_info[0]['employee_name']."</td></tr>";
897 $message .= "<tr style='color:#666666;'><td><strong>Unit:</strong> </td><td>".$emp_info[0]['IdtUnits'][0]['uni_name']."</td></tr>";
898 $message .= "<tr style='color:#666666;'><td><strong>Position:</strong> </td><td>".$emp_info[0]['IdtPositions'][0]['pos_name']." / ".$emp_info[0]['IdtPositions'][0]['pos_name_es']."</td></tr>";
899 $message .= "<tr style='color:#666666;'><td><strong>Supervisor:</strong> </td><td>".$emp_info[0]['supervisor_name']."</td></tr>";
900 $message .= "<tr style='color:#666666;'><td><strong>Articles Infringed:</strong> </td><td>".$sArticle_Details."</td></tr>";
901 $message .= "<tr style='color:#666666;'><td><strong>Suggested Sanction:</strong> </td><td>".$sSuggested_Sanction_Name."</td></tr>";
902 $message .= "<tr style='color:#666666;'><td><strong>Sanction Imposed:</strong> </td><td>".$sImposed_Sanction_Name."</td></tr>";
903 $message .= "</table>";
904 $message .= "<br><div><font face='Arial' size='2'><b>Confidentiality Notice: </b></font></div>";
905 $message .= "<div style='font-size:1.3em'><font face='Arial' size='1'>This e-mail transmission, and any documents, files or previous e-mail messages attached to it may contain confidential information that is legally privileged. If you are not the intended recipient, or a person responsible for delivering it to the intended recipient, you are hereby notified that any disclosure, copying, distribution or use of any of the information contained in or attached to this transmission is STRICTLY PROHIBITED. If you have received this transmission in error, please immediately notify the sender. Please destroy the original transmission and its attachments without reading or saving in any manner.</font></div>";
906 $message .= "</body></html>";
907
908 $sqlNotif = "SELECT n.not_usr_email FROM idt_notification n INNER JOIN idt_users_units uun ON n.not_usr_id = uun.uun_usr_empid WHERE n.not_active = 1 AND uun.uun_uni_id = $noti_uni_dpc;";
909 $aIdtNotification = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sqlNotif)->fetchAll();
910
911 $aRecipients = array();
912 foreach ($aIdtNotification as $key => $reminders_active) {
913 $aRecipients[] = $reminders_active['not_usr_email'];
914 }
915 //The list of parameter must be separate by comma
916 $oListEmailsStr = sfConfig::get('irdp_list_emails_notif_applied_hint');
917 $aListEmailsStr = explode(',', $oListEmailsStr);
918 if ( count($aListEmailsStr) > 0 || count($aRecipients) > 0 ) {
919 if (count($aRecipients) <= 0) {
920 $aRecipients = $aListEmailsStr;
921 }
922 $mailHint->sendNotificationEmail($message, $aRecipients);
923 }
924
925 //Set subject
926 $sMailSubject = sfConfig::get('irdp_notification_sanction_approval_subject');
927 $sMailSubject = str_replace("[%DP Id%]", $iDpIdNum, $sMailSubject);
928
929 if (sfConfig::get('irdp_notification_enabled') == 1){
930 if ($iVoidDmApproval == 1){
931 /* Send the message to people in charge of approve it */
932 $this->logMessage("DP (referer -> dp/setsanction): Selected sanction needs an additional approval. Try to send notifications. Notifications enabled " . sfConfig::get('irdp_notification_enabled'));
933
934 /* Get the recipients list */
935 try {
936 $sql = "SELECT usr_email FROM idt_users u
937 INNER JOIN idt_users_roles r ON r.uro_usr_id = u.usr_empid
938 WHERE ((r.uro_rol_id = " . $iVoidDmApprovalRole . " AND r.uro_active = 1) OR usr_currposition IN(
939 SELECT rpo_pos_id
940 FROM idt_roles_positions rp
941 WHERE rpo_rol_id = " . $iVoidDmApprovalRole . " AND rp.rpo_active = 1)) AND usr_email != ''";
942
943 $aEmailList = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql)->fetchAll();
944
945 // agregamos la persona que edita el IR a las notificaciones
946 $exist = false;
947
948 foreach ($aEmailList as $key => $value){
949 if ($value['usr_email'] == $userEmail){
950 $exist = true;
951 break;
952 }
953 }
954 if (!$exist){
955 array_push($aEmailList, array('usr_email' => $userEmail)); // add creator email
956 }
957
958 // add supMail
959 $oUser = new IdtUsers;
960 $oUser = Doctrine_Core::getTable(IdtUsers)->findOneByUsrEmpid($iEmpid);
961 if ($oUser){
962 $supId = $oUser->getUsrSupervisor();
963 if ($supId){
964 $oUser = null;
965 $oUser = Doctrine_Core::getTable(IdtUsers)->findOneByUsrEmpid($supId);
966 if ($oUser){
967 $supEmail = $oUser->getUsrEmail();
968 $managerId = $oUser->getUsrSupervisor();
969
970 $exist = false;
971 foreach ($aEmailList as $key => $value){
972 if ($value['usr_email'] == $supEmail){
973 $exist = true;
974 break;
975 }
976 }
977 if (!$exist){
978 array_push($aEmailList, array('usr_email' => $supEmail)); // add supervisor email
979
980 }
981 }
982 }
983 }
984
985 // add 2nd level manager
986 if ($managerId > 0){
987 $oUser = new IdtUsers;
988 $oUser = Doctrine_Core::getTable(IdtUsers)->findOneByUsrEmpid($managerId);
989 if ($oUser){
990 $managerEmail = $oUser->getUsrEmail();
991
992 $exist = false;
993 foreach ($aEmailList as $key => $value){
994 if ($value['usr_email'] == $managerEmail){
995 $exist = true;
996 break;
997 }
998 }
999 if (!$exist){
1000 array_push($aEmailList, array('usr_email' => $managerEmail)); // add supervisor email
1001 }
1002 }
1003 }
1004
1005 if (count($aEmailList) > 0) {
1006
1007 //Set recipients
1008 foreach ($aEmailList as $key => $value){
1009 $oMailNotification->setTo($value['usr_email']);
1010 }
1011
1012 //Setting parameters
1013 $oMailNotification->setMessage(sfConfig::get('irdp_notification_sanction_approval_content') . $sMailContent);
1014 $oMailNotification->setSubject($sMailSubject);
1015 $result = $oMailNotification->send();
1016
1017 if (!$result['error']){
1018 $error_msg = $error_msg . __("<br>Because the current sanction doesn't meet the Hints Guide criteria you won't be able
1019 to edit the form by now. You have to wait for the approval of the sanction selected.
1020 The request for approval has been sent.");
1021 } else{
1022 $error_msg = $error_msg . __("<br>Because the current sanction doesn't meet the Hints Guide criteria you won't be able
1023 to edit the form by now. You have to wait for the approval of the sanction selected.");
1024 $this->logMessage("DP (referer -> dp/setsanction): Couldn't be sent. There was an error during this operation");
1025 }
1026 }
1027 } catch (Exception $e) {
1028 $error_msg = $error_msg . __("<br>Because the current sanction doesn't meet the Hints Guide criteria you won't be able
1029 to edit the form by now. You have to wait for the approval of the sanction selected.");
1030 $this->logMessage("DP (referer -> dp/setsanction): Notifications requestiing the approval of the selected sanction could not be sent");
1031 }
1032 } else
1033 {
1034 /* Send a message to the people in charge of fill in the form */
1035 $aRecipients = $oMailNotification->getRecipients($aState[0]['IdtDisciplinaryProcessProcesses']['IdtDisciplinaryProcessStatesCatalog'][0]['dst_id'], $aUserInformation['profile']['usr_department_id'], $iEmpid);
1036 if (!$aRecipients['error']){
1037 $aRecipients = $aRecipients['mail_list'];
1038 /* Set the list of recipients */
1039 // agregamos la persona que edita el IR a las notificaciones
1040 $exist = false;
1041 foreach ($aRecipients as $value){
1042 if ($value == $userEmail){
1043 $exist = true;
1044 break;
1045 }
1046 }
1047 if (!$exist){
1048 $aRecipients[] = $userEmail; // add creator email
1049 }
1050
1051 foreach ($aRecipients as $mail){
1052 if ($mail != ''){
1053 $oMailNotification->setTo($mail);
1054 }
1055 }
1056
1057 // add supMail
1058 $oUser = new IdtUsers;
1059 $oUser = Doctrine_Core::getTable(IdtUsers)->findOneByUsrEmpid($iEmpid);
1060 if ($oUser){
1061 $supId = $oUser->getUsrSupervisor();
1062 if ($supId){
1063 $oUser = null;
1064 $oUser = Doctrine_Core::getTable(IdtUsers)->findOneByUsrEmpid($supId);
1065 if ($oUser){
1066 $supEmail = $oUser->getUsrEmail();
1067 $managerId = $oUser->getUsrSupervisor();
1068 $exist = false;
1069 foreach ($aRecipients as $value){
1070 if ($value == $supEmail){
1071 $exist = true;
1072 break;
1073 }
1074 }
1075 if (!$exist){
1076 $aRecipients[] = $supEmail; // add supervisor email
1077 $oMailNotification->setTo($supEmail); // add supervisor
1078 }
1079 }
1080 }
1081 }
1082
1083 // add 2nd level manager
1084 if ($managerId > 0){
1085 $oUser = new IdtUsers;
1086 $oUser = Doctrine_Core::getTable(IdtUsers)->findOneByUsrEmpid($managerId);
1087 if ($oUser){
1088 $managerEmail = $oUser->getUsrEmail();
1089 $exist = false;
1090 foreach ($aRecipients as $value){
1091 if ($value == $managerEmail){
1092 $exist = true;
1093 break;
1094 }
1095 }
1096 if (!$exist){
1097 $aRecipients[] = $managerEmail; // add supervisor email
1098 $oMailNotification->setTo($managerEmail); // add supervisor
1099 }
1100 }
1101 }
1102 if (count($aRecipients) > 0){
1103 //Setting parameters
1104 $oMailNotification->setMessage(sfConfig::get('irdp_notification_dp_create_content') . $sMailContent);
1105 $oMailNotification->setSubject($sMailSubject);
1106 $result = $oMailNotification->send();
1107 }
1108 if (!$result['error']){
1109 $error_msg = $error_msg . __("The Hint has been applied.");
1110 if (!$iReasonOverrideFrm) {
1111 $error_msg = $error_msg . __("The Hint has been applied.");
1112 }else{
1113 $error_msg = $error_msg . __("The override Hint request has been sent.");
1114 }
1115 } else{
1116 $error_msg = $error_msg . __("The Hint has been applied. But, there was an error sending the email notifications");
1117 $this->logMessage("DP (referer -> dp/setsanction): Notifications couldn't be sent. There was an error during this operation");
1118 }
1119 } else{
1120 $error_msg = $error_msg . __("The Hint has been applied. But, notifications couldn't be sent");
1121 $this->logMessage("DP (referer -> dp/setsanction): The Hint has been applied.
1122 But, notifications couldn't be sent because no recipients were returned byt the
1123 function MailNotification->getRecipientes(" . $aState[0]['IdtDisciplinaryProcessProcesses']['IdtDisciplinaryProcessStatesCatalog'][0]['dst_id'] .
1124 "," . $aUserInformation['profile']['usr_department_id'] . ")");
1125 }
1126 }
1127 }
1128 } catch (Exception $e) {
1129 echo $e->getMessage();
1130 die();
1131 $error = true;
1132 $error_msg = __("There was an error trying to update the information");
1133 $this->logMessage('dp/setsanction - ' . $e);
1134 }
1135 }
1136 } else{
1137 $error = true;
1138 $error_msg = __("Process couldn't be completed. The selected form doesn't have a Process associated");
1139 }
1140 } else{
1141 $error = true;
1142 $error_msg = __("Hint not valid. Error: " . $iArticle . "." . $iConfiguration . "." . $iSanction);
1143 }
1144 } else{
1145 $error = true;
1146 $error_msg = __("Couln't find user " . $iEmpid);
1147 }
1148 } else{
1149 $error = true;
1150 $error_msg = __("Couln't find Hints Guide id " . $iConfiguration);
1151 }
1152 }
1153
1154 $encoded = json_encode(array('error' => $error, 'error_msg' => $error_msg, 'error_detail' => $sErrorDetail, 'dp' => $iDpId, 'form' => $iFormId, 'voiddmapp' => $iVoidDmApproval));
1155 $this->getResponse()->setContent($encoded);
1156
1157 return(sfView::NONE);
1158 }
1159 /**
1160 * Load form
1161 *
1162 * @param sfRequest $request A request object
1163 */
1164 public function executeEdit(sfWebRequest $request)
1165 {
1166
1167 $this->forward404If($request->getParameter('id') == null, __("Document id cannot be null"));
1168 $this->forward404If($request->getParameter('dp') == null, __("Hint Process id cannot be null"));
1169
1170 /* Check if the form exists. At the same time a left join is done to check if
1171 * the current form has an attached Legal Document. This variable
1172 * will be used in the Action-Button as an additional condition to show or
1173 * hide the "Legal Document" botton and avoid to load an empty form that only
1174 * will show errors :S
1175 */
1176
1177// $q = Doctrine_Core::getTable('IdtForm')
1178// ->createQuery('f')
1179// ->leftJoin('f.IdtDisciplinaryProcessProcesses p ON f.frm_proc_id = p.dpr_id')
1180// ->leftJoin('f.IdtLegalDocument l ON l.ldo_frm_id = f.frm_id OR l.ldo_proc_id = p.dpr_id')
1181// ->where('f.frm_id =?', array($request->getParameter('id')));
1182// $qw = $q->getSqlQuery();
1183
1184 if (sfConfig::get('irdp_show_legaldoc_by_process') == 1)
1185 {
1186 // verificar configuracion para usar el documento legal
1187 $this->form = Doctrine_Core::getTable('IdtForm')
1188 ->createQuery('f')
1189 ->leftJoin('f.IdtDisciplinaryProcessProcesses p ON f.frm_proc_id = p.dpr_id')
1190 ->leftJoin('f.IdtLegalDocument l ON l.ldo_proc_id = p.dpr_id AND l.ldo_active = 1')
1191 ->where('f.frm_id =?', array($request->getParameter('id')))
1192 ->fetchArray();
1193 } else if (sfConfig::get('irdp_show_legaldoc_by_process') == 2)
1194 {
1195 // por ambos proceso o formulario
1196 $this->form = Doctrine_Core::getTable('IdtForm')
1197 ->createQuery('f')
1198 ->leftJoin('f.IdtDisciplinaryProcessProcesses p ON f.frm_proc_id = p.dpr_id')
1199 ->leftJoin('f.IdtLegalDocument l ON (l.ldo_frm_id = f.frm_id OR l.ldo_proc_id = p.dpr_id) AND l.ldo_active = 1')
1200 ->where('f.frm_id =?', array($request->getParameter('id')))
1201 ->fetchArray();
1202 } else
1203 {
1204 // por formulario comportamiento por defecto
1205 $this->form = Doctrine_Core::getTable('IdtForm')
1206 ->createQuery('f')
1207 ->leftJoin('f.IdtDisciplinaryProcessProcesses p ON f.frm_proc_id = p.dpr_id')
1208 ->leftJoin('f.IdtLegalDocument l ON l.ldo_frm_id = f.frm_id AND l.ldo_active = 1')
1209 ->where('f.frm_id =?', array($request->getParameter('id')))
1210 ->fetchArray();
1211 }
1212
1213 $this->forward404If(count($this->form) <= 0, __("Record not found"));
1214
1215 /* Catch form id and dp id */
1216 $this->form_id = $request->getParameter('id');
1217 $this->dp_id = $request->getParameter('dp');
1218
1219 /* Check if the dp exists */
1220 $this->disciplinary_process = Doctrine_Core::getTable('IdtDisciplinaryProcess')
1221 ->createQuery('d')
1222 ->where('d.dpc_id =?', array($request->getParameter('dp')))
1223 ->fetchArray();
1224
1225 $this->forward404If(count($this->form) <= 0, __("Record not found"));
1226
1227 /* If this dp requires dm approval, and the answer has not been provided yet
1228 * redirect this user to the follow up screen again...because they cannot update it yet
1229 */
1230
1231 if ($this->disciplinary_process[0]['dpc_vdm_required'] == 1 && $this->disciplinary_process[0]['dpc_vdm_approved'] == 0)
1232 {
1233 $this->redirect('dp/followup');
1234 } else
1235 {
1236 /* Get date format */
1237 $oDateFormater = new DateFormater();
1238 $this->sDateFormatJs = $this->form[0]['frm_date_format'];
1239 $this->sDateFormatPhp = $oDateFormater->getPhpDateFormat($this->form[0]['frm_date_format']);
1240
1241 /* Get the catalog of available date formats */
1242 $this->aDateFormats = $oDateFormater->getAvailableDateFormats();
1243
1244 /* Get employee information */
1245 $this->employee_fields_selected = Doctrine_Core::getTable('IdtFormEmployeeData')
1246 ->createQuery('q')
1247 ->where('q.fed_frm_id =? AND q.fed_active=?', array($request->getParameter('id'), 1))
1248 ->innerJoin('q.IdtFormEmployeeFields f ON f.fef_id = q.fed_fef_id')
1249 ->orderBy('q.fed_fef_id ASC')
1250 ->fetchArray();
1251
1252 /* Total of employee information fields selected */
1253 $this->total_employee_selected_fields = 0;
1254
1255 foreach ($this->employee_fields_selected as $efs)
1256 {
1257 if ($efs['IdtFormEmployeeFields']['fef_category'] == 1)
1258 {
1259 $this->total_employee_selected_fields++;
1260 }
1261 }
1262
1263 /* Get employee values */
1264 // removed -> Employee_Personal_Identification_Number
1265 $this->employee_data = Doctrine_Query::create()
1266 ->select("u.usr_empid AS Employee_Id, CONCAT(IFNULL(u.usr_fname,''),' ', IFNULL(u.usr_mname,''),' ',IFNULL(u.usr_lname,''),' ',IFNULL(u.usr_sname,'')) AS Employee_Name,
1267 IFNULL(u.usr_hiredate,'N/A') AS Hire_Date,IFNULL(p.pos_name_es,'N/A') AS Position, IFNULL(CONCAT(u2.usr_fname,' ',u2.usr_lname),'N/A') AS Supervisor,
1268 IFNULL(CONCAT(u3.usr_fname,' ',u3.usr_lname),'N/A') AS 2nd_Level_Manager,IFNULL(d.dpc_emission_date, 'N/A') AS DP_Date,
1269 IFNULL(d.dpc_incident_date, 'N/A') AS Incident_Date, IFNULL(s.dms_name, 'N/A') AS Type_of_Sanction, n.uni_name AS Department, n.uni_id AS UNIT_ID,
1270 s.dms_id, d.dpc_id, GROUP_CONCAT(i.dpi_dma_id), GROUP_CONCAT(a.dma_art_id) AS Articles, usr_identity_doc_number AS Personal_Identification_Number
1271 ")
1272 ->from('IdtUsers u')
1273 ->where('u.usr_empid =?', array($this->disciplinary_process[0]['dpc_usr_empid']))
1274 ->leftJoin('u.IdtPositions p ON p.pos_id = u.usr_currposition')
1275 ->leftJoin('u.IdtUsers u2 ON u2.usr_empid = u.usr_supervisor')
1276 ->leftJoin('u.IdtUnits n ON n.uni_id = u.usr_currdept')
1277 ->leftJoin('u.IdtUsers u3 ON u3.usr_empid = u2.usr_supervisor')
1278 ->leftJoin('u.IdtDisciplinaryProcess d ON d.dpc_usr_empid = u.usr_empid AND d.dpc_id = ' . $request->getParameter('dp'))
1279 ->leftJoin('d.IdtDisciplinaryMatrixSanctions s ON d.dpc_dms_id = s.dms_id')
1280 ->leftJoin('d.IdtDisciplinaryProcessInfringements i ON i.dpi_dpc_id = d.dpc_id')
1281 ->leftJoin('i.IdtDisciplinaryMatrixArticles a ON a.dma_id = i.dpi_dma_id')
1282 ->fetchArray();
1283 //echo $this->employee_data->getSqlQuery();
1284 //echo $this->disciplinary_process[0]['dpc_usr_empid'];
1285
1286 $this->disciplinary_process_information = Doctrine_Query::create()
1287 ->select('p.dpc_id, i.dpi_id, a.dma_id, s.dms_name AS Sanction, c.dmc_name AS Category, GROUP_CONCAT(a.dma_art_id, " - ", a.dma_desc SEPARATOR " ") as Articles, a.dma_expiration AS Expiration,
1288 a.dma_sup_low AS Law_Supporting_Article, p.dpc_suspended_date1, p.dpc_suspended_date1, p.dpc_suspended_date2, p.dpc_suspended_date3, p.dpc_suspended_date4, p.dpc_returning_date')
1289 ->from('IdtDisciplinaryProcess p')
1290 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = p.dpc_dms_id')
1291 ->innerJoin('p.IdtDisciplinaryProcessInfringements i ON i.dpi_dpc_id = p.dpc_id')
1292 ->innerJoin('i.IdtDisciplinaryMatrixArticles a ON a.dma_id = i.dpi_dma_id')
1293 ->innerJoin('a.IdtDisciplinaryMatrixCategories c ON c.dmc_id = a.dma_dmc_id')
1294 ->where('p.dpc_id =?', array($request->getParameter('dp')))
1295 ->groupBy('dpc_id')
1296 ->fetchArray();
1297 /* Get the form */
1298 $formManager = new formManager();
1299
1300 $this->formStructure = $formManager->getDP($request->getParameter('id'), $request->getParameter('dp'));
1301 $this->preview_form = $this->formStructure['form'];
1302
1303 /* Get the required fields */
1304 $this->required_fields = Doctrine_Core::getTable('IdtFormFields')
1305 ->createQuery('r')
1306 ->innerJoin('r.IdtFormCustomFields ON fcf_id = fld_fcf_id')
1307 ->where('fld_frm_id =? AND fld_required =?', array($request->getParameter('id'), 1))
1308 ->fetchArray();
1309
1310 /* Get signatures */
1311 $sql = " SELECT TBL.wdid, p.pos_name_es AS POSITION, IFNULL(TBL.NAME, '') AS NAME, IFNULL(TBL.DATE, '') AS DATE
1312 FROM idt_form_signatures i
1313 INNER JOIN idt_positions p ON p.pos_id = i.fsi_pos_id
1314 LEFT JOIN (
1315 SELECT u.usr_empid as wdid, CONCAT(u.usr_fname,' ', u.usr_lname) AS NAME,u.usr_currposition AS POSITION, h.dph_creation_date AS DATE
1316 FROM idt_disciplinary_process_state_history h
1317 INNER JOIN idt_users u ON u.usr_empid = h.dph_created_by
1318 WHERE h.dph_dpc_id = " . $this->dp_id . " AND u.usr_currposition IN(SELECT s.fsi_pos_id FROM idt_form_signatures s WHERE s.fsi_frm_id = " . $this->form_id . " AND s.fsi_active = 1)
1319 ) TBL ON TBL.POSITION = i.fsi_pos_id
1320 WHERE i.fsi_frm_id = " . $this->form_id . " AND i.fsi_active = 1
1321 ";
1322 $sql2 = " SELECT
1323 u.usr_empid as wdid,
1324 pos.pos_name as POSITION,
1325 CONCAT(u.usr_fname,' ', u.usr_lname) AS NAME,
1326 p.dpc_creation_date AS DATE
1327 FROM idt_disciplinary_process p
1328 RIGHT JOIN idt_users u on u.usr_empid = p.dpc_created_by
1329 RIGHT JOIN idt_positions pos on pos.pos_id = u.usr_currposition
1330 where p.dpc_id = " . $this->dp_id . "
1331 ";
1332
1333 $result = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql)->fetchAll();
1334 $resultCreatedBy = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql2)->fetchAll();
1335
1336 /*
1337 * This part of code verify if the person that created the DP is not exists into the signatures assigned.
1338 * If NOT/False, that will add the signature into the array. Christian Sum 14/12/2016
1339 */
1340 $exists = false;
1341 $finalResult = array();
1342 foreach ($result as $val) {
1343 if ($val['wdid'] == $resultCreatedBy[0]['wdid']){
1344 $exists = true;
1345 }
1346 if($val['wdid']!=""){
1347 $finalResult[] = $val;
1348
1349 }
1350 }
1351 if (!$exists){
1352 $finalResult[]=$resultCreatedBy[0];
1353 }
1354
1355 $this->aFormSignatures = $finalResult;
1356
1357 /* Get this user permissions */
1358 $rolesManager = new RolesManager();
1359 $this->aUserDPPermissions = $rolesManager->getDPPermissions($this->getUser()->getAttribute('id'), $this->employee_data[0]['Employee_Id'], $this->disciplinary_process[0]['dpc_curr_state'], $this->employee_data[0]['UNIT_ID']);
1360
1361 $this->getUser()->setAttribute('form_permissions', $this->aUserDPPermissions);
1362
1363 /* Set page submenu options and backlink label. I do this, because access to this
1364 * action can be done from Follow ups section and Serch section
1365 */
1366 $sRefererUrl = $request->getReferer();
1367
1368 if ($sRefererUrl != null)
1369 {
1370 $sMethod = substr($sRefererUrl, strpos($sRefererUrl, "/dp/") + 4);
1371 $this->sSubMenuOption = "dp_" . $sMethod;
1372
1373 if ($sMethod != 'search')
1374 {
1375 $this->sBacklinkLabel = substr($sRefererUrl, strpos($sRefererUrl, "/dp/") + 1);
1376 } else
1377 {
1378 $this->sBacklinkLabel = substr($sRefererUrl, strpos($sRefererUrl, "/dp/") + 1); // . "?id=" . $this->disciplinary_process[0]['dpc_usr_empid'];
1379 $this->getUser()->setAttribute("sempid", $this->disciplinary_process[0]['dpc_usr_empid']);
1380 }
1381 } else
1382 {
1383 $this->sSubMenuOption = "dp_followups";
1384 $this->sBacklinkLabel = "dp/followups";
1385 }
1386
1387 /* *********************************************************************************
1388 * GET IR RELATED WITH THIS DP
1389 * ******************************************************************************** */
1390 $dpId = intval($request->getParameter('dp'));
1391
1392 //$irRelatedDp = new IdtDpRelatedIr;
1393 $irRelatedDp = Doctrine_Core::getTable("IdtDpRelatedIr")->findOneByDriDpIdAndDriActive($dpId, 1);
1394 if ($irRelatedDp)
1395 {
1396 $this->irRelatedId = 'IR' . str_pad($irRelatedDp->getDriIrId(), 4, "0", STR_PAD_LEFT);
1397 } else
1398 {
1399 $this->irRelatedId = null;
1400 }
1401
1402 /* * ** display or hide Ir Associated div **** */
1403 if ($this->getUser()->hasCredential(14))
1404 { // permiso para vincular IR con DP
1405 $this->showLink = true;
1406 } else
1407 {
1408 $this->showLink = false;
1409 }
1410 }
1411 }
1412
1413
1414 /**
1415 * Load Comment form
1416 *
1417 * @param sfRequest $request A request object
1418 */
1419 public function executeEditcomments(sfWebRequest $request)
1420 {
1421 /* Get the comments for this dp */
1422 $this->comments = Doctrine_Core::getTable('IdtDisciplinaryProcessComments')
1423 ->createQuery('c')
1424 ->innerJoin('c.IdtUsers u ON u.usr_empid = c.dco_created_by')
1425 ->where('c.dco_dpc_id =? AND c.dco_active =?', array($request->getParameter('dp'), 1)) //Pending add the current state id
1426 ->orderBy('c.dco_creation_date DESC')
1427 ->fetchArray();
1428
1429 /* Get this user permissions */
1430 $this->aUserDPPermissions = $this->getUser()->getAttribute('form_permissions');
1431 }
1432
1433
1434 /**
1435 * Load Follow up information
1436 *
1437 * @param sfRequest $request A request object
1438 */
1439 public function executeEditfollowup(sfWebRequest $request)
1440 {
1441 $this->aFollowUp = array();
1442
1443 if ($request->getParameter('dp') != null)
1444 {
1445 /* Get state history */
1446 $this->aDPStateHistory = Doctrine_Core::getTable('IdtDisciplinaryProcessStateHistory')
1447 ->createQuery('h')
1448 ->innerJoin('h.IdtDisciplinaryProcessStatesCatalog s ON s.dst_id = h.dph_dst_id')
1449 ->innerJoin('h.IdtUsers u ON u.usr_empid = h.dph_created_by')
1450 ->where('h.dph_dpc_id =? AND h.dph_active =?', array($request->getParameter('dp'), 1))
1451 ->orderBy('dph_id ASC')
1452 ->fetchArray();
1453 }
1454
1455 /* Get */
1456 foreach ($this->aDPStateHistory as $hindex => $h)
1457 {
1458 $this->aFollowUp[$hindex]['date'] = $h['dph_creation_date'];
1459 $this->aFollowUp[$hindex]['state'] = $h['IdtDisciplinaryProcessStatesCatalog']['dst_name'];
1460
1461 if (($hindex + 1) > (count($this->aDPStateHistory) - 1))
1462 {
1463 $this->aFollowUp[$hindex]['user'] = '';
1464 } else if ($hindex == 0)
1465 {
1466 $this->aFollowUp[$hindex]['user'] = $h['IdtUsers']['usr_fname'] . " " . $h['IdtUsers']['usr_lname'];
1467 } else
1468 {
1469 $this->aFollowUp[$hindex]['user'] = $this->aDPStateHistory[$hindex + 1]['IdtUsers']['usr_fname'] . " " . $this->aDPStateHistory[$hindex + 1]['IdtUsers']['usr_lname'];
1470 }
1471 }
1472 }
1473
1474
1475 /**
1476 * Load Follow up information
1477 *
1478 * @param sfRequest $request A request object
1479 */
1480 public function executeEditmodificationlog(sfWebRequest $request)
1481 {
1482 if ($request->getParameter('dp') != null)
1483 {
1484 /* Get state history */
1485 $this->aDPModificationLog = Doctrine_Core::getTable('IdtDisciplinaryProcessFormChangesLog')
1486 ->createQuery('h')
1487 ->innerJoin('h.IdtUsers u ON u.usr_empid = h.fcl_created_by')
1488 ->where('h.fcl_dpc_id =? AND h.fcl_active =?', array($request->getParameter('dp'), 1))
1489 ->orderBy('fcl_id ASC')
1490 ->fetchArray();
1491 }
1492 }
1493
1494
1495 /**
1496 * Load Uploaded files
1497 *
1498 * @param sfRequest $request A request object
1499 */
1500 public function executeEdituploads(sfWebRequest $request)
1501 {
1502 $this->aUploadedFiles = array();
1503 $aUserIds = array();
1504 $sWebLocation = sfConfig::get('irdp_uploaded_files_path');
1505
1506 $iDpId = $request->getParameter('dp');
1507 $upload_path = substr(dirname(__FILE__), 0, (strpos(dirname(__FILE__), "apps"))) . '/web/uploads/files/';
1508
1509 foreach (glob($upload_path . $iDpId . "_*") as $filename)
1510 {
1511 $sFullFileName = $filename = substr($filename, strrpos($filename, "/"));
1512 $filename = substr($filename, 0, strrpos($filename, "."));
1513 $aFilenameParts = explode("_", $filename);
1514
1515 $this->aUploadedFiles[] = array(
1516 'path' => $sWebLocation . $sFullFileName,
1517 'user' => $aFilenameParts[1],
1518 'date' => date('Y-m-d', $aFilenameParts[2])
1519 );
1520
1521 $aUserIds[] = $aFilenameParts[1];
1522 }
1523
1524 /* Check if array aUsers has elements then get the names of the people
1525 * who uploaded the files
1526 */
1527 $aUsers = Doctrine_Core::getTable('IdtUsers')
1528 ->createQuery('u')
1529 ->whereIn('u.usr_empid', $aUserIds)
1530 ->fetchArray();
1531
1532 /* Now in aUploadedFiles array replace the Ids for names */
1533 if (count($aUserIds) > 0)
1534 {
1535 foreach ($this->aUploadedFiles as $key => $val)
1536 {
1537 foreach ($aUsers as $u)
1538 {
1539 if ($val['user'] == $u['usr_empid'])
1540 {
1541 $this->aUploadedFiles[$key]['user'] = $u['usr_fname'] . " " . $u['usr_lname'];
1542 break;
1543 }
1544 }
1545 }
1546 }
1547 }
1548
1549
1550 /**
1551 * Update form
1552 */
1553 public function executeUpdatedp(sfWebRequest $request)
1554 {
1555 /* Variables */
1556 $error = false;
1557 $error_msg = '';
1558 $values = array();
1559 $bUpdateDp = false;
1560
1561 $formManager = new formManager();
1562 $field_mapping = $formManager->getFormMap($request->getParameter('form_id'));
1563
1564 if (!$field_mapping['error'])
1565 {
1566 /* Catch the values submitted */
1567 foreach ($field_mapping['data'] as $field)
1568 {
1569 if (in_array($field['type'], array('input', 'select', 'textarea')))
1570 {
1571 if (is_array($request->getParameter($field['name'])))
1572 {
1573 foreach ($request->getParameter($field['name']) as $key => $el)
1574 {
1575 $values[] = array('id' => $field['id'], 'value' => $el, 'corr' => ($key + 1));
1576 }
1577 } else
1578 {
1579 $values[] = array('id' => $field['id'], 'value' => $request->getParameter($field['name']), 'corr' => 1);
1580 }
1581 }
1582 }
1583
1584 /* Disable all the values for this form */
1585 Doctrine_Query::create()
1586 ->update('IdtDisciplinaryProcessData d')
1587 ->set('d.dpd_active', '0')
1588 ->set('d.dpd_updated_by', $this->getUser()->getAttribute('id'))
1589 ->set('d.dpd_updated_date', '"' . date('Y-m-d H:i:m', time()) . '"')
1590 ->WhereIn('d.dpd_dpc_id', $request->getParameter('dp_id'))
1591 ->execute();
1592
1593 foreach ($values as $v)
1594 {
1595 /* Update the values in the */
1596 $current_value = Doctrine_Core::getTable('IdtDisciplinaryProcessData')
1597 ->createQuery('d')
1598 ->where('d.dpd_dpc_id =? AND d.dpd_fld_id =? AND d.dpd_fld_corr =?', array($request->getParameter('dp_id'), $v['id'], $v['corr']))
1599 ->execute();
1600
1601 if (count($current_value) > 0)
1602 {
1603 /* Get the old value for log purposes */
1604 $sOldValue = $current_value[0]['dpd_value'];
1605 $current_value[0]->setDpdValue($v['value']);
1606 $current_value[0]->setDpdUpdatedBy($this->getUser()->getAttribute('id'));
1607 $current_value[0]->setDpdUpdatedDate(date('Y-m-d H:i:s', time()));
1608 $current_value[0]->setDpdActive(1);
1609
1610 try {
1611 $current_value[0]->save();
1612
1613 /* Save in the log file the values that have been changed to keep
1614 * a track */
1615 if ($sOldValue != $v['value'])
1616 {
1617 $oFormChangesLog = new IdtDisciplinaryProcessFormChangesLog();
1618
1619 $oFormChangesLog->setFclDpcId($request->getParameter('dp_id'));
1620 $oFormChangesLog->setFclFldId($v['id']);
1621 $oFormChangesLog->setFclFldPosition($v['corr']);
1622 $oFormChangesLog->setFclOldValue($sOldValue);
1623 $oFormChangesLog->setFclNewValue($v['value']);
1624 $oFormChangesLog->setFclCreatedBy($this->getUser()->getAttribute('id'));
1625 $oFormChangesLog->setFclCreationDate(date('Y-m-d H:i:s', time()));
1626 $oFormChangesLog->setFclActive(1);
1627 $oFormChangesLog->save();
1628 }
1629 } catch (Exception $e) {
1630 $error = true;
1631 $error_msg = __("Sorry. But, your form couldn't be saved.") . $e;
1632 }
1633 } else
1634 {
1635 $dp = new IdtDisciplinaryProcessData();
1636 $dp->setDpdDpcId($request->getParameter('dp_id'));
1637 $dp->setDpdFldId($v['id']);
1638 $dp->setDpdFldCorr($v['corr']);
1639 $dp->setDpdValue($v['value']);
1640 $dp->setDpdCreatedBy($this->getUser()->getAttribute('id'));
1641 $dp->setDpdCreationDate(date('Y-m-d H:i:s', time()));
1642 $dp->setDpdActive(1);
1643
1644
1645 /* Try to store the information */
1646 try {
1647 $dp->save();
1648 } catch (Exception $e) {
1649 $error = true;
1650 $error_msg = __("Sorry. But, your changes couldn't be saved.");
1651 }
1652 }
1653 }
1654
1655
1656 /* * *********** Update dates in disciplinary Process ************** */
1657 //Finally update the inciden and emission date in case any of them
1658 //were set by the user
1659 $sDpDate = '';
1660 $sIncidentDate = '';
1661 $suspendedDate1 = '';
1662 $suspendedDate2 = '';
1663 $suspendedDate3 = '';
1664 $suspendedDate4 = '';
1665 $returningDate = '';
1666 /* Get the emission date */
1667 if ($request->getParameter('dp_date') != null)
1668 {
1669 $bUpdateDp = true;
1670 $sDpDate = date('Y-m-d', strtotime($request->getParameter('dp_date')));
1671 }
1672
1673 /* Get the incident date */
1674 if ($request->getParameter('incident_date') != null)
1675 {
1676 $bUpdateDp = true;
1677 $sIncidentDate = date('Y-m-d', strtotime($request->getParameter('incident_date')));
1678 }
1679 /* Getting suspended dates*/
1680 if ($request->getParameter('susp_date1') != null) {
1681 $tmp_date1 = DateTime::createFromFormat('j/M/Y', $request->getParameter('susp_date1'));
1682 $suspendedDate1 = date('Y-m-d', strtotime($tmp_date1->format('Y-m-d')));
1683 }
1684 if ($request->getParameter('susp_date2') != null) {
1685 $tmp_date2 = DateTime::createFromFormat('j/M/Y', $request->getParameter('susp_date2'));
1686 $suspendedDate2 = date('Y-m-d', strtotime($tmp_date2->format('Y-m-d')));
1687 }
1688 if ($request->getParameter('susp_date3') != null) {
1689 $tmp_date3 = DateTime::createFromFormat('j/M/Y', $request->getParameter('susp_date3'));
1690 $suspendedDate3 = date('Y-m-d', strtotime($tmp_date3->format('Y-m-d')));
1691 }
1692 if ($request->getParameter('susp_date4') != null) {
1693 $tmp_date4 = DateTime::createFromFormat('j/M/Y', $request->getParameter('susp_date4'));
1694 $suspendedDate4 = date('Y-m-d', strtotime($tmp_date4->format('Y-m-d')));
1695 }
1696 /* If any of these dates were set then proceed to update the DP record and the
1697 * History table */
1698 if ($bUpdateDp)
1699 {
1700 $oDisciplinaryProcess = Doctrine_Core::getTable('IdtDisciplinaryProcess')
1701 ->createQuery('p')
1702 ->where('p.dpc_id =?', array($request->getParameter('dp_id')))
1703 ->execute();
1704
1705 $oDisciplinaryProcessReport = Doctrine_Core::getTable('IdtHistoryDisciplinaryProcess')
1706 ->createQuery('h')
1707 ->where('h.hdp_dpc_id =?', array($request->getParameter('dp_id')))
1708 ->execute();
1709
1710 if ($sDpDate != '')
1711 {
1712 $oDisciplinaryProcess[0]->setDpcEmissionDate($sDpDate);
1713 $oDisciplinaryProcessReport[0]->setHdpEmissionDate($sDpDate);
1714 $oDisciplinaryProcessReport[0]->setHdpExpirationDate(date('Y-m-d', strtotime(date('Y-m-d', strtotime($sDpDate)) . " +" . $oDisciplinaryProcessReport[0]->getHdpDmaExpiration() . " month")));
1715 }
1716
1717 if ($sIncidentDate != '')
1718 {
1719 $oDisciplinaryProcess[0]->setDpcIncidentDate($sIncidentDate);
1720 $oDisciplinaryProcessReport[0]->setHdpIncidentDate($sIncidentDate);
1721 }
1722
1723 if ($suspendedDate1 != '')
1724 {
1725 $oDisciplinaryProcess[0]->setDpcSuspendedDate1($suspendedDate1);
1726 }
1727 if ($suspendedDate2 != '')
1728 {
1729 $oDisciplinaryProcess[0]->setDpcSuspendedDate2($suspendedDate2);
1730 }
1731 if ($suspendedDate3 != '')
1732 {
1733 $oDisciplinaryProcess[0]->setDpcSuspendedDate3($suspendedDate3);
1734 }
1735 if ($suspendedDate4 != '')
1736 {
1737 $oDisciplinaryProcess[0]->setDpcSuspendedDate4($suspendedDate4);
1738 }
1739 if ($request->getParameter('returned_date') != null) {
1740 $oDisciplinaryProcess[0]->setDpcReturningDate($request->getParameter('returned_date'));
1741 }
1742 if ($request->getParameter('Paragraph_text0') != null) {
1743 $oDisciplinaryProcess[0]->setDpcLdocComment2($request->getParameter('Paragraph_text0'));
1744 }
1745 $oDisciplinaryProcess[0]->setDpcUpdatedBy($this->getUser()->getAttribute('id'));
1746 $oDisciplinaryProcess[0]->setDpcUpdatedDate(date('Y-m-d H:i:s', time()));
1747 $oDisciplinaryProcess[0]->save();
1748
1749 $oDisciplinaryProcessReport[0]->setHdpUpdatedBy($this->getUser()->getAttribute('id'));
1750 $oDisciplinaryProcessReport[0]->setHdpUpdatedDate(date('Y-m-d H:i:s', time()));
1751 $oDisciplinaryProcessReport[0]->save();
1752 }
1753 } else
1754 {
1755 $error = true;
1756 $error_msg = $field_mapping['error_msg'];
1757 }
1758
1759 if (!$error)
1760 {
1761 $error_msg = __("Your changes were successfully saved");
1762 }
1763
1764 $encoded = json_encode(array('error' => $error, 'error_msg' => $error_msg));
1765 $this->getResponse()->setContent($encoded);
1766 return sfView::NONE;
1767 }
1768
1769
1770 /**
1771 * Update comment list
1772 *
1773 * @param sfRequest $request A request object
1774 */
1775 public function executeSavecomment(sfWebRequest $request)
1776 {
1777 /* Variables */
1778 $error = false;
1779 $error_msg = '';
1780 $aData = array();
1781
1782 $sComment = $request->getParameter('comment');
1783 $iDpid = $request->getParameter('dpid');
1784
1785 /* Only if the dpid and the comment are valids it will try to store the comment */
1786 if ($iDpid != null)
1787 {
1788 if ($sComment != null)
1789 {
1790
1791 /* Get current state id */
1792 $aDisciplinaryProcess = Doctrine_Core::getTable('IdtDisciplinaryProcess')
1793 ->createQuery('p')
1794 ->where('p.dpc_id =?', array($iDpid))
1795 ->fetchArray();
1796
1797 if (count($aDisciplinaryProcess) > 0)
1798 {
1799
1800 /* Try to store the comment */
1801 $oComment = new IdtDisciplinaryProcessComments();
1802 $tCurrentTime = date('Y-m-d H:i:s', time());
1803
1804 $oComment->setDcoDpcId($iDpid);
1805 $oComment->setDcoDstId($aDisciplinaryProcess[0]['dpc_curr_state']);
1806 $oComment->setDcoComment($sComment);
1807 $oComment->setDcoCreatedBy($this->getUser()->getAttribute('id'));
1808 $oComment->setDcoCreationDate($tCurrentTime);
1809 $oComment->setDcoActive(1);
1810
1811 /* If no error is produced after saving the record, then return the data
1812 * that will be shown in the comments box
1813 */
1814 try {
1815 $oComment->save();
1816
1817 /* Get the name of this user */
1818 $oUser = Doctrine_Core::getTable('IdtUsers')
1819 ->createQuery('u')
1820 ->where('u.usr_empid =?', array($this->getUser()->getAttribute('id')))
1821 ->fetchArray();
1822
1823 if (count($oUser) > 0)
1824 {
1825 $systemTime = sfConfig::get('irdp_dateformat_date');
1826 $aData = array(
1827 'name' => $oUser[0]['usr_fname'] . " " . $oUser[0]['usr_lname'],
1828 'comment' => $sComment,
1829 'time' => date($systemTime, strtotime($tCurrentTime)),
1830 'state' => 1
1831 );
1832 } else
1833 {
1834 $error = true;
1835 $error_msg = __("There was a problem trying to recover the message.");
1836 }
1837 } catch (Exception $e) {
1838 $error = true;
1839 $error_msg = __("There was an error trying to save your comment. " . $e);
1840 }
1841 } else
1842 {
1843 $error = true;
1844 $error_msg = __("Couldn't find Hint Process Id " . $iDpid);
1845 }
1846 } else
1847 {
1848 $error = true;
1849 $error_msg = __("Comment not valid.");
1850 }
1851 } else
1852 {
1853 $error = true;
1854 $error_msg = __("Hint Process id " . $iDpid . " not valid.");
1855 }
1856
1857 $encoded = json_encode(array('error' => $error, 'error_msg' => $error_msg, 'data' => $aData));
1858 $this->getResponse()->setContent($encoded);
1859
1860 return(sfView::NONE);
1861 }
1862
1863 /* ************************************************
1864 * guardar fecha de impresion del documento legal
1865 * ************************************************ */
1866
1867
1868 public function executeSavePrintDateLdoc(sfWebRequest $request)
1869 {
1870 $data = Array();
1871 $data['message'] = Array();
1872 date_default_timezone_set('America/Guatemala');
1873 $dpId = $request->getParameter('dp');
1874 if ($dpId > 0)
1875 {
1876 $oDP = new IdtDisciplinaryProcess;
1877 $oDP = Doctrine_Core::getTable("IdtDisciplinaryProcess")->find($dpId);
1878 if ($oDP->getDpcLdocPrinted() == NULL)
1879 {
1880 try {
1881 $oDP->setdpcLdocPrinted(date('Y-m-d H:i:s'));
1882 $oDP->save();
1883 } catch (Exception $exc) {
1884 $data['error'] = $exc->getMessage();
1885 }
1886 } else
1887 {
1888 $data['message'] = 'existe';
1889 }
1890 }
1891
1892 $encoded = json_encode($data);
1893 $this->getResponse()->setContent($encoded);
1894 return(sfView::NONE);
1895 }
1896
1897
1898 /**
1899 * Load print version of this form
1900 *
1901 * @param sfRequest $request A request object
1902 */
1903 public function executePrintpreview(sfWebRequest $request)
1904 {
1905
1906 $this->forward404If($request->getParameter('id') == null, __("Document id cannot be null"));
1907 $this->forward404If($request->getParameter('dp') == null, __("Hint Process id cannot be null"));
1908
1909 //Check if record exists
1910 $this->form = Doctrine_Core::getTable('IdtForm')
1911 ->createQuery('c')
1912 ->where('c.frm_id =?', array($request->getParameter('id')))
1913 ->execute();
1914
1915 $this->forward404If(count($this->form) <= 0, __("Record not found"));
1916
1917 /* Check if the dp exists */
1918 $this->disciplinary_process = Doctrine_Core::getTable('IdtDisciplinaryProcess')
1919 ->createQuery('d')
1920 ->where('d.dpc_id =?', array($request->getParameter('dp')))
1921 ->fetchArray();
1922
1923 $this->forward404If(count($this->form) <= 0, __("Record not found"));
1924
1925 /* Catch form id and dp id */
1926 $this->form_id = $request->getParameter('id');
1927 $this->dp_id = $request->getParameter('dp');
1928
1929 /* Get date format */
1930 $oDateFormater = new DateFormater();
1931 $aDateFormatCatalog = $oDateFormater->getAvailableDateFormats();
1932 $this->sDateFormatJs = $this->form[0]['frm_date_format'];
1933 $this->sDateFormatPhp = $oDateFormater->getPhpDateFormat($this->form[0]['frm_date_format']);
1934
1935 /* Get employee information */
1936 $this->employee_fields_selected = $empData = Doctrine_Core::getTable('IdtFormEmployeeData')
1937 ->createQuery('q')
1938 ->where('q.fed_frm_id =? AND q.fed_active=?', array($request->getParameter('id'), 1))
1939 ->innerJoin('q.IdtFormEmployeeFields f ON f.fef_id = q.fed_fef_id')
1940 ->orderBy('q.fed_fef_id ASC')
1941 ->fetchArray();
1942
1943 /* Total of employee information fields selected */
1944 $this->total_employee_selected_fields = 0;
1945
1946 foreach ($this->employee_fields_selected as $efs)
1947 {
1948 if ($efs['IdtFormEmployeeFields']['fef_category'] == 1)
1949 {
1950 $this->total_employee_selected_fields++;
1951 }
1952 }
1953
1954 /* Get employee values */
1955 $this->employee_data = Doctrine_Query::create()
1956 ->select("u.usr_empid AS Employee_Id, CONCAT(IFNULL(u.usr_fname,''),' ', IFNULL(u.usr_mname,''),' ',IFNULL(u.usr_lname,''),' ',IFNULL(u.usr_sname,'')) AS Employee_Name,
1957 IFNULL(DATE_FORMAT(u.usr_hiredate,'" . sfConfig::get('irdp_dateformat_database') . "'),'N/A') AS Hire_Date, IFNULL(p.pos_name_es,'N/A') AS Position,
1958 IFNULL(CONCAT(u2.usr_fname,' ',u2.usr_lname),'N/A') AS Supervisor, IFNULL(CONCAT(u3.usr_fname,' ',u3.usr_lname),'N/A') AS 2nd_Level_Manager,
1959 IFNULL(DATE_FORMAT(d.dpc_emission_date,'" . sfConfig::get('irdp_dateformat_database') . "'), 'N/A') AS DP_Date, IFNULL(DATE_FORMAT(d.dpc_incident_date,'" . sfConfig::get('irdp_dateformat_database') . "'), 'N/A') AS Incident_Date, IFNULL(s.dms_name, 'N/A') AS Type_of_Sanction, n.uni_name AS Department, s.dms_id, d.dpc_id,
1960 GROUP_CONCAT(i.dpi_dma_id), GROUP_CONCAT(a.dma_art_id) AS Articles, usr_identity_doc_number AS Personal_Identification_Number
1961 ")
1962 ->from('IdtUsers u')
1963 ->where('u.usr_empid =?', array($this->disciplinary_process[0]['dpc_usr_empid']))
1964 ->leftJoin('u.IdtPositions p ON p.pos_id = u.usr_currposition')
1965 ->leftJoin('u.IdtUsers u2 ON u2.usr_empid = u.usr_supervisor')
1966 ->leftJoin('u.IdtUnits n ON n.uni_id = u.usr_currdept')
1967 ->leftJoin('u.IdtUsers u3 ON u3.usr_empid = u2.usr_supervisor')
1968 ->leftJoin('u.IdtDisciplinaryProcess d ON d.dpc_usr_empid = u.usr_empid AND d.dpc_id = ' . $request->getParameter('dp'))
1969 ->leftJoin('d.IdtDisciplinaryMatrixSanctions s ON d.dpc_dms_id = s.dms_id')
1970 ->leftJoin('d.IdtDisciplinaryProcessInfringements i ON i.dpi_dpc_id = d.dpc_id')
1971 ->leftJoin('i.IdtDisciplinaryMatrixArticles a ON a.dma_id = i.dpi_dma_id')
1972 ->fetchArray();
1973
1974 $this->disciplinary_process_information = Doctrine_Query::create()
1975 ->select('p.dpc_id, i.dpi_id, a.dma_id, s.dms_name AS Sanction, c.dmc_name AS Category, GROUP_CONCAT(a.dma_art_id, " - ", a.dma_desc SEPARATOR " ") as Articles, a.dma_expiration AS Expiration,
1976 a.dma_sup_low AS Law_Supporting_Article, p.dpc_suspended_date1, p.dpc_suspended_date1, p.dpc_suspended_date2, p.dpc_suspended_date3, p.dpc_suspended_date4, p.dpc_returning_date')
1977 ->from('IdtDisciplinaryProcess p')
1978 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = p.dpc_dms_id')
1979 ->innerJoin('p.IdtDisciplinaryProcessInfringements i ON i.dpi_dpc_id = p.dpc_id')
1980 ->innerJoin('i.IdtDisciplinaryMatrixArticles a ON a.dma_id = i.dpi_dma_id')
1981 ->innerJoin('a.IdtDisciplinaryMatrixCategories c ON c.dmc_id = a.dma_dmc_id')
1982 ->where('p.dpc_id =?', array($request->getParameter('dp')))
1983 ->groupBy('dpc_id')
1984 ->fetchArray();
1985 /* Get the form */
1986 $formManager = new formManager();
1987 $this->formStructure = $formManager->getPrintVersion($request->getParameter('id'), $request->getParameter('dp'));
1988 $this->preview_form = $this->formStructure['form'];
1989
1990 /* Get the required fields */
1991 $this->required_fields = Doctrine_Core::getTable('IdtFormFields')
1992 ->createQuery('r')
1993 ->innerJoin('r.IdtFormCustomFields ON fcf_id = fld_fcf_id')
1994 ->where('fld_frm_id =? AND fld_required =?', array($request->getParameter('id'), 1))
1995 ->fetchArray();
1996
1997 /* Get signatures */
1998 $sql = " SELECT TBL.wdid, p.pos_name_es AS POSITION, IFNULL(TBL.NAME, '') AS NAME, IFNULL(TBL.DATE, '') AS DATE
1999 FROM idt_form_signatures i
2000 INNER JOIN idt_positions p ON p.pos_id = i.fsi_pos_id
2001 LEFT JOIN (
2002 SELECT u.usr_empid as wdid, CONCAT(u.usr_fname,' ', u.usr_lname) AS NAME,u.usr_currposition AS POSITION, h.dph_creation_date AS DATE
2003 FROM idt_disciplinary_process_state_history h
2004 INNER JOIN idt_users u ON u.usr_empid = h.dph_created_by
2005 WHERE h.dph_dpc_id = " . $this->dp_id . " AND u.usr_currposition IN(SELECT s.fsi_pos_id FROM idt_form_signatures s WHERE s.fsi_frm_id = " . $this->form_id . " AND s.fsi_active = 1)
2006 ) TBL ON TBL.POSITION = i.fsi_pos_id
2007 WHERE i.fsi_frm_id = " . $this->form_id . " AND i.fsi_active = 1
2008 ";
2009 $sql2 = " SELECT
2010 u.usr_empid as wdid,
2011 pos.pos_name_es as POSITION,
2012 CONCAT(u.usr_fname,' ', u.usr_lname) AS NAME,
2013 p.dpc_creation_date AS DATE
2014 FROM idt_disciplinary_process p
2015 RIGHT JOIN idt_users u on u.usr_empid = p.dpc_created_by
2016 RIGHT JOIN idt_positions pos on pos.pos_id = u.usr_currposition
2017 where p.dpc_id = " . $this->dp_id . "
2018 ";
2019
2020 $result = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql)->fetchAll();
2021 $resultCreatedBy = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql2)->fetchAll();
2022
2023 /*
2024 * This part of code verify if the person that created the DP is not exists into the signatures assigned.
2025 * If NOT/False, that will add the signature into the array. Christian Sum 14/12/2016
2026 */
2027 $exists = false;
2028 $finalResult = array();
2029 foreach ($result as $val) {
2030 if ($val['wdid'] == $resultCreatedBy[0]['wdid']){
2031 $exists = true;
2032 }
2033 if($val['wdid']!=""){
2034 $finalResult[] = $val;
2035
2036 }
2037 }
2038 if (!$exists){
2039 $finalResult[]=$resultCreatedBy[0];
2040 }
2041
2042 $this->aFormSignatures = $finalResult;
2043
2044
2045 $this->iMinInputSize = sfConfig::get('irdp_form_font_size');
2046 }
2047
2048
2049 /**
2050 * Load print version of the legal document
2051 *
2052 * @param sfRequest $request A request object
2053 */
2054 public function executePrintlegaldocument(sfWebRequest $request)
2055 {
2056 /* Variables */
2057 $sLegalDocContent = '';
2058 $DPId = intval($request->getParameter('dp'));
2059 $this->bAskAdditionalInformation = false;
2060 $this->sAskAdditionalInfoFields = 'true';
2061 $oView = "";
2062
2063 $aNumberNames = array(
2064 __("zero"),
2065 __("one"),
2066 __("two"),
2067 __("three"),
2068 __("four"),
2069 __("five"),
2070 __("six"),
2071 __("seven"),
2072 __("eight"),
2073 __("nine"),
2074 __("ten"),
2075 __("eleven"),
2076 __("twelve"),
2077 __("thirteen"),
2078 __("fourteen"),
2079 __("fifteen"),
2080 __("sixteen"),
2081 __("seventeen"),
2082 __("eighteen"),
2083 __("nineteen"),
2084 __("twenty"),
2085 __("twenty-one"),
2086 __("twenty-two"),
2087 __("twenty-three"),
2088 __("twenty-four"),
2089 __("twenty-five"),
2090 __("twenty-six"),
2091 __("twenty-seven"),
2092 __("twenty-eight"),
2093 __("twenty-nine"),
2094 __("thirty"),
2095 __("thrity-one"),
2096 __("thrity-two"),
2097 __("thrity-three"),
2098 __("thrity-four"),
2099 __("thrity-five"),
2100 __("thrity-six"),
2101 __("thrity-seven"),
2102 __("thrity-eight"),
2103 __("thrity-nine"),
2104 __("forty"),
2105 __("forty-one"),
2106 __("forty-two"),
2107 __("forty-three"),
2108 __("forty-four"),
2109 __("forty-five"),
2110 __("forty-six"),
2111 __("forty-seven"),
2112 __("forty-eight"),
2113 __("forty-nive"),
2114 __("fifty"),
2115 __("fifty-one"),
2116 __("fifty-two"),
2117 __("fifty-three"),
2118 __("fifty-four"),
2119 __("fifty-five"),
2120 __("fifty-six"),
2121 __("fifty-seven"),
2122 __("fifty-eight"),
2123 __("fifty-nine")
2124 );
2125
2126 $aYears = array(
2127 2012 => __("two thousand twelve"),
2128 2013 => __("two thousand thirteen"),
2129 2014 => __("two thousand fourteen"),
2130 2015 => __("two thousand fifteen"),
2131 2016 => __("two thousand sixteen"),
2132 2017 => __("two thousand seventeen"),
2133 2018 => __("two thousand eightteen"),
2134 2019 => __("two thousand nineteen"),
2135 2020 => __("two thousand twenty"),
2136 2021 => __("two thousand twenty one"),
2137 2022 => __("two thousand twenty two")
2138 );
2139
2140 $aLongMonthName = array(
2141 1 => __("January"),
2142 2 => __("February"),
2143 3 => __("March"),
2144 4 => __("April"),
2145 5 => __("May"),
2146 6 => __("June"),
2147 7 => __("July"),
2148 8 => __("August"),
2149 9 => __("September"),
2150 10 => __("October"),
2151 11 => __("November"),
2152 12 => __("December")
2153 );
2154
2155 date_default_timezone_set('America/Guatemala');
2156 //---- formatos para fechas y tiempo
2157 //$testContent = 'En la ciudad de Guatemala, el día [%Printed Date%] del Mes [%Printed Month%] del año [%Printed Year%], siendo las [%Printed Hour%] horas con [%Printed Minutes%] minutos.';
2158 $dateDay = date('j', time());
2159 $dateMonth = date('n', time());
2160 $dateYear = date('Y', time());
2161 $hour = date("G");
2162 $sMin = date("i"); // viene en formato con 0 a la izquierda los menores que 10
2163 $min = strval($sMin); // convierto a string para usar en array ya que 08 y 09 los toma como octal
2164 //---------------------------------
2165
2166 /* Check that */
2167 $this->forward404If($request->getParameter('id') == null, __("Document id cannot be null"));
2168 $this->forward404If($request->getParameter('dp') == null, __("Hint Process id cannot be null"));
2169
2170 /* Get Legal Document */
2171 // obtener la configuracion del documento legal
2172 if (sfConfig::get('irdp_show_legaldoc_by_process') == 1)
2173 {
2174 // por proceso
2175 $aLegalDocument = Doctrine_Core::getTable('IdtLegalDocument')
2176 ->createQuery('l')
2177 ->leftJoin('l.IdtDisciplinaryProcessProcesses p ON l.ldo_proc_id = p.dpr_id')
2178 ->leftJoin('l.IdtForm f ON f.frm_proc_id = p.dpr_id')
2179 ->where('f.frm_id =? AND l.ldo_active = 1 AND f.frm_active = 1', array($request->getParameter('id')))
2180 ->fetchArray();
2181 } else if (sfConfig::get('irdp_show_legaldoc_by_process') == 2)
2182 {
2183 // por ambos formulario o proceso
2184 $aLegalDocument = Doctrine_Core::getTable('IdtLegalDocument')
2185 ->createQuery('l')
2186 ->leftJoin('l.IdtForm f ON l.ldo_frm_id = f.frm_id OR f.frm_proc_id = l.ldo_proc_id')
2187 ->Where('f.frm_active = 1 AND l.ldo_active = 1 AND f.frm_id = ?', array($request->getParameter('id')))
2188 ->fetchArray();
2189 } else
2190 {
2191 // por formulario comportamiento defecto
2192 $aLegalDocument = Doctrine_Core::getTable('IdtLegalDocument')
2193 ->createQuery('l')
2194 ->where('l.ldo_frm_id =? AND l.ldo_active = 1', array($request->getParameter('id')))
2195 ->fetchArray();
2196 }
2197
2198 /* Get form details, specially because we need the date format */
2199 $this->form = Doctrine_Core::getTable('IdtForm')
2200 ->createQuery('f')
2201 ->where('f.frm_id =?', $request->getParameter('id'))
2202 ->fetchArray();
2203
2204 if (count($aLegalDocument > 0) && ($DPId > 0))
2205 {
2206 /* Get the data of the current user */
2207
2208 // obtenemos la conexion activa
2209 $con = Doctrine_Manager::getInstance()->getCurrentConnection();
2210
2211 // obtenemos los countries seleccionados en CR
2212 $sQuery = "SELECT usr.usr_empid AS VHUR, CONCAT(usr.usr_fname, ' ', usr.usr_mname, ' ', usr.usr_lname,' ', usr.usr_sname) AS NAME, p.pos_name_es AS EMP_NAME_POS,";
2213 $sQuery.=" IFNULL(usr.usr_identity_doc_number, '') AS PIN, usr.usr_hiredate AS HIREDATE,";
2214 $sQuery.=" p.pos_name_es AS POSITION, un.uni_name AS UNIT, dp.dpc_incident_date AS INCIDENT_DATE,";
2215 $sQuery.=" dp.dpc_creation_date DP_DATE, dms.dms_name AS SANCTION, CONCAT(sup.usr_fname, ' ', sup.usr_mname, ' ', sup.usr_lname,' ', sup.usr_sname) AS SUPERVISOR, ps.pos_name_es AS SUP_POS_NAME,";
2216 $sQuery.=" CONCAT(mgr.usr_fname, ' ', mgr.usr_mname, ' ', mgr.usr_lname,' ', mgr.usr_sname) AS 2LEVELSUP, dp.dpc_ldoc_comment1 AS COMMENT_1, dp.dpc_ldoc_comment2 AS COMMENT_2,";
2217 $sQuery.=" sup.usr_identity_doc_number AS SUP_DPI, mgr.usr_identity_doc_number AS 2ND_DPI, dma.dma_desc AS ARTICLES,";
2218 $sQuery.=" dma2.dma_sup_low AS LAW_SUPPORT, dma.dma_expiration AS EXPIRATION, dmc.dmc_name AS CATEGORY,";
2219 $sQuery.=" dp.dpc_additional_witness AS witnessName, dp.dpc_add_witness_document AS witnessDoc,";
2220 $sQuery.=" dp.dpc_ldoc_created, dp.dpc_ldoc_printed, dp.dpc_sup_comment, s.sit_address, s.sit_name, dp.dpc_suspended_date1 AS SUSP_DATE1, dp.dpc_suspended_date2 AS SUSP_DATE2, dp.dpc_suspended_date3 AS SUSP_DATE3, dp.dpc_suspended_date4 AS SUSP_DATE4, dp.dpc_returning_date AS RETURNING_DATE";
2221 $sQuery.=" FROM idt_disciplinary_process dp ";
2222 $sQuery.=" INNER JOIN idt_users usr ON usr.usr_empid = dp.dpc_usr_empid ";
2223 $sQuery.=" LEFT JOIN idt_units un ON dp.dpc_uni_id = un.uni_id ";
2224 $sQuery.=" LEFT JOIN idt_positions p ON p.pos_id = dp.dpc_pos_id ";
2225 $sQuery.=" LEFT JOIN idt_users sup ON sup.usr_empid = dp.dpc_sup_id ";
2226 $sQuery.=" LEFT JOIN idt_positions ps ON ps.pos_id = sup.usr_currposition ";
2227 $sQuery.=" LEFT JOIN idt_users mgr ON mgr.usr_empid = sup.usr_supervisor ";
2228 $sQuery.=" LEFT JOIN idt_disciplinary_matrix_sanctions dms ON dms.dms_id = dp.dpc_dms_id ";
2229 $sQuery.=" LEFT JOIN idt_disciplinary_process_infringements i ON i.dpi_id = dp.dpc_id ";
2230 $sQuery.=" LEFT JOIN idt_disciplinary_matrix_articles dma ON dma.dma_id = i.dpi_dma_id ";
2231 $sQuery.=" LEFT JOIN idt_disciplinary_process_infringements dpi ON dpi.dpi_dpc_id = dp.dpc_id ";
2232 $sQuery.=" LEFT JOIN idt_disciplinary_matrix_articles dma2 ON dma2.dma_id = dpi.dpi_dma_id ";
2233 $sQuery.=" LEFT JOIN idt_disciplinary_matrix_categories dmc ON dmc.dmc_id = dma.dma_dmc_id ";
2234 $sQuery.=" LEFT JOIN idt_sites s ON s.sit_id = dp.dpc_site_id ";
2235 $sQuery.="WHERE dpc_id = {$DPId} LIMIT 1;";
2236
2237 //$con = $con->prepare($sQuery);
2238 $oEmployee = $con->execute($sQuery);
2239 foreach ($oEmployee as $aEmployee)
2240 {
2241
2242 }
2243
2244 /* Check user's dpi in case that value will be required in the legal document */
2245 $aCuser = Doctrine_Core::getTable('IdtUsers')
2246 ->createQuery('u')
2247 ->where('u.usr_empid =?', array($this->getUser()->getAttribute('id')))
2248 ->fetchArray();
2249 $aCuserPosition = Doctrine_Core::getTable('IdtPositions')
2250 ->createQuery('p')
2251 ->Where('p.pos_id =?', array($aCuser[0]['usr_currposition']))
2252 ->fetchArray();
2253 if (count($aEmployee) > 0)
2254 {
2255 $oDateFormat = new DateFormater();
2256 $aDateFormats = $oDateFormat->getAvailableDateFormats();
2257 $sDateFormat = $this->form[0]['frm_date_format'];
2258 $sDateFormat = $oDateFormat->getPhpDateFormat($sDateFormat);
2259
2260 $sLegalDocContent = $aLegalDocument[0]['ldo_content'];
2261
2262 /* This section is based on a request made by GT HR. If the legal document includes the
2263 * Personal Identification Number, but that value has not being set yet, the sistem will
2264 * request the current user to add that number manually
2265 */
2266
2267 /* Check that this property has been enabled */
2268 $aEmployeeFields = Doctrine_Core::getTable('IdtFormEmployeeFields')
2269 ->createQuery('f')
2270 ->where('f.fef_name =? AND f.fef_active =?', array('Personal Identification Number', 1))
2271 ->fetchArray();
2272
2273
2274 if (count($aEmployeeFields) > 0 && strpos($sLegalDocContent, '[%Personal Identification Number%]') !== FALSE && $aEmployee['PIN'] == '')
2275 {
2276 $this->bAskAdditionalInformation = true;
2277 $this->sAskAdditionalInfoFields = $this->sAskAdditionalInfoFields . '|fpin';
2278 }
2279
2280 if (count($aEmployeeFields) > 0 && strpos($sLegalDocContent, '[%Creator Personal Identification Number%]') !== FALSE && $aCuser[0]['usr_identity_doc_number'] == '')
2281 {
2282 $this->bAskAdditionalInformation = true;
2283 $this->sAskAdditionalInfoFields = $this->sAskAdditionalInfoFields . '|fupin';
2284 }
2285 }
2286 }
2287 $sLegalDocContent = str_replace('[%Printed Hour%]', $aNumberNames[$hour], $sLegalDocContent);
2288 $sLegalDocContent = str_replace('[%Printed Minutes%]', $aNumberNames[intval($min)], $sLegalDocContent);
2289 if ($this->bAskAdditionalInformation)
2290 {
2291 echo $this->sAskAdditionalInfoFields;
2292 } else if ($DPId > 0)
2293 {
2294 // completamos la conversion de los datos del formato
2295 $userFullName = $aCuser[0]['usr_fname'] . ' ' . $aCuser[0]['usr_mname'] . ' ' . $aCuser[0]['usr_lname'] . ' ' . $aCuser[0]['usr_sname'];
2296
2297 $sLegalDocContent = str_replace('[%Creator Name%]', $userFullName, $sLegalDocContent);
2298 $sLegalDocContent = str_replace('[%Creator Position%]', $aCuserPosition[0]['pos_name_es'], $sLegalDocContent);
2299
2300 $sLegalDocContent = str_replace('[%Employee Id%]', $aEmployee['VHUR'], $sLegalDocContent);
2301 $sLegalDocContent = str_replace('[%Hire Date%]', date($sDateFormat, strtotime($aEmployee['HIREDATE'])), $sLegalDocContent);
2302 $sLegalDocContent = str_replace('[%Position%]', $aEmployee['POSITION'], $sLegalDocContent);
2303 $sLegalDocContent = str_replace('[%Supervisor%]', $aEmployee['SUPERVISOR'], $sLegalDocContent);
2304 $sLegalDocContent = str_replace('[%Supervisor Pos Name%]', $aEmployee['SUP_POS_NAME'], $sLegalDocContent);
2305 $sLegalDocContent = str_replace('[%Employee Name%]', $aEmployee['NAME'], $sLegalDocContent);
2306 $sLegalDocContent = str_replace('[%Employee Position%]', $aEmployee['EMP_NAME_POS'], $sLegalDocContent);
2307 $sLegalDocContent = str_replace('[%Department%]', $aEmployee['UNIT'], $sLegalDocContent);
2308 $sLegalDocContent = str_replace('[%2nd Level Manager%]', $aEmployee['2LEVELSUP'], $sLegalDocContent);
2309 $sLegalDocContent = str_replace('[%DP Date%]', date($sDateFormat, strtotime($aEmployee['DP_DATE'])), $sLegalDocContent);
2310 $sLegalDocContent = str_replace('[%Incident Date%]', date($sDateFormat, strtotime($aEmployee['INCIDENT_DATE'])), $sLegalDocContent);
2311 $sLegalDocContent = str_replace('[%Sanction%]', $aEmployee['SANCTION'], $sLegalDocContent);
2312 $sLegalDocContent = str_replace('[%Personal Identification Number%]', $aEmployee['PIN'], $sLegalDocContent);
2313 $sLegalDocContent = str_replace('[%Creator Personal Identification Number%]', $aCuser[0]['usr_identity_doc_number'], $sLegalDocContent);
2314
2315 $sLegalDocContent = str_replace('[%Employee Comment%]', $aEmployee['COMMENT_1'], $sLegalDocContent);
2316 $sLegalDocContent = str_replace('[%Supervisor Comments%]', $aEmployee['dpc_sup_comment'], $sLegalDocContent);
2317 $sLegalDocContent = str_replace('[%Other Comment%]', $aEmployee['COMMENT_2'], $sLegalDocContent);
2318 $sLegalDocContent = str_replace('[%Additional Witness%]', $aEmployee['witnessName'], $sLegalDocContent);
2319 $sLegalDocContent = str_replace('[%Additional Witness Document%]', $aEmployee['witnessDoc'], $sLegalDocContent);
2320
2321 $sLegalDocContent = str_replace('[%Articles%]', $aEmployee['ARTICLES'], $sLegalDocContent);
2322 $sLegalDocContent = str_replace('[%Law Supporting Article%]', $aEmployee['LAW_SUPPORT'], $sLegalDocContent);
2323 $sLegalDocContent = str_replace('[%Expiration%]', $aEmployee['EXPIRATION'], $sLegalDocContent);
2324 $sLegalDocContent = str_replace('[%Category%]', $aEmployee['CATEGORY'], $sLegalDocContent);
2325
2326 $sLegalDocContent = str_replace('[%Supervisor Document%]', $aEmployee['SUP_DPI'], $sLegalDocContent);
2327 $sLegalDocContent = str_replace('[%2nd Level Manager Document%]', $aEmployee['2ND_DPI'], $sLegalDocContent);
2328 $sLegalDocContent = str_replace('[%Site Address%]', $aEmployee['sit_address'], $sLegalDocContent);
2329 $newSuspDateLegDoc1 = "";
2330 $newSuspDateLegDoc2 = "";
2331 $newSuspDateLegDoc3 = "";
2332 $newSuspDateLegDoc4 = "";
2333 if ($aEmployee['SUSP_DATE1'] != "") {
2334 $iSuspDateLegalDoc1 = explode("-",$aEmployee['SUSP_DATE1']);
2335 $newSuspDateLegDoc1 = $aNumberNames[ltrim($iSuspDateLegalDoc1[2], "0")] . " de " . $aLongMonthName[intval(ltrim($iSuspDateLegalDoc1[1], '0'))] . " de " . $aYears[$iSuspDateLegalDoc1[0]];
2336 }
2337 if ($aEmployee['SUSP_DATE2'] != "") {
2338 $iSuspDateLegalDoc2 = explode("-",$aEmployee['SUSP_DATE2']);
2339 $newSuspDateLegDoc2 = $aNumberNames[ltrim($iSuspDateLegalDoc2[2], "0")] . " de " . $aLongMonthName[intval(ltrim($iSuspDateLegalDoc2[1], '0'))] . " de " . $aYears[$iSuspDateLegalDoc2[0]];
2340 }
2341 if ($aEmployee['SUSP_DATE3'] != "") {
2342 $iSuspDateLegalDoc3 = explode("-",$aEmployee['SUSP_DATE3']);
2343 $newSuspDateLegDoc3 = $aNumberNames[ltrim($iSuspDateLegalDoc3[2], "0")] . " de " . $aLongMonthName[intval(ltrim($iSuspDateLegalDoc3[1], '0'))] . " de " . $aYears[$iSuspDateLegalDoc3[0]];
2344 }
2345 if ($aEmployee['SUSP_DATE4'] != "") {
2346 $iSuspDateLegalDoc4 = explode("-",$aEmployee['SUSP_DATE4']);
2347 $newSuspDateLegDoc4 = $aNumberNames[ltrim($iSuspDateLegalDoc4[2], "0")] . " de " . $aLongMonthName[intval(ltrim($iSuspDateLegalDoc4[1], '0'))] . " de " . $aYears[$iSuspDateLegalDoc4[0]];
2348 }
2349 $sLegalDocContent = str_replace('[%Suspended Date1%]', $newSuspDateLegDoc1, $sLegalDocContent);
2350 $sLegalDocContent = str_replace('[%Suspended Date2%]', $newSuspDateLegDoc2, $sLegalDocContent);
2351 $sLegalDocContent = str_replace('[%Suspended Date3%]', $newSuspDateLegDoc3, $sLegalDocContent);
2352 $sLegalDocContent = str_replace('[%Suspended Date4%]', $newSuspDateLegDoc4, $sLegalDocContent);
2353 $sLegalDocContent = str_replace('[%Returning Dates%]', $aEmployee['RETURNING_DATE'], $sLegalDocContent);
2354 // preparar fecha de creacion del documento legal
2355 if ($aEmployee['dpc_ldoc_created'] != NULL)
2356 {
2357 //convertimos el formato de la base de datos cuando ya existe el valor
2358 $createdDate = date('Y-m-d H:i:s', strtotime($aEmployee['dpc_ldoc_created']));
2359 $createdDay = date('j', strtotime($aEmployee['dpc_ldoc_created']));
2360 $createdMonth = date('n', strtotime($aEmployee['dpc_ldoc_created']));
2361 $createdYear = date('Y', strtotime($aEmployee['dpc_ldoc_created']));
2362
2363 $createdHour = date("G", strtotime($aEmployee['dpc_ldoc_created']));
2364 $sCreatedMin = date("i", strtotime($aEmployee['dpc_ldoc_created'])); // viene en formato con 0 a la izquierda los menores que 10
2365 $createdMin = strval($sCreatedMin); // convierto a string para usar en array ya que 08 y 09 los toma como octal
2366 //get date time legal doc created
2367 $sLegalDocContent = str_replace('[%Created Date%]', $aNumberNames[$createdDay], $sLegalDocContent);
2368 $sLegalDocContent = str_replace('[%Created Month%]', $aLongMonthName[$createdMonth], $sLegalDocContent);
2369 $sLegalDocContent = str_replace('[%Created Year%]', $aYears[$createdYear], $sLegalDocContent);
2370
2371 $sLegalDocContent = str_replace('[%Created Hour%]', $aNumberNames[$hour], $sLegalDocContent);
2372 $sLegalDocContent = str_replace('[%Created Minutes%]', $aNumberNames[intval($min)], $sLegalDocContent);
2373 } else
2374 {
2375 // si no existe el registro mostramos fecha y hora actual
2376 /* Set actual date time to string */
2377 $sLegalDocContent = str_replace('[%Created Date%]', $dateDay, $sLegalDocContent);
2378 $sLegalDocContent = str_replace('[%Created Month%]', $dateMonth, $sLegalDocContent);
2379 $sLegalDocContent = str_replace('[%Created Year%]', $dateYear, $sLegalDocContent);
2380
2381 $sLegalDocContent = str_replace('[%Created Hour%]', $aNumberNames[$hour], $sLegalDocContent);
2382 $sLegalDocContent = str_replace('[%Created Minutes%]', $aNumberNames[intval($min)], $sLegalDocContent);
2383
2384 //Guardar en la base de datos la fecha y hora
2385 $oDPInfo = new IdtDisciplinaryProcess;
2386 try {
2387 $oDPInfo = Doctrine_Core::getTable('IdtDisciplinaryProcess')->findOneByDpcId($DPId);
2388 $oDPInfo->setDpcLdocCreated(date('Y-m-d H:i:s', time()));
2389 $oDPInfo->save();
2390 } catch (Exception $ex) {
2391 echo $ex->getMessage();
2392 }
2393 }
2394
2395 // preparar fecha de impresion del documento legal
2396 if ($aEmployee['dpc_ldoc_printed'] != NULL)
2397 {
2398 $printDate = date('Y-m-d H:i:s', strtotime($aEmployee['dpc_ldoc_printed']));
2399 $printDay = date('j', strtotime($aEmployee['dpc_ldoc_printed']));
2400 $printMonth = date('n', strtotime($aEmployee['dpc_ldoc_printed']));
2401 $printdYear = date('Y', strtotime($aEmployee['dpc_ldoc_printed']));
2402
2403 //get date time legal doc created
2404 $sLegalDocContent = str_replace('[%Printed Date%]', $aNumberNames[$printDay], $sLegalDocContent);
2405 $sLegalDocContent = str_replace('[%Printed Month%]', $aLongMonthName[$printMonth], $sLegalDocContent);
2406 $sLegalDocContent = str_replace('[%Printed Year%]', $aYears[$printdYear], $sLegalDocContent);
2407 $sLegalDocContent = str_replace('[%Printed Hour%]', $aNumberNames[$hour], $sLegalDocContent);
2408 $sLegalDocContent = str_replace('[%Printed Minutes%]', $aNumberNames[intval($min)], $sLegalDocContent);
2409 }
2410
2411 /* Get signatures for this document */
2412 $aLegalDocumentSignatures = Doctrine_Core::getTable('IdtLegalDocumentSignatures')
2413 ->createQuery('s')
2414 ->where('lds_ldo_id =? AND lds_active =?', array($aLegalDocument[0]['ldo_id'], 1))
2415 ->fetchArray();
2416
2417 $oView = $this->getPartial("printlegaldocument", array('aLegalDocumentSignatures' => $aLegalDocumentSignatures,
2418 'sLegalDocumentContent' => $sLegalDocContent,
2419 'form' => $this->form,
2420 'aLegalDocument' => $aLegalDocument,
2421 ));
2422
2423 $this->getResponse()->setContent($oView);
2424 }
2425
2426 return(sfView::NONE);
2427 }
2428
2429 /*
2430 * Update de Personal Identification Number
2431 *
2432 * @param int $dp Current disciplinary Process
2433 * @param int $pin User's Personal Identfication Number
2434 *
2435 */
2436
2437
2438 public function executeUpdatepinnumber(sfWebRequest $request)
2439 {
2440 $bError = false;
2441 $sErrorMsg = "";
2442 $sEpin = '';
2443 $sUpin = '';
2444 $sComment1 = '';
2445 $sComment2 = '';
2446 $sCommentsup = '';
2447 $witnessName = null;
2448 $witnessDoc = null;
2449 $locationSelected = null;
2450
2451 //@save
2452 if ($request->getParameter('dp') != null)
2453 {
2454 if ($request->getParameter('pin') != null)
2455 {
2456 $sEpin = $request->getParameter('pin');
2457 }
2458
2459 if ($request->getParameter('upin') != null)
2460 {
2461 $sUpin = $request->getParameter('upin');
2462 }
2463
2464 if ($request->getParameter('locationSelected') != null)
2465 {
2466 $locationSelected = intval($request->getParameter('locationSelected'));
2467 }
2468
2469 $sComment1 = $request->getParameter('comment1') != '' ? $request->getParameter('comment1') : NULL;
2470 $sComment2 = $request->getParameter('comment2') != '' ? $request->getParameter('comment2') : NULL;
2471 $sCommentsup = $request->getParameter('commentsup') != '' ? $request->getParameter('commentsup') : NULL;
2472 $witnessName = $request->getParameter('witnessName') != '' ? $request->getParameter('witnessName') : NULL;
2473 $witnessDoc = $request->getParameter('witnessDoc') != '' ? $request->getParameter('witnessDoc') : NULL;
2474
2475 /* Update Employee pin */
2476 $aDpInfo = Doctrine_Core::getTable('IdtDisciplinaryProcess')
2477 ->createQuery('d')
2478 ->where('d.dpc_id =?', array($request->getParameter('dp')))
2479 ->execute();
2480
2481 if (count($aDpInfo) > 0)
2482 {
2483 if ($request->getParameter('pin') != '')
2484 {
2485 $oUser = Doctrine_Core::getTable('IdtUsers')
2486 ->createQuery('u')
2487 ->where('u.usr_empid =?', array($aDpInfo[0]->getDpcUsrEmpid()))
2488 ->execute();
2489
2490 $oUser[0]->setUsrIdentityDocNumber($sEpin); // $request->getParameter('pin');
2491 $oUser[0]->save();
2492 }
2493
2494
2495 /* Update comments */
2496 $aDpInfo[0]->setDpcLdocComment1($sComment1);
2497 $aDpInfo[0]->setDpcLdocComment2($sComment2);
2498 $aDpInfo[0]->setDpcSupComment($sCommentsup);
2499 $aDpInfo[0]->setDpcAdditionalWitness($witnessName);
2500 $aDpInfo[0]->setDpcAddWitnessDocument($witnessDoc);
2501 if ($locationSelected > 0)
2502 {
2503 $aDpInfo[0]->setDpcSiteId($locationSelected);
2504 }
2505 try {
2506 $aDpInfo[0]->save();
2507 } catch (Exception $exc) {
2508 echo $exc->getMessage();
2509 }
2510 }
2511
2512
2513 /* Update User dpi */
2514 if ($sUpin != '')
2515 {
2516 $oThisuser = Doctrine_Core::getTable('IdtUsers')
2517 ->createQuery('u')
2518 ->where('u.usr_empid =?', array($this->getUser()->getAttribute('id')))
2519 ->execute();
2520
2521 $oThisuser[0]->setUsrIdentityDocNumber($sUpin);
2522 $oThisuser[0]->save();
2523 }
2524 }
2525
2526 $encode = json_encode(array("error" => $bError, "error_msg" => $sErrorMsg));
2527 $this->getResponse()->setContent($encode);
2528
2529 return(sfView::NONE);
2530 }
2531
2532 /*
2533 * Update dp current status
2534 * Update the current status on both the historical table and the dp information
2535 *
2536 * @param int $dp Current disciplinary process id
2537 * @param int $form_id Form id
2538 * @param int $transition_type Trasition type - 1 Approve, 0 Deny
2539 * @return array $error Return if there was an error during the current operation and
2540 * an informative message
2541 *
2542 */
2543
2544
2545 public function executeUpdatedpstatus(sfWebRequest $request)
2546 {
2547 /* Variables */
2548 $bError = false;
2549 $sErrorMsg = '';
2550 $dp = '';
2551 $iOldState = 0;
2552
2553 if ($request->getParameter('dp') != null && $request->getParameter('transition_type') != null && $request->getParameter('form_id'))
2554 {
2555 /* First get the current state, and get the next state based on the type of
2556 * decision approve|deny
2557 */
2558 $oDisciplinaryProcess = Doctrine_Core::getTable('IdtDisciplinaryProcess')
2559 ->createQuery('p')
2560 ->where('dpc_id =?', array($request->getParameter('dp')))
2561 ->execute();
2562
2563 $oDisciplinaryProcessHistory = Doctrine_Core::getTable('IdtHistoryDisciplinaryProcess')
2564 ->createQuery('h')
2565 ->where('hdp_dpc_id =?', array($request->getParameter('dp')))
2566 ->execute();
2567
2568 if (count($oDisciplinaryProcess) > 0)
2569 {
2570 /* Get Process id. Because a form is associated with a process we get
2571 * the information of the form in order to get the id of the process
2572 */
2573 $aForm = Doctrine_Core::getTable('IdtForm')
2574 ->createQuery('f')
2575 ->where('f.frm_id =? AND f.frm_active =?', array($request->getParameter('form_id'), 1))
2576 ->fetchArray();
2577
2578 if (count($aForm) > 0)
2579 {
2580 /* Get the new state and update the dp history */
2581 $aState = Doctrine_Core::getTable('IdtDisciplinaryProcessTransitions')
2582 ->createQuery('t')
2583 ->innerJoin('t.IdtDisciplinaryProcessStatesCatalog s ON s.dst_id = t.dpt_new_sta')
2584 ->where('t.dpt_dpr_id =? AND t.dpt_old_sta =? AND dpt_active =? AND dpt_tran_type =?', array($aForm[0]['frm_proc_id'], $oDisciplinaryProcess[0]->getDpcCurrState(), 1, $request->getParameter('transition_type')))
2585 ->fetchArray();
2586
2587 if (count($aState) > 0)
2588 {
2589 /* update the "current state" field in the dp information */
2590 $iOldState = $oDisciplinaryProcess[0]->getDpcCurrState();
2591 $oDisciplinaryProcess[0]->setDpcCurrState($aState[0]['dpt_new_sta']);
2592
2593 /* Check if this is the process last state and in that case set the field dpc_dgs_status equal 2 (Completed) */
2594 if ($aState[0]['IdtDisciplinaryProcessStatesCatalog']['dst_sta_cat'] == 3)
2595 {
2596 $oDisciplinaryProcess[0]->setDpcDgsStatus(2);
2597 $oDisciplinaryProcessHistory[0]->setHdpDgsStatus(2);
2598 }
2599
2600 try {
2601 $oDisciplinaryProcess[0]->save();
2602 //$oDisciplinaryProcessHistory[0]->save();
2603
2604 /* Add the new state in history table */
2605 $sComment = '';
2606
2607 if ($request->getParameter('comment') != null)
2608 {
2609 $sComment = $request->getParameter('comment');
2610 }
2611
2612 $oNewStatus = new IdtDisciplinaryProcessStateHistory();
2613 $oNewStatus->setDphDpcId($request->getParameter('dp'));
2614 $oNewStatus->setDphDstId($aState[0]['dpt_new_sta']);
2615 $oNewStatus->setDphComments($sComment);
2616 $oNewStatus->setDphCreatedBy($this->getUser()->getAttribute('id'));
2617 $oNewStatus->setDphCreationDate(date('Y-m-d H:i:s', time()));
2618 $oNewStatus->setDphActive(1);
2619 $oNewStatus->save();
2620
2621 /* Send an email notification to alert users about the change
2622 * in the status of this process
2623 */
2624 $aTransition = array(
2625 'process' => $aForm[0]['frm_proc_id'],
2626 'old_state' => $iOldState,
2627 'new_state' => $aState[0]['dpt_new_sta'],
2628 'comment' => $sComment,
2629 'resolution' => $request->getParameter('transition_type'),
2630 'dp_id' => $request->getParameter('dp')
2631 );
2632
2633 /* Check if notifications have been enabled, and try to send email notifications */
2634 if (sfConfig::get('irdp_notification_enabled') == 1)
2635 {
2636 /* Try to send notifications */
2637 $this->logMessage("Trying to send notification...");
2638 $this->logMessage("DP (referer -> dp/updatedpstatus): " . $request->getParameter('dp') . ". TRANSITION: " . $aTransition . ". USER: " . $this->getUser()->getAttribute('id'));
2639 $oNotificationsManager = new MailNotification();
2640
2641 $result = $oNotificationsManager->sendDPNotification($request->getParameter('dp'), $aTransition, $this->getUser());
2642
2643 /* Finally, set the message to inform the view that the page must be reload
2644 * in order to show the new state and update the button container based on
2645 * the permissions assigned to the new state
2646 */
2647 if ($result['error'] == false)
2648 {
2649 $this->getUser()->setFlash('success', __('Hint Process status has been updated.'));
2650 } else
2651 {
2652 $bError = true;
2653 $sErrorMsg = __("Hint Process status has been updated. But, notifications could not be sent.");
2654 $this->getUser()->setFlash('success', $sErrorMsg);
2655 }
2656 } else
2657 {
2658 $this->getUser()->setFlash('success', __('Hint Process status has been updated.'));
2659 }
2660 } catch (Exception $e) {
2661 $bError = true;
2662 $sErrorMsg = __("We're Sorry. But the current state of the process couldn't be updated.");
2663 }
2664 } else
2665 {
2666 $bError = true;
2667 $sErrorMsg = __("New status couldn't be defined.");
2668 }
2669 } else
2670 {
2671 $bError = true;
2672 $sErrorMsg = __("Form id - " . $request->getParameter('form_id') . "doesn't exist.");
2673 }
2674 } else
2675 {
2676 $bError = true;
2677 $sErrorMsg = __("Hint Process id - " . $request->getParameter('dp') . "doesn't exist.");
2678 }
2679 } else
2680 {
2681 $bError = true;
2682
2683 if ($request->getParameter('dp') == null)
2684 {
2685 $sErrorMsg = __("Hint Process id is not valid: " . $request->getParameter('dp'));
2686 } else if ($request->getParameter('form_id') == null)
2687 {
2688 $sErrorMsg = __("Form id is not valid: " . $request->getParameter('form_id'));
2689 } else
2690 {
2691 $sErrorMsg = __("Transition Type has not been declared.");
2692 }
2693 }
2694
2695 $encoded = json_encode(array('bError' => $bError, 'sErrorMsg' => $sErrorMsg));
2696 $this->getResponse()->setContent($encoded);
2697
2698 return(sfView::NONE);
2699 }
2700
2701 /*
2702 * Cancel disciplinary process
2703 *
2704 * This function will cancel an open disciplinary process
2705 *
2706 */
2707
2708
2709 public function executeCanceldp(sfWebRequest $request)
2710 {
2711 /* Set the value of a disciplinary process dpc_dgs_status to 3 */
2712 $bError = false;
2713 $sErrorMsg = '';
2714
2715 if ($request->getParameter('dp') != null)
2716 {
2717 $oDisciplinaryProcess = Doctrine_Core::getTable('IdtDisciplinaryProcess')
2718 ->createQuery('d')
2719 ->where('dpc_id =?', array($request->getParameter('dp')))
2720 ->execute();
2721
2722 if (count($oDisciplinaryProcess) > 0)
2723 {
2724 /* Add the new state in history table */
2725 $sComment = '';
2726
2727 if ($request->getParameter('comment') != null)
2728 {
2729 $sComment = $request->getParameter('comment');
2730 }
2731
2732 $oDisciplinaryProcess[0]->setDpcDgsStatus(3);
2733 $oDisciplinaryProcess[0]->setDpcComment($sComment);
2734
2735 try {
2736 $oDisciplinaryProcess->save();
2737
2738 /* Update historical record */
2739 $oDisciplinaryProcessHistory = Doctrine_Core::getTable('IdtHistoryDisciplinaryProcess')
2740 ->createQuery('h')
2741 ->where('h.hdp_dpc_id =?', array($request->getParameter('dp')))
2742 ->execute();
2743
2744 $oDisciplinaryProcessHistory[0]->setHdpDgsStatus(3);
2745 $oDisciplinaryProcessHistory[0]->save();
2746
2747 $this->getUser()->setFlash('success', __('Hint Process has been canceled.'));
2748 } catch (Exception $e) {
2749 $bError = true;
2750 $sErrorMsg = __("Hint Process couldn't be updated.");
2751 }
2752 } else
2753 {
2754 $bError = true;
2755 $sErrorMsg = __("Hint Process id is not valid: " . $request->getParameter('dp'));
2756 }
2757 } else
2758 {
2759 $bError = true;
2760 $sErrorMsg = __("Hint Process id is not valid: " . $request->getParameter('dp'));
2761 }
2762
2763 $encoded = json_encode(array('bError' => $bError, 'sErrorMsg' => $sErrorMsg));
2764 $this->getResponse()->setContent($encoded);
2765
2766 return(sfView::NONE);
2767 }
2768
2769
2770 /**
2771 * Upload files
2772 *
2773 * @param sfRequest $request A request object
2774 */
2775 public function executeUploadfile(sfWebRequest $request)
2776 {
2777 $this->error = array('error' => 'false', 'error_msg' => '');
2778 $upload_path = substr(dirname(__FILE__), 0, (strpos(dirname(__FILE__), "apps"))) . '/web/uploads/files/';
2779 $valid_extensions = array('jpg', 'png', 'pdf');
2780
2781 $file = $request->getFiles('ufile');
2782 $iDpId = $request->getParameter('dpid');
2783
2784 //Name shuld not be empty
2785 if (strlen($file['name']) > 0)
2786 {
2787 //Check the file extension
2788 $filename_parts = explode(".", $file['name']);
2789 $iUserId = $this->getUser()->getAttribute("id");
2790 $sNewFileName = $iDpId . "_" . $iUserId . "_" . time() . "." . $filename_parts[1];
2791
2792 if (in_array($filename_parts[count($filename_parts) - 1], $valid_extensions))
2793 { //IN case the filename has also periods we always get the last part
2794 $result = move_uploaded_file($file['tmp_name'], $upload_path . $sNewFileName);
2795
2796 if (!$result)
2797 {
2798 $this->error['error'] = 'true';
2799 $this->error['error_msg'] = __("Sorry, but there was a problem when trying to upload the file");
2800 } else
2801 {
2802 //Return the name of the image in the second parameter
2803 $this->error['error_msg'] = $file['name'];
2804 }
2805 } else
2806 {
2807 $this->error['error'] = 'true';
2808 $this->error['error_msg'] = __("Wrong file extension.");
2809 }
2810 } else
2811 {
2812 $this->error['error'] = 'true';
2813 $this->error['error_msg'] = __("Filename couldn't be empty");
2814 }
2815
2816 echo $this->error['error'] . "|" . $this->error['error_msg'] . "|" . $file['name'];
2817
2818 return(sfView::NONE);
2819 }
2820
2821
2822 /**
2823 * Show the list of Dps pending of my approval
2824 *
2825 * @param sfRequest $request A request object
2826 */
2827 public function executeFollowup(sfWebRequest $request)
2828 {
2829 /* Variables */
2830 $bError = false;
2831 $sErrorMsg = '';
2832 $this->iViewPrivileges = array(1);
2833 $this->aOpenFollowUps = array();
2834 $aFollowUps = array();
2835 $oUser = $this->getUser();
2836
2837 $oRolesManager = new RolesManager();
2838 $aUserRolesUnits = $oRolesManager->getUserRolesUnits($this->getUser()->getAttribute('id'));
2839
2840 $this->iViewPrivileges = $aUserRolesUnits['all_view_permissions'];
2841
2842 foreach ($this->iViewPrivileges as $vp)
2843 {
2844 /* Get allowed states for this role */
2845 $aValidStates = Doctrine_Query::create()
2846 ->select('p.*,t.dpt_old_sta')
2847 ->from('IdtDisciplinaryProcessTransitionPermissions p')
2848 ->innerJoin('p.IdtDisciplinaryProcessTransitions t ON t.dpt_id = p.dtp_dpt_id')
2849 ->where('p.dtp_rol_id =?', $vp[0])
2850 ->fetchArray();
2851
2852 $states = array();
2853 foreach ($aValidStates as $vs)
2854 {
2855 $states[] = $vs['IdtDisciplinaryProcessTransitions']['dpt_old_sta'];
2856 }
2857
2858 /* Get the data based on the user roles, view privileges and accounts */
2859 switch ($vp[1])
2860 { //$aUserRolesUnits['view_permission']) {
2861 case 1:
2862 /* User will be able to see only their subordinates information */
2863 $aFollowUps = Doctrine_Query::create()
2864 ->select('p.*, u.*,s.*, t.*, c.*, st.*')
2865 ->from('IdtDisciplinaryProcess p')
2866 ->innerJoin('p.IdtDisciplinaryProcessStatesCatalog st ON p.dpc_curr_state = st.dst_id')
2867 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
2868 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
2869 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
2870 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
2871 ->where('p.dpc_sup_id =? AND p.dpc_active =? AND p.dpc_dgs_status =?', array($this->getUser()->getAttribute('id'), 1, 1))
2872 ->whereIn('p.dpc_curr_state', $states)
2873 ->andWhere("p.dpc_usr_empid !=" . $oUser->getAttribute('id'))
2874 ->fetchArray();
2875
2876 break;
2877 case 2:
2878 $aFollowUps = Doctrine_Query::create()
2879 ->select('p.*, u.*,s.*, t.*, c.*, st.*, CONCAT(u2.usr_fname, " ", u2.usr_lname) AS SUP')
2880 ->from('IdtDisciplinaryProcess p')
2881 ->innerJoin('p.IdtDisciplinaryProcessStatesCatalog st ON p.dpc_curr_state = st.dst_id')
2882 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
2883 ->innerJoin('p.IdtUsers u2 ON u2.usr_empid = p.dpc_sup_id')
2884 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
2885 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
2886 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
2887 ->where('p.dpc_active =? AND p.dpc_dgs_status =?', array(1, 1))
2888 ->andWhereIn('p.dpc_uni_id', $aUserRolesUnits['units'])
2889 ->whereIn('p.dpc_curr_state', $states)
2890 ->andWhere("p.dpc_usr_empid !=" . $oUser->getAttribute('id'))
2891 ->fetchArray();
2892
2893 break;
2894 case 3:
2895 /* User will be able to see the information of all the account that they
2896 have assigned */
2897 $aFollowUps = Doctrine_Query::create()
2898 ->select('p.*, u.*, s.*, t.*, c.*, st.*, CONCAT(u2.usr_fname, " ", u2.usr_lname) AS SUP')
2899 ->from('IdtDisciplinaryProcess p')
2900 ->innerJoin('p.IdtDisciplinaryProcessStatesCatalog st ON p.dpc_curr_state = st.dst_id')
2901 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
2902 ->innerJoin('p.IdtUsers u2 ON u2.usr_empid = p.dpc_sup_id')
2903 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
2904 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
2905 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
2906 ->where('p.dpc_active =? AND p.dpc_dgs_status =?', array(1, 1))
2907 ->andWhereIn('p.dpc_uni_id', $aUserRolesUnits['multiple_units'])
2908 ->whereIn('p.dpc_curr_state', $states)
2909 ->andWhere("p.dpc_usr_empid !=" . $oUser->getAttribute('id'))
2910 ->fetchArray();
2911
2912 break;
2913 case 4:
2914 $aFollowUps = Doctrine_Query::create()
2915 ->select('p.*, u.*,s.*, t.*, c.*, st.*, CONCAT(u2.usr_fname, " ", u2.usr_lname) AS SUP')
2916 ->from('IdtDisciplinaryProcess p')
2917 ->innerJoin('p.IdtDisciplinaryProcessStatesCatalog st ON p.dpc_curr_state = st.dst_id')
2918 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
2919 ->innerJoin('p.IdtUsers u2 ON u2.usr_empid = p.dpc_sup_id')
2920 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
2921 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
2922 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
2923 ->where('p.dpc_active =? AND p.dpc_dgs_status =?', array(1, 1))
2924 ->whereIn('p.dpc_curr_state', $states)
2925 ->andWhere("p.dpc_usr_empid !=" . $oUser->getAttribute('id'))
2926 ->fetchArray();
2927
2928 break;
2929 case 5:
2930 /* Get my direct reports */
2931 $this->aDirectReports = Doctrine_Query::create()
2932 ->select('u.usr_empid')
2933 ->from('IdtUsers u')
2934 ->where('u.usr_supervisor =?', array($this->getUser()->getAttribute('id')))
2935 ->fetchArray();
2936
2937 $aSups = array();
2938
2939 foreach ($this->aDirectReports as $dr)
2940 {
2941 $aSups[] = $dr['usr_empid'];
2942 }
2943
2944 /* User will be able to see only their subordinates information */
2945 $aFollowUps = Doctrine_Query::create()
2946 ->select('p.*, u.*,s.*, t.*, c.*, st.*')
2947 ->from('IdtDisciplinaryProcess p')
2948 ->innerJoin('p.IdtDisciplinaryProcessStatesCatalog st ON p.dpc_curr_state = st.dst_id')
2949 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
2950 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
2951 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
2952 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
2953 ->where('p.dpc_active =? AND p.dpc_dgs_status =?', array(1, 1))
2954 ->whereIn('p.dpc_sup_id', $aSups)
2955 ->whereIn('p.dpc_curr_state', $states)
2956 ->fetchArray();
2957 break;
2958 default:
2959 break;
2960 }
2961
2962
2963 $this->aOpenFollowUps = array_merge($this->aOpenFollowUps, $aFollowUps);
2964 }
2965 }
2966
2967
2968 /**
2969 * Search user's Disciplinary Processes
2970 *
2971 * @param sfRequest $request A request object
2972 */
2973 public function executeSearch(sfWebRequest $request)
2974 {
2975 $this->iEmployeeId = 0;
2976 $this->bReferer = false;
2977
2978 if ($this->getUser()->hasAttribute('sempid'))
2979 {
2980 $this->iEmployeeId = $this->getUser()->getAttribute('sempid');
2981 $this->bReferer = true;
2982
2983 /* Remove this attribute, because it'll be used once, when the user is getting
2984 * back from the edit form. */
2985 $this->getUser()->offsetUnset("sempid");
2986 }
2987 }
2988
2989
2990 /**
2991 * Show the list of Disciplinary Processes assigned to a user
2992 *
2993 * @param sfRequest $request A request object
2994 */
2995 public function executeGetuserinformation(sfWebRequest $request)
2996 {
2997 /* Variables */
2998 $bError = false;
2999 $sErrorMsg = '';
3000 $aUserInfo = array();
3001 $aDps = array();
3002 $allowed = false;
3003 $oUser = $this->getUser();
3004
3005 if ($request->isMethod(sfRequest::POST))
3006 {
3007 if ($request->getParameter('id') != null)
3008 {
3009 $this->aProfile = array();
3010 $this->picture_width = (sfConfig::get('irdp_user_pictures_width') * 0.9) . 'px';
3011 $this->picture_height = (sfConfig::get('irdp_user_pictures_height') * 0.9) . 'px';
3012
3013 //Init array
3014 $this->aProfile['empid'] = '';
3015 $this->aProfile['pos_name'] = '';
3016 $this->aProfile['usr_name'] = '';
3017 $this->aProfile['acc_name'] = '';
3018 $this->aProfile['hiredate'] = '';
3019 $this->aProfile['sup_name'] = '';
3020 $this->aProfile['2levsup_name'] = '';
3021 $this->aProfile['usr_picture'] = '';
3022
3023 /* Get user profile from session variables */
3024 $oUserProfile = new UserManager();
3025 $aUserInfo = $oUserProfile->getUserProfile($request->getParameter('id'));
3026
3027 if (!$aUserInfo['error'])
3028 {
3029 /* Check if you are allowed to visualize this user information */
3030 $oRolesManager = new RolesManager();
3031 $aUserRolesUnits = $oRolesManager->getUserRolesUnits($this->getUser()->getAttribute('id'));
3032
3033 /* Get the list of roles that can open a request */
3034 $aRoles = Doctrine_Core::getTable('IdtDisciplinaryProcessPermissions')
3035 ->createQuery('p')
3036 ->innerJoin('p.IdtRoles r ON r.rol_id = p.dpe_rol_id')
3037 ->whereIn('r.rol_id', $aUserRolesUnits['roles'])
3038 ->andWhere('r.rol_active = 1 AND p.dpe_active = 1')
3039 ->fetchArray();
3040
3041 $aValidRoles = array();
3042 $allRoles = Array();
3043 foreach ($aRoles as $cp)
3044 {
3045 $aValidRoles[] = array($cp['dpe_rol_id'], $cp['IdtRoles']['rol_rvp_id']);
3046 $allRoles[] = $cp['IdtRoles']['rol_id'];
3047 }
3048
3049
3050 foreach ($aValidRoles as $vp)
3051 {
3052
3053 switch ($vp[1])
3054 {
3055 case 1:
3056 if ($aUserInfo['profile']['usr_supervisor_id'] == $this->getUser()->getAttribute('id'))
3057 {
3058 $allowed = true;
3059 }
3060 break;
3061
3062 case 2:
3063 if (in_array($aUserInfo['profile']['usr_department_id'], $aUserRolesUnits['units']) === true)
3064 {
3065 $allowed = true;
3066 }
3067 break;
3068 case 3:
3069 if (in_array($aUserInfo['profile']['usr_department_id'], $aUserRolesUnits['multiple_units']) === true)
3070 {
3071 $allowed = true;
3072 }
3073 break;
3074 case 4:
3075 $allowed = true;
3076 break;
3077
3078 case 5:
3079 /* Second level manager - Get the list of my subordinates */
3080 $aSubordinates = Doctrine_Core::getTable('IdtUsers')
3081 ->createQuery('u')
3082 ->where('usr_supervisor =? AND usr_active =?', array($this->getUser()->getAttribute('id'), 1))
3083 ->fetchArray();
3084
3085 $aPossibleSups = array();
3086
3087 foreach ($aSubordinates as $sub)
3088 {
3089 $aPossibleSups[] = $sub['usr_empid'];
3090 $this->logMessage($sub['usr_empid']);
3091 }
3092
3093 /* Be aware that this user is an idirect subordinate */
3094 foreach ($aPossibleSups as $sup)
3095 {
3096 if ($aUserInfo['profile']['usr_supervisor_id'] == $sup)
3097 {
3098 $allowed = true;
3099 }
3100 }
3101 break;
3102 }
3103 }
3104 if ($allowed){
3105 $oDateFormat = new DateFormater();
3106 $hireDate = $aUserInfo['profile']['usr_hiredate']; // ya viene con formato correcto
3107
3108 $this->aProfile['empid'] = $request->getParameter('id');
3109 $this->aProfile['pos_name'] = $aUserInfo['profile']['usr_position_name'];
3110 $this->aProfile['usr_name'] = $aUserInfo['profile']['usr_name'];
3111 $this->aProfile['acc_name'] = $aUserInfo['profile']['usr_department_name'];
3112 $this->aProfile['hiredate'] = $hireDate;
3113 $this->aProfile['sup_name'] = $aUserInfo['profile']['usr_supervisor_name'];
3114 $this->aProfile['man_name'] = $aUserInfo['profile']['usr_seclevelsup_name'];
3115 $this->aProfile['picture'] = sfConfig::get('irdp_user_pictures_path') . $aUserInfo['profile']['usr_picture'];
3116
3117 /* Get User dps */
3118 $aUserDps = Doctrine_Core::getTable('IdtDisciplinaryProcess')
3119 ->createQuery('d')
3120 ->innerJoin('d.IdtUsers u ON u.usr_empid = d.dpc_sup_id')
3121 ->innerJoin('d.IdtDisciplinaryMatrixSanctions s ON s.dms_id = d.dpc_dms_id')
3122 ->where('dpc_usr_empid =? AND dpc_active =?', array($request->getParameter('id'), 1))
3123 ->andWhere('dpc_usr_empid !=' . $oUser->getAttribute('id'))
3124 ->fetchArray();
3125
3126 if (count($aUserDps) > 0)
3127 {
3128
3129 // obtenemos la conexion activa
3130 $con = Doctrine_Manager::getInstance()->getCurrentConnection();
3131
3132 // validad permisos para editar en este workflow
3133 foreach ($aUserDps as $dp)
3134 {
3135
3136 $dpId = $dp['dpc_id'];
3137
3138 // obtenemos los countries seleccionados en CR
3139 $q = " SELECT tp.dtp_rol_id, group_concat(t.dpt_id) as dpt_id, t.*, tp.*, p.*
3140 FROM idt_disciplinary_process p
3141 inner join idt_form f ON p.dpc_form_id = f.frm_id
3142 inner join idt_disciplinary_process_transitions t ON f.frm_proc_id = t.dpt_dpr_id AND t.dpt_old_sta = p.dpc_curr_state
3143 inner join idt_disciplinary_process_transition_permissions tp ON tp.dtp_dpt_id = t.dpt_id
3144 WHERE p.dpc_active = 1 AND t.dpt_active = 1 AND tp.dtp_active = 1 AND dpc_usr_empid != " . $oUser->getAttribute('id') . " AND p.dpc_id = " . $dpId . "
3145 GROUP BY tp.dtp_rol_id;";
3146
3147 $oRolTransition = $con->execute($q);
3148 $exist = false;
3149 foreach ($oRolTransition as $value)
3150 {
3151 if (in_array($value['dtp_rol_id'], $allRoles))
3152 {
3153 $exist = true;
3154 break;
3155 }
3156 }
3157
3158 if ($exist)
3159 {
3160 $aTemp['hasPermission'] = 'true';
3161 } else
3162 {
3163 $aTemp['hasPermission'] = 'false';
3164 }
3165
3166 $aTemp['id'] = str_pad($dp['dpc_id'], 4, "0", STR_PAD_LEFT);
3167 $aTemp['form'] = $dp['dpc_form_id'];
3168 $aTemp['type'] = $dp['IdtDisciplinaryMatrixSanctions']['dms_name'];
3169 $aTemp['supervisor'] = $dp['IdtUsers']['usr_fname'] . ' ' . $dp['IdtUsers']['usr_lname'];
3170 $aTemp['dp_id'] = $dp['dpc_id'];
3171 $aTemp['form_id'] = $dp['dpc_form_id'];
3172 $aTemp['global_estatus'] = "";
3173
3174 if ($dp['dpc_incident_date'] != '' && $dp['dpc_incident_date'] != null)
3175 {
3176 $aTemp['incident_date'] = $oDateFormat->formatDate($dp['dpc_incident_date']);
3177 } else
3178 {
3179 $aTemp['incident_date'] = 'N/A';
3180 }
3181
3182 if ($dp['dpc_emission_date'] != '' && $dp['dpc_emission_date'] != null)
3183 {
3184 $aTemp['emission_date'] = $oDateFormat->formatDate($dp['dpc_emission_date']);
3185 } else
3186 {
3187 $aTemp['emission_date'] = 'N/A';
3188 }
3189
3190 /* Indicate the global status of the disciplinary process, whether it's open, closed or invalid */
3191 if ($dp['dpc_dgs_status'] == 1)
3192 {
3193 $aTemp['global_estatus'] = __("Open");
3194 } else if ($dp['dpc_dgs_status'] == 2)
3195 {
3196 $aTemp['global_estatus'] = __("Closed");
3197 //$aTemp['hasPermission'] = 'true'; -> permitir ver dps cerrados
3198 } else if ($dp['dpc_dgs_status'] == 3)
3199 {
3200 $aTemp['global_estatus'] = __("Invalid");
3201 }
3202
3203 $aDps[] = $aTemp;
3204 }
3205 }
3206 } else
3207 {
3208 $bError = true;
3209 $sErrorMsg = __("You aren't allowed to see user's information.");
3210 }
3211 } else
3212 {
3213 $bError = true;
3214 $sErrorMsg = __("User information couldn'be recoreverd");
3215 }
3216 } else
3217 {
3218 $bError = true;
3219 $bErrorMsg = __("Employee Id can't be null");
3220 }
3221 }
3222
3223 $encoded = json_encode(array('bError' => $bError, 'sErrorMsg' => $sErrorMsg, 'data' => $this->aProfile, 'dps' => $aDps));
3224 $this->getResponse()->setContent($encoded);
3225 return sfView::NONE;
3226 }
3227
3228
3229 /**
3230 * Show the list of Dps pending of my approval
3231 *
3232 * @param sfRequest $request A request object
3233 */
3234 public function executeDmapproval(sfWebRequest $request)
3235 {
3236 /* Variables */
3237 $bError = false;
3238 $sErrorMsg = '';
3239 $this->iViewPrivileges = 1;
3240 $this->aOpenFollowUps = array();
3241 $aFollowUps = array();
3242
3243 /* Check if current user has the role that can approve void DM requests */
3244 $oRolesManager = new RolesManager();
3245 $aEntities = $oRolesManager->getUserRolesUnits($this->getUser()->getAttribute('id'));
3246
3247 $aConfigurations = Doctrine_Core::getTable('IdtDisciplinaryMatrixConfigurations')
3248 ->createQuery('c')
3249 ->where('dcf_active =?', array(1))
3250 ->andWhereIn('dcf_vdm_role', $aEntities['roles'])
3251 ->fetchArray();
3252
3253 if (count($aConfigurations) > 0)
3254 {
3255
3256 $oRolesManager = new RolesManager();
3257 $aUserRolesUnits = $oRolesManager->getUserRolesUnits($this->getUser()->getAttribute('id'));
3258
3259 $this->iViewPrivileges = $aUserRolesUnits['all_view_permissions'];
3260
3261 foreach ($this->iViewPrivileges as $vp)
3262 {
3263
3264 /* Get the data based on the user roles, view privileges and accounts */
3265 switch ($vp[1])
3266 { //$aUserRolesUnits['view_permission']) {
3267 case 1:
3268 /* User will be able to see only their subordinates information */
3269 $aFollowUps = Doctrine_Query::create()
3270 ->select('p.*, u.*,s.*, t.*, c.*, s.dms_name AS SANCTION, s2.dms_name AS SUGGESTED_SANCTION')
3271 ->from('IdtDisciplinaryProcess p')
3272 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
3273 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
3274 ->innerJoin('p.IdtDisciplinaryProcessSuggestedSanctions ss ON ss.dps_dpc_id = p.dpc_id')
3275 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s2 ON s2.dms_id = ss.dps_dms_id')
3276 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
3277 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
3278 ->where('p.dpc_sup_id =? AND p.dpc_active =? AND p.dpc_dgs_status =?', array($this->getUser()->getAttribute('id'), 1, 1))
3279 ->andWhere('p.dpc_vdm_required =? AND p.dpc_vdm_approved =?', array(1, 0))
3280 ->fetchArray();
3281
3282 break;
3283 case 2:
3284 /* User will be able to see their account information */
3285 $aFollowUps = Doctrine_Query::create()
3286 ->select('p.*, u.*,s.*, t.*, c.*, s.dms_name AS SANCTION, s2.dms_name AS SUGGESTED_SANCTION')
3287 ->from('IdtDisciplinaryProcess p')
3288 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
3289 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
3290 ->innerJoin('p.IdtDisciplinaryProcessSuggestedSanctions ss ON ss.dps_dpc_id = p.dpc_id')
3291 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s2 ON s2.dms_id = ss.dps_dms_id')
3292 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
3293 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
3294 ->where('p.dpc_active =? AND p.dpc_dgs_status =?', array(1, 1))
3295 ->andwherein('p.dpc_uni_id', $aUserRolesUnits['units'])
3296 ->andWhere('p.dpc_vdm_required =? AND p.dpc_vdm_approved =?', array(1, 0))
3297 ->fetchArray();
3298 break;
3299 case 3:
3300 /* User will be able to see the information of all the account that they
3301 have assigned */
3302 $aFollowUps = Doctrine_Query::create()
3303 ->select('p.*, u.*,s.*, t.*, c.*, s.dms_name AS SANCTION, s2.dms_name AS SUGGESTED_SANCTION')
3304 ->from('IdtDisciplinaryProcess p')
3305 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
3306 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
3307 ->innerJoin('p.IdtDisciplinaryProcessSuggestedSanctions ss ON ss.dps_dpc_id = p.dpc_id')
3308 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s2 ON s2.dms_id = ss.dps_dms_id')
3309 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
3310 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
3311 ->where('p.dpc_active =? AND p.dpc_dgs_status =?', array(1, 1))
3312 ->andWhereIn('p.dpc_uni_id', $aUserRolesUnits['multiple_units'])
3313 ->andWhere('p.dpc_vdm_required =? AND p.dpc_vdm_approved =?', array(1, 0))
3314 ->fetchArray();
3315
3316 break;
3317 case 4:
3318 $aFollowUps = Doctrine_Query::create()
3319 ->select('p.*, u.*,s.*, t.*, c.*, s.dms_name AS SANCTION, s2.dms_name AS SUGGESTED_SANCTION')
3320 ->from('IdtDisciplinaryProcess p')
3321 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
3322 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
3323 ->innerJoin('p.IdtDisciplinaryProcessSuggestedSanctions ss ON ss.dps_dpc_id = p.dpc_id')
3324 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s2 ON s2.dms_id = ss.dps_dms_id')
3325 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
3326 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
3327 ->where('p.dpc_active =? AND p.dpc_dgs_status =?', array(1, 1))
3328 ->andWhere('p.dpc_vdm_required =? AND p.dpc_vdm_approved =?', array(1, 0))
3329 ->fetchArray();
3330
3331 break;
3332 case 5:
3333 /* Get my direct reports */
3334 $this->aDirectReports = Doctrine_Query::create()
3335 ->select('u.usr_empid')
3336 ->from('IdtUsers u')
3337 ->where('u.usr_supervisor =?', array($this->getUser()->getAttribute('id')))
3338 ->fetchArray();
3339
3340 $aSups = array();
3341
3342 foreach ($this->aDirectReports as $dr)
3343 {
3344 $aSups[] = $dr['usr_empid'];
3345 }
3346
3347 /* User will be able to see only their subordinates information */
3348 $aFollowUps = Doctrine_Query::create()
3349 ->select('p.*, u.*,s.*, t.*, c.*, s.dms_name AS SANCTION, s2.dms_name AS SUGGESTED_SANCTION')
3350 ->from('IdtDisciplinaryProcess p')
3351 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
3352 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
3353 ->innerJoin('p.IdtDisciplinaryProcessSuggestedSanctions ss ON ss.dps_dpc_id = p.dpc_id')
3354 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s2 ON s2.dms_id = ss.dps_dms_id')
3355 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
3356 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
3357 ->where('p.dpc_sup_id =? AND p.dpc_active =? AND p.dpc_dgs_status =?', array($this->getUser()->getAttribute('id'), 1, 1))
3358 ->andWhere('p.dpc_vdm_required =? AND p.dpc_vdm_approved =?', array(1, 0))
3359 ->andWhereIn('p.dpc_sup_id', $aSups)
3360 ->fetchArray();
3361
3362
3363 break;
3364 default:
3365 break;
3366 }
3367
3368 $this->aOpenFollowUps = array_merge($this->aOpenFollowUps, $aFollowUps);
3369 }
3370 } else
3371 {
3372 $this->forward('default', 'secure');
3373 }
3374 }
3375
3376
3377 /**
3378 * Show the list of Dps pending of my approval
3379 *
3380 * @param sfRequest $request A request object
3381 */
3382 public function executeGetvoiddminfo(sfWebRequest $request)
3383 {
3384 /* Variables */
3385 $bError = false;
3386 $sErrorMsg = '';
3387 $aSanctions = array();
3388 $aProfile = array();
3389
3390 if ($request->isMethod(sfRequest::POST))
3391 {
3392
3393 if ($request->getParameter("dp") != null)
3394 {
3395 //Get dp selected sanction and suggested sanctions
3396 $aSanctions = Doctrine_Query::create()
3397 ->select('p.dpc_usr_empid AS EMPID, p.dpc_id AS DPID, s1.dms_name AS SANCTION, s2.dms_name AS SUGGESTED_SANCTION, CONCAT(u.usr_fname," ",u.usr_lname) AS IMPOSER, p.dpc_reason_override as reason')
3398 ->from('IdtDisciplinaryProcess p')
3399 ->innerJoin('p.IdtDisciplinaryProcessSuggestedSanctions g ON g.dps_dpc_id = p.dpc_id')
3400 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s1 ON s1.dms_id = p.dpc_dms_id AND s1.dms_active = 1')
3401 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s2 ON g.dps_dms_id = s2.dms_id AND s1.dms_active = 1')
3402 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_created_by')
3403 ->where('p.dpc_id =?', array($request->getParameter("dp")))
3404 ->fetchArray();
3405
3406 if (count($aSanctions) > 0)
3407 {
3408 //Now get user profile
3409 $user = new UserManager();
3410 $profile = $user->getUserProfile($aSanctions[0]['EMPID']);
3411
3412 if (!$profile['error'])
3413 {
3414 $oDateFormater = new dateFormater();
3415
3416 $aProfile['empid'] = $aSanctions[0]['EMPID'];
3417 $aProfile['name'] = $profile['profile']['usr_name'];
3418 $aProfile['supervisor'] = $profile['profile']['usr_supervisor_name'];
3419 $aProfile['position'] = $profile['profile']['usr_position_name'];
3420 $aProfile['unit'] = $profile['profile']['usr_department_name'];
3421 $aProfile['hired_date'] = $oDateFormater->formatDate($profile['profile']['usr_hiredate']);
3422 $aProfile['secsupervisor'] = $profile['profile']['usr_seclevelsup_name'];
3423 $aProfile['reason'] = $aSanctions[0]['reason'];
3424 $aSanctions['suggested_sanction'] = $aSanctions[0]['SUGGESTED_SANCTION'];
3425 $aSanctions['imposed_sanction'] = $aSanctions[0]['SANCTION'];
3426 } else
3427 {
3428 $bError = true;
3429 $sErrorMsg = __("Error trying to get information");
3430 }
3431 } else
3432 {
3433 $bError = true;
3434 $sErrorMsg = __("Error trying to get information");
3435 }
3436 } else
3437 {
3438 $bError = true;
3439 $sErrorMsg = __("Hint Process Id cannot be null");
3440 }
3441 }
3442
3443 $encoded = json_encode(array('error' => $bError, 'error_msg' => $sErrorMsg, 'profile' => $aProfile, 'sanctions' => $aSanctions));
3444 $this->getResponse()->setContent($encoded);
3445 return(sfView::NONE);
3446 }
3447
3448
3449 public function executeApprovesanctionresponse(sfWebRequest $request)
3450 {
3451 //Variables
3452 $bError = false;
3453 $sErrorMsg = '';
3454 $sReply = __("Approved");
3455
3456 if ($request->getParameter('dpid') != null)
3457 {
3458 if ($request->getParameter('answer') != null)
3459 {
3460
3461 /* Update the DP record */
3462 $oDisciplinaryProcess = Doctrine_Core::getTable('IdtDisciplinaryProcess')
3463 ->createQuery('p')
3464 ->where('p.dpc_id =?', array($request->getParameter('dpid')))
3465 ->execute();
3466
3467 if (count($oDisciplinaryProcess) > 0)
3468 {
3469 $oDisciplinaryProcess[0]->setDpcVdmApproved($request->getParameter('answer'));
3470 $oDisciplinaryProcess[0]->setDpcVdmApprovedBy($this->getUser()->getAttribute('id'));
3471 $oDisciplinaryProcess[0]->setDpcVdmApprovedDate(date('Y-m-d H:i:s', time()));
3472
3473 /* Because the sanction was rejected invalidate this DP */
3474 if ($request->getParameter('answer') == 2)
3475 {
3476 $oDisciplinaryProcess[0]->setDpcDgsStatus(3);
3477 $oDisciplinaryProcess[0]->setDpcComment($request->getParameter('reason')); /* THis is the reason why it wasn't approved */
3478 $sReply = __("Denied");
3479 }
3480
3481 /* Now try to update the DP */
3482 try {
3483 $oDisciplinaryProcess[0]->save();
3484 $this->getUser()->setFlash('success', __("The Hint Process" . str_pad($request->getParameter('dpid'), 4, "0", STR_PAD_LEFT) . " was succesfully updated."));
3485
3486 if (sfConfig::get('irdp_notification_enabled'))
3487 {
3488 /* Try to send notification */
3489 $oMailNotification = new MailNotification();
3490 $aContactList = $oMailNotification->getRecipients($oDisciplinaryProcess[0]['dpc_curr_state'], $oDisciplinaryProcess[0]['dpc_uni_id']);
3491
3492 if (count($aContactList['mail_list']) > 0)
3493 {
3494 foreach ($aContactList['mail_list'] as $mail)
3495 {
3496 if ($mail != "")
3497 {
3498 $oMailNotification->setTo($mail);
3499 }
3500 }
3501
3502 /* Set message and subject */
3503 $sSubject = str_replace("[%DP Id%]", $request->getParameter('dpid'), sfConfig::get('irdp_notification_dp_sanction_approval_reply_subject'));
3504 $sMessage = str_replace("[%Reply%]", $sReply, sfConfig::get('irdp_notification_dp_sanction_approval_reply_content'));
3505 $result = $oMailNotification->send();
3506
3507 if ($result['error'] == false)
3508 {
3509 $this->logMessage("Hint Approval Hints Guide (referer->dp/dmapproval): An error was produced when trying to send an update on Hint " . $request->getParameter('dpid'));
3510 $this->logMessage("Values - Reply: " . $request->getParameter('answer'));
3511 }
3512 }
3513 }
3514 } catch (Exception $e) {
3515 $bError = true;
3516 $sErrorMsg = __("Hint Process couldn't be updated");
3517 }
3518 } else
3519 {
3520 $bError = true;
3521 $sErrorMsg = __("Hint Process record couldn't be found");
3522 }
3523 } else
3524 {
3525 $bError = true;
3526 $sErrorMsg = __("You should approve or reject this sanction.");
3527 }
3528 } else
3529 {
3530 $bError = true;
3531 $sErrorMsg = __("Hint Process Id cannot be null");
3532 }
3533
3534 $encoded = json_encode(array('error' => $bError, 'error_msg' => $sErrorMsg));
3535 $this->getResponse()->setContent($encoded);
3536 return(sfView::NONE);
3537 }
3538
3539
3540 /**
3541 * Show the list of void disciplinary matrix that I have approved
3542 *
3543 * @param sfRequest $request A request object
3544 */
3545 public function executeMydmapprovals(sfWebRequest $request)
3546 {
3547 $this->aOpenFollowUps = Doctrine_Query::create()
3548 ->select('p.*, u.*,s.*, t.*, c.*, s.dms_name AS SANCTION, s2.dms_name AS SUGGESTED_SANCTION')
3549 ->from('IdtDisciplinaryProcess p')
3550 ->innerJoin('p.IdtUsers u ON u.usr_empid = p.dpc_usr_empid')
3551 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s ON s.dms_id = dpc_dms_id')
3552 ->innerJoin('p.IdtDisciplinaryProcessSuggestedSanctions ss ON ss.dps_dpc_id = p.dpc_id')
3553 ->innerJoin('p.IdtDisciplinaryMatrixSanctions s2 ON s2.dms_id = ss.dps_dms_id')
3554 ->innerJoin('p.IdtPositions t ON t.pos_id = p.dpc_pos_id')
3555 ->innerJoin('p.IdtUnits c ON c.uni_id = p.dpc_uni_id')
3556 ->where('p.dpc_active =?', array(1))
3557 ->andWhere('p.dpc_vdm_required =? AND p.dpc_vdm_approved_by =?', array(1, $this->getUser()->getAttribute('id')))
3558 ->fetchArray();
3559 }
3560
3561
3562 /**
3563 * Show the list of void disciplinary matrix that I have approved
3564 *
3565 * @param sfRequest $request A request object
3566 */
3567 public function executeDpreport(sfWebRequest $request)
3568 {
3569 /* Get the sanction list */
3570 $this->aSanctions = Doctrine_Core::getTable('IdtDisciplinaryMatrixSanctions')
3571 ->createQuery('s')
3572 ->where('s.dms_active =?', array(1))
3573 ->fetchArray();
3574 }
3575
3576 /*
3577 * Show all the disciplinary created or processed during a period of time.
3578 *
3579 * @params date from Start date
3580 * @params date to End date
3581 * @params Int type Type of sanction
3582 * @return array Return an array with error messages in case something fail
3583 * and the data returned
3584 */
3585
3586
3587 public function executeGetdpreport(sfWebRequest $request)
3588 {
3589 $bError = false;
3590 $sErrorMsg = '';
3591
3592 $empId = $this->getUser()->getAttribute('id');
3593 $report = $this->getReport($request->getParameter("from"), $request->getParameter("to"), $request->getParameter("type"), $empId);
3594
3595 error_reporting(0);
3596 $encoded = json_encode(array('error' => $report['error'], 'error_msg' => $report['error_msg'], 'data' => $report['data']));
3597 $this->getResponse()->setContent($encoded);
3598
3599 return(sfView::NONE);
3600 }
3601
3602 /*
3603 * Export report to Excel
3604 *
3605 * @params date from Start date
3606 * @params date to End date
3607 * @params Int type Type of sanction
3608 * @return array Return an array with error messages in case something fail
3609 * and the data returned
3610 *
3611 */
3612
3613
3614 public function executeExporttoexcel(sfWebRequest $request)
3615 {
3616 $bError = false;
3617 $sErrorMsg = '';
3618
3619 $empId = $this->getUser()->getAttribute('id');
3620 $report = $this->getReport($request->getParameter("from"), $request->getParameter("to"), $request->getParameter("type"), $empId);
3621 $this->aReport = $report['data'];
3622 }
3623
3624 /*
3625 * Get Report
3626 *
3627 * @params date from Start date
3628 * @params date to End date
3629 * @return array Data returned by query
3630 *
3631 */
3632
3633
3634 private function getReport($from, $to, $type, $empId)
3635 {
3636 $bError = false;
3637 $sErrorMsg = '';
3638 $sFilter = '';
3639 $oUser = $this->getUser();
3640
3641 // *************************************************************************************
3642 // se agrega esta parte para aplicar roles en los resultados de los reportes de los DP's
3643 // *************************************************************************************
3644 $aRoles = array();
3645 $iViewPrivileges = array(1);
3646 $iViewPermissions = array();
3647 $aMyUnits = array();
3648 $aMultipleUnits = array();
3649 $permission = array();
3650
3651 // get all_view_permissions for user
3652 $oRolesManager = new RolesManager();
3653 $aUserRolesUnits = $oRolesManager->getUserRolesUnits($empId);
3654
3655 $aRoles = $aUserRolesUnits['roles'];
3656 $iViewPrivileges = $aUserRolesUnits['all_view_permissions']; // 1-My team 2-My account 3-Multiple account 4-Unrestricted 5-My Team Second Level
3657 $aMyUnits = $aUserRolesUnits['units'];
3658 $aMultipleUnits = $aUserRolesUnits['multiple_units'];
3659 $iViewPermissions = $aUserRolesUnits['view_permission'];
3660
3661 foreach ($iViewPrivileges as $oPrivileges)
3662 {
3663 $permission = array_merge($permission, $oPrivileges);
3664 }
3665
3666 $filterViewPermission = '';
3667 if (in_array('4', $permission))
3668 { // 4-Unrestricted puede ver todo
3669 // ver todo
3670 } else
3671 {
3672 if (in_array('5', $permission))
3673 { // 1-My team 5-My Team Second Level
3674 if ($filterViewPermission != '')
3675 {
3676 $filterViewPermission .= " AND ( h.hdp_sup_id = $empId OR h.hdp_seclev_sup_id = $empId )";
3677 } else
3678 {
3679 $filterViewPermission = " ( h.hdp_sup_id = $empId OR h.hdp_seclev_sup_id = $empId )";
3680 }
3681 } elseif (in_array('1', $permission))
3682 { // 1-My team
3683 if ($filterViewPermission != '')
3684 {
3685 $filterViewPermission .= " AND h.hdp_sup_id = $empId";
3686 } else
3687 {
3688 $filterViewPermission = " h.hdp_sup_id = $empId";
3689 }
3690 }
3691
3692
3693 if (in_array('2', $permission) && in_array('3', $permission))
3694 { // 2-My account 3-Multiple account
3695 $aAccountList = array();
3696 $aAccountList = array_merge($aMyUnits, $aMultipleUnits);
3697
3698 if ($filterViewPermission != '')
3699 {
3700 $filterViewPermission .= " AND h.hdp_uni_id IN(" . implode($aAccountList, ',') . ")";
3701 } else
3702 {
3703 $filterViewPermission = " h.hdp_uni_id IN(" . implode($aAccountList, ',') . ")";
3704 }
3705 } elseif (in_array('2', $permission) && (count($aMyUnits) > 0))
3706 { // 2-My account
3707 if ($filterViewPermission != '')
3708 {
3709 $filterViewPermission .= " OR h.hdp_uni_id IN(" . implode($aMyUnits, ',') . ")";
3710 } else
3711 {
3712 $filterViewPermission = " h.hdp_uni_id IN(" . implode($aMyUnits, ',') . ")";
3713 }
3714 } elseif (in_array('3', $permission) && (count($aMultipleUnits) > 0))
3715 { // 3-Multiple account
3716 if ($filterViewPermission != '')
3717 {
3718 $filterViewPermission .= " OR h.hdp_uni_id IN(" . implode($aMultipleUnits, ',') . ")";
3719 } else
3720 {
3721 $filterViewPermission = " h.hdp_uni_id IN(" . implode($aMultipleUnits, ',') . ")";
3722 }
3723 }
3724 } //
3725
3726 if ($from != null)
3727 {
3728 //$from = str_replace("/", "-", $from);
3729 $from = convertDate::getMsqlDateFormat($from);
3730
3731 if ($type != null)
3732 {
3733 if ($type != "all")
3734 {
3735 $sFilter = $sFilter . " h.hdp_applied_sanction_id = " . $type . " AND ";
3736 }
3737 }
3738
3739 if ($to != null)
3740 {
3741 //$to = str_replace("/", "-", $to);
3742 $to = convertDate::getMsqlDateFormat($to);
3743 $sFilter = $sFilter . " (h.hdp_emission_date >= '" . date('Y-m-d', strtotime($from)) . "' AND h.hdp_emission_date <= '" . date('Y-m-d', strtotime($to)) . "')";
3744 } else
3745 {
3746 $sFilter = $sFilter . " h.hdp_emission_date >= '" . date('Y-m-d', strtotime($from)) . "'";
3747 }
3748
3749 if (($filterViewPermission != '') && ($sFilter != ''))
3750 {
3751 $sFilter .= ' AND ' . $filterViewPermission;
3752 } else if ($sFilter == '')
3753 {
3754 $sFilter = $filterViewPermission;
3755 }
3756 // *************************************************************************************
3757
3758 $sql = "SELECT IF(TBL.hdp_dgs_status = 1, 'Open', IF(TBL.hdp_dgs_status = 2, 'Closed', IF(TBL.hdp_dgs_status = 3, 'Invalid', 'N/A'))) AS GLOBAL_STATUS,
3759 TBL.*, c.dst_name AS STATE, DATE_FORMAT(TBL.hdp_incident_date,'" . sfConfig::get('irdp_dateformat_database') . "') AS hdp_incident_date,
3760 DATE_FORMAT(TBL.hdp_emission_date,'" . sfConfig::get('irdp_dateformat_database') . "') AS hdp_emission_date,
3761 DATE_FORMAT(TBL.hdp_expiration_date,'" . sfConfig::get('irdp_dateformat_database') . "') AS hdp_expiration_date, p.dpc_form_id
3762 FROM (
3763 SELECT h.*, MAX(s.dph_id) AS LAST_STATE_ID
3764 FROM idt_history_disciplinary_process h
3765 INNER JOIN idt_disciplinary_process_state_history s ON s.dph_dpc_id = h.hdp_dpc_id
3766 WHERE " . $sFilter . "
3767 GROUP BY h.hdp_dpc_id
3768 ORDER BY LAST_STATE_ID
3769 ) AS TBL
3770 INNER JOIN idt_disciplinary_process_state_history s2 ON s2.dph_id = TBL.LAST_STATE_ID
3771 INNER JOIN idt_disciplinary_process_states_catalog c ON c.dst_id = s2.dph_dst_id
3772 INNER JOIN idt_disciplinary_process p ON p.dpc_id = TBL.hdp_dpc_id
3773 WHERE p.dpc_usr_empid !=" . $oUser->getAttribute('id');
3774 //echo $sql;
3775
3776 $aReport = Doctrine_Manager::getInstance()->getCurrentConnection()->execute($sql)->fetchAll();
3777 } else
3778 {
3779 $bError = true;
3780 $sErrorMsg = __("A start date must be provided.");
3781 }
3782
3783 return array('error' => $bError, 'error_msg' => $sErrorMsg, 'data' => $aReport);
3784 }
3785
3786 /*
3787 * Get Legal Document Data
3788 *
3789 * @params date from Start date
3790 * @params date to End date
3791 * @return array Data returned by query
3792 *
3793 */
3794
3795
3796 public function executeGetlegaldocfields(sfWebRequest $request)
3797 {
3798 $bError = false;
3799 $sErrorMsg = '';
3800
3801 /* Check that */
3802 $this->forward404If($request->getParameter('id') == null, __("Document id cannot be null"));
3803 $this->forward404If($request->getParameter('dp') == null, __("Hint Process id cannot be null"));
3804
3805 /* Get user and employee pin */
3806 $this->aEmployee = $aEmployee = Doctrine_Core::getTable('IdtDisciplinaryProcess')
3807 ->createQuery('d')
3808 ->innerJoin('d.IdtUsers u ON d.dpc_usr_empid = u.usr_empid')
3809 ->where('d.dpc_id =?', array($request->getParameter('dp')))
3810 ->limit('1')
3811 ->fetchArray();
3812
3813 $this->aUser = Doctrine_Core::getTable('IdtUsers')
3814 ->createQuery('u')
3815 ->where('u.usr_empid =?', array($this->getUser()->getAttribute('id')))
3816 ->fetchArray();
3817
3818 // ----------------------------------------------------------------------------------------------------------------
3819 // Here gets the Site Address List Information to add dropdown options to change the locations in legal document.
3820 // Only filter locations than: sit_display_in_legaldoc == 1
3821 // This values be returned to: iranddp\apps\frontend\modules\dp\templates\editSuccess.php view
3822 // @@ if need update locations available list please go to: backend.php/catalogs/sites
3823 // @@ from backend main menu: Settings >> Catalogs >> Sites
3824 // @@ use a backend variable: use_locations_address = 1
3825 // ------------------------------------------------------------------------------------------------------------------
3826 $optionSiteList = "none";
3827 if ((sfConfig::get('irdp_use_locations_address') == 1) || (sfConfig::get('irdp_use_locations_address') == true))
3828 {
3829 /* Get site information list */
3830 $siteList = Doctrine_Core::getTable('IdtSites')
3831 ->createQuery('s')
3832 ->where('s.sit_display_in_legaldoc =?', 1)
3833 ->fetchArray();
3834 if (count($siteList) > 0)
3835 {
3836 //$optionSiteList = "";
3837 //if ($aEmployee[0]['dpc_site_id'] == NULL){
3838 $optionSiteList = "<option value='' disabled selected>" . __('Please select a location from the list...') . "</option>";
3839 //}
3840 foreach ($siteList as $value)
3841 {
3842 $isSelected = $aEmployee[0]['dpc_site_id'] == $value['sit_id'] ? 'selected' : '';
3843 $optionSiteList.= "<option value='{$value['sit_id']}' data-address='{$value['sit_address']}' {$isSelected} >{$value['sit_name']}</option>";
3844 }
3845 } else
3846 {
3847 $optionSiteList = "void_list";
3848 }
3849 }
3850
3851 // ------------------------------------- End changes -------------------------------------
3852
3853 $iUserPin = '';
3854 $iEmployeePin = '';
3855 $sComment1 = '';
3856 $sComment2 = '';
3857 $sCommentSup = '';
3858 $sWitnessName = '';
3859 $sWitnessDoc = '';
3860
3861 if (count($this->aEmployee) > 0)
3862 {
3863 $iUserPin = $this->aEmployee[0]['IdtUsers']['usr_identity_doc_number'];
3864 $sComment1 = $this->aEmployee[0]['dpc_ldoc_comment1'];
3865 $sComment2 = $this->aEmployee[0]['dpc_ldoc_comment2'];
3866 $sCommentSup = $this->aEmployee[0]['dpc_sup_comment'];
3867 $sWitnessName = $this->aEmployee[0]['dpc_additional_witness'];
3868 $sWitnessDoc = $this->aEmployee[0]['dpc_add_witness_document'];
3869 } else
3870 {
3871 $bError = true;
3872 $sErrorMsg = __("Employee information couldn't be retrieved");
3873 }
3874
3875 if (count($this->aUser) > 0)
3876 {
3877 $iEmployeePin = $this->aUser[0]['usr_identity_doc_number'];
3878 } else
3879 {
3880 $bError = true;
3881 $sErrorMsg = __("User information couldn't be retrieved");
3882 }
3883
3884 error_reporting(0);
3885
3886 $encoded = json_encode(array(
3887 'error' => $bError,
3888 'error_msg' => $sErrorMsg,
3889 'emp_pin' => $iUserPin,
3890 'usr_pin' => $iEmployeePin,
3891 'comment1' => $sComment1,
3892 'comment2' => $sComment2,
3893 'commentsup' => $sCommentSup,
3894 'witnessName' => $sWitnessName,
3895 'witnessDoc' => $sWitnessDoc,
3896 'optionSiteList' => $optionSiteList
3897 ));
3898
3899 $this->getResponse()->setContent($encoded);
3900
3901 return(sfView::NONE);
3902 }
3903
3904 public function executeGetUserCulture(){
3905 $data = array();
3906 $data['lang']=sfContext::getInstance()->getUser()->getAttribute('language');
3907 $this->getResponse()->setContent(json_encode($data));
3908 return(sfView::NONE);
3909 }
3910 /**
3911 * Executes userinfo
3912 * First step - retrieve user information
3913 *
3914 *
3915 * @param sfRequest $request A request object
3916 */
3917 public function executeSenmailnot(sfWebRequest $request)
3918 {
3919 $mail = new PhpMailerNotif();
3920 $message = '<html><body>';
3921 $message .= "<span style='font-size:14pt;font-family:Arial;color:rgb(73,22,109);background-color:transparent;font-weight:700;vertical-align:baseline;white-space:pre-wrap'>Hints for Success Tracker </span><br><br>";
3922 $message .= "<span style='font-size:10pt;font-family:Arial;color:rgb(102,102,102);background-color:transparent;vertical-align:baseline;white-space:pre-wrap'><br>The following DP has been created.<br>Details:<br><br></span><br><br>";
3923 $message .= '<table rules="all" width="100%" style="border-color: #8c68a6;" cellpadding="10">';
3924 $message .= "<tr style='background: #72CF0C; color:#FFF;'><td><strong>Hint Number:</strong> </td><td>DP12121</td></tr>";
3925 $message .= "<tr style='color:#666666;'><td><strong>Employee Name:</strong> </td><td>Francisco Toche</td></tr>";
3926 $message .= "<tr style='color:#666666;'><td><strong>Unit:</strong> </td><td>Information Services</td></tr>";
3927 $message .= "<tr style='color:#666666;'><td><strong>Position:</strong> </td><td>Software Developer</td></tr>";
3928 $message .= "<tr style='color:#666666;'><td><strong>Supervisor:</strong> </td><td>Maria Velasco</td></tr>";
3929 $message .= "</table>";
3930 $message .= "</body></html>";
3931 $aIdtNotification = Doctrine_Query::create()
3932 ->select('n.not_usr_email')
3933 ->from('IdtNotification n')
3934 ->where('n.not_active = ?', array(1))
3935 ->fetchArray();
3936 $aRecipients = array();
3937 foreach ($aIdtNotification as $key => $reminders_active) {
3938 $aRecipients[] = $reminders_active['not_usr_email'];
3939 }
3940 $mail->sendNotificationEmail($message, array(''));
3941 }
3942}