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