dolibarr 22.0.5
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-2024 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-2025 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';
35require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
36require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
37require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
38require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
39require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
40require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
41require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
42require_once DOL_DOCUMENT_ROOT.'/core/lib/holiday.lib.php';
43require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
44require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
45
54// Get parameters
55$action = GETPOST('action', 'aZ09');
56$cancel = GETPOST('cancel', 'alpha');
57$confirm = GETPOST('confirm', 'alpha');
58$backtopage = GETPOST('backtopage', 'alpha'); // if not set, a default page will be used
59$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); // if not set, $backtopage will be used
60
61$id = GETPOSTINT('id');
62$ref = GETPOST('ref', 'alpha');
63$fuserid = (GETPOSTINT('fuserid') ? GETPOSTINT('fuserid') : $user->id);
64$users = (GETPOST('users', 'array') ? GETPOST('users', 'array') : array($user->id));
65$groups = GETPOST('groups', 'array');
66$socid = GETPOSTINT('socid');
67$autoValidation = GETPOSTINT('autoValidation');
68$AutoSendMail = GETPOSTINT('AutoSendMail');
69
70// Load translation files required by the page
71$langs->loadLangs(array("other", "holiday", "mails", "trips"));
72
73$error = 0;
74
75$now = dol_now();
76
77$childids = $user->getAllChildIds(1);
78
79$morefilter = '';
80if (getDolGlobalString('HOLIDAY_HIDE_FOR_NON_SALARIES')) {
81 $morefilter = 'AND employee = 1';
82}
83
84$object = new Holiday($db);
85
86$extrafields = new ExtraFields($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_advance')) {
212 $error++;
213 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
214 } elseif (!$user->hasRight('holiday', 'writeall_advance') && !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);
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 $sql = ' SELECT DISTINCT u.rowid,u.lastname,u.firstname from ' . MAIN_DB_PREFIX . 'user as u';
278 $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'usergroup_user as ug on ug.fk_user = u.rowid ';
279 $sql .= ' WHERE fk_usergroup in (' .$db->sanitize(implode(',', $groups)) . ')';
280 $resql = $db->query($sql);
281
282 if ($resql) {
283 while ($obj = $db->fetch_object($resql)) {
284 $TusersToProcess[$obj->rowid] = $obj->rowid;
285 }
286 }
288 if (is_array($users) && count($users) > 0) {
289 foreach ($users as $u) {
290 $TusersToProcess[$u] = $u;
291 }
292 }
293 foreach ($TusersToProcess as $u) {
294 // Check if there is already holiday for this period pour chaque user
295 $verifCP = $object->verifDateHolidayCP($u, $date_debut, $date_fin, $halfday);
296 if (!$verifCP) {
297 //setEventMessages($langs->trans("alreadyCPexist"), null, 'errors');
298
299 $userError = new User($db);
300 $result = $userError->fetch($u);
301
302 if ($result) {
303 setEventMessages($langs->trans("UseralreadyCPexist", $userError->firstname . ' '. $userError->lastname), null, 'errors');
304 } else {
305 setEventMessages($langs->trans("ErrorUserFetch", $u), null, 'errors');
306 }
307
308 $error++;
309 $action = 'create';
310 }
311 }
312
313 if (!$error) {
314 $db->begin();
315 // non errors we can insert all
316 foreach ($TusersToProcess as $u) {
317 $object = new Holiday($db);
318 $object->fk_user = $u;
319 $object->description = $description;
320 $object->fk_validator = $approverid;
321 $object->fk_type = $type;
322 $object->date_debut = $date_debut;
323 $object->date_fin = $date_fin;
324 $object->halfday = $halfday;
325
326 $result = $object->create($user);
327
328 if ($result <= 0) {
329 setEventMessages($object->error, $object->errors, 'errors');
330 $error++;
331 } else {
332 //@TODO changer le nom si validated
333 if ($autoValidation) {
334 $htemp = new Holiday($db);
335 $htemp->fetch($result);
336
337 $htemp->status = Holiday::STATUS_VALIDATED;
338 $resultValidated = $htemp->update($approverid);
339
340 if ($resultValidated < 0) {
341 setEventMessages($object->error, $object->errors, 'errors');
342 $error++;
343 }
344 // we can auto send mail if we are in auto validation behavior
345
346 if ($AutoSendMail && !$error) {
347 // send a mail to the user
348 $returnSendMail = sendMail($result, $permissiontoadd, $now, $autoValidation);
349 if (!empty($returnSendMail->msg)) {
350 setEventMessage($returnSendMail->msg, $returnSendMail->style);
351 }
352 }
353 }
354 }
355 }
356 }
357 // If no SQL error we redirect to the request card
358 if (!$error) {
359 $db->commit();
360 header('Location: '.DOL_URL_ROOT.'/holiday/list.php');
361 exit;
362 } else {
363 $db->rollback();
364 }
365 }
366 }
367}
368
369
370
371/*
372 * View
373 */
374
375$form = new Form($db);
376$object = new Holiday($db);
377
378$listhalfday = array('morning' => $langs->trans("Morning"), "afternoon" => $langs->trans("Afternoon"));
379
380$title = $langs->trans('Leave');
381$help_url = 'EN:Module_Holiday';
382
383llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-holiday page-card_group');
384
385if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') {
386 // If user has no permission to create a leave
387 if ((in_array($fuserid, $childids) && !$user->hasRight('holiday', 'writeall')) || (!in_array($fuserid, $childids) && (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || !$user->hasRight('holiday', 'writeall_advance')))) {
388 $errors[] = $langs->trans('CantCreateCP');
389 } else {
390 // Form to add a leave request
391 print load_fiche_titre($langs->trans('MenuCollectiveAddCP'), '', 'title_hrm.png');
392
393 // Error management
394 if (GETPOST('error')) {
395 switch (GETPOST('error')) {
396 case 'datefin':
397 $errors[] = $langs->trans('ErrorEndDateCP');
398 break;
399 case 'SQL_Create':
400 $errors[] = $langs->trans('ErrorSQLCreateCP');
401 break;
402 case 'CantCreate':
403 $errors[] = $langs->trans('CantCreateCP');
404 break;
405 case 'Valideur':
406 $errors[] = $langs->trans('InvalidValidatorCP');
407 break;
408 case 'nodatedebut':
409 $errors[] = $langs->trans('NoDateDebut');
410 break;
411 case 'nodatefin':
412 $errors[] = $langs->trans('NoDateFin');
413 break;
414 case 'DureeHoliday':
415 $errors[] = $langs->trans('ErrorDureeCP');
416 break;
417 case 'alreadyCP':
418 $errors[] = $langs->trans('alreadyCPexist');
419 break;
420 }
421
422 setEventMessages('', $errors, 'errors');
423 }
424
425
426 print '<script type="text/javascript">
427 $( document ).ready(function() {
428
429 if( $("input[name=autoValidation]").is(":checked") ){
430 $("#AutoSendMail").prop("disabled", false);
431 $("#AutoSendMail").prop("checked", true);
432
433 } else {
434 $("#AutoSendMail").prop("disabled", true);
435 $("#AutoSendMail").prop("checked", false);
436 }
437
438 $("input[name=autoValidation]").click( function(e) {
439
440
441 if( $("input[name=autoValidation]").is(":checked") ){
442 $("#AutoSendMail").prop("disabled", false);
443 $("#AutoSendMail").prop("checked", true);
444 } else {
445 $("#AutoSendMail").prop("disabled", true);
446 $("#AutoSendMail").prop("checked", false);
447 }
448 });
449
450
451
452 $("input.button-save").click("submit", function(e) {
453 console.log("Call valider()");
454 if (document.demandeCP.date_debut_.value != "")
455 {
456 if(document.demandeCP.date_fin_.value != "")
457 {
458 if(document.demandeCP.valideur.value != "-1") {
459 return true;
460 }
461 else {
462 alert("'.dol_escape_js($langs->transnoentities('InvalidValidatorCP')).'");
463 return false;
464 }
465 }
466 else
467 {
468 alert("'.dol_escape_js($langs->transnoentities('NoDateFin')).'");
469 return false;
470 }
471 }
472 else
473 {
474 alert("'.dol_escape_js($langs->transnoentities('NoDateDebut')).'");
475 return false;
476 }
477 })
478
479 $("#autoValidation").change(function(){
480 if( $("input[name=autoValidation]").is(":checked") ){
481 $("#AutoSendMail").prop("disabled", false);
482 } else {
483 $("#AutoSendMail").prop("disabled", true);
484 $("#AutoSendMail").prop("checked", false);
485 }
486 })
487 });
488 </script>'."\n";
489
490
491 // Formulaire de demande
492 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" name="demandeCP">'."\n";
493 print '<input type="hidden" name="token" value="'.newToken().'" />'."\n";
494 print '<input type="hidden" name="action" value="add" />'."\n";
495
496 print dol_get_fiche_head();
497
498 print '<table class="border centpercent">';
499 print '<tbody>';
500
501 // Groups of users
502 print '<tr>';
503 print '<td class="titlefield fieldrequired">';
504 print $form->textwithpicto($langs->trans("groups"), $langs->trans("fusionGroupsUsers"));
505 print '</td>';
506 print '<td>';
507 print img_picto($langs->trans("groups"), 'group', 'class="pictofixedwidth"');
508
509 $sql = ' SELECT rowid, nom from '.MAIN_DB_PREFIX.'usergroup WHERE entity IN ('.getEntity('usergroup').')';
510 $resql = $db->query($sql);
511 $Tgroup = array();
512 while ($obj = $db->fetch_object($resql)) {
513 $Tgroup[$obj->rowid] = $obj->nom;
514 }
515
516 print $form->multiselectarray('groups', $Tgroup, GETPOST('groups', 'array'), 0, 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
517
518 print '</td>';
519
520 // Users
521 print '<tr>';
522 print '<td class="titlefield fieldrequired">';
523 print $form->textwithpicto($langs->trans("users"), $langs->trans("fusionGroupsUsers"));
524 print '<td>';
525 print img_picto($langs->trans("users"), 'user', 'class="pictofixedwidth"');
526
527 $sql = 'SELECT u.rowid, u.lastname, u.firstname, u.login, u.photo FROM '.MAIN_DB_PREFIX.'user as u';
528 $sql .= ' WHERE 1 = 1';
529 $sql .= empty($morefilter) ? '' : $morefilter;
530
531 $userlist = array();
532 $userstatic = new User($db);
533
534 $resql = $db->query($sql);
535 if ($resql) {
536 while ($obj = $db->fetch_object($resql)) {
537 $userstatic->id = $obj->rowid;
538 $userstatic->login = $obj->login;
539 $userstatic->firstname = $obj->firstname;
540 $userstatic->lastname = $obj->lastname;
541 $userstatic->photo = $obj->photo;
542
543 $userlist[$obj->rowid] = array(
544 'id' => $obj->rowid,
545 'label' => dolGetFirstLastname($obj->firstname, $obj->lastname),
546 'data-html' => $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' '.dolGetFirstLastname($obj->firstname, $obj->lastname)
547 );
548 }
549 }
550
551 print img_picto('', 'users', 'class="pictofixedwidth"') . $form->multiselectarray('users', $userlist, GETPOST('users', 'array'), 0, 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
552 print '</td>';
553
554 // Type
555 print '<tr>';
556 print '<td class="fieldrequired">'.$langs->trans("Type").'</td>';
557 print '<td>';
558 $typeleaves = $object->getTypes(1, -1);
559 $arraytypeleaves = array();
560 foreach ($typeleaves as $key => $val) {
561 $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']);
562 $labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')' : '');
563 $arraytypeleaves[$val['rowid']] = $labeltoshow;
564 }
565 print $form->selectarray('type', $arraytypeleaves, (GETPOST('type', 'alpha') ? GETPOST('type', 'alpha') : ''), 1, 0, 0, '', 0, 0, 0, '', '', 1);
566 if ($user->admin) {
567 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
568 }
569 print '</td>';
570 print '</tr>';
571
572 // Date start
573 print '<tr>';
574 print '<td class="fieldrequired">';
575 print $form->textwithpicto($langs->trans("DateDebCP"), $langs->trans("FirstDayOfHoliday"));
576 print '</td>';
577 print '<td>';
578 // Si la demande ne vient pas de l'agenda
579 if (!GETPOST('date_debut_')) {
580 print $form->selectDate(-1, 'date_debut_', 0, 0, 0, '', 1, 1);
581 } else {
582 $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_debut_month'), GETPOSTINT('date_debut_day'), GETPOSTINT('date_debut_year'));
583 print $form->selectDate($tmpdate, 'date_debut_', 0, 0, 0, '', 1, 1);
584 }
585 print ' &nbsp; &nbsp; ';
586 print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday', 'alpha') ? GETPOST('starthalfday', 'alpha') : 'morning'));
587 print '</td>';
588 print '</tr>';
589
590 // Date end
591 print '<tr>';
592 print '<td class="fieldrequired">';
593 print $form->textwithpicto($langs->trans("DateFinCP"), $langs->trans("LastDayOfHoliday"));
594 print '</td>';
595 print '<td>';
596 if (!GETPOST('date_fin_')) {
597 print $form->selectDate(-1, 'date_fin_', 0, 0, 0, '', 1, 1);
598 } else {
599 $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_fin_month'), GETPOSTINT('date_fin_day'), GETPOSTINT('date_fin_year'));
600 print $form->selectDate($tmpdate, 'date_fin_', 0, 0, 0, '', 1, 1);
601 }
602 print ' &nbsp; &nbsp; ';
603 print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday', 'alpha') ? GETPOST('endhalfday', 'alpha') : 'afternoon'));
604 print '</td>';
605 print '</tr>';
606
607 // Approver
608 print '<tr>';
609 print '<td class="fieldrequired">'.$langs->trans("ReviewedByCP").'</td>';
610 print '<td>';
611
612 $object = new Holiday($db);
613 $include_users = $object->fetch_users_approver_holiday();
614 if (empty($include_users)) {
615 print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays");
616 } else {
617 // Defined default approver (the forced approved of user or the supervisor if no forced value defined)
618 // Note: This use will be set only if the deinfed approvr has permission to approve so is inside include_users
619 $defaultselectuser = (empty($user->fk_user_holiday_validator) ? $user->fk_user : $user->fk_user_holiday_validator);
620 if (getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR')) {
621 $defaultselectuser = getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR'); // Can force default approver
622 }
623 if (GETPOSTINT('valideur') > 0) {
624 $defaultselectuser = GETPOSTINT('valideur');
625 }
626 $s = $form->select_dolusers($defaultselectuser, "valideur", 1, null, 0, $include_users, '', '0,'.$conf->entity, 0, 0, '', 0, '', 'minwidth200 maxwidth500');
627 print img_picto('', 'user').$form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
628 }
629
630
631 print '</td>';
632 print '</tr>';
633
634 //auto validation ON CREATE
635 print '<tr><td>'.$langs->trans("AutoValidationOnCreate").'</td><td>';
636 print '<input type="checkbox" id="autoValidation" name="autoValidation" value="1"'.($autoValidation ? ' checked="checked"' : '').'>';
637 print '</td></tr>'."\n";
638
639
640 //no auto SEND MAIL
641 print '<tr><td>'.$langs->trans("AutoSendMail").'</td><td>';
642 print '<input type="checkbox" id="AutoSendMail" name="AutoSendMail" value="1"'.($AutoSendMail ? ' checked="checked"' : '').'>';
643 print '</td></tr>'."\n";
644
645 // Description
646 print '<tr>';
647 print '<td>'.$langs->trans("DescCP").'</td>';
648 print '<td class="tdtop">';
649 $doleditor = new DolEditor('description', GETPOST('description', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor'), ROWS_3, '90%');
650 print $doleditor->Create(1);
651 print '</td></tr>';
652
653 // Other attributes
654 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
655
656 print '</tbody>';
657 print '</table>';
658
659 print dol_get_fiche_end();
660
661 print $form->buttonsSaveCancel("SendRequestCollectiveCP");
662
663 print '</from>'."\n";
664 }
665} else {
666 if ($error) {
667 print '<div class="tabBar">';
668 print $error;
669 print '<br><br><input type="button" value="'.$langs->trans("ReturnCP").'" class="button" onclick="history.go(-1)" />';
670 print '</div>';
671 }
672}
673
674// End of page
675llxFooter();
676
677if (is_object($db)) {
678 $db->close();
679}
680
692function sendMail($id, $cancreate, $now, $autoValidation)
693{
694 $objStd = new stdClass();
695 $objStd->msg = '';
696 $objStd->status = 'success';
697 $objStd->error = 0;
698 $objStd->style = '';
699
700 global $db, $user, $langs;
701
702 $object = new Holiday($db);
703
704 $result = $object->fetch($id);
705
706 if ($result) {
707 // If draft and owner of leave
708 if ($object->status == Holiday::STATUS_VALIDATED && $cancreate) {
709 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
710
711 //if ($autoValidation) $object->status = Holiday::STATUS_VALIDATED;
712
713 $verif = $object->validate($user);
714
715 if ($verif > 0) {
716 // To
717 $destinataire = new User($db);
718 $destinataire->fetch($object->fk_validator);
719 $emailTo = $destinataire->email;
720
721
722 if (!$emailTo) {
723 dol_syslog("Expected validator has no email, so we redirect directly to finished page without sending email");
724
725 $objStd->error++;
726 $objStd->msg = $langs->trans('ErrorMailRecipientIsEmpty');
727 $objStd->status = 'error';
728 $objStd->style = "warnings";
729 return $objStd;
730 }
731
732 // From
733 $expediteur = new User($db);
734 $expediteur->fetch($object->fk_user);
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);
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:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
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 send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage a WYSIWYG editor.
Class to manage standard extra fields.
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.
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
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...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dol_now($mode='auto')
Return date for now.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($object, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='')
Show information in HTML for admin users or standard users.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
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.