dolibarr 25.0.0-alpha
card_group.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2011 Dimitri Mouillard <dmouillard@teclib.com>
3 * Copyright (C) 2012-2016 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2012-2016 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
6 * Copyright (C) 2017-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
7 * Copyright (C) 2014-2017 Ferran Marcet <fmarcet@2byte.es>
8 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
9 * Copyright (C) 2020-2021 Udo Tamm <dev@dolibit.de>
10 * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
11 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 3 of the License, orwrite
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 */
26
33// Load Dolibarr environment
34require '../main.inc.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
46require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
48require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
49require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
50require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
51require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
52require_once DOL_DOCUMENT_ROOT.'/core/lib/holiday.lib.php';
53require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
54
55
56// Get parameters
57$action = GETPOST('action', 'aZ09');
58$cancel = GETPOST('cancel', 'alpha');
59$confirm = GETPOST('confirm', 'alpha');
60$backtopage = GETPOST('backtopage', 'alpha'); // if not set, a default page will be used
61$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); // if not set, $backtopage will be used
62
63$id = GETPOSTINT('id');
64$ref = GETPOST('ref', 'alpha');
65$fuserid = (GETPOSTINT('fuserid') ? GETPOSTINT('fuserid') : $user->id);
66$users = (GETPOST('users', 'array') ? GETPOST('users', 'array') : array($user->id));
67$groups = GETPOST('groups', 'array');
68$socid = GETPOSTINT('socid');
69$autoValidation = GETPOSTINT('autoValidation');
70$AutoSendMail = GETPOSTINT('AutoSendMail');
71
72// Load translation files required by the page
73$langs->loadLangs(array("other", "holiday", "mails", "trips"));
74
75$error = 0;
76
77$now = dol_now();
78
79$childids = $user->getAllChildIds(1);
80
81$morefilter = '';
82if (getDolGlobalString('HOLIDAY_HIDE_FOR_NON_SALARIES')) {
83 $morefilter = 'AND employee = 1';
84}
85
86$object = new Holiday($db);
87
88// fetch optionals attributes and labels
89$extrafields->fetch_name_optionals_label($object->table_element);
90
91if (($id > 0) || $ref) {
92 $object->fetch($id, $ref);
93
94 // Check current user can read this leave request
95 $canread = 0;
96 if ($user->hasRight('holiday', 'readall')) {
97 $canread = 1;
98 }
99 if ($user->hasRight('holiday', 'read') && in_array($object->fk_user, $childids)) {
100 $canread = 1;
101 }
102 if (!$canread) {
104 }
105}
106
107// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
108$hookmanager->initHooks(array('holidaycard', 'globalcard'));
109
110$permissiontoadd = 0;
111$permissiontoaddall = 0;
112if ($user->hasRight('holiday', 'write') && in_array($fuserid, $childids)) {
113 $permissiontoadd = 1;
114}
115if ($user->hasRight('holiday', 'writeall')) {
116 $permissiontoadd = 1;
117 $permissiontoaddall = 1;
118}
119
120$candelete = 0;
121if ($user->hasRight('holiday', 'delete')) {
122 $candelete = 1;
123}
124if ($object->status == Holiday::STATUS_DRAFT && $user->hasRight('holiday', 'write') && in_array($object->fk_user, $childids)) {
125 $candelete = 1;
126}
127
128// Protection if external user
129if ($user->socid) {
130 $socid = $user->socid;
131}
132$result = restrictedArea($user, 'holiday', $object->id, 'holiday', '', '', 'rowid', $object->status);
133
134// A collective leave request is created for any users and groups, so it needs the permission to create leave requests for everybody (the form is shown only with it)
135if ($action == 'add' && !$user->hasRight('holiday', 'writeall')) {
137}
138
139
140/*
141 * Actions
142 */
143
144$parameters = array('socid' => $socid);
145$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
146if ($reshook < 0) {
147 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
148}
149
150if (empty($reshook)) {
151 $backurlforlist = DOL_URL_ROOT.'/holiday/list.php';
152
153 if (empty($backtopage) || ($cancel && empty($id))) {
154 if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
155 if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
156 $backtopage = $backurlforlist;
157 } else {
158 $backtopage = DOL_URL_ROOT.'/holiday/card_group.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
159 }
160 }
161 }
162
163 if ($cancel) {
164 if (!empty($backtopageforcancel)) {
165 header("Location: ".$backtopageforcancel);
166 exit;
167 } elseif (!empty($backtopage)) {
168 header("Location: ".$backtopage);
169 exit;
170 }
171 $action = '';
172 }
173
174 // Add leave request
175 if ($action == 'add' && $permissiontoadd) {
176 $users = GETPOST('users', 'array');
177 $groups = GETPOST('groups', 'array');
178
179 $date_debut = dol_mktime(0, 0, 0, GETPOSTINT('date_debut_month'), GETPOSTINT('date_debut_day'), GETPOSTINT('date_debut_year'));
180 $date_fin = dol_mktime(0, 0, 0, GETPOSTINT('date_fin_month'), GETPOSTINT('date_fin_day'), GETPOSTINT('date_fin_year'));
181 $date_debut_gmt = dol_mktime(0, 0, 0, GETPOSTINT('date_debut_month'), GETPOSTINT('date_debut_day'), GETPOSTINT('date_debut_year'), 1);
182 $date_fin_gmt = dol_mktime(0, 0, 0, GETPOSTINT('date_fin_month'), GETPOSTINT('date_fin_day'), GETPOSTINT('date_fin_year'), 1);
183 $starthalfday = GETPOST('starthalfday');
184 $endhalfday = GETPOST('endhalfday');
185 $type = GETPOSTINT('type');
186
187 $halfday = 0;
188 if ($starthalfday == 'afternoon' && $endhalfday == 'morning') {
189 $halfday = 2;
190 } elseif ($starthalfday == 'afternoon') {
191 $halfday = -1;
192 } elseif ($endhalfday == 'morning') {
193 $halfday = 1;
194 }
195
196 $approverid = GETPOSTINT('valideur');
197 $description = trim(GETPOST('description', 'restricthtml'));
198
199 // Check that leave is for a user inside the hierarchy or advanced permission for all is set
200 if (!$permissiontoaddall) {
201 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
202 if (!$user->hasRight('holiday', 'write')) {
203 $error++;
204 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
205 } elseif (!in_array($fuserid, $childids)) {
206 $error++;
207 setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
208 $action = 'create';
209 }
210 } else {
211 if (!$user->hasRight('holiday', 'write') && !$user->hasRight('holiday', 'writeall')) {
212 $error++;
213 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
214 } elseif (!$user->hasRight('holiday', 'writeall') && !in_array($fuserid, $childids)) {
215 $error++;
216 setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
217 $action = 'create';
218 }
219 }
220 }
221 // If no groups and no users
222 if (empty($groups) && empty($users)) {
223 setEventMessages($langs->trans("ErrorFieldRequiredUserOrGroup"), null, 'errors');
224 //setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UserOrGroup")), null, 'errors');
225 //setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Group")), null, 'errors');
226 $error++;
227 $action = 'create';
228 }
229 // If no type
230 if ($type <= 0) {
231 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
232 $error++;
233 $action = 'create';
234 }
235
236 // If no start date
237 if (empty($date_debut)) {
238 setEventMessages($langs->trans("NoDateDebut"), null, 'errors');
239 $error++;
240 $action = 'create';
241 }
242 // If no end date
243 if (empty($date_fin)) {
244 setEventMessages($langs->trans("NoDateFin"), null, 'errors');
245 $error++;
246 $action = 'create';
247 }
248 // If start date after end date
249 if ($date_debut > $date_fin) {
250 setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors');
251 $error++;
252 $action = 'create';
253 }
254
255 // If there is no Business Days within request
256 $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday, $mysoc->country_id);
257 if ($nbopenedday < 0.5) {
258 setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); // No working day
259 $error++;
260 $action = 'create';
261 }
262
263 // If no validator designated
264 if ($approverid < 1) {
265 setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors');
266 $error++;
267 }
268
269 $result = 0;
270
271
272 if (!$error) {
273 $TusersToProcess = array();
274 // usergroup select
275 // better perf on single sql
277 if (is_array($groups) && count($groups) > 0) {
278 $sql = ' SELECT DISTINCT u.rowid,u.lastname,u.firstname from ' . MAIN_DB_PREFIX . 'user as u';
279 $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'usergroup_user as ug on ug.fk_user = u.rowid ';
280 $sql .= ' WHERE fk_usergroup in (' .$db->sanitize(implode(',', $groups)) . ')';
281 $resql = $db->query($sql);
282
283 if ($resql) {
284 while ($obj = $db->fetch_object($resql)) {
285 $TusersToProcess[$obj->rowid] = $obj->rowid;
286 }
287 }
288 }
290 if (is_array($users) && count($users) > 0) {
291 foreach ($users as $u) {
292 $TusersToProcess[$u] = $u;
293 }
294 }
295 foreach ($TusersToProcess as $u) {
296 // Check if there is already holiday for this period for each user
297 $verifCP = $object->verifDateHolidayCP($u, $date_debut, $date_fin, $halfday);
298 if (!$verifCP) {
299 //setEventMessages($langs->trans("alreadyCPexist"), null, 'errors');
300
301 $userError = new User($db);
302 $result = $userError->fetch($u);
303
304 if ($result) {
305 setEventMessages($langs->trans("UseralreadyCPexist", $userError->firstname . ' '. $userError->lastname), null, 'errors');
306 } else {
307 setEventMessages($langs->trans("ErrorUserFetch", $u), null, 'errors');
308 }
309
310 $error++;
311 $action = 'create';
312 }
313 }
314
315 if (!$error) {
316 $db->begin();
317 // non errors we can insert all
318 foreach ($TusersToProcess as $u) {
319 $object = new Holiday($db);
320 $object->fk_user = $u;
321 $object->description = $description;
322 $object->fk_validator = $approverid;
323 $object->fk_type = $type;
324 $object->date_debut = $date_debut;
325 $object->date_fin = $date_fin;
326 $object->halfday = $halfday;
327
328 $result = $object->create($user);
329
330 if ($result <= 0) {
331 setEventMessages($object->error, $object->errors, 'errors');
332 $error++;
333 } else {
334 if ($autoValidation) {
335 $htemp = new Holiday($db);
336 $htemp->fetch($result);
337
338 $htemp->status = Holiday::STATUS_VALIDATED;
339 $approver = new User($db);
340 $approver->fetch($approverid);
341 $resultValidated = $htemp->validate($approver);
342
343 if ($resultValidated < 0) {
344 setEventMessages($object->error, $object->errors, 'errors');
345 $error++;
346 }
347 // we can auto send mail if we are in auto validation behavior
348
349 if ($AutoSendMail && !$error) {
350 // send a mail to the user
351 $returnSendMail = sendMail($result, $permissiontoadd, $now, $autoValidation);
352 if (!empty($returnSendMail->msg)) {
353 setEventMessage($returnSendMail->msg, $returnSendMail->style);
354 }
355 }
356 }
357 }
358 }
359 }
360 // If no SQL error we redirect to the request card
361 if (!$error) {
362 $db->commit();
363 header('Location: '.DOL_URL_ROOT.'/holiday/list.php');
364 exit;
365 } else {
366 $db->rollback();
367 }
368 }
369 }
370}
371
372
373
374/*
375 * View
376 */
377
378$form = new Form($db);
379$object = new Holiday($db);
380
381$listhalfday = array('morning' => $langs->trans("Morning"), "afternoon" => $langs->trans("Afternoon"));
382
383$title = $langs->trans('Leave');
384$help_url = 'EN:Module_Holiday';
385$errors = array();
386
387llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-holiday page-card_group');
388
389if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') {
390 // If user has no permission to create a leave
391 if ((in_array($fuserid, $childids) && !$user->hasRight('holiday', 'writeall')) || (!in_array($fuserid, $childids) && (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || !$user->hasRight('holiday', 'writeall')))) {
392 $errors[] = $langs->trans('CantCreateCP');
393 } else {
394 // Form to add a leave request
395 print load_fiche_titre($langs->trans('MenuCollectiveAddCP'), '', 'title_hrm.png');
396
397 // Error management
398 if (GETPOST('error')) {
399 switch (GETPOST('error')) {
400 case 'datefin':
401 $errors[] = $langs->trans('ErrorEndDateCP');
402 break;
403 case 'SQL_Create':
404 $errors[] = $langs->trans('ErrorSQLCreateCP');
405 break;
406 case 'CantCreate':
407 $errors[] = $langs->trans('CantCreateCP');
408 break;
409 case 'Valideur':
410 $errors[] = $langs->trans('InvalidValidatorCP');
411 break;
412 case 'nodatedebut':
413 $errors[] = $langs->trans('NoDateDebut');
414 break;
415 case 'nodatefin':
416 $errors[] = $langs->trans('NoDateFin');
417 break;
418 case 'DureeHoliday':
419 $errors[] = $langs->trans('ErrorDureeCP');
420 break;
421 case 'alreadyCP':
422 $errors[] = $langs->trans('alreadyCPexist');
423 break;
424 }
425
426 setEventMessages('', $errors, 'errors');
427 }
428
429
430 print '<script type="text/javascript">
431 $( document ).ready(function() {
432
433 if( $("input[name=autoValidation]").is(":checked") ){
434 $("#AutoSendMail").prop("disabled", false);
435 $("#AutoSendMail").prop("checked", true);
436
437 } else {
438 $("#AutoSendMail").prop("disabled", true);
439 $("#AutoSendMail").prop("checked", false);
440 }
441
442 $("input[name=autoValidation]").click( function(e) {
443
444
445 if( $("input[name=autoValidation]").is(":checked") ){
446 $("#AutoSendMail").prop("disabled", false);
447 $("#AutoSendMail").prop("checked", true);
448 } else {
449 $("#AutoSendMail").prop("disabled", true);
450 $("#AutoSendMail").prop("checked", false);
451 }
452 });
453
454
455
456 $("input.button-save").click("submit", function(e) {
457 console.log("Call valider()");
458 if (document.demandeCP.date_debut_.value != "")
459 {
460 if(document.demandeCP.date_fin_.value != "")
461 {
462 if(document.demandeCP.valideur.value != "-1") {
463 return true;
464 }
465 else {
466 alert(\''.dol_escape_js($langs->transnoentities('InvalidValidatorCP')).'\');
467 return false;
468 }
469 }
470 else
471 {
472 alert(\''.dol_escape_js($langs->transnoentities('NoDateFin')).'\');
473 return false;
474 }
475 }
476 else
477 {
478 alert(\''.dol_escape_js($langs->transnoentities('NoDateDebut')).'\');
479 return false;
480 }
481 })
482
483 $("#autoValidation").change(function(){
484 if( $("input[name=autoValidation]").is(":checked") ){
485 $("#AutoSendMail").prop("disabled", false);
486 } else {
487 $("#AutoSendMail").prop("disabled", true);
488 $("#AutoSendMail").prop("checked", false);
489 }
490 })
491 });
492 </script>'."\n";
493
494
495 // Leave request form
496 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" name="demandeCP">'."\n";
497 print '<input type="hidden" name="token" value="'.newToken().'" />'."\n";
498 print '<input type="hidden" name="action" value="add" />'."\n";
499
500 print dol_get_fiche_head();
501
502 print '<table class="border centpercent">';
503 print '<tbody>';
504
505 // Groups of users
506 print '<tr>';
507 print '<td class="titlefield fieldrequired">';
508 print $form->textwithpicto($langs->trans("groups"), $langs->trans("fusionGroupsUsers"));
509 print '</td>';
510 print '<td>';
511 print img_picto($langs->trans("groups"), 'group', 'class="pictofixedwidth"');
512
513 $sql = ' SELECT rowid, nom from '.MAIN_DB_PREFIX.'usergroup WHERE entity IN ('.getEntity('usergroup').')';
514 $resql = $db->query($sql);
515 $Tgroup = array();
516 while ($obj = $db->fetch_object($resql)) {
517 $Tgroup[$obj->rowid] = $obj->nom;
518 }
519
520 print $form->multiselectarray('groups', $Tgroup, GETPOST('groups', 'array'), 0, 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
521
522 print '</td>';
523
524 // Users
525 print '<tr>';
526 print '<td class="titlefield fieldrequired">';
527 print $form->textwithpicto($langs->trans("users"), $langs->trans("fusionGroupsUsers"));
528 print '<td>';
529 print img_picto($langs->trans("users"), 'user', 'class="pictofixedwidth"');
530
531 $sql = 'SELECT u.rowid, u.lastname, u.firstname, u.login, u.photo FROM '.MAIN_DB_PREFIX.'user as u';
532 $sql .= ' WHERE 1 = 1';
533 $sql .= empty($morefilter) ? '' : $morefilter;
534
535 $userlist = array();
536 $userstatic = new User($db);
537
538 $resql = $db->query($sql);
539 if ($resql) {
540 while ($obj = $db->fetch_object($resql)) {
541 $userstatic->id = $obj->rowid;
542 $userstatic->login = $obj->login;
543 $userstatic->firstname = $obj->firstname;
544 $userstatic->lastname = $obj->lastname;
545 $userstatic->photo = $obj->photo;
546
547 $userlist[$obj->rowid] = array(
548 'id' => $obj->rowid,
549 'label' => dolGetFirstLastname($obj->firstname, $obj->lastname),
550 'data-html' => $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' '.dolGetFirstLastname($obj->firstname, $obj->lastname)
551 );
552 }
553 }
554
555 print img_picto('', 'users', 'class="pictofixedwidth"') . $form->multiselectarray('users', $userlist, GETPOST('users', 'array'), 0, 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
556 print '</td>';
557
558 // Type
559 print '<tr>';
560 print '<td class="fieldrequired">'.$langs->trans("Type").'</td>';
561 print '<td>';
562 $typeleaves = $object->getTypes(1, -1);
563 $arraytypeleaves = array();
564 foreach ($typeleaves as $key => $val) {
565 $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']);
566 $labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')' : '');
567 $arraytypeleaves[$val['rowid']] = $labeltoshow;
568 }
569 print $form->selectarray('type', $arraytypeleaves, (GETPOST('type', 'alpha') ? GETPOST('type', 'alpha') : ''), 1, 0, 0, '', 0, 0, 0, '', '', 1);
570 if ($user->admin) {
571 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
572 }
573 print '</td>';
574 print '</tr>';
575
576 // Date start
577 print '<tr>';
578 print '<td class="fieldrequired">';
579 print $form->textwithpicto($langs->trans("DateDebCP"), $langs->trans("FirstDayOfHoliday"));
580 print '</td>';
581 print '<td>';
582 // If the request does not come from the agenda
583 if (!GETPOST('date_debut_')) {
584 print $form->selectDate(-1, 'date_debut_', 0, 0, 0, '', 1, 1);
585 } else {
586 $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_debut_month'), GETPOSTINT('date_debut_day'), GETPOSTINT('date_debut_year'));
587 print $form->selectDate($tmpdate, 'date_debut_', 0, 0, 0, '', 1, 1);
588 }
589 print ' &nbsp; &nbsp; ';
590 print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday', 'alpha') ? GETPOST('starthalfday', 'alpha') : 'morning'));
591 print '</td>';
592 print '</tr>';
593
594 // Date end
595 print '<tr>';
596 print '<td class="fieldrequired">';
597 print $form->textwithpicto($langs->trans("DateFinCP"), $langs->trans("LastDayOfHoliday"));
598 print '</td>';
599 print '<td>';
600 if (!GETPOST('date_fin_')) {
601 print $form->selectDate(-1, 'date_fin_', 0, 0, 0, '', 1, 1);
602 } else {
603 $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_fin_month'), GETPOSTINT('date_fin_day'), GETPOSTINT('date_fin_year'));
604 print $form->selectDate($tmpdate, 'date_fin_', 0, 0, 0, '', 1, 1);
605 }
606 print ' &nbsp; &nbsp; ';
607 print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday', 'alpha') ? GETPOST('endhalfday', 'alpha') : 'afternoon'));
608 print '</td>';
609 print '</tr>';
610
611 // Approver
612 print '<tr>';
613 print '<td class="fieldrequired">'.$langs->trans("ReviewedByCP").'</td>';
614 print '<td>';
615
616 $object = new Holiday($db);
617 $include_users = $object->fetch_users_approver_holiday();
618 if (empty($include_users)) {
619 print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays");
620 } else {
621 // Defined default approver (the forced approver of user or the supervisor if no forced value defined)
622 // Note: This use will be set only if the defined approver has permission to approve so is inside include_users
623 $defaultselectuser = (empty($user->fk_user_holiday_validator) ? $user->fk_user : $user->fk_user_holiday_validator);
624 if (getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR')) {
625 $defaultselectuser = getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR'); // Can force default approver
626 }
627 if (GETPOSTINT('valideur') > 0) {
628 $defaultselectuser = GETPOSTINT('valideur');
629 }
630 $s = $form->select_dolusers($defaultselectuser, "valideur", 1, null, 0, $include_users, '', '0,'.$conf->entity, 0, 0, '', 0, '', 'minwidth200 maxwidth500');
631 print img_picto('', 'user').$form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
632 }
633
634
635 print '</td>';
636 print '</tr>';
637
638 //auto validation ON CREATE
639 print '<tr><td>'.$langs->trans("AutoValidationOnCreate").'</td><td>';
640 print '<input type="checkbox" id="autoValidation" name="autoValidation" value="1"'.($autoValidation ? ' checked="checked"' : '').'>';
641 print '</td></tr>'."\n";
642
643
644 //no auto SEND MAIL
645 print '<tr><td>'.$langs->trans("AutoSendMail").'</td><td>';
646 print '<input type="checkbox" id="AutoSendMail" name="AutoSendMail" value="1"'.($AutoSendMail ? ' checked="checked"' : '').'>';
647 print '</td></tr>'."\n";
648
649 // Description
650 print '<tr>';
651 print '<td>'.$langs->trans("DescCP").'</td>';
652 print '<td class="tdtop">';
653 $doleditor = new DolEditor('description', GETPOST('description', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor'), ROWS_3, '90%');
654 print $doleditor->Create(1);
655 print '</td></tr>';
656
657 // Other attributes
658 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
659
660 print '</tbody>';
661 print '</table>';
662
663 print dol_get_fiche_end();
664
665 print $form->buttonsSaveCancel("SendRequestCollectiveCP");
666
667 print '</from>'."\n";
668 }
669} else {
670 if ($error) {
671 print '<div class="tabBar">';
672 print $error;
673 print '<br><br><input type="button" value="'.$langs->trans("ReturnCP").'" class="button" onclick="history.go(-1)" />';
674 print '</div>';
675 }
676}
677
678// End of page
679llxFooter();
680
681if (is_object($db)) {
682 $db->close();
683}
684
696function sendMail($id, $cancreate, $now, $autoValidation)
697{
698 $objStd = new stdClass();
699 $objStd->msg = '';
700 $objStd->status = 'success';
701 $objStd->error = 0;
702 $objStd->style = '';
703
704 global $db, $user, $langs;
705
706 $object = new Holiday($db);
707
708 $result = $object->fetch($id);
709
710 if ($result) {
711 // If draft and owner of leave
712 if ($object->status == Holiday::STATUS_VALIDATED && $cancreate) {
713 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
714
715 //if ($autoValidation) $object->status = Holiday::STATUS_VALIDATED;
716
717 $verif = $object->validate($user);
718
719 if ($verif > 0) {
720 // To
721 $destinataire = new User($db);
722 $destinataire->fetch($object->fk_validator);
723 $emailTo = $destinataire->email;
724
725
726 if (!$emailTo) {
727 dol_syslog("Expected validator has no email, so we redirect directly to finished page without sending email");
728
729 $objStd->error++;
730 $objStd->msg = $langs->trans('ErrorMailRecipientIsEmpty');
731 $objStd->status = 'error';
732 $objStd->style = "warnings";
733 return $objStd;
734 }
735
736 // From
737 $expediteur = new User($db);
738 $expediteur->fetch($object->fk_user);
739
740 //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
741 $emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
742
743 // Subject
744 $societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
745 if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
746 $societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
747 }
748
749 $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysToValidate");
750
751 // Content
752 $message = "<p>".$langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",</p>\n";
753
754 $message .= "<p>".$langs->transnoentities("HolidaysToValidateBody")."</p>\n";
755
756
757 // option to warn the validator in case of too short delay
758 if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_TOO_LOW_DELAY')) {
759 $delayForRequest = 0; // TODO Set delay depending of holiday leave type
760 if ($delayForRequest) {
761 $nowplusdelay = dol_time_plus_duree($now, $delayForRequest, 'd');
762
763 if ($object->date_debut < $nowplusdelay) {
764 $message = "<p>".$langs->transnoentities("HolidaysToValidateDelay", $delayForRequest)."</p>\n";
765 }
766 }
767 }
768
769 // option to notify the validator if the balance is less than the request
770 // (only for leave types that actually use the balance counter)
771 if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_NEGATIVE_BALANCE')) {
772 $affectingtypes = $object->getTypes(1, 1);
773 if (!empty($affectingtypes[$object->fk_type])) {
774 $nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday, $expediteur->country_id, $object->fk_user);
775
776 if ($nbopenedday > $object->getCPforUser($object->fk_user, $object->fk_type)) {
777 $message .= "<p>".$langs->transnoentities("HolidaysToValidateAlertSolde")."</p>\n";
778 }
779 }
780 }
781
782 $typeleaves = $object->getTypes(1, -1);
783 $labeltoshow = (($typeleaves[$object->fk_type]['code'] && $langs->trans($typeleaves[$object->fk_type]['code']) != $typeleaves[$object->fk_type]['code']) ? $langs->trans($typeleaves[$object->fk_type]['code']) : $typeleaves[$object->fk_type]['label']);
784
785 if ($object->halfday == 2) {
786 $starthalfdaykey = "Afternoon";
787 $endhalfdaykey = "Morning";
788 } elseif ($object->halfday == -1) {
789 $starthalfdaykey = "Afternoon";
790 $endhalfdaykey = "Afternoon";
791 } elseif ($object->halfday == 1) {
792 $starthalfdaykey = "Morning";
793 $endhalfdaykey = "Morning";
794 } elseif ($object->halfday == 0 || $object->halfday == 2) {
795 $starthalfdaykey = "Morning";
796 $endhalfdaykey = "Afternoon";
797 } else {
798 // For static analysis, ensure variables are defined
799 $starthalfdaykey = "InvalidHalfday";
800 $endhalfdaykey = "InvalidHalfday";
801 }
802
803 $link = dol_buildpath("/holiday/card.php", 3) . '?id='.$object->id;
804
805 $message .= "<ul>";
806 $message .= "<li>".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."</li>\n";
807 $message .= "<li>".$langs->transnoentitiesnoconv("Type")." : ".(empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow)."</li>\n";
808 $message .= "<li>".$langs->transnoentitiesnoconv("Period")." : ".dol_print_date($object->date_debut, 'day')." ".$langs->transnoentitiesnoconv($starthalfdaykey)." ".$langs->transnoentitiesnoconv("To")." ".dol_print_date($object->date_fin, 'day')." ".$langs->transnoentitiesnoconv($endhalfdaykey)."</li>\n";
809 $message .= "<li>".$langs->transnoentitiesnoconv("Link").' : <a href="'.$link.'" target="_blank">'.$link."</a></li>\n";
810 $message .= "</ul>\n";
811
812 $trackid = 'leav'.$object->id;
813
814 $sendtobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_HOLIDAY_TO');
815
816 $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', $sendtobcc, 0, 1, '', '', $trackid);
817
818 // Sending the email
819 $result = $mail->sendfile();
820
821 if (!$result) {
822 $objStd->error++;
823 $objStd->msg = $langs->trans('ErrorMailNotSend');
824 $objStd->style = "warnings";
825 $objStd->status = 'error';
826 } else {
827 $objStd->msg = $langs->trans('MailSent');
828 }
829
830 return $objStd;
831 } else {
832 $objStd->error++;
833 $objStd->msg = $langs->trans('ErrorVerif');
834 $objStd->status = 'error';
835 $objStd->style = "errors";
836 return $objStd;
837 }
838 }
839 } else {
840 $objStd->error++;
841 $objStd->msg = $langs->trans('ErrorloadUserOnSendingMail');
842 $objStd->status = 'error';
843 $objStd->style = "warnings";
844 return $objStd;
845 }
846
847 return $objStd;
848}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
if(is_object( $db)) sendMail($id, $cancreate, $now, $autoValidation)
send email to validator for current leave represented by (id)
Class to manage generation of HTML components Only common components must be here.
Class of the module paid holiday.
const STATUS_VALIDATED
Validated status.
const STATUS_DRAFT
Draft status.
Class to manage Dolibarr users.
global $mysoc
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $countryCodeOrId='', $user_id=0)
Function to return number of working days (and text of units) between two dates (working days)
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:166
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
treeview li table
No Email.