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