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