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
135/*
136 * Actions
137 */
138
139$parameters = array('socid' => $socid);
140$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
141if ($reshook < 0) {
142 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
143}
144
145if (empty($reshook)) {
146 $backurlforlist = DOL_URL_ROOT.'/holiday/list.php';
147
148 if (empty($backtopage) || ($cancel && empty($id))) {
149 if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
150 if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
151 $backtopage = $backurlforlist;
152 } else {
153 $backtopage = DOL_URL_ROOT.'/holiday/card_group.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
154 }
155 }
156 }
157
158 if ($cancel) {
159 if (!empty($backtopageforcancel)) {
160 header("Location: ".$backtopageforcancel);
161 exit;
162 } elseif (!empty($backtopage)) {
163 header("Location: ".$backtopage);
164 exit;
165 }
166 $action = '';
167 }
168
169 // Add leave request
170 if ($action == 'add' && $permissiontoadd) {
171 $users = GETPOST('users', 'array');
172 $groups = GETPOST('groups', 'array');
173
174 $date_debut = dol_mktime(0, 0, 0, GETPOSTINT('date_debut_month'), GETPOSTINT('date_debut_day'), GETPOSTINT('date_debut_year'));
175 $date_fin = dol_mktime(0, 0, 0, GETPOSTINT('date_fin_month'), GETPOSTINT('date_fin_day'), GETPOSTINT('date_fin_year'));
176 $date_debut_gmt = dol_mktime(0, 0, 0, GETPOSTINT('date_debut_month'), GETPOSTINT('date_debut_day'), GETPOSTINT('date_debut_year'), 1);
177 $date_fin_gmt = dol_mktime(0, 0, 0, GETPOSTINT('date_fin_month'), GETPOSTINT('date_fin_day'), GETPOSTINT('date_fin_year'), 1);
178 $starthalfday = GETPOST('starthalfday');
179 $endhalfday = GETPOST('endhalfday');
180 $type = GETPOSTINT('type');
181
182 $halfday = 0;
183 if ($starthalfday == 'afternoon' && $endhalfday == 'morning') {
184 $halfday = 2;
185 } elseif ($starthalfday == 'afternoon') {
186 $halfday = -1;
187 } elseif ($endhalfday == 'morning') {
188 $halfday = 1;
189 }
190
191 $approverid = GETPOSTINT('valideur');
192 $description = trim(GETPOST('description', 'restricthtml'));
193
194 // Check that leave is for a user inside the hierarchy or advanced permission for all is set
195 if (!$permissiontoaddall) {
196 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
197 if (!$user->hasRight('holiday', 'write')) {
198 $error++;
199 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
200 } elseif (!in_array($fuserid, $childids)) {
201 $error++;
202 setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
203 $action = 'create';
204 }
205 } else {
206 if (!$user->hasRight('holiday', 'write') && !$user->hasRight('holiday', 'writeall')) {
207 $error++;
208 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
209 } elseif (!$user->hasRight('holiday', 'writeall') && !in_array($fuserid, $childids)) {
210 $error++;
211 setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
212 $action = 'create';
213 }
214 }
215 }
216 // If no groups and no users
217 if (empty($groups) && empty($users)) {
218 setEventMessages($langs->trans("ErrorFieldRequiredUserOrGroup"), null, 'errors');
219 //setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UserOrGroup")), null, 'errors');
220 //setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Group")), null, 'errors');
221 $error++;
222 $action = 'create';
223 }
224 // If no type
225 if ($type <= 0) {
226 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
227 $error++;
228 $action = 'create';
229 }
230
231 // If no start date
232 if (empty($date_debut)) {
233 setEventMessages($langs->trans("NoDateDebut"), null, 'errors');
234 $error++;
235 $action = 'create';
236 }
237 // If no end date
238 if (empty($date_fin)) {
239 setEventMessages($langs->trans("NoDateFin"), null, 'errors');
240 $error++;
241 $action = 'create';
242 }
243 // If start date after end date
244 if ($date_debut > $date_fin) {
245 setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors');
246 $error++;
247 $action = 'create';
248 }
249
250 // If there is no Business Days within request
251 $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday, $mysoc->country_id);
252 if ($nbopenedday < 0.5) {
253 setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); // No working day
254 $error++;
255 $action = 'create';
256 }
257
258 // If no validator designated
259 if ($approverid < 1) {
260 setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors');
261 $error++;
262 }
263
264 $result = 0;
265
266
267 if (!$error) {
268 $TusersToProcess = array();
269 // usergroup select
270 // better perf on single sql
272 if (is_array($groups) && count($groups) > 0) {
273 $sql = ' SELECT DISTINCT u.rowid,u.lastname,u.firstname from ' . MAIN_DB_PREFIX . 'user as u';
274 $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'usergroup_user as ug on ug.fk_user = u.rowid ';
275 $sql .= ' WHERE fk_usergroup in (' .$db->sanitize(implode(',', $groups)) . ')';
276 $resql = $db->query($sql);
277
278 if ($resql) {
279 while ($obj = $db->fetch_object($resql)) {
280 $TusersToProcess[$obj->rowid] = $obj->rowid;
281 }
282 }
283 }
285 if (is_array($users) && count($users) > 0) {
286 foreach ($users as $u) {
287 $TusersToProcess[$u] = $u;
288 }
289 }
290 foreach ($TusersToProcess as $u) {
291 // Check if there is already holiday for this period for each user
292 $verifCP = $object->verifDateHolidayCP($u, $date_debut, $date_fin, $halfday);
293 if (!$verifCP) {
294 //setEventMessages($langs->trans("alreadyCPexist"), null, 'errors');
295
296 $userError = new User($db);
297 $result = $userError->fetch($u);
298
299 if ($result) {
300 setEventMessages($langs->trans("UseralreadyCPexist", $userError->firstname . ' '. $userError->lastname), null, 'errors');
301 } else {
302 setEventMessages($langs->trans("ErrorUserFetch", $u), null, 'errors');
303 }
304
305 $error++;
306 $action = 'create';
307 }
308 }
309
310 if (!$error) {
311 $db->begin();
312 // non errors we can insert all
313 foreach ($TusersToProcess as $u) {
314 $object = new Holiday($db);
315 $object->fk_user = $u;
316 $object->description = $description;
317 $object->fk_validator = $approverid;
318 $object->fk_type = $type;
319 $object->date_debut = $date_debut;
320 $object->date_fin = $date_fin;
321 $object->halfday = $halfday;
322
323 $result = $object->create($user);
324
325 if ($result <= 0) {
326 setEventMessages($object->error, $object->errors, 'errors');
327 $error++;
328 } else {
329 if ($autoValidation) {
330 $htemp = new Holiday($db);
331 $htemp->fetch($result);
332
333 $htemp->status = Holiday::STATUS_VALIDATED;
334 $approver = new User($db);
335 $approver->fetch($approverid);
336 $resultValidated = $htemp->validate($approver);
337
338 if ($resultValidated < 0) {
339 setEventMessages($object->error, $object->errors, 'errors');
340 $error++;
341 }
342 // we can auto send mail if we are in auto validation behavior
343
344 if ($AutoSendMail && !$error) {
345 // send a mail to the user
346 $returnSendMail = sendMail($result, $permissiontoadd, $now, $autoValidation);
347 if (!empty($returnSendMail->msg)) {
348 setEventMessage($returnSendMail->msg, $returnSendMail->style);
349 }
350 }
351 }
352 }
353 }
354 }
355 // If no SQL error we redirect to the request card
356 if (!$error) {
357 $db->commit();
358 header('Location: '.DOL_URL_ROOT.'/holiday/list.php');
359 exit;
360 } else {
361 $db->rollback();
362 }
363 }
364 }
365}
366
367
368
369/*
370 * View
371 */
372
373$form = new Form($db);
374$object = new Holiday($db);
375
376$listhalfday = array('morning' => $langs->trans("Morning"), "afternoon" => $langs->trans("Afternoon"));
377
378$title = $langs->trans('Leave');
379$help_url = 'EN:Module_Holiday';
380$errors = array();
381
382llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-holiday page-card_group');
383
384if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') {
385 // If user has no permission to create a leave
386 if ((in_array($fuserid, $childids) && !$user->hasRight('holiday', 'writeall')) || (!in_array($fuserid, $childids) && (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || !$user->hasRight('holiday', 'writeall')))) {
387 $errors[] = $langs->trans('CantCreateCP');
388 } else {
389 // Form to add a leave request
390 print load_fiche_titre($langs->trans('MenuCollectiveAddCP'), '', 'title_hrm.png');
391
392 // Error management
393 if (GETPOST('error')) {
394 switch (GETPOST('error')) {
395 case 'datefin':
396 $errors[] = $langs->trans('ErrorEndDateCP');
397 break;
398 case 'SQL_Create':
399 $errors[] = $langs->trans('ErrorSQLCreateCP');
400 break;
401 case 'CantCreate':
402 $errors[] = $langs->trans('CantCreateCP');
403 break;
404 case 'Valideur':
405 $errors[] = $langs->trans('InvalidValidatorCP');
406 break;
407 case 'nodatedebut':
408 $errors[] = $langs->trans('NoDateDebut');
409 break;
410 case 'nodatefin':
411 $errors[] = $langs->trans('NoDateFin');
412 break;
413 case 'DureeHoliday':
414 $errors[] = $langs->trans('ErrorDureeCP');
415 break;
416 case 'alreadyCP':
417 $errors[] = $langs->trans('alreadyCPexist');
418 break;
419 }
420
421 setEventMessages('', $errors, 'errors');
422 }
423
424
425 print '<script type="text/javascript">
426 $( document ).ready(function() {
427
428 if( $("input[name=autoValidation]").is(":checked") ){
429 $("#AutoSendMail").prop("disabled", false);
430 $("#AutoSendMail").prop("checked", true);
431
432 } else {
433 $("#AutoSendMail").prop("disabled", true);
434 $("#AutoSendMail").prop("checked", false);
435 }
436
437 $("input[name=autoValidation]").click( function(e) {
438
439
440 if( $("input[name=autoValidation]").is(":checked") ){
441 $("#AutoSendMail").prop("disabled", false);
442 $("#AutoSendMail").prop("checked", true);
443 } else {
444 $("#AutoSendMail").prop("disabled", true);
445 $("#AutoSendMail").prop("checked", false);
446 }
447 });
448
449
450
451 $("input.button-save").click("submit", function(e) {
452 console.log("Call valider()");
453 if (document.demandeCP.date_debut_.value != "")
454 {
455 if(document.demandeCP.date_fin_.value != "")
456 {
457 if(document.demandeCP.valideur.value != "-1") {
458 return true;
459 }
460 else {
461 alert(\''.dol_escape_js($langs->transnoentities('InvalidValidatorCP')).'\');
462 return false;
463 }
464 }
465 else
466 {
467 alert(\''.dol_escape_js($langs->transnoentities('NoDateFin')).'\');
468 return false;
469 }
470 }
471 else
472 {
473 alert(\''.dol_escape_js($langs->transnoentities('NoDateDebut')).'\');
474 return false;
475 }
476 })
477
478 $("#autoValidation").change(function(){
479 if( $("input[name=autoValidation]").is(":checked") ){
480 $("#AutoSendMail").prop("disabled", false);
481 } else {
482 $("#AutoSendMail").prop("disabled", true);
483 $("#AutoSendMail").prop("checked", false);
484 }
485 })
486 });
487 </script>'."\n";
488
489
490 // Leave request form
491 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" name="demandeCP">'."\n";
492 print '<input type="hidden" name="token" value="'.newToken().'" />'."\n";
493 print '<input type="hidden" name="action" value="add" />'."\n";
494
495 print dol_get_fiche_head();
496
497 print '<table class="border centpercent">';
498 print '<tbody>';
499
500 // Groups of users
501 print '<tr>';
502 print '<td class="titlefield fieldrequired">';
503 print $form->textwithpicto($langs->trans("groups"), $langs->trans("fusionGroupsUsers"));
504 print '</td>';
505 print '<td>';
506 print img_picto($langs->trans("groups"), 'group', 'class="pictofixedwidth"');
507
508 $sql = ' SELECT rowid, nom from '.MAIN_DB_PREFIX.'usergroup WHERE entity IN ('.getEntity('usergroup').')';
509 $resql = $db->query($sql);
510 $Tgroup = array();
511 while ($obj = $db->fetch_object($resql)) {
512 $Tgroup[$obj->rowid] = $obj->nom;
513 }
514
515 print $form->multiselectarray('groups', $Tgroup, GETPOST('groups', 'array'), 0, 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
516
517 print '</td>';
518
519 // Users
520 print '<tr>';
521 print '<td class="titlefield fieldrequired">';
522 print $form->textwithpicto($langs->trans("users"), $langs->trans("fusionGroupsUsers"));
523 print '<td>';
524 print img_picto($langs->trans("users"), 'user', 'class="pictofixedwidth"');
525
526 $sql = 'SELECT u.rowid, u.lastname, u.firstname, u.login, u.photo FROM '.MAIN_DB_PREFIX.'user as u';
527 $sql .= ' WHERE 1 = 1';
528 $sql .= empty($morefilter) ? '' : $morefilter;
529
530 $userlist = array();
531 $userstatic = new User($db);
532
533 $resql = $db->query($sql);
534 if ($resql) {
535 while ($obj = $db->fetch_object($resql)) {
536 $userstatic->id = $obj->rowid;
537 $userstatic->login = $obj->login;
538 $userstatic->firstname = $obj->firstname;
539 $userstatic->lastname = $obj->lastname;
540 $userstatic->photo = $obj->photo;
541
542 $userlist[$obj->rowid] = array(
543 'id' => $obj->rowid,
544 'label' => dolGetFirstLastname($obj->firstname, $obj->lastname),
545 'data-html' => $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' '.dolGetFirstLastname($obj->firstname, $obj->lastname)
546 );
547 }
548 }
549
550 print img_picto('', 'users', 'class="pictofixedwidth"') . $form->multiselectarray('users', $userlist, GETPOST('users', 'array'), 0, 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
551 print '</td>';
552
553 // Type
554 print '<tr>';
555 print '<td class="fieldrequired">'.$langs->trans("Type").'</td>';
556 print '<td>';
557 $typeleaves = $object->getTypes(1, -1);
558 $arraytypeleaves = array();
559 foreach ($typeleaves as $key => $val) {
560 $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']);
561 $labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')' : '');
562 $arraytypeleaves[$val['rowid']] = $labeltoshow;
563 }
564 print $form->selectarray('type', $arraytypeleaves, (GETPOST('type', 'alpha') ? GETPOST('type', 'alpha') : ''), 1, 0, 0, '', 0, 0, 0, '', '', 1);
565 if ($user->admin) {
566 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
567 }
568 print '</td>';
569 print '</tr>';
570
571 // Date start
572 print '<tr>';
573 print '<td class="fieldrequired">';
574 print $form->textwithpicto($langs->trans("DateDebCP"), $langs->trans("FirstDayOfHoliday"));
575 print '</td>';
576 print '<td>';
577 // If the request does not come from the agenda
578 if (!GETPOST('date_debut_')) {
579 print $form->selectDate(-1, 'date_debut_', 0, 0, 0, '', 1, 1);
580 } else {
581 $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_debut_month'), GETPOSTINT('date_debut_day'), GETPOSTINT('date_debut_year'));
582 print $form->selectDate($tmpdate, 'date_debut_', 0, 0, 0, '', 1, 1);
583 }
584 print ' &nbsp; &nbsp; ';
585 print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday', 'alpha') ? GETPOST('starthalfday', 'alpha') : 'morning'));
586 print '</td>';
587 print '</tr>';
588
589 // Date end
590 print '<tr>';
591 print '<td class="fieldrequired">';
592 print $form->textwithpicto($langs->trans("DateFinCP"), $langs->trans("LastDayOfHoliday"));
593 print '</td>';
594 print '<td>';
595 if (!GETPOST('date_fin_')) {
596 print $form->selectDate(-1, 'date_fin_', 0, 0, 0, '', 1, 1);
597 } else {
598 $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_fin_month'), GETPOSTINT('date_fin_day'), GETPOSTINT('date_fin_year'));
599 print $form->selectDate($tmpdate, 'date_fin_', 0, 0, 0, '', 1, 1);
600 }
601 print ' &nbsp; &nbsp; ';
602 print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday', 'alpha') ? GETPOST('endhalfday', 'alpha') : 'afternoon'));
603 print '</td>';
604 print '</tr>';
605
606 // Approver
607 print '<tr>';
608 print '<td class="fieldrequired">'.$langs->trans("ReviewedByCP").'</td>';
609 print '<td>';
610
611 $object = new Holiday($db);
612 $include_users = $object->fetch_users_approver_holiday();
613 if (empty($include_users)) {
614 print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays");
615 } else {
616 // Defined default approver (the forced approver of user or the supervisor if no forced value defined)
617 // Note: This use will be set only if the defined approver has permission to approve so is inside include_users
618 $defaultselectuser = (empty($user->fk_user_holiday_validator) ? $user->fk_user : $user->fk_user_holiday_validator);
619 if (getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR')) {
620 $defaultselectuser = getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR'); // Can force default approver
621 }
622 if (GETPOSTINT('valideur') > 0) {
623 $defaultselectuser = GETPOSTINT('valideur');
624 }
625 $s = $form->select_dolusers($defaultselectuser, "valideur", 1, null, 0, $include_users, '', '0,'.$conf->entity, 0, 0, '', 0, '', 'minwidth200 maxwidth500');
626 print img_picto('', 'user').$form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
627 }
628
629
630 print '</td>';
631 print '</tr>';
632
633 //auto validation ON CREATE
634 print '<tr><td>'.$langs->trans("AutoValidationOnCreate").'</td><td>';
635 print '<input type="checkbox" id="autoValidation" name="autoValidation" value="1"'.($autoValidation ? ' checked="checked"' : '').'>';
636 print '</td></tr>'."\n";
637
638
639 //no auto SEND MAIL
640 print '<tr><td>'.$langs->trans("AutoSendMail").'</td><td>';
641 print '<input type="checkbox" id="AutoSendMail" name="AutoSendMail" value="1"'.($AutoSendMail ? ' checked="checked"' : '').'>';
642 print '</td></tr>'."\n";
643
644 // Description
645 print '<tr>';
646 print '<td>'.$langs->trans("DescCP").'</td>';
647 print '<td class="tdtop">';
648 $doleditor = new DolEditor('description', GETPOST('description', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor'), ROWS_3, '90%');
649 print $doleditor->Create(1);
650 print '</td></tr>';
651
652 // Other attributes
653 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
654
655 print '</tbody>';
656 print '</table>';
657
658 print dol_get_fiche_end();
659
660 print $form->buttonsSaveCancel("SendRequestCollectiveCP");
661
662 print '</from>'."\n";
663 }
664} else {
665 if ($error) {
666 print '<div class="tabBar">';
667 print $error;
668 print '<br><br><input type="button" value="'.$langs->trans("ReturnCP").'" class="button" onclick="history.go(-1)" />';
669 print '</div>';
670 }
671}
672
673// End of page
674llxFooter();
675
676if (is_object($db)) {
677 $db->close();
678}
679
691function sendMail($id, $cancreate, $now, $autoValidation)
692{
693 $objStd = new stdClass();
694 $objStd->msg = '';
695 $objStd->status = 'success';
696 $objStd->error = 0;
697 $objStd->style = '';
698
699 global $db, $user, $langs;
700
701 $object = new Holiday($db);
702
703 $result = $object->fetch($id);
704
705 if ($result) {
706 // If draft and owner of leave
707 if ($object->status == Holiday::STATUS_VALIDATED && $cancreate) {
708 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
709
710 //if ($autoValidation) $object->status = Holiday::STATUS_VALIDATED;
711
712 $verif = $object->validate($user);
713
714 if ($verif > 0) {
715 // To
716 $destinataire = new User($db);
717 $destinataire->fetch($object->fk_validator);
718 $emailTo = $destinataire->email;
719
720
721 if (!$emailTo) {
722 dol_syslog("Expected validator has no email, so we redirect directly to finished page without sending email");
723
724 $objStd->error++;
725 $objStd->msg = $langs->trans('ErrorMailRecipientIsEmpty');
726 $objStd->status = 'error';
727 $objStd->style = "warnings";
728 return $objStd;
729 }
730
731 // From
732 $expediteur = new User($db);
733 $expediteur->fetch($object->fk_user);
734
735 //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
736 $emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
737
738 // Subject
739 $societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
740 if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
741 $societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
742 }
743
744 $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysToValidate");
745
746 // Content
747 $message = "<p>".$langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",</p>\n";
748
749 $message .= "<p>".$langs->transnoentities("HolidaysToValidateBody")."</p>\n";
750
751
752 // option to warn the validator in case of too short delay
753 if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_TOO_LOW_DELAY')) {
754 $delayForRequest = 0; // TODO Set delay depending of holiday leave type
755 if ($delayForRequest) {
756 $nowplusdelay = dol_time_plus_duree($now, $delayForRequest, 'd');
757
758 if ($object->date_debut < $nowplusdelay) {
759 $message = "<p>".$langs->transnoentities("HolidaysToValidateDelay", $delayForRequest)."</p>\n";
760 }
761 }
762 }
763
764 // option to notify the validator if the balance is less than the request
765 // (only for leave types that actually use the balance counter)
766 if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_NEGATIVE_BALANCE')) {
767 $affectingtypes = $object->getTypes(1, 1);
768 if (!empty($affectingtypes[$object->fk_type])) {
769 $nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday, $expediteur->country_id, $object->fk_user);
770
771 if ($nbopenedday > $object->getCPforUser($object->fk_user, $object->fk_type)) {
772 $message .= "<p>".$langs->transnoentities("HolidaysToValidateAlertSolde")."</p>\n";
773 }
774 }
775 }
776
777 $typeleaves = $object->getTypes(1, -1);
778 $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']);
779
780 if ($object->halfday == 2) {
781 $starthalfdaykey = "Afternoon";
782 $endhalfdaykey = "Morning";
783 } elseif ($object->halfday == -1) {
784 $starthalfdaykey = "Afternoon";
785 $endhalfdaykey = "Afternoon";
786 } elseif ($object->halfday == 1) {
787 $starthalfdaykey = "Morning";
788 $endhalfdaykey = "Morning";
789 } elseif ($object->halfday == 0 || $object->halfday == 2) {
790 $starthalfdaykey = "Morning";
791 $endhalfdaykey = "Afternoon";
792 } else {
793 // For static analysis, ensure variables are defined
794 $starthalfdaykey = "InvalidHalfday";
795 $endhalfdaykey = "InvalidHalfday";
796 }
797
798 $link = dol_buildpath("/holiday/card.php", 3) . '?id='.$object->id;
799
800 $message .= "<ul>";
801 $message .= "<li>".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."</li>\n";
802 $message .= "<li>".$langs->transnoentitiesnoconv("Type")." : ".(empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow)."</li>\n";
803 $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";
804 $message .= "<li>".$langs->transnoentitiesnoconv("Link").' : <a href="'.$link.'" target="_blank">'.$link."</a></li>\n";
805 $message .= "</ul>\n";
806
807 $trackid = 'leav'.$object->id;
808
809 $sendtobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_HOLIDAY_TO');
810
811 $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', $sendtobcc, 0, 1, '', '', $trackid);
812
813 // Sending the email
814 $result = $mail->sendfile();
815
816 if (!$result) {
817 $objStd->error++;
818 $objStd->msg = $langs->trans('ErrorMailNotSend');
819 $objStd->style = "warnings";
820 $objStd->status = 'error';
821 } else {
822 $objStd->msg = $langs->trans('MailSent');
823 }
824
825 return $objStd;
826 } else {
827 $objStd->error++;
828 $objStd->msg = $langs->trans('ErrorVerif');
829 $objStd->status = 'error';
830 $objStd->style = "errors";
831 return $objStd;
832 }
833 }
834 } else {
835 $objStd->error++;
836 $objStd->msg = $langs->trans('ErrorloadUserOnSendingMail');
837 $objStd->status = 'error';
838 $objStd->style = "warnings";
839 return $objStd;
840 }
841
842 return $objStd;
843}
$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:280
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.
treeview li table
No Email.
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:141
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140
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.