dolibarr 23.0.4
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 if (is_array($groups) && count($groups) > 0) {
275 $sql = ' SELECT DISTINCT u.rowid,u.lastname,u.firstname from ' . MAIN_DB_PREFIX . 'user as u';
276 $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'usergroup_user as ug on ug.fk_user = u.rowid ';
277 $sql .= ' WHERE fk_usergroup in (' .$db->sanitize(implode(',', $groups)) . ')';
278 $resql = $db->query($sql);
279
280 if ($resql) {
281 while ($obj = $db->fetch_object($resql)) {
282 $TusersToProcess[$obj->rowid] = $obj->rowid;
283 }
284 }
285 }
287 if (is_array($users) && count($users) > 0) {
288 foreach ($users as $u) {
289 $TusersToProcess[$u] = $u;
290 }
291 }
292 foreach ($TusersToProcess as $u) {
293 // Check if there is already holiday for this period pour chaque user
294 $verifCP = $object->verifDateHolidayCP($u, $date_debut, $date_fin, $halfday);
295 if (!$verifCP) {
296 //setEventMessages($langs->trans("alreadyCPexist"), null, 'errors');
297
298 $userError = new User($db);
299 $result = $userError->fetch($u);
300
301 if ($result) {
302 setEventMessages($langs->trans("UseralreadyCPexist", $userError->firstname . ' '. $userError->lastname), null, 'errors');
303 } else {
304 setEventMessages($langs->trans("ErrorUserFetch", $u), null, 'errors');
305 }
306
307 $error++;
308 $action = 'create';
309 }
310 }
311
312 if (!$error) {
313 $db->begin();
314 // non errors we can insert all
315 foreach ($TusersToProcess as $u) {
316 $object = new Holiday($db);
317 $object->fk_user = $u;
318 $object->description = $description;
319 $object->fk_validator = $approverid;
320 $object->fk_type = $type;
321 $object->date_debut = $date_debut;
322 $object->date_fin = $date_fin;
323 $object->halfday = $halfday;
324
325 $result = $object->create($user);
326
327 if ($result <= 0) {
328 setEventMessages($object->error, $object->errors, 'errors');
329 $error++;
330 } else {
331 //@TODO changer le nom si validated
332 if ($autoValidation) {
333 $htemp = new Holiday($db);
334 $htemp->fetch($result);
335
336 $htemp->status = Holiday::STATUS_VALIDATED;
337 $resultValidated = $htemp->update($approverid);
338
339 if ($resultValidated < 0) {
340 setEventMessages($object->error, $object->errors, 'errors');
341 $error++;
342 }
343 // we can auto send mail if we are in auto validation behavior
344
345 if ($AutoSendMail && !$error) {
346 // send a mail to the user
347 $returnSendMail = sendMail($result, $permissiontoadd, $now, $autoValidation);
348 if (!empty($returnSendMail->msg)) {
349 setEventMessage($returnSendMail->msg, $returnSendMail->style);
350 }
351 }
352 }
353 }
354 }
355 }
356 // If no SQL error we redirect to the request card
357 if (!$error) {
358 $db->commit();
359 header('Location: '.DOL_URL_ROOT.'/holiday/list.php');
360 exit;
361 } else {
362 $db->rollback();
363 }
364 }
365 }
366}
367
368
369
370/*
371 * View
372 */
373
374$form = new Form($db);
375$object = new Holiday($db);
376
377$listhalfday = array('morning' => $langs->trans("Morning"), "afternoon" => $langs->trans("Afternoon"));
378
379$title = $langs->trans('Leave');
380$help_url = 'EN:Module_Holiday';
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_advance')))) {
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 // Formulaire de demande
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 // Si la demande ne vient pas de l'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);
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
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.