dolibarr 21.0.0-alpha
card_group.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2011 Dimitri Mouillard <dmouillard@teclib.com>
3 * Copyright (C) 2012-2016 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2012-2016 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
6 * Copyright (C) 2017-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
7 * Copyright (C) 2014-2017 Ferran Marcet <fmarcet@2byte.es>
8 * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
9 * Copyright (C) 2020-2021 Udo Tamm <dev@dolibit.de>
10 * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
11 * Copyright (C) 2024 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
46// Get parameters
47$action = GETPOST('action', 'aZ09');
48$cancel = GETPOST('cancel', 'alpha');
49$confirm = GETPOST('confirm', 'alpha');
50$backtopage = GETPOST('backtopage', 'alpha'); // if not set, a default page will be used
51$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); // if not set, $backtopage will be used
52
53$id = GETPOSTINT('id');
54$ref = GETPOST('ref', 'alpha');
55$fuserid = (GETPOSTINT('fuserid') ? GETPOSTINT('fuserid') : $user->id);
56$users = (GETPOST('users', 'array') ? GETPOST('users', 'array') : array($user->id));
57$groups = GETPOST('groups', 'array');
58$socid = GETPOSTINT('socid');
59$autoValidation = GETPOSTINT('autoValidation');
60$AutoSendMail = GETPOSTINT('AutoSendMail');
61
62// Load translation files required by the page
63$langs->loadLangs(array("other", "holiday", "mails", "trips"));
64
65$error = 0;
66
67$now = dol_now();
68
69$childids = $user->getAllChildIds(1);
70
71$morefilter = '';
72if (getDolGlobalString('HOLIDAY_HIDE_FOR_NON_SALARIES')) {
73 $morefilter = 'AND employee = 1';
74}
75
76$object = new Holiday($db);
77
78$extrafields = new ExtraFields($db);
79
80// fetch optionals attributes and labels
81$extrafields->fetch_name_optionals_label($object->table_element);
82
83if (($id > 0) || $ref) {
84 $object->fetch($id, $ref);
85
86 // Check current user can read this leave request
87 $canread = 0;
88 if ($user->hasRight('holiday', 'readall')) {
89 $canread = 1;
90 }
91 if ($user->hasRight('holiday', 'read') && in_array($object->fk_user, $childids)) {
92 $canread = 1;
93 }
94 if (!$canread) {
96 }
97}
98
99// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
100$hookmanager->initHooks(array('holidaycard', 'globalcard'));
101
102$permissiontoadd = 0;
103$permissiontoaddall = 0;
104if ($user->hasRight('holiday', 'write') && in_array($fuserid, $childids)) {
105 $permissiontoadd = 1;
106}
107if ($user->hasRight('holiday', 'writeall')) {
108 $permissiontoadd = 1;
109 $permissiontoaddall = 1;
110}
111
112$candelete = 0;
113if ($user->hasRight('holiday', 'delete')) {
114 $candelete = 1;
115}
116if ($object->status == Holiday::STATUS_DRAFT && $user->hasRight('holiday', 'write') && in_array($object->fk_user, $childids)) {
117 $candelete = 1;
118}
119
120// Protection if external user
121if ($user->socid) {
122 $socid = $user->socid;
123}
124$result = restrictedArea($user, 'holiday', $object->id, 'holiday', '', '', 'rowid', $object->status);
125
126
127/*
128 * Actions
129 */
130
131$parameters = array('socid' => $socid);
132$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
133if ($reshook < 0) {
134 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
135}
136
137if (empty($reshook)) {
138 $backurlforlist = DOL_URL_ROOT.'/holiday/list.php';
139
140 if (empty($backtopage) || ($cancel && empty($id))) {
141 if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
142 if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
143 $backtopage = $backurlforlist;
144 } else {
145 $backtopage = DOL_URL_ROOT.'/holiday/card_group.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
146 }
147 }
148 }
149
150 if ($cancel) {
151 if (!empty($backtopageforcancel)) {
152 header("Location: ".$backtopageforcancel);
153 exit;
154 } elseif (!empty($backtopage)) {
155 header("Location: ".$backtopage);
156 exit;
157 }
158 $action = '';
159 }
160
161 // Add leave request
162 if ($action == 'add' && $permissiontoadd) {
163 $users = GETPOST('users', 'array');
164 $groups = GETPOST('groups', 'array');
165
166 $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'));
167 $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'));
168 $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1);
169 $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1);
170 $starthalfday = GETPOST('starthalfday');
171 $endhalfday = GETPOST('endhalfday');
172 $type = GETPOSTINT('type');
173
174 $halfday = 0;
175 if ($starthalfday == 'afternoon' && $endhalfday == 'morning') {
176 $halfday = 2;
177 } elseif ($starthalfday == 'afternoon') {
178 $halfday = -1;
179 } elseif ($endhalfday == 'morning') {
180 $halfday = 1;
181 }
182
183 $approverid = GETPOSTINT('valideur');
184 $description = trim(GETPOST('description', 'restricthtml'));
185
186 // Check that leave is for a user inside the hierarchy or advanced permission for all is set
187 if (!$permissiontoaddall) {
188 if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
189 if (!$user->hasRight('holiday', 'write')) {
190 $error++;
191 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
192 } elseif (!in_array($fuserid, $childids)) {
193 $error++;
194 setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
195 $action = 'create';
196 }
197 } else {
198 if (!$user->hasRight('holiday', 'write') && !$user->hasRight('holiday', 'writeall_advance')) {
199 $error++;
200 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
201 } elseif (!$user->hasRight('holiday', 'writeall_advance') && !in_array($fuserid, $childids)) {
202 $error++;
203 setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
204 $action = 'create';
205 }
206 }
207 }
208 // If no groups and no users
209 if (empty($groups) && empty($users)) {
210 setEventMessages($langs->trans("ErrorFieldRequiredUserOrGroup"), null, 'errors');
211 //setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UserOrGroup")), null, 'errors');
212 //setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Group")), null, 'errors');
213 $error++;
214 $action = 'create';
215 }
216 // If no type
217 if ($type <= 0) {
218 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
219 $error++;
220 $action = 'create';
221 }
222
223 // If no start date
224 if (empty($date_debut)) {
225 setEventMessages($langs->trans("NoDateDebut"), null, 'errors');
226 $error++;
227 $action = 'create';
228 }
229 // If no end date
230 if (empty($date_fin)) {
231 setEventMessages($langs->trans("NoDateFin"), null, 'errors');
232 $error++;
233 $action = 'create';
234 }
235 // If start date after end date
236 if ($date_debut > $date_fin) {
237 setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors');
238 $error++;
239 $action = 'create';
240 }
241
242 // If there is no Business Days within request
243 $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday);
244 if ($nbopenedday < 0.5) {
245 setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); // No working day
246 $error++;
247 $action = 'create';
248 }
249
250 // If no validator designated
251 if ($approverid < 1) {
252 setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors');
253 $error++;
254 }
255
256 $result = 0;
257
258
259 if (!$error) {
260 $TusersToProcess = array();
261 // usergroup select
262 // better perf on single sql
264 $sql = ' SELECT DISTINCT u.rowid,u.lastname,u.firstname from ' . MAIN_DB_PREFIX . 'user as u';
265 $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'usergroup_user as ug on ug.fk_user = u.rowid ';
266 $sql .= ' WHERE fk_usergroup in (' .$db->sanitize(implode(',', $groups)) . ')';
267 $resql = $db->query($sql);
268
269 if ($resql) {
270 while ($obj = $db->fetch_object($resql)) {
271 $TusersToProcess[$obj->rowid] = $obj->rowid;
272 }
273 }
275 if (is_array($users) && count($users) > 0) {
276 foreach ($users as $u) {
277 $TusersToProcess[$u] = $u;
278 }
279 }
280 foreach ($TusersToProcess as $u) {
281 // Check if there is already holiday for this period pour chaque user
282 $verifCP = $object->verifDateHolidayCP($u, $date_debut, $date_fin, $halfday);
283 if (!$verifCP) {
284 //setEventMessages($langs->trans("alreadyCPexist"), null, 'errors');
285
286 $userError = new User($db);
287 $result = $userError->fetch($u);
288
289 if ($result) {
290 setEventMessages($langs->trans("UseralreadyCPexist", $userError->firstname . ' '. $userError->lastname), null, 'errors');
291 } else {
292 setEventMessages($langs->trans("ErrorUserFetch", $u), null, 'errors');
293 }
294
295 $error++;
296 $action = 'create';
297 }
298 }
299
300 if (!$error) {
301 $db->begin();
302 // non errors we can insert all
303 foreach ($TusersToProcess as $u) {
304 $object = new Holiday($db);
305 $object->fk_user = $u;
306 $object->description = $description;
307 $object->fk_validator = $approverid;
308 $object->fk_type = $type;
309 $object->date_debut = $date_debut;
310 $object->date_fin = $date_fin;
311 $object->halfday = $halfday;
312
313 $result = $object->create($user);
314
315 if ($result <= 0) {
316 setEventMessages($object->error, $object->errors, 'errors');
317 $error++;
318 } else {
319 //@TODO changer le nom si validated
320 if ($autoValidation) {
321 $htemp = new Holiday($db);
322 $htemp->fetch($result);
323
324 $htemp->status = Holiday::STATUS_VALIDATED;
325 $resultValidated = $htemp->update($approverid);
326
327 if ($resultValidated < 0) {
328 setEventMessages($object->error, $object->errors, 'errors');
329 $error++;
330 }
331 // we can auto send mail if we are in auto validation behavior
332
333 if ($AutoSendMail && !$error) {
334 // send a mail to the user
335 $returnSendMail = sendMail($result, $permissiontoadd, $now, $autoValidation);
336 if (!empty($returnSendMail->msg)) {
337 setEventMessage($returnSendMail->msg, $returnSendMail->style);
338 }
339 }
340 }
341 }
342 }
343 }
344 // If no SQL error we redirect to the request card
345 if (!$error) {
346 $db->commit();
347 header('Location: '.DOL_URL_ROOT.'/holiday/list.php');
348 exit;
349 } else {
350 $db->rollback();
351 }
352 }
353 }
354}
355
356
357
358/*
359 * View
360 */
361
362$form = new Form($db);
363$object = new Holiday($db);
364
365$listhalfday = array('morning' => $langs->trans("Morning"), "afternoon" => $langs->trans("Afternoon"));
366
367$title = $langs->trans('Leave');
368$help_url = 'EN:Module_Holiday';
369
370llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-holiday page-card_group');
371
372if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') {
373 // If user has no permission to create a leave
374 if ((in_array($fuserid, $childids) && !$user->hasRight('holiday', 'writeall')) || (!in_array($fuserid, $childids) && (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || !$user->hasRight('holiday', 'writeall_advance')))) {
375 $errors[] = $langs->trans('CantCreateCP');
376 } else {
377 // Form to add a leave request
378 print load_fiche_titre($langs->trans('MenuCollectiveAddCP'), '', 'title_hrm.png');
379
380 // Error management
381 if (GETPOST('error')) {
382 switch (GETPOST('error')) {
383 case 'datefin':
384 $errors[] = $langs->trans('ErrorEndDateCP');
385 break;
386 case 'SQL_Create':
387 $errors[] = $langs->trans('ErrorSQLCreateCP');
388 break;
389 case 'CantCreate':
390 $errors[] = $langs->trans('CantCreateCP');
391 break;
392 case 'Valideur':
393 $errors[] = $langs->trans('InvalidValidatorCP');
394 break;
395 case 'nodatedebut':
396 $errors[] = $langs->trans('NoDateDebut');
397 break;
398 case 'nodatefin':
399 $errors[] = $langs->trans('NoDateFin');
400 break;
401 case 'DureeHoliday':
402 $errors[] = $langs->trans('ErrorDureeCP');
403 break;
404 case 'alreadyCP':
405 $errors[] = $langs->trans('alreadyCPexist');
406 break;
407 }
408
409 setEventMessages($errors, null, 'errors');
410 }
411
412
413 print '<script type="text/javascript">
414 $( document ).ready(function() {
415
416 if( $("input[name=autoValidation]").is(":checked") ){
417 $("#AutoSendMail").prop("disabled", false);
418 $("#AutoSendMail").prop("checked", true);
419
420 } else {
421 $("#AutoSendMail").prop("disabled", true);
422 $("#AutoSendMail").prop("checked", false);
423 }
424
425 $("input[name=autoValidation]").click( function(e) {
426
427
428 if( $("input[name=autoValidation]").is(":checked") ){
429 $("#AutoSendMail").prop("disabled", false);
430 $("#AutoSendMail").prop("checked", true);
431 } else {
432 $("#AutoSendMail").prop("disabled", true);
433 $("#AutoSendMail").prop("checked", false);
434 }
435 });
436
437
438
439 $("input.button-save").click("submit", function(e) {
440 console.log("Call valider()");
441 if (document.demandeCP.date_debut_.value != "")
442 {
443 if(document.demandeCP.date_fin_.value != "")
444 {
445 if(document.demandeCP.valideur.value != "-1") {
446 return true;
447 }
448 else {
449 alert("'.dol_escape_js($langs->transnoentities('InvalidValidatorCP')).'");
450 return false;
451 }
452 }
453 else
454 {
455 alert("'.dol_escape_js($langs->transnoentities('NoDateFin')).'");
456 return false;
457 }
458 }
459 else
460 {
461 alert("'.dol_escape_js($langs->transnoentities('NoDateDebut')).'");
462 return false;
463 }
464 })
465
466 $("#autoValidation").change(function(){
467 if( $("input[name=autoValidation]").is(":checked") ){
468 $("#AutoSendMail").prop("disabled", false);
469 } else {
470 $("#AutoSendMail").prop("disabled", true);
471 $("#AutoSendMail").prop("checked", false);
472 }
473 })
474 });
475 </script>'."\n";
476
477
478 // Formulaire de demande
479 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" name="demandeCP">'."\n";
480 print '<input type="hidden" name="token" value="'.newToken().'" />'."\n";
481 print '<input type="hidden" name="action" value="add" />'."\n";
482
483 print dol_get_fiche_head();
484
485 print '<table class="border centpercent">';
486 print '<tbody>';
487
488 // Groups of users
489 print '<tr>';
490 print '<td class="titlefield fieldrequired">';
491 print $form->textwithpicto($langs->trans("groups"), $langs->trans("fusionGroupsUsers"));
492 print '</td>';
493 print '<td>';
494 print img_picto($langs->trans("groups"), 'group', 'class="pictofixedwidth"');
495
496 $sql = ' SELECT rowid, nom from '.MAIN_DB_PREFIX.'usergroup WHERE entity IN ('.getEntity('usergroup').')';
497 $resql = $db->query($sql);
498 $Tgroup = array();
499 while ($obj = $db->fetch_object($resql)) {
500 $Tgroup[$obj->rowid] = $obj->nom;
501 }
502
503 print $form->multiselectarray('groups', $Tgroup, GETPOST('groups', 'array'), '', 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
504
505 print '</td>';
506
507 // Users
508 print '<tr>';
509 print '<td class="titlefield fieldrequired">';
510 print $form->textwithpicto($langs->trans("users"), $langs->trans("fusionGroupsUsers"));
511 print '<td>';
512 print img_picto($langs->trans("users"), 'user', 'class="pictofixedwidth"');
513
514 $sql = 'SELECT u.rowid, u.lastname, u.firstname, u.login, u.photo FROM '.MAIN_DB_PREFIX.'user as u';
515 $sql .= ' WHERE 1 = 1';
516 $sql .= !empty($morefilter) ? $morefilter : '';
517
518 $userlist = array();
519 $userstatic = new User($db);
520
521 $resql = $db->query($sql);
522 if ($resql) {
523 while ($obj = $db->fetch_object($resql)) {
524 $userstatic->id = $obj->rowid;
525 $userstatic->login = $obj->login;
526 $userstatic->firstname = $obj->fistname;
527 $userstatic->lastname = $obj->lastname;
528 $userstatic->photo = $obj->photo;
529
530 $userlist[$obj->rowid] = array(
531 'id' => $obj->rowid,
532 'label' => dolGetFirstLastname($obj->firstname, $obj->lastname),
533 'data-html' => $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' '.dolGetFirstLastname($obj->firstname, $obj->lastname)
534 );
535 }
536 }
537
538 print img_picto('', 'users', 'class="pictofixedwidth"') . $form->multiselectarray('users', $userlist, GETPOST('users', 'array'), '', 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
539 print '</td>';
540
541 // Type
542 print '<tr>';
543 print '<td class="fieldrequired">'.$langs->trans("Type").'</td>';
544 print '<td>';
545 $typeleaves = $object->getTypes(1, -1);
546 $arraytypeleaves = array();
547 foreach ($typeleaves as $key => $val) {
548 $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']);
549 $labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')' : '');
550 $arraytypeleaves[$val['rowid']] = $labeltoshow;
551 }
552 print $form->selectarray('type', $arraytypeleaves, (GETPOST('type', 'alpha') ? GETPOST('type', 'alpha') : ''), 1, 0, 0, '', 0, 0, 0, '', '', true);
553 if ($user->admin) {
554 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
555 }
556 print '</td>';
557 print '</tr>';
558
559 // Date start
560 print '<tr>';
561 print '<td class="fieldrequired">';
562 print $form->textwithpicto($langs->trans("DateDebCP"), $langs->trans("FirstDayOfHoliday"));
563 print '</td>';
564 print '<td>';
565 // Si la demande ne vient pas de l'agenda
566 if (!GETPOST('date_debut_')) {
567 print $form->selectDate(-1, 'date_debut_', 0, 0, 0, '', 1, 1);
568 } else {
569 $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_debut_month'), GETPOSTINT('date_debut_day'), GETPOSTINT('date_debut_year'));
570 print $form->selectDate($tmpdate, 'date_debut_', 0, 0, 0, '', 1, 1);
571 }
572 print ' &nbsp; &nbsp; ';
573 print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday', 'alpha') ? GETPOST('starthalfday', 'alpha') : 'morning'));
574 print '</td>';
575 print '</tr>';
576
577 // Date end
578 print '<tr>';
579 print '<td class="fieldrequired">';
580 print $form->textwithpicto($langs->trans("DateFinCP"), $langs->trans("LastDayOfHoliday"));
581 print '</td>';
582 print '<td>';
583 if (!GETPOST('date_fin_')) {
584 print $form->selectDate(-1, 'date_fin_', 0, 0, 0, '', 1, 1);
585 } else {
586 $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_fin_month'), GETPOSTINT('date_fin_day'), GETPOSTINT('date_fin_year'));
587 print $form->selectDate($tmpdate, 'date_fin_', 0, 0, 0, '', 1, 1);
588 }
589 print ' &nbsp; &nbsp; ';
590 print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday', 'alpha') ? GETPOST('endhalfday', 'alpha') : 'afternoon'));
591 print '</td>';
592 print '</tr>';
593
594 // Approver
595 print '<tr>';
596 print '<td class="fieldrequired">'.$langs->trans("ReviewedByCP").'</td>';
597 print '<td>';
598
599 $object = new Holiday($db);
600 $include_users = $object->fetch_users_approver_holiday();
601 if (empty($include_users)) {
602 print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays");
603 } else {
604 // Defined default approver (the forced approved of user or the supervisor if no forced value defined)
605 // Note: This use will be set only if the deinfed approvr has permission to approve so is inside include_users
606 $defaultselectuser = (empty($user->fk_user_holiday_validator) ? $user->fk_user : $user->fk_user_holiday_validator);
607 if (getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR')) {
608 $defaultselectuser = getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR'); // Can force default approver
609 }
610 if (GETPOSTINT('valideur') > 0) {
611 $defaultselectuser = GETPOSTINT('valideur');
612 }
613 $s = $form->select_dolusers($defaultselectuser, "valideur", 1, '', 0, $include_users, '', '0,'.$conf->entity, 0, 0, '', 0, '', 'minwidth200 maxwidth500');
614 print img_picto('', 'user').$form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
615 }
616
617
618 print '</td>';
619 print '</tr>';
620
621 //auto validation ON CREATE
622 print '<tr><td>'.$langs->trans("AutoValidationOnCreate").'</td><td>';
623 print '<input type="checkbox" id="autoValidation" name="autoValidation" value="1"'.($autoValidation ? ' checked="checked"' : '').'>';
624 print '</td></tr>'."\n";
625
626
627 //no auto SEND MAIL
628 print '<tr><td>'.$langs->trans("AutoSendMail").'</td><td>';
629 print '<input type="checkbox" id="AutoSendMail" name="AutoSendMail" value="1"'.($AutoSendMail ? ' checked="checked"' : '').'>';
630 print '</td></tr>'."\n";
631
632 // Description
633 print '<tr>';
634 print '<td>'.$langs->trans("DescCP").'</td>';
635 print '<td class="tdtop">';
636 $doleditor = new DolEditor('description', GETPOST('description', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', 0, false, isModEnabled('fckeditor'), ROWS_3, '90%');
637 print $doleditor->Create(1);
638 print '</td></tr>';
639
640 // Other attributes
641 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
642
643 print '</tbody>';
644 print '</table>';
645
646 print dol_get_fiche_end();
647
648 print $form->buttonsSaveCancel("SendRequestCollectiveCP");
649
650 print '</from>'."\n";
651 }
652} else {
653 if ($error) {
654 print '<div class="tabBar">';
655 print $error;
656 print '<br><br><input type="button" value="'.$langs->trans("ReturnCP").'" class="button" onclick="history.go(-1)" />';
657 print '</div>';
658 }
659}
660
661// End of page
662llxFooter();
663
664if (is_object($db)) {
665 $db->close();
666}
667
679function sendMail($id, $cancreate, $now, $autoValidation)
680{
681 $objStd = new stdClass();
682 $objStd->msg = '';
683 $objStd->status = 'success';
684 $objStd->error = 0;
685 $objStd->style = '';
686
687 global $db, $user, $langs;
688
689 $object = new Holiday($db);
690
691 $result = $object->fetch($id);
692
693 if ($result) {
694 // If draft and owner of leave
695 if ($object->status == Holiday::STATUS_VALIDATED && $cancreate) {
696 $object->oldcopy = dol_clone($object, 2);
697
698 //if ($autoValidation) $object->status = Holiday::STATUS_VALIDATED;
699
700 $verif = $object->validate($user);
701
702 if ($verif > 0) {
703 // To
704 $destinataire = new User($db);
705 $destinataire->fetch($object->fk_validator);
706 $emailTo = $destinataire->email;
707
708
709 if (!$emailTo) {
710 dol_syslog("Expected validator has no email, so we redirect directly to finished page without sending email");
711
712 $objStd->error++;
713 $objStd->msg = $langs->trans('ErrorMailRecipientIsEmpty');
714 $objStd->status = 'error';
715 $objStd->style = "warnings";
716 return $objStd;
717 }
718
719 // From
720 $expediteur = new User($db);
721 $expediteur->fetch($object->fk_user);
722 //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
723 $emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
724
725 // Subject
726 $societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
727 if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
728 $societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
729 }
730
731 $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysToValidate");
732
733 // Content
734 $message = "<p>".$langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",</p>\n";
735
736 $message .= "<p>".$langs->transnoentities("HolidaysToValidateBody")."</p>\n";
737
738
739 // option to warn the validator in case of too short delay
740 if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_TOO_LOW_DELAY')) {
741 $delayForRequest = 0; // TODO Set delay depending of holiday leave type
742 if ($delayForRequest) {
743 $nowplusdelay = dol_time_plus_duree($now, $delayForRequest, 'd');
744
745 if ($object->date_debut < $nowplusdelay) {
746 $message = "<p>".$langs->transnoentities("HolidaysToValidateDelay", $delayForRequest)."</p>\n";
747 }
748 }
749 }
750
751 // option to notify the validator if the balance is less than the request
752 if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_NEGATIVE_BALANCE')) {
753 $nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday);
754
755 if ($nbopenedday > $object->getCPforUser($object->fk_user, $object->fk_type)) {
756 $message .= "<p>".$langs->transnoentities("HolidaysToValidateAlertSolde")."</p>\n";
757 }
758 }
759
760 $typeleaves = $object->getTypes(1, -1);
761 $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']);
762
763 if ($object->halfday == 2) {
764 $starthalfdaykey = "Afternoon";
765 $endhalfdaykey = "Morning";
766 } elseif ($object->halfday == -1) {
767 $starthalfdaykey = "Afternoon";
768 $endhalfdaykey = "Afternoon";
769 } elseif ($object->halfday == 1) {
770 $starthalfdaykey = "Morning";
771 $endhalfdaykey = "Morning";
772 } elseif ($object->halfday == 0 || $object->halfday == 2) {
773 $starthalfdaykey = "Morning";
774 $endhalfdaykey = "Afternoon";
775 }
776
777 $link = dol_buildpath("/holiday/card.php", 3) . '?id='.$object->id;
778
779 $message .= "<ul>";
780 $message .= "<li>".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."</li>\n";
781 $message .= "<li>".$langs->transnoentitiesnoconv("Type")." : ".(empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow)."</li>\n";
782 $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";
783 $message .= "<li>".$langs->transnoentitiesnoconv("Link").' : <a href="'.$link.'" target="_blank">'.$link."</a></li>\n";
784 $message .= "</ul>\n";
785
786 $trackid = 'leav'.$object->id;
787
788 $sendtobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_HOLIDAY_TO');
789
790 $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', $sendtobcc, 0, 1, '', '', $trackid);
791
792 // Sending the email
793 $result = $mail->sendfile();
794
795 if (!$result) {
796 $objStd->error++;
797 $objStd->msg = $langs->trans('ErrorMailNotSend');
798 $objStd->style = "warnings";
799 $objStd->status = 'error';
800 } else {
801 $objStd->msg = $langs->trans('MailSent');
802 }
803
804 return $objStd;
805 } else {
806 $objStd->error++;
807 $objStd->msg = $langs->trans('ErrorVerif');
808 $objStd->status = 'error';
809 $objStd->style = "errors";
810 return $objStd;
811 }
812 }
813 } else {
814 $objStd->error++;
815 $objStd->msg = $langs->trans('ErrorloadUserOnSendingMail');
816 $objStd->status = 'error';
817 $objStd->style = "warnings";
818 return $objStd;
819 }
820
821 return $objStd;
822}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
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:70
if(is_object( $db)) sendMail($id, $cancreate, $now, $autoValidation)
send email to validator for current leave represented by (id)
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage a WYSIWYG editor.
Class to manage standard extra fields.
Class to manage generation of HTML components Only common components must be here.
Class of the module paid holiday.
const STATUS_VALIDATED
Validated status.
const STATUS_DRAFT
Draft status.
Class to manage Dolibarr users.
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:124
llxFooter()
Footer empty.
Definition document.php:107
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
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)
Show tabs of a record.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dol_now($mode='auto')
Return date for now.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
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.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='')
Show information in HTML for admin users or standard users.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
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.