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