dolibarr 25.0.0-alpha
holiday.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2011 Dimitri Mouillard <dmouillard@teclib.com>
3 * Copyright (C) 2012-2014 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2012-2016 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
6 * Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es>
7 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
9 * Copyright (C) 2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
30require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31
32
36class Holiday extends CommonObject
37{
41 public $element = 'holiday';
42
47 public $TRIGGER_PREFIX = 'HOLIDAY';
48
52 public $table_element = 'holiday';
53
57 public $fk_element = 'fk_holiday';
58
62 public $picto = 'holiday';
63
67 public $fk_user;
68
72 public $date_create = '';
73
77 public $description;
78
82 public $date_debut = '';
83
87 public $date_fin = '';
88
92 public $date_debut_gmt = '';
93
97 public $date_fin_gmt = '';
98
102 public $halfday = '';
103
108 public $statut = 0;
109
113 public $fk_validator;
114
118 public $date_valid = 0;
119
123 public $fk_user_valid;
124
128 public $date_approval;
129
133 public $fk_user_approve;
134
138 public $date_refuse = 0;
139
143 public $fk_user_refuse;
144
148 public $date_cancel = 0;
149
153 public $fk_user_cancel;
154
158 public $fk_user_create;
159
163 public $detail_refuse = '';
164
168 public $fk_type;
169
173 public $holiday = array();
174
175 public $events = array();
176
180 public $logs = array();
181
182
186 const STATUS_DRAFT = 1;
202 const STATUS_REFUSED = 5;
203
204
210 public function __construct($db)
211 {
212 $this->db = $db;
213
214 $this->ismultientitymanaged = 0;
215 }
216
217
225 public function getNextNumRef($objsoc)
226 {
227 global $langs, $conf;
228 $langs->load("order");
229
230 if (!getDolGlobalString('HOLIDAY_ADDON')) {
231 $conf->global->HOLIDAY_ADDON = 'mod_holiday_madonna';
232 }
233
234 if (getDolGlobalString('HOLIDAY_ADDON')) {
235 $mybool = false;
236
237 $file = getDolGlobalString('HOLIDAY_ADDON') . ".php";
238 $classname = getDolGlobalString('HOLIDAY_ADDON');
239
240 // Include file with class
241 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
242 foreach ($dirmodels as $reldir) {
243 $dir = dol_buildpath($reldir."core/modules/holiday/");
244
245 // Load file with numbering class (if found)
246 $mybool = ((bool) @include_once $dir.$file) || $mybool;
247 }
248
249 if (!$mybool) {
250 dol_print_error(null, "Failed to include file ".$file);
251 return '';
252 }
253
254 $obj = new $classname();
255 '@phan-var-force ModelNumRefHolidays $obj';
257 $numref = $obj->getNextValue($objsoc, $this);
258
259 if ($numref != "") {
260 return $numref;
261 } else {
262 $this->error = $obj->error;
263 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
264 return "";
265 }
266 } else {
267 print $langs->trans("Error")." ".$langs->trans("Error_HOLIDAY_ADDON_NotDefined");
268 return "";
269 }
270 }
271
277 public function updateBalance()
278 {
279 $this->db->begin();
280
281 // Update sold of vocations
282 $result = $this->updateSoldeCP();
283
284 // Check nb of users into table llx_holiday_users and update with empty lines
285 //if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser'));
286
287 if ($result >= 0) {
288 $this->db->commit();
289 return 0; // for cronjob use (0 is OK, any other value is an error code)
290 } else {
291 $this->db->rollback();
292 return -1;
293 }
294 }
295
303 public function create($user, $notrigger = 0)
304 {
305 global $conf;
306 $error = 0;
307
308 $now = dol_now();
309
310 // Check parameters
311 if (empty($this->fk_user) || !is_numeric($this->fk_user) || $this->fk_user < 0) {
312 $this->error = "ErrorBadParameterFkUser";
313 return -1;
314 }
315 if (empty($this->fk_validator) || !is_numeric($this->fk_validator) || $this->fk_validator < 0) {
316 $this->error = "ErrorBadParameterFkValidator";
317 return -1;
318 }
319 if (empty($this->fk_type) || !is_numeric($this->fk_type) || $this->fk_type < 0) {
320 $this->error = "ErrorBadParameterFkType";
321 return -1;
322 }
323
324 // Insert request
325 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday(";
326 $sql .= "ref,";
327 $sql .= "fk_user,";
328 $sql .= "date_create,";
329 $sql .= "description,";
330 $sql .= "date_debut,";
331 $sql .= "date_fin,";
332 $sql .= "halfday,";
333 $sql .= "statut,";
334 $sql .= "fk_validator,";
335 $sql .= "fk_type,";
336 $sql .= "fk_user_create,";
337 $sql .= "entity";
338 $sql .= ") VALUES (";
339 $sql .= "'(PROV)',";
340 $sql .= " ".((int) $this->fk_user).",";
341 $sql .= " '".$this->db->idate($now)."',";
342 $sql .= " '".$this->db->escape($this->description)."',";
343 $sql .= " '".$this->db->idate($this->date_debut)."',";
344 $sql .= " '".$this->db->idate($this->date_fin)."',";
345 $sql .= " ".((int) $this->halfday).",";
346 $sql .= " '1',";
347 $sql .= " ".((int) $this->fk_validator).",";
348 $sql .= " ".((int) $this->fk_type).",";
349 $sql .= " ".((int) $user->id).",";
350 $sql .= " ".((int) $conf->entity);
351 $sql .= ")";
352
353 $this->db->begin();
354
355 dol_syslog(get_class($this)."::create", LOG_DEBUG);
356 $resql = $this->db->query($sql);
357 if (!$resql) {
358 $error++;
359 $this->errors[] = "Error ".$this->db->lasterror();
360 }
361
362 if (!$error) {
363 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday");
364
365 if ($this->id) {
366 // update ref
367 $initialref = '(PROV'.$this->id.')';
368 if (!empty($this->ref)) {
369 $initialref = $this->ref;
370 }
371
372 $sql = 'UPDATE '.MAIN_DB_PREFIX."holiday SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id);
373 if ($this->db->query($sql)) {
374 $this->ref = $initialref;
375 $result = $this->insertExtraFields();
376 if ($result < 0) {
377 $error++;
378 }
379
380 if (!$error && !$notrigger) {
381 // Call trigger
382 $result = $this->call_trigger('HOLIDAY_CREATE', $user);
383 if ($result < 0) {
384 $error++;
385 }
386 // End call triggers
387 }
388 }
389 }
390 }
391
392 // Commit or rollback
393 if ($error) {
394 foreach ($this->errors as $errmsg) {
395 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
396 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
397 }
398 $this->db->rollback();
399 return -1 * $error;
400 } else {
401 $this->db->commit();
402 return $this->id;
403 }
404 }
405
406
414 public function fetch($id, $ref = '')
415 {
416 $sql = "SELECT";
417 $sql .= " cp.rowid,";
418 $sql .= " cp.ref,";
419 $sql .= " cp.fk_user,";
420 $sql .= " cp.date_create,";
421 $sql .= " cp.description,";
422 $sql .= " cp.date_debut,";
423 $sql .= " cp.date_fin,";
424 $sql .= " cp.halfday,";
425 $sql .= " cp.statut as status,";
426 $sql .= " cp.fk_validator,";
427 $sql .= " cp.date_valid,";
428 $sql .= " cp.fk_user_valid,";
429 $sql .= " cp.date_approval,";
430 $sql .= " cp.fk_user_approve,";
431 $sql .= " cp.date_refuse,";
432 $sql .= " cp.fk_user_refuse,";
433 $sql .= " cp.date_cancel,";
434 $sql .= " cp.fk_user_cancel,";
435 $sql .= " cp.detail_refuse,";
436 $sql .= " cp.note_private,";
437 $sql .= " cp.note_public,";
438 $sql .= " cp.fk_user_create,";
439 $sql .= " cp.fk_type,";
440 $sql .= " cp.entity";
441 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
442 if ($id > 0) {
443 $sql .= " WHERE cp.rowid = ".((int) $id);
444 } else {
445 $sql .= " WHERE cp.ref = '".$this->db->escape($ref)."'";
446 }
447
448 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
449 $resql = $this->db->query($sql);
450 if ($resql) {
451 if ($this->db->num_rows($resql)) {
452 $obj = $this->db->fetch_object($resql);
453
454 $this->id = (int) $obj->rowid;
455 $this->ref = (string) ($obj->ref ? $obj->ref : $obj->rowid);
456 $this->fk_user = (int) $obj->fk_user;
457 $this->date_create = $this->db->jdate($obj->date_create);
458 $this->description = $obj->description;
459
460 $this->date_debut = $this->db->jdate($obj->date_debut);
461 $this->date_fin = $this->db->jdate($obj->date_fin);
462 $this->date_debut_gmt = $this->db->jdate($obj->date_debut, 1);
463 $this->date_fin_gmt = $this->db->jdate($obj->date_fin, 1);
464
465 $this->halfday = (int) $obj->halfday;
466 $this->status = (int) $obj->status;
467 $this->statut = (int) $obj->status; // deprecated
468 $this->fk_validator = $obj->fk_validator;
469 $this->date_valid = $this->db->jdate($obj->date_valid);
470 $this->fk_user_valid = $obj->fk_user_valid;
471 $this->user_validation_id = $obj->fk_user_valid;
472 $this->date_approval = $this->db->jdate($obj->date_approval);
473 $this->fk_user_approve = $obj->fk_user_approve;
474 $this->date_refuse = $this->db->jdate($obj->date_refuse);
475 $this->fk_user_refuse = $obj->fk_user_refuse;
476 $this->date_cancel = $this->db->jdate($obj->date_cancel);
477 $this->fk_user_cancel = $obj->fk_user_cancel;
478 $this->detail_refuse = $obj->detail_refuse;
479 $this->note_private = $obj->note_private;
480 $this->note_public = $obj->note_public;
481 $this->fk_user_create = $obj->fk_user_create;
482 $this->fk_type = $obj->fk_type;
483 $this->entity = $obj->entity;
484
485 $this->fetch_optionals();
486
487 $result = 1;
488 } else {
489 $result = 0;
490 }
491 $this->db->free($resql);
492
493 return $result;
494 } else {
495 $this->error = "Error ".$this->db->lasterror();
496 return -1;
497 }
498 }
499
508 public function fetchByUser($user_id, $order = '', $filter = '')
509 {
510 $this->holiday = [];
511 $sql = "SELECT";
512 $sql .= " cp.rowid,";
513 $sql .= " cp.ref,";
514
515 $sql .= " cp.fk_user,";
516 $sql .= " cp.fk_type,";
517 $sql .= " cp.date_create,";
518 $sql .= " cp.tms as date_modification,";
519 $sql .= " cp.description,";
520 $sql .= " cp.date_debut,";
521 $sql .= " cp.date_fin,";
522 $sql .= " cp.halfday,";
523 $sql .= " cp.statut as status,";
524 $sql .= " cp.fk_validator,";
525 $sql .= " cp.date_valid,";
526 $sql .= " cp.fk_user_valid,";
527 $sql .= " cp.date_approval,";
528 $sql .= " cp.fk_user_approve,";
529 $sql .= " cp.date_refuse,";
530 $sql .= " cp.fk_user_refuse,";
531 $sql .= " cp.date_cancel,";
532 $sql .= " cp.fk_user_cancel,";
533 $sql .= " cp.detail_refuse,";
534
535 $sql .= " uu.lastname as user_lastname,";
536 $sql .= " uu.firstname as user_firstname,";
537 $sql .= " uu.login as user_login,";
538 $sql .= " uu.statut as user_status,";
539 $sql .= " uu.photo as user_photo,";
540
541 $sql .= " ua.lastname as validator_lastname,";
542 $sql .= " ua.firstname as validator_firstname,";
543 $sql .= " ua.login as validator_login,";
544 $sql .= " ua.statut as validator_status,";
545 $sql .= " ua.photo as validator_photo";
546
547 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
548 $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
549 $sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid"; // Hack needed for search on the list
550 $sql .= " AND cp.fk_user IN (".$this->db->sanitize($user_id).")";
551
552 // Selection filter
553 if (!empty($filter)) {
554 $sql .= $filter; // @phan-suppress-current-line SqlInjection
555 }
556
557 // Order of display of the result
558 if (!empty($order)) {
559 $sql .= $order; // @phan-suppress-current-line SqlInjection
560 }
561
562 dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG);
563 $resql = $this->db->query($sql);
564
565 // If no SQL error
566 if ($resql) {
567 $i = 0;
568 $tab_result = $this->holiday;
569 $num = $this->db->num_rows($resql);
570
571 // If no registration
572 if (!$num) {
573 return 2;
574 }
575
576 // List the records and add them to the table
577 while ($i < $num) {
578 $obj = $this->db->fetch_object($resql);
579
580 $tab_result[$i]['rowid'] = (int) $obj->rowid;
581 $tab_result[$i]['id'] = (int) $obj->rowid;
582 $tab_result[$i]['ref'] = (string) ($obj->ref ? $obj->ref : $obj->rowid);
583
584 $tab_result[$i]['fk_user'] = (int) $obj->fk_user;
585 $tab_result[$i]['fk_type'] = (int) $obj->fk_type;
586 $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
587 $tab_result[$i]['date_modification'] = $this->db->jdate($obj->date_modification);
588 $tab_result[$i]['description'] = (string) $obj->description;
589 $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
590 $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
591 $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
592 $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
593 $tab_result[$i]['halfday'] = (int) $obj->halfday;
594 $tab_result[$i]['statut'] = (int) $obj->status;
595 $tab_result[$i]['status'] = (int) $obj->status;
596 $tab_result[$i]['fk_validator'] = (int) $obj->fk_validator;
597 $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
598 $tab_result[$i]['fk_user_valid'] = (int) $obj->fk_user_valid;
599 $tab_result[$i]['date_approval'] = $this->db->jdate($obj->date_approval);
600 $tab_result[$i]['fk_user_approve'] = (int) $obj->fk_user_approve;
601 $tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
602 $tab_result[$i]['fk_user_refuse'] = (int) $obj->fk_user_refuse;
603 $tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
604 $tab_result[$i]['fk_user_cancel'] = (int) $obj->fk_user_cancel;
605 $tab_result[$i]['detail_refuse'] = (string) $obj->detail_refuse;
606
607 $tab_result[$i]['user_firstname'] = (string) $obj->user_firstname;
608 $tab_result[$i]['user_lastname'] = (string) $obj->user_lastname;
609 $tab_result[$i]['user_login'] = (string) $obj->user_login;
610 $tab_result[$i]['user_statut'] = (int) $obj->user_status;
611 $tab_result[$i]['user_status'] = (int) $obj->user_status;
612 $tab_result[$i]['user_photo'] = (string) $obj->user_photo;
613
614 $tab_result[$i]['validator_firstname'] = (string) $obj->validator_firstname;
615 $tab_result[$i]['validator_lastname'] = (string) $obj->validator_lastname;
616 $tab_result[$i]['validator_login'] = (string) $obj->validator_login;
617 $tab_result[$i]['validator_statut'] = (int) $obj->validator_status;
618 $tab_result[$i]['validator_status'] = (int) $obj->validator_status;
619 $tab_result[$i]['validator_photo'] = (string) $obj->validator_photo;
620
621 $i++;
622 }
623
624 // Returns 1 with the filled array
625 $this->holiday = $tab_result;
626 return 1;
627 } else {
628 // SQL Error
629 $this->error = "Error ".$this->db->lasterror();
630 return -1;
631 }
632 }
633
641 public function fetchAll($sqlOrder, $sqlFilter)
642 {
643 $sql = "SELECT";
644 $sql .= " cp.rowid,";
645 $sql .= " cp.ref,";
646 $sql .= " cp.fk_user,";
647 $sql .= " cp.fk_type,";
648 $sql .= " cp.date_create,";
649 $sql .= " cp.tms as date_modification,";
650 $sql .= " cp.description,";
651 $sql .= " cp.date_debut,";
652 $sql .= " cp.date_fin,";
653 $sql .= " cp.halfday,";
654 $sql .= " cp.statut as status,";
655 $sql .= " cp.fk_validator,";
656 $sql .= " cp.date_valid,";
657 $sql .= " cp.fk_user_valid,";
658 $sql .= " cp.date_approval,";
659 $sql .= " cp.fk_user_approve,";
660 $sql .= " cp.date_refuse,";
661 $sql .= " cp.fk_user_refuse,";
662 $sql .= " cp.date_cancel,";
663 $sql .= " cp.fk_user_cancel,";
664 $sql .= " cp.detail_refuse,";
665
666 $sql .= " uu.lastname as user_lastname,";
667 $sql .= " uu.firstname as user_firstname,";
668 $sql .= " uu.login as user_login,";
669 $sql .= " uu.statut as user_status,";
670 $sql .= " uu.photo as user_photo,";
671
672 $sql .= " ua.lastname as validator_lastname,";
673 $sql .= " ua.firstname as validator_firstname,";
674 $sql .= " ua.login as validator_login,";
675 $sql .= " ua.statut as validator_status,";
676 $sql .= " ua.photo as validator_photo";
677
678 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
679 $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
680 $sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack needed for search on the list
681
682 // Selection filtering
683 if (!empty($sqlFilter)) {
684 $sql .= $sqlFilter;
685 }
686
687 // order of display
688 if (!empty($sqlOrder)) {
689 $sql .= $sqlOrder;
690 }
691
692 dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
693 $resql = $this->db->query($sql);
694
695 // If no SQL error
696 if ($resql) {
697 $i = 0;
698 $tab_result = $this->holiday;
699 $num = $this->db->num_rows($resql);
700
701 // If no registration
702 if (!$num) {
703 return 2;
704 }
705
706 // List the records and add them to the table
707 while ($i < $num) {
708 $obj = $this->db->fetch_object($resql);
709
710 $tab_result[$i]['rowid'] = (int) $obj->rowid;
711 $tab_result[$i]['id'] = (int) $obj->rowid;
712 $tab_result[$i]['ref'] = (string) ($obj->ref ? $obj->ref : $obj->rowid);
713
714 $tab_result[$i]['fk_user'] = (int) $obj->fk_user;
715 $tab_result[$i]['fk_type'] = (int) $obj->fk_type;
716 $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
717 $tab_result[$i]['date_modification'] = $this->db->jdate($obj->date_modification);
718 $tab_result[$i]['description'] = (string) $obj->description;
719 $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
720 $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
721 $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
722 $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
723 $tab_result[$i]['halfday'] = (int) $obj->halfday;
724 $tab_result[$i]['statut'] = (int) $obj->status;
725 $tab_result[$i]['status'] = (int) $obj->status;
726 $tab_result[$i]['fk_validator'] = (int) $obj->fk_validator;
727 $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
728 $tab_result[$i]['fk_user_valid'] = (int) $obj->fk_user_valid;
729 $tab_result[$i]['date_approval'] = $this->db->jdate($obj->date_approval);
730 $tab_result[$i]['fk_user_approve'] = (int) $obj->fk_user_approve;
731 $tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
732 $tab_result[$i]['fk_user_refuse'] = (int) $obj->fk_user_refuse;
733 $tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
734 $tab_result[$i]['fk_user_cancel'] = (int) $obj->fk_user_cancel;
735 $tab_result[$i]['detail_refuse'] = (string) $obj->detail_refuse;
736
737 $tab_result[$i]['user_firstname'] = (string) $obj->user_firstname;
738 $tab_result[$i]['user_lastname'] = (string) $obj->user_lastname;
739 $tab_result[$i]['user_login'] = (string) $obj->user_login;
740 $tab_result[$i]['user_statut'] = (int) $obj->user_status;
741 $tab_result[$i]['user_status'] = (int) $obj->user_status;
742 $tab_result[$i]['user_photo'] = (string) $obj->user_photo;
743
744 $tab_result[$i]['validator_firstname'] = (string) $obj->validator_firstname;
745 $tab_result[$i]['validator_lastname'] = (string) $obj->validator_lastname;
746 $tab_result[$i]['validator_login'] = (string) $obj->validator_login;
747 $tab_result[$i]['validator_statut'] = (int) $obj->validator_status;
748 $tab_result[$i]['validator_status'] = (int) $obj->validator_status;
749 $tab_result[$i]['validator_photo'] = (string) $obj->validator_photo;
750
751 $i++;
752 }
753 // Returns 1 and adds the array to the variable
754 $this->holiday = $tab_result;
755 return 1;
756 } else {
757 // SQL Error
758 $this->error = "Error ".$this->db->lasterror();
759 return -1;
760 }
761 }
762
763
771 public function validate($user = null, $notrigger = 0)
772 {
773 global $conf, $langs;
774 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
775 $error = 0;
776
777
778 $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type, true);
779
780 if ($checkBalance > 0) {
781 $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
782
783 // Use the GMT variants: num_public_holiday(), called by num_open_day(), refuses a range whose
784 // length is not a whole number of days, and a range spanning a DST transition is 23h or 25h
785 // long in the server timezone. It then returns a string and the subtraction fatals.
786 $datedebutforcount = !empty($this->date_debut_gmt) ? $this->date_debut_gmt : $this->date_debut;
787 $datefinforcount = !empty($this->date_fin_gmt) ? $this->date_fin_gmt : $this->date_fin;
788 $daysAsked = num_open_day($datedebutforcount, $datefinforcount, 0, 1, 0, '', $this->fk_user);
789
790 if (($balance - $daysAsked) < 0) {
791 $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
792 return -1;
793 }
794 }
795
796 // Define new ref
797 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref) || $this->ref == $this->id) {
798 $num = $this->getNextNumRef(null);
799 } else {
800 $num = (string) $this->ref;
801 }
802 $this->newref = dol_sanitizeFileName($num);
803
804 // Update status
805 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
806 $sql .= " fk_user_valid = ".((int) $user->id).",";
807 $sql .= " date_valid = '".$this->db->idate(dol_now())."',";
808 if (!empty($this->status) && is_numeric($this->status)) {
809 $sql .= " statut = ".((int) $this->status).",";
810 } else {
811 $this->error = 'Property status must be a numeric value';
812 $error++;
813 }
814 $sql .= " ref = '".$this->db->escape($num)."'";
815 $sql .= " WHERE rowid = ".((int) $this->id);
816
817 $this->db->begin();
818
819 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
820 $resql = $this->db->query($sql);
821 if (!$resql) {
822 $error++;
823 $this->errors[] = "Error ".$this->db->lasterror();
824 }
825
826 if (!$error) {
827 if (!$notrigger) {
828 // Call trigger
829 $result = $this->call_trigger('HOLIDAY_VALIDATE', $user);
830 if ($result < 0) {
831 $error++;
832 }
833 // End call triggers
834 }
835 }
836
837 if (!$error) {
838 $this->oldref = $this->ref;
839
840 // Rename directory if dir was a temporary ref
841 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
842 // Now we rename also files into index
843 $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filename = CONCAT('" . $this->db->escape($this->newref) . "', SUBSTR(filename, " . (strlen($this->ref) + 1) . ")), filepath = 'holiday/" . $this->db->escape($this->newref) . "'";
844 $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%' AND filepath = 'holiday/" . $this->db->escape($this->ref) . "' and entity = " . ((int) $conf->entity);
845 $resql = $this->db->query($sql);
846 if (!$resql) {
847 $error++;
848 $this->error = $this->db->lasterror();
849 }
850 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'holiday/".$this->db->escape($this->newref)."'";
851 $sql .= " WHERE filepath = 'holiday/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
852 $resql = $this->db->query($sql);
853 if (!$resql) {
854 $error++;
855 $this->error = $this->db->lasterror();
856 }
857
858 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
859 $oldref = dol_sanitizeFileName($this->ref);
860 $newref = dol_sanitizeFileName($num);
861 $dirsource = $conf->holiday->multidir_output[$this->entity] . '/' . $oldref;
862 $dirdest = $conf->holiday->multidir_output[$this->entity] . '/' . $newref;
863 if (!$error && file_exists($dirsource)) {
864 dol_syslog(get_class($this) . "::validate rename dir " . $dirsource . " into " . $dirdest);
865 if (@rename($dirsource, $dirdest)) {
866 dol_syslog("Rename ok");
867 // Rename docs starting with $oldref with $newref
868 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^' . preg_quote($oldref, '/'));
869 foreach ($listoffiles as $fileentry) {
870 $dirsource = $fileentry['name'];
871 $dirdest = preg_replace('/^' . preg_quote($oldref, '/') . '/', $newref, $dirsource);
872 $dirsource = $fileentry['path'] . '/' . $dirsource;
873 $dirdest = $fileentry['path'] . '/' . $dirdest;
874 @rename($dirsource, $dirdest);
875 }
876 }
877 }
878 }
879 }
880
881
882 // Commit or rollback
883 if ($error) {
884 foreach ($this->errors as $errmsg) {
885 dol_syslog(get_class($this)."::validate ".$errmsg, LOG_ERR);
886 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
887 }
888 $this->db->rollback();
889 return -1 * $error;
890 } else {
891 $this->db->commit();
892 return 1;
893 }
894 }
895
896
904 public function approve($user = null, $notrigger = 0)
905 {
906 $error = 0;
907
908 $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type, true);
909
910 if ($checkBalance > 0) {
911 $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
912
913 // Use the GMT variants: num_public_holiday(), called by num_open_day(), refuses a range whose
914 // length is not a whole number of days, and a range spanning a DST transition is 23h or 25h
915 // long in the server timezone. It then returns a string and the subtraction fatals.
916 $datedebutforcount = !empty($this->date_debut_gmt) ? $this->date_debut_gmt : $this->date_debut;
917 $datefinforcount = !empty($this->date_fin_gmt) ? $this->date_fin_gmt : $this->date_fin;
918 $daysAsked = num_open_day($datedebutforcount, $datefinforcount, 0, 1, 0, '', $this->fk_user);
919
920 if (($balance - $daysAsked) < 0) {
921 $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
922 return -1;
923 }
924 }
925
926 // Update request
927 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
928 $sql .= " description= '".$this->db->escape($this->description)."',";
929 if (!empty($this->date_debut)) {
930 $sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
931 } else {
932 $error++;
933 }
934 if (!empty($this->date_fin)) {
935 $sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
936 } else {
937 $error++;
938 }
939 $sql .= " halfday = ".((int) $this->halfday).",";
940 if (!empty($this->status) && is_numeric($this->status)) {
941 $sql .= " statut = ".((int) $this->status).",";
942 } else {
943 $error++;
944 }
945 if (!empty($this->fk_validator)) {
946 $sql .= " fk_validator = ".((int) $this->fk_validator).",";
947 } else {
948 $error++;
949 }
950 if (!empty($this->date_valid)) {
951 $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
952 } else {
953 $sql .= " date_valid = NULL,";
954 }
955 if (!empty($this->fk_user_valid)) {
956 $sql .= " fk_user_valid = ".((int) $this->fk_user_valid).",";
957 } else {
958 $sql .= " fk_user_valid = NULL,";
959 }
960 if (!empty($this->date_approval)) {
961 $sql .= " date_approval = '".$this->db->idate($this->date_approval)."',";
962 } else {
963 $sql .= " date_approval = NULL,";
964 }
965 if (!empty($this->fk_user_approve)) {
966 $sql .= " fk_user_approve = ".((int) $this->fk_user_approve).",";
967 } else {
968 $sql .= " fk_user_approve = NULL,";
969 }
970 if (!empty($this->date_refuse)) {
971 $sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
972 } else {
973 $sql .= " date_refuse = NULL,";
974 }
975 if (!empty($this->fk_user_refuse)) {
976 $sql .= " fk_user_refuse = ".((int) $this->fk_user_refuse).",";
977 } else {
978 $sql .= " fk_user_refuse = NULL,";
979 }
980 if (!empty($this->date_cancel)) {
981 $sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
982 } else {
983 $sql .= " date_cancel = NULL,";
984 }
985 if (!empty($this->fk_user_cancel)) {
986 $sql .= " fk_user_cancel = ".((int) $this->fk_user_cancel).",";
987 } else {
988 $sql .= " fk_user_cancel = NULL,";
989 }
990 if (!empty($this->detail_refuse)) {
991 $sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
992 } else {
993 $sql .= " detail_refuse = NULL";
994 }
995 $sql .= " WHERE rowid = ".((int) $this->id);
996
997 $this->db->begin();
998
999 dol_syslog(get_class($this)."::approve", LOG_DEBUG);
1000 $resql = $this->db->query($sql);
1001 if (!$resql) {
1002 $error++;
1003 $this->errors[] = "Error ".$this->db->lasterror();
1004 }
1005
1006 if (!$error) {
1007 if (!$notrigger) {
1008 // Call trigger
1009 $result = $this->call_trigger('HOLIDAY_APPROVE', $user);
1010 if ($result < 0) {
1011 $error++;
1012 }
1013 // End call triggers
1014 }
1015 }
1016
1017 // Commit or rollback
1018 if ($error) {
1019 foreach ($this->errors as $errmsg) {
1020 dol_syslog(get_class($this)."::approve ".$errmsg, LOG_ERR);
1021 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1022 }
1023 $this->db->rollback();
1024 return -1 * $error;
1025 } else {
1026 $this->db->commit();
1027 return 1;
1028 }
1029 }
1030
1038 public function update($user = null, $notrigger = 0)
1039 {
1040 $error = 0;
1041
1042 $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type, true);
1043
1044 if ($checkBalance > 0 && $this->status != self::STATUS_DRAFT && $this->status != self::STATUS_CANCELED) {
1045 $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
1046
1047 // Use the GMT variants: num_public_holiday(), called by num_open_day(), refuses a range whose
1048 // length is not a whole number of days, and a range spanning a DST transition is 23h or 25h
1049 // long in the server timezone. It then returns a string and the subtraction fatals.
1050 $datedebutforcount = !empty($this->date_debut_gmt) ? $this->date_debut_gmt : $this->date_debut;
1051 $datefinforcount = !empty($this->date_fin_gmt) ? $this->date_fin_gmt : $this->date_fin;
1052 $daysAsked = num_open_day($datedebutforcount, $datefinforcount, 0, 1, 0, '', $this->fk_user);
1053
1054 if (($balance - $daysAsked) < 0) {
1055 $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
1056 return -1;
1057 }
1058 }
1059
1060 // Update request
1061 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
1062
1063 $sql .= " description= '".$this->db->escape($this->description)."',";
1064
1065 if (!empty($this->date_create)) {
1066 $sql .= " date_create = '".$this->db->idate($this->date_create)."',";
1067 } else {
1068 $error++;
1069 }
1070 if (!empty($this->date_debut)) {
1071 $sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
1072 } else {
1073 $error++;
1074 }
1075 if (!empty($this->date_fin)) {
1076 $sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
1077 } else {
1078 $error++;
1079 }
1080 $sql .= " halfday = ".((int) $this->halfday).",";
1081 if (!empty($this->status) && is_numeric($this->status)) {
1082 $sql .= " statut = ".((int) $this->status).",";
1083 } else {
1084 $error++;
1085 }
1086 if (!empty($this->fk_validator)) {
1087 $sql .= " fk_validator = ".((int) $this->fk_validator).",";
1088 } else {
1089 $error++;
1090 }
1091 if (!empty($this->date_valid)) {
1092 $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
1093 } else {
1094 $sql .= " date_valid = NULL,";
1095 }
1096 if (!empty($this->fk_user_valid)) {
1097 $sql .= " fk_user_valid = ".((int) $this->fk_user_valid).",";
1098 } else {
1099 $sql .= " fk_user_valid = NULL,";
1100 }
1101 if (!empty($this->date_approval)) {
1102 $sql .= " date_approval = '".$this->db->idate($this->date_approval)."',";
1103 } else {
1104 $sql .= " date_approval = NULL,";
1105 }
1106 if (!empty($this->fk_user_approve)) {
1107 $sql .= " fk_user_approve = ".((int) $this->fk_user_approve).",";
1108 } else {
1109 $sql .= " fk_user_approve = NULL,";
1110 }
1111 if (!empty($this->date_refuse)) {
1112 $sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
1113 } else {
1114 $sql .= " date_refuse = NULL,";
1115 }
1116 if (!empty($this->fk_user_refuse)) {
1117 $sql .= " fk_user_refuse = ".((int) $this->fk_user_refuse).",";
1118 } else {
1119 $sql .= " fk_user_refuse = NULL,";
1120 }
1121 if (!empty($this->date_cancel)) {
1122 $sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
1123 } else {
1124 $sql .= " date_cancel = NULL,";
1125 }
1126 if (!empty($this->fk_user_cancel)) {
1127 $sql .= " fk_user_cancel = ".((int) $this->fk_user_cancel).",";
1128 } else {
1129 $sql .= " fk_user_cancel = NULL,";
1130 }
1131 if (!empty($this->detail_refuse)) {
1132 $sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
1133 } else {
1134 $sql .= " detail_refuse = NULL";
1135 }
1136
1137 $sql .= " WHERE rowid = ".((int) $this->id);
1138
1139 $this->db->begin();
1140
1141 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1142 $resql = $this->db->query($sql);
1143 if (!$resql) {
1144 $error++;
1145 $this->errors[] = "Error ".$this->db->lasterror();
1146 }
1147
1148 if (!$error) {
1149 $result = $this->insertExtraFields();
1150 if ($result < 0) {
1151 $error++;
1152 }
1153 }
1154
1155 if (!$error) {
1156 if (!$notrigger && $user !== null) {
1157 // Call trigger
1158 $result = $this->call_trigger('HOLIDAY_MODIFY', $user);
1159 if ($result < 0) {
1160 $error++;
1161 }
1162 // End call triggers
1163 }
1164 }
1165
1166 // Commit or rollback
1167 if ($error) {
1168 foreach ($this->errors as $errmsg) {
1169 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1170 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1171 }
1172 $this->db->rollback();
1173 return -1 * $error;
1174 } else {
1175 $this->db->commit();
1176 return 1;
1177 }
1178 }
1179
1180
1188 public function delete($user, $notrigger = 0)
1189 {
1190 global $conf, $langs;
1191 $error = 0;
1192
1193 $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday";
1194 $sql .= " WHERE rowid=".((int) $this->id);
1195
1196 $this->db->begin();
1197
1198 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1199 $resql = $this->db->query($sql);
1200 if (!$resql) {
1201 $error++;
1202 $this->errors[] = "Error ".$this->db->lasterror();
1203 }
1204
1205 if (!$error) {
1206 if (!$notrigger) {
1207 // Call trigger
1208 $result = $this->call_trigger('HOLIDAY_DELETE', $user);
1209 if ($result < 0) {
1210 $error++;
1211 }
1212 // End call triggers
1213 }
1214 }
1215
1216 // Commit or rollback
1217 if ($error) {
1218 foreach ($this->errors as $errmsg) {
1219 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1220 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1221 }
1222 $this->db->rollback();
1223 return -1 * $error;
1224 } else {
1225 $this->db->commit();
1226 return 1;
1227 }
1228 }
1229
1243 public function verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday = 0)
1244 {
1245 $this->fetchByUser($fk_user, '', '');
1246
1247 foreach ($this->holiday as $infos_CP) {
1248 if ($infos_CP['statut'] == Holiday::STATUS_CANCELED) {
1249 continue; // ignore not validated holidays
1250 }
1251 if ($infos_CP['statut'] == Holiday::STATUS_REFUSED) {
1252 continue; // ignore refused holidays
1253 }
1254 //var_dump("--");
1255 //var_dump("old: ".dol_print_date($infos_CP['date_debut'],'dayhour').' '.dol_print_date($infos_CP['date_fin'],'dayhour').' '.$infos_CP['halfday']);
1256 //var_dump("new: ".dol_print_date($dateStart,'dayhour').' '.dol_print_date($dateEnd,'dayhour').' '.$halfday);
1257
1258 // A new leave can fully contain an existing leave, so neither endpoint is inside the existing range.
1259 if ($dateStart < $infos_CP['date_debut'] && $dateEnd > $infos_CP['date_fin']) {
1260 return false;
1261 }
1262
1263 if ($halfday == 0) {
1264 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1265 return false;
1266 }
1267 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1268 return false;
1269 }
1270 } elseif ($halfday == -1) {
1271 // new start afternoon, new end afternoon
1272 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1273 if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1274 return false;
1275 }
1276 }
1277 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1278 if ($dateStart < $dateEnd) {
1279 return false;
1280 }
1281 if ($dateEnd < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1282 return false;
1283 }
1284 }
1285 } elseif ($halfday == 1) {
1286 // new start morning, new end morning
1287 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1288 if ($dateStart < $dateEnd) {
1289 return false;
1290 }
1291 if ($dateStart > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1292 return false;
1293 }
1294 }
1295 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1296 if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1297 return false;
1298 }
1299 }
1300 } elseif ($halfday == 2) {
1301 // new start afternoon, new end morning
1302 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1303 if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1304 return false;
1305 }
1306 }
1307 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1308 if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1309 return false;
1310 }
1311 }
1312 } else {
1313 dol_print_error(null, 'Bad value of parameter halfday when calling function verifDateHolidayCP');
1314 }
1315 }
1316
1317 return true;
1318 }
1319
1320
1330 public function verifDateHolidayForTimestamp($fk_user, $timestamp, $status = '-1')
1331 {
1332 $isavailablemorning = true;
1333 $isavailableafternoon = true;
1334
1335 // Check into leave requests
1336 $sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday, cp.statut as status";
1337 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
1338 $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
1339 $sql .= " AND cp.fk_user = ".(int) $fk_user;
1340 $sql .= " AND cp.date_debut <= '".$this->db->idate($timestamp)."' AND cp.date_fin >= '".$this->db->idate($timestamp)."'";
1341 if ($status != '-1') {
1342 $sql .= " AND cp.statut IN (".$this->db->sanitize($status).")";
1343 }
1344
1345 $resql = $this->db->query($sql);
1346 if ($resql) {
1347 $num_rows = $this->db->num_rows($resql); // Note, we can have 2 records if on is morning and the other one is afternoon
1348 if ($num_rows > 0) {
1349 $arrayofrecord = array();
1350 $i = 0;
1351 while ($i < $num_rows) {
1352 $obj = $this->db->fetch_object($resql);
1353
1354 // Note: $obj->halfday is 0:Full days, 2:Start afternoon end morning, -1:Start afternoon, 1:End morning
1355 $arrayofrecord[$obj->rowid] = array('date_start' => $this->db->jdate($obj->date_start), 'date_end' => $this->db->jdate($obj->date_end), 'halfday' => $obj->halfday, 'status' => $obj->status);
1356 $i++;
1357 }
1358
1359 // We found a record, user is on holiday by default, so is not available is true.
1360 $isavailablemorning = true;
1361 foreach ($arrayofrecord as $record) {
1362 if ($timestamp == $record['date_start'] && $record['halfday'] == 2) {
1363 continue;
1364 }
1365 if ($timestamp == $record['date_start'] && $record['halfday'] == -1) {
1366 continue;
1367 }
1368 $isavailablemorning = false;
1369 break;
1370 }
1371 $isavailableafternoon = true;
1372 foreach ($arrayofrecord as $record) {
1373 if ($timestamp == $record['date_end'] && $record['halfday'] == 2) {
1374 continue;
1375 }
1376 if ($timestamp == $record['date_end'] && $record['halfday'] == 1) {
1377 continue;
1378 }
1379 $isavailableafternoon = false;
1380 break;
1381 }
1382 }
1383 } else {
1384 dol_print_error($this->db);
1385 }
1386
1387 $result = array('morning' => (int) $isavailablemorning, 'afternoon' => (int) $isavailableafternoon);
1388 if (!$isavailablemorning) {
1389 $result['morning_reason'] = 'leave_request';
1390 }
1391 if (!$isavailableafternoon) {
1392 $result['afternoon_reason'] = 'leave_request';
1393 }
1394 return $result;
1395 }
1396
1403 public function getTooltipContentArray($params)
1404 {
1405 global $langs;
1406
1407 $langs->load('holiday');
1408 $nofetch = !empty($params['nofetch']);
1409
1410 $datas = array();
1411 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Holiday").'</u>';
1412 if (isset($this->status)) {
1413 $datas['picto'] .= ' '.$this->getLibStatut(5);
1414 }
1415 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1416 // show type for this record only in ajax to not overload lists
1417 if (!$nofetch && !empty($this->fk_type)) {
1418 $typeleaves = $this->getTypes(1, -1);
1419 if (empty($typeleaves[$this->fk_type])) {
1420 $labeltoshow = $langs->trans("TypeWasDisabledOrRemoved", $this->fk_type);
1421 } else {
1422 $labeltoshow = (($typeleaves[$this->fk_type]['code'] && $langs->trans($typeleaves[$this->fk_type]['code']) != $typeleaves[$this->fk_type]['code']) ? $langs->trans($typeleaves[$this->fk_type]['code']) : $typeleaves[$this->fk_type]['label']);
1423 }
1424 $datas['type'] = '<br><b>'.$langs->trans("Type") . ':</b> ' . $labeltoshow;
1425 }
1426 if (isset($this->halfday) && !empty($this->date_debut) && !empty($this->date_fin)) {
1427 $listhalfday = array(
1428 'morning' => $langs->trans("Morning"),
1429 "afternoon" => $langs->trans("Afternoon")
1430 );
1431 $starthalfday = ($this->halfday == -1 || $this->halfday == 2) ? 'afternoon' : 'morning';
1432 $endhalfday = ($this->halfday == 1 || $this->halfday == 2) ? 'morning' : 'afternoon';
1433 $datas['date_start'] = '<br><b>'.$langs->trans('DateDebCP') . '</b>: '. dol_print_date($this->date_debut, 'day') . '&nbsp;&nbsp;<span class="opacitymedium">'.$langs->trans($listhalfday[$starthalfday]).'</span>';
1434 $datas['date_end'] = '<br><b>'.$langs->trans('DateFinCP') . '</b>: '. dol_print_date($this->date_fin, 'day') . '&nbsp;&nbsp;<span class="opacitymedium">'.$langs->trans($listhalfday[$endhalfday]).'</span>';
1435 }
1436
1437
1438 return $datas;
1439 }
1440
1450 public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '')
1451 {
1452 global $conf, $langs, $hookmanager;
1453
1454 if (!empty($conf->dol_no_mouse_hover)) {
1455 $notooltip = 1; // Force disable tooltips
1456 }
1457
1458 $result = '';
1459 $params = [
1460 'id' => $this->id,
1461 'objecttype' => $this->element,
1462 'nofetch' => 1,
1463 ];
1464 $classfortooltip = 'classfortooltip';
1465 $dataparams = '';
1466 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1467 $classfortooltip = 'classforajaxtooltip';
1468 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1469 $label = '';
1470 } else {
1471 $label = implode($this->getTooltipContentArray($params));
1472 }
1473
1474 $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
1475
1476 //if ($option != 'nolink')
1477 //{
1478 // Add param to save lastsearch_values or not
1479 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1480 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1481 $add_save_lastsearch_values = 1;
1482 }
1483 if ($add_save_lastsearch_values) {
1484 $url .= '&save_lastsearch_values=1';
1485 }
1486 //}
1487
1488 $linkclose = '';
1489 if (empty($notooltip)) {
1490 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1491 $label = $langs->trans("ShowMyObject");
1492 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1493 }
1494 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1495 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1496 } else {
1497 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1498 }
1499
1500 $linkstart = '<a href="'.$url.'"';
1501 $linkstart .= $linkclose.'>';
1502 $linkend = '</a>';
1503
1504 $result .= $linkstart;
1505
1506 if ($withpicto) {
1507 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
1508 }
1509 if ($withpicto != 2) {
1510 $result .= $this->ref;
1511 }
1512 $result .= $linkend;
1513
1514 global $action;
1515 $hookmanager->initHooks(array($this->element . 'dao'));
1516 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1517 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1518 if ($reshook > 0) {
1519 $result = $hookmanager->resPrint;
1520 } else {
1521 $result .= $hookmanager->resPrint;
1522 }
1523 return $result;
1524 }
1525
1526
1533 public function getLibStatut($mode = 0)
1534 {
1535 return $this->LibStatut($this->status, $mode, $this->date_debut);
1536 }
1537
1538 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1547 public function LibStatut($status, $mode = 0, $startdate = '')
1548 {
1549 // phpcs:enable
1550 global $langs;
1551
1552 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1553 global $langs;
1554 //$langs->load("mymodule");
1555 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('DraftCP');
1556 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ToReviewCP');
1557 $this->labelStatus[self::STATUS_APPROVED] = $langs->transnoentitiesnoconv('ApprovedCP');
1558 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('CancelCP');
1559 $this->labelStatus[self::STATUS_REFUSED] = $langs->transnoentitiesnoconv('RefuseCP');
1560 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('DraftCP');
1561 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ToReviewCP');
1562 $this->labelStatusShort[self::STATUS_APPROVED] = $langs->transnoentitiesnoconv('ApprovedCP');
1563 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('CancelCP');
1564 $this->labelStatusShort[self::STATUS_REFUSED] = $langs->transnoentitiesnoconv('RefuseCP');
1565 }
1566
1567 $params = array();
1568 $statusType = 'status6';
1569 if (!empty($startdate) && $startdate >= dol_now()) { // If not yet passed, we use a green "in live" color
1570 $statusType = 'status4';
1571 $params = array('tooltip' => $this->labelStatus[$status].' - '.$langs->trans("Forthcoming"));
1572 }
1573 if ($status == self::STATUS_DRAFT) {
1574 $statusType = 'status0';
1575 }
1576 if ($status == self::STATUS_VALIDATED) {
1577 $statusType = 'status1';
1578 }
1579 if ($status == self::STATUS_CANCELED) {
1580 $statusType = 'status9';
1581 }
1582 if ($status == self::STATUS_REFUSED) {
1583 $statusType = 'status9';
1584 }
1585
1586 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode, '', $params);
1587 }
1588
1589
1598 public function selectStatutCP($selected = 0, $htmlname = 'select_statut', $morecss = 'minwidth125')
1599 {
1600 global $langs;
1601
1602 // List of status label
1603 $name = array('DraftCP', 'ToReviewCP', 'ApprovedCP', 'CancelCP', 'RefuseCP');
1604 $nb = count($name) + 1;
1605
1606 // Select HTML
1607 $out = '<select name="'.$htmlname.'" id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'">'."\n";
1608 $out .= '<option value="-1">&nbsp;</option>'."\n";
1609
1610 // Loop on status
1611 for ($i = 1; $i < $nb; $i++) {
1612 if ($i == $selected) {
1613 $out .= '<option value="'.$i.'" selected>'.$langs->trans($name[$i - 1]).'</option>'."\n";
1614 } else {
1615 $out .= '<option value="'.$i.'">'.$langs->trans($name[$i - 1]).'</option>'."\n";
1616 }
1617 }
1618
1619 $out .= "</select>\n";
1620
1621 $showempty = 0;
1622 $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($showempty < 0 ? (string) $showempty : '-1'), $morecss);
1623
1624 return $out;
1625 }
1626
1634 public function updateConfCP($name, $value)
1635 {
1636 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1637 $sql .= " value = '".$this->db->escape($value)."'";
1638 $sql .= " WHERE name = '".$this->db->escape($name)."'";
1639
1640 dol_syslog(get_class($this).'::updateConfCP name='.$name, LOG_DEBUG);
1641 $result = $this->db->query($sql);
1642 if ($result) {
1643 return true;
1644 }
1645
1646 return false;
1647 }
1648
1657 public function getConfCP($name, $createifnotfound = '')
1658 {
1659 $sql = "SELECT value";
1660 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_config";
1661 $sql .= " WHERE name = '".$this->db->escape($name)."'";
1662
1663 dol_syslog(get_class($this).'::getConfCP name='.$name.' createifnotfound='.$createifnotfound, LOG_DEBUG);
1664 $result = $this->db->query($sql);
1665
1666 if ($result) {
1667 $obj = $this->db->fetch_object($result);
1668 // Return value
1669 if (empty($obj)) {
1670 if ($createifnotfound) {
1671 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)";
1672 $sql .= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')";
1673 $result = $this->db->query($sql);
1674 if ($result) {
1675 return $createifnotfound;
1676 } else {
1677 $this->error = $this->db->lasterror();
1678 return -2;
1679 }
1680 } else {
1681 return '';
1682 }
1683 } else {
1684 return $obj->value;
1685 }
1686 } else {
1687 // Erreur SQL
1688 $this->error = $this->db->lasterror();
1689 return -1;
1690 }
1691 }
1692
1701 public function updateSoldeCP($userID = 0, $nbHoliday = 0, $fk_type = 0)
1702 {
1703 global $user, $langs;
1704
1705 $error = 0;
1706
1707 if (empty($userID) && empty($nbHoliday) && empty($fk_type)) {
1708 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
1709 $langs->load("holiday");
1710
1711 $decrease = getDolGlobalInt('HOLIDAY_DECREASE_AT_END_OF_MONTH');
1712
1713 // If updated for everyone at the beginning of the month
1714 $now = dol_now();
1715
1716 // Get month of last update
1717 $stringInDBForLastUpdate = $this->getConfCP('lastUpdate', dol_print_date($now, '%Y%m%d%H%M%S')); // Example '20200101120000'
1718 // The lastUpdate config row is created empty (value NULL) at install, so getConfCP() returns an empty value
1719 // the first time. Treat an empty value as "start from now" (like define_holiday.php does) instead of a very
1720 // old date, otherwise the catch-up loop below would credit every user with years of monthly accrual at once.
1721 if (empty($stringInDBForLastUpdate)) {
1722 $stringInDBForLastUpdate = dol_print_date($now, '%Y%m%d%H%M%S');
1723 }
1724 // Protection when $lastUpdate has a not valid value
1725 if ($stringInDBForLastUpdate < '20000101000000') {
1726 $stringInDBForLastUpdate = '20000101000000';
1727 }
1728 $lastUpdate = dol_stringtotime($stringInDBForLastUpdate);
1729 //print 'lastUpdate:'.$lastUpdate;exit;
1730
1731 $yearMonthLastUpdate = dol_print_date($lastUpdate, '%Y%m');
1732 $yearMonthNow = dol_print_date($now, '%Y%m');
1733 //print 'yearMonthLastUpdate='.$yearMonthLastUpdate.' yearMonthNow='.$yearMonthNow;
1734
1735 // If month date is not same than the one of last update (the one we saved in database), then we update the timestamp and balance of each open user,
1736 // catching up to the current month if a gap is detected
1737 while ($yearMonthLastUpdate < $yearMonthNow) {
1738 $this->db->begin();
1739
1740 $year = dol_print_date($lastUpdate, '%Y');
1741 $month = dol_print_date($lastUpdate, '%m');
1742
1743 $users = $this->fetchUsers(false, false, ' AND u.statut > 0');
1744 $nbUser = count($users);
1745
1746 $typeleaves = $this->getTypes(1, 1);
1747
1748 // Update each user counter
1749 foreach ($users as $userCounter) {
1750 $nbDaysToAdd = (isset($typeleaves[$userCounter['type']]['newbymonth']) ? $typeleaves[$userCounter['type']]['newbymonth'] : 0);
1751 if (empty($nbDaysToAdd)) {
1752 continue;
1753 }
1754
1755 dol_syslog("We update leave type id ".$userCounter['type']." for user id ".$userCounter['rowid'], LOG_DEBUG);
1756
1757 $nowHoliday = (float) $userCounter['nb_holiday'];
1758 $newSolde = $nowHoliday + $nbDaysToAdd;
1759
1760 // We add a log for each user when its balance gets increased
1761 $this->addLogCP($user->id, $userCounter['rowid'], $langs->trans('HolidayMonthlyCredit'), $newSolde, $userCounter['type']);
1762
1763 $result = $this->updateSoldeCP($userCounter['rowid'], $newSolde, $userCounter['type']);
1764
1765 if ($result < 0) {
1766 $this->db->rollback();
1767 return -1;
1768 }
1769
1770 if (empty($decrease)) {
1771 continue;
1772 }
1773
1774 // We fetch a user's holiday in the current month and then calculate the number of days to deduct if he has at least one registered
1775 $filter = " AND cp.statut = ".((int) self::STATUS_APPROVED);
1776 $filter .= " AND cp.date_fin >= '".$this->db->idate(dol_stringtotime(dol_print_date($lastUpdate, '%Y-%m-01')))."'";
1777 $filter .= " AND cp.date_debut <= '".$this->db->idate(dol_stringtotime(dol_print_date($lastUpdate, '%Y-%m-t')))."'";
1778 $filter .= " AND cp.fk_type = ".((int) $userCounter['type']);
1779 $this->fetchByUser($userCounter['id'], '', $filter);
1780
1781 if (empty($this->holiday)) {
1782 continue;
1783 }
1784
1785 $startOfMonth = dol_mktime(0, 0, 0, (int) $month, 1, (int) $year, 1);
1786 $endOfMonth = dol_mktime(0, 0, 0, (int) $month, (int) dol_print_date($lastUpdate, 't'), (int) $year, 1);
1787
1788 foreach ($this->holiday as $obj) {
1789 $startDate = $obj['date_debut_gmt'];
1790 $endDate = $obj['date_fin_gmt'];
1791
1792 if ($startDate <= $endOfMonth && $startDate < $startOfMonth) {
1793 $startDate = $startOfMonth;
1794 }
1795
1796 if ($startOfMonth <= $endDate && $endDate > $endOfMonth) {
1797 $endDate = $endOfMonth;
1798 }
1799
1800 $nbDaysToDeduct = (int) num_open_day($startDate, $endDate, 0, 1, $obj['halfday'], $obj['country_id'], $obj['fk_user']);
1801
1802 if ($nbDaysToDeduct <= 0) {
1803 continue;
1804 }
1805
1806 $newSolde -= $nbDaysToDeduct;
1807
1808 // We add a log for each user when its balance gets decreased
1809 $this->addLogCP($user->id, $userCounter['rowid'], $obj['ref'].' - '.$langs->trans('HolidayConsumption'), $newSolde, $userCounter['type']);
1810
1811 $result = $this->updateSoldeCP($userCounter['rowid'], $newSolde, $userCounter['type']);
1812
1813 if ($result < 0) {
1814 $this->db->rollback();
1815 return -1;
1816 }
1817 }
1818 }
1819
1820 // Updating the date of the last monthly balance update
1821 $newMonth = dol_get_next_month((int) dol_print_date($lastUpdate, '%m'), (int) dol_print_date($lastUpdate, '%Y'));
1822 $lastUpdate = dol_mktime(0, 0, 0, (int) $newMonth['month'], 1, (int) $newMonth['year']);
1823
1824 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1825 $sql .= " value = '".$this->db->escape(dol_print_date($lastUpdate, '%Y%m%d%H%M%S'))."'";
1826 $sql .= " WHERE name = 'lastUpdate'";
1827 $result = $this->db->query($sql);
1828
1829 if (!$result) {
1830 $this->db->rollback();
1831 return -1;
1832 }
1833
1834 $this->db->commit();
1835
1836 $yearMonthLastUpdate = dol_print_date($lastUpdate, '%Y%m');
1837 }
1838
1839 return 1;
1840 } else {
1841 // Update for one user
1842 $nbHoliday = price2num($nbHoliday, 5);
1843
1844 $sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users";
1845 $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1846 $resql = $this->db->query($sql);
1847 if ($resql) {
1848 $num = $this->db->num_rows($resql);
1849
1850 if ($num > 0) {
1851 // Update for user
1852 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET";
1853 $sql .= " nb_holiday = ".((float) $nbHoliday);
1854 $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1855 $result = $this->db->query($sql);
1856 if (!$result) {
1857 $error++;
1858 $this->errors[] = $this->db->lasterror();
1859 }
1860 } else {
1861 // Insert for user
1862 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users(nb_holiday, fk_user, fk_type) VALUES (";
1863 $sql .= ((float) $nbHoliday);
1864 $sql .= ", ".(int) $userID.", ".(int) $fk_type.")";
1865 $result = $this->db->query($sql);
1866 if (!$result) {
1867 $error++;
1868 $this->errors[] = $this->db->lasterror();
1869 }
1870 }
1871 } else {
1872 $this->errors[] = $this->db->lasterror();
1873 $error++;
1874 }
1875
1876 if (!$error) {
1877 return 1;
1878 } else {
1879 return -1;
1880 }
1881 }
1882 }
1883
1891 public function getCPforUser($user_id, $fk_type = 0)
1892 {
1893 $sql = "SELECT nb_holiday";
1894 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users";
1895 $sql .= " WHERE fk_user = ".(int) $user_id;
1896 if ($fk_type > 0) {
1897 $sql .= " AND fk_type = ".(int) $fk_type;
1898 }
1899
1900 dol_syslog(get_class($this).'::getCPforUser user_id='.$user_id.' type_id='.$fk_type, LOG_DEBUG);
1901 $result = $this->db->query($sql);
1902 if ($result) {
1903 $obj = $this->db->fetch_object($result);
1904 //return number_format($obj->nb_holiday,2);
1905 if ($obj) {
1906 return $obj->nb_holiday;
1907 } else {
1908 return null;
1909 }
1910 } else {
1911 return null;
1912 }
1913 }
1914
1923 public function fetchUsers($stringlist = true, $type = true, $sqlFilters = '')
1924 {
1925 dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG);
1926
1927 if ($stringlist) {
1928 if ($type) {
1929 // If user of Dolibarr
1930 $sql = "SELECT";
1931 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1932 $sql .= " DISTINCT";
1933 }
1934 $sql .= " u.rowid";
1935 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
1936
1937 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1938 $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1939 $sql .= " WHERE ((ug.fk_user = u.rowid";
1940 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
1941 $sql .= " OR u.entity = 0)"; // Show always superadmin
1942 } else {
1943 $sql .= " WHERE u.entity IN (".getEntity('user').")";
1944 }
1945 $sql .= " AND u.statut > 0";
1946 $sql .= " AND u.employee = 1"; // We only want employee users for holidays
1947 if ($sqlFilters) {
1948 $sql .= $sqlFilters;
1949 }
1950
1951 $resql = $this->db->query($sql);
1952
1953 // If no SQL error
1954 if ($resql) {
1955 $i = 0;
1956 $num = $this->db->num_rows($resql);
1957 $stringlist = '';
1958
1959 // User listing loops
1960 while ($i < $num) {
1961 $obj = $this->db->fetch_object($resql);
1962
1963 if ($i == 0) {
1964 $stringlist .= $obj->rowid;
1965 } else {
1966 $stringlist .= ', '.$obj->rowid;
1967 }
1968
1969 $i++;
1970 }
1971 // Returns the user table
1972 return $stringlist;
1973 } else {
1974 // SQL error
1975 $this->error = "Error ".$this->db->lasterror();
1976 return -1;
1977 }
1978 } else {
1979 // We want only list of vacation balance for user ids
1980 $sql = "SELECT DISTINCT cpu.fk_user";
1981 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
1982 $sql .= " WHERE cpu.fk_user = u.rowid";
1983 if ($sqlFilters) {
1984 $sql .= $sqlFilters;
1985 }
1986
1987 $resql = $this->db->query($sql);
1988
1989 // If no SQL error
1990 if ($resql) {
1991 $i = 0;
1992 $num = $this->db->num_rows($resql);
1993 $stringlist = '';
1994
1995 // User listing loops
1996 while ($i < $num) {
1997 $obj = $this->db->fetch_object($resql);
1998
1999 if ($i == 0) {
2000 $stringlist .= $obj->fk_user;
2001 } else {
2002 $stringlist .= ', '.$obj->fk_user;
2003 }
2004
2005 $i++;
2006 }
2007 // Returns the user table
2008 return $stringlist;
2009 } else {
2010 // SQL error
2011 $this->error = "Error ".$this->db->lasterror();
2012 return -1;
2013 }
2014 }
2015 } else {
2016 // If false, return array
2017 // List for Dolibarr users
2018 if ($type) {
2019 // If we need users of Dolibarr
2020 $sql = "SELECT";
2021 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2022 $sql .= " DISTINCT";
2023 }
2024 $sql .= " u.rowid, u.lastname, u.firstname, u.gender, u.fk_country as country_id, u.photo, u.employee, u.statut as status, u.fk_user";
2025 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2026
2027 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2028 $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2029 $sql .= " WHERE ((ug.fk_user = u.rowid";
2030 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
2031 $sql .= " OR u.entity = 0)"; // Show always superadmin
2032 } else {
2033 $sql .= " WHERE u.entity IN (".getEntity('user').")";
2034 }
2035
2036 $sql .= " AND u.statut > 0";
2037 $sql .= " AND u.employee = 1"; // We only want employee users for holidays
2038 if ($sqlFilters) {
2039 $sql .= $sqlFilters;
2040 }
2041
2042 $resql = $this->db->query($sql);
2043
2044 // If no SQL error
2045 if ($resql) {
2046 $i = 0;
2047 $tab_result = $this->holiday;
2048 $num = $this->db->num_rows($resql);
2049
2050 // User listing loops
2051 while ($i < $num) {
2052 $obj = $this->db->fetch_object($resql);
2053
2054 $tab_result[$i]['rowid'] = (int) $obj->rowid; // rowid of user
2055 $tab_result[$i]['id'] = (int) $obj->rowid; // id of user
2056 $tab_result[$i]['name'] = $obj->lastname; // deprecated
2057 $tab_result[$i]['lastname'] = $obj->lastname;
2058 $tab_result[$i]['firstname'] = $obj->firstname;
2059 $tab_result[$i]['gender'] = $obj->gender;
2060 $tab_result[$i]['status'] = (int) $obj->status;
2061 $tab_result[$i]['employee'] = (int) $obj->employee;
2062 $tab_result[$i]['photo'] = $obj->photo;
2063 $tab_result[$i]['fk_user'] = (int) $obj->fk_user; // rowid of manager
2064 $tab_result[$i]['country_id'] = (int) $obj->country_id; // id of country of user
2065 //$tab_result[$i]['type'] = $obj->type;
2066 //$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
2067
2068 $i++;
2069 }
2070 // Returns the user table
2071 return $tab_result;
2072 } else {
2073 // SQL error
2074 $this->errors[] = "Error ".$this->db->lasterror();
2075 return -1;
2076 }
2077 } else {
2078 // List of vacation balance users
2079 $sql = "SELECT cpu.fk_type, cpu.nb_holiday, u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut as status, u.fk_user";
2080 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
2081 $sql .= " WHERE cpu.fk_user = u.rowid";
2082 if ($sqlFilters) {
2083 $sql .= $sqlFilters;
2084 }
2085
2086 $resql = $this->db->query($sql);
2087
2088 // If no SQL error
2089 if ($resql) {
2090 $i = 0;
2091 $tab_result = $this->holiday;
2092 $num = $this->db->num_rows($resql);
2093
2094 // User listing loops
2095 while ($i < $num) {
2096 $obj = $this->db->fetch_object($resql);
2097
2098 $tab_result[$i]['rowid'] = $obj->rowid; // rowid of user
2099 $tab_result[$i]['id'] = $obj->rowid; // id of user
2100 $tab_result[$i]['name'] = $obj->lastname; // deprecated
2101 $tab_result[$i]['lastname'] = $obj->lastname;
2102 $tab_result[$i]['firstname'] = $obj->firstname;
2103 $tab_result[$i]['gender'] = $obj->gender;
2104 $tab_result[$i]['status'] = $obj->status;
2105 $tab_result[$i]['employee'] = $obj->employee;
2106 $tab_result[$i]['photo'] = $obj->photo;
2107 $tab_result[$i]['fk_user'] = $obj->fk_user; // rowid of manager
2108
2109 $tab_result[$i]['type'] = $obj->fk_type;
2110 $tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
2111
2112 $i++;
2113 }
2114 // Returns the user table
2115 return $tab_result;
2116 } else {
2117 // SQL error
2118 $this->error = "Error ".$this->db->lasterror();
2119 return -1;
2120 }
2121 }
2122 }
2123 }
2124
2125
2126 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2134 {
2135 // phpcs:enable
2136 $users_validator = array();
2137
2138 $sql = "SELECT DISTINCT ur.fk_user";
2139 $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2140 $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
2141 $sql .= "UNION";
2142 $sql .= " SELECT DISTINCT ugu.fk_user";
2143 $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2144 $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
2145 //print $sql;
2146
2147 dol_syslog(get_class($this)."::fetch_users_approver_holiday sql=".$sql);
2148 $result = $this->db->query($sql);
2149 if ($result) {
2150 $num_rows = $this->db->num_rows($result);
2151 $i = 0;
2152 while ($i < $num_rows) {
2153 $objp = $this->db->fetch_object($result);
2154 array_push($users_validator, $objp->fk_user);
2155 $i++;
2156 }
2157 return $users_validator;
2158 } else {
2159 $this->error = $this->db->lasterror();
2160 dol_syslog(get_class($this)."::fetch_users_approver_holiday Error ".$this->error, LOG_ERR);
2161 return -1;
2162 }
2163 }
2164
2165
2171 public function countActiveUsers()
2172 {
2173 $sql = "SELECT count(u.rowid) as compteur";
2174 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2175 $sql .= " WHERE u.statut > 0";
2176
2177 $result = $this->db->query($sql);
2178 $object = $this->db->fetch_object($result);
2179
2180 return $object->compteur;
2181 }
2188 {
2189 $sql = "SELECT count(u.rowid) as compteur";
2190 $sql .= " FROM ".MAIN_DB_PREFIX."user as u LEFT JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)";
2191 $sql .= " WHERE u.statut > 0 AND hu.fk_user IS NULL";
2192
2193 $result = $this->db->query($sql);
2194 $object = $this->db->fetch_object($result);
2195
2196 return $object->compteur;
2197 }
2198
2206 public function verifNbUsers($userDolibarrWithoutCP, $userCP)
2207 {
2208 if (empty($userCP)) {
2209 $userCP = 0;
2210 }
2211 dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP);
2212 return 1;
2213 }
2214
2215
2226 public function addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
2227 {
2228 $error = 0;
2229
2230 $prev_solde = price2num((float) $this->getCPforUser($fk_user_update, $fk_type), 5);
2231 $new_solde = price2num($new_solde, 5);
2232 //print "$prev_solde == $new_solde";
2233
2234 if ($prev_solde == $new_solde) {
2235 return 0;
2236 }
2237
2238 $this->db->begin();
2239
2240 // Insert request
2241 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_logs (";
2242 $sql .= "date_action,";
2243 $sql .= "fk_user_action,";
2244 $sql .= "fk_user_update,";
2245 $sql .= "type_action,";
2246 $sql .= "prev_solde,";
2247 $sql .= "new_solde,";
2248 $sql .= "fk_type";
2249 $sql .= ") VALUES (";
2250 $sql .= " '".$this->db->idate(dol_now())."',";
2251 $sql .= " ".((int) $fk_user_action).",";
2252 $sql .= " ".((int) $fk_user_update).",";
2253 $sql .= " '".$this->db->escape($label)."',";
2254 $sql .= " ".((float) $prev_solde).",";
2255 $sql .= " ".((float) $new_solde).",";
2256 $sql .= " ".((int) $fk_type);
2257 $sql .= ")";
2258
2259 $resql = $this->db->query($sql);
2260 if (!$resql) {
2261 $error++;
2262 $this->errors[] = "Error ".$this->db->lasterror();
2263 }
2264
2265 $optRowid = 0;
2266 if (!$error) {
2267 $optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs");
2268 }
2269
2270 // Commit or rollback
2271 if ($error) {
2272 foreach ($this->errors as $errmsg) {
2273 dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR);
2274 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2275 }
2276 $this->db->rollback();
2277 return -1 * $error;
2278 } else {
2279 $this->db->commit();
2280 return $optRowid;
2281 }
2282 }
2283
2291 public function fetchLog($sqlorder, $sqlwhere)
2292 {
2293 $sql = "SELECT";
2294 $sql .= " cpl.rowid,";
2295 $sql .= " cpl.date_action,";
2296 $sql .= " cpl.fk_user_action,";
2297 $sql .= " cpl.fk_user_update,";
2298 $sql .= " cpl.type_action,";
2299 $sql .= " cpl.prev_solde,";
2300 $sql .= " cpl.new_solde,";
2301 $sql .= " cpl.fk_type";
2302 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_logs as cpl";
2303 $sql .= " WHERE cpl.rowid > 0"; // To avoid error with other search and criteria
2304
2305 // Filter
2306 if (!empty($sqlwhere)) {
2307 $sql .= " ".$sqlwhere;
2308 }
2309
2310 // Order
2311 if (!empty($sqlorder)) {
2312 $sql .= " ".$sqlorder;
2313 }
2314
2315 dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG);
2316 $resql = $this->db->query($sql);
2317
2318 // If no error SQL
2319 if ($resql) {
2320 $i = 0;
2321 $tab_result = $this->logs;
2322 $num = $this->db->num_rows($resql);
2323
2324 // If no record
2325 if (!$num) {
2326 return 2;
2327 }
2328
2329 // Loop on result to fill the array
2330 while ($i < $num) {
2331 $obj = $this->db->fetch_object($resql);
2332
2333 $tab_result[$i]['rowid'] = (int) $obj->rowid;
2334 $tab_result[$i]['id'] = (int) $obj->rowid;
2335 $tab_result[$i]['date_action'] = (string) $obj->date_action;
2336 $tab_result[$i]['fk_user_action'] = (int) $obj->fk_user_action;
2337 $tab_result[$i]['fk_user_update'] = (int) $obj->fk_user_update;
2338 $tab_result[$i]['type_action'] = (string) $obj->type_action;
2339 $tab_result[$i]['prev_solde'] = (float) $obj->prev_solde;
2340 $tab_result[$i]['new_solde'] = (float) $obj->new_solde;
2341 $tab_result[$i]['fk_type'] = (int) $obj->fk_type;
2342
2343 $i++;
2344 }
2345 // Returns 1 and adds the array to the variable
2346 $this->logs = $tab_result;
2347 return 1;
2348 } else {
2349 // SQL error
2350 $this->error = "Error ".$this->db->lasterror();
2351 return -1;
2352 }
2353 }
2354
2355
2363 public function getTypes($active = -1, $affect = -1)
2364 {
2365 global $mysoc;
2366
2367 $sql = "SELECT rowid, code, label, affect, delay, newbymonth";
2368 $sql .= " FROM ".MAIN_DB_PREFIX."c_holiday_types";
2369 $sql .= " WHERE (fk_country IS NULL OR fk_country = ".((int) $mysoc->country_id).')';
2370 $sql .= " AND entity IN (0, ".getEntity('c_holiday_types').")"; // Need entity 0 (holiday types common to all countries= + current entity).
2371 if ($active >= 0) {
2372 $sql .= " AND active = ".((int) $active);
2373 }
2374 if ($affect >= 0) {
2375 $sql .= " AND affect = ".((int) $affect);
2376 }
2377 $sql .= " ORDER BY sortorder";
2378
2379 $result = $this->db->query($sql);
2380 if ($result) {
2381 $num = $this->db->num_rows($result);
2382 if ($num) {
2383 $types = array();
2384 while ($obj = $this->db->fetch_object($result)) {
2385 $types[$obj->rowid] = array(
2386 'id' => $obj->rowid,
2387 'rowid' => $obj->rowid,
2388 'code' => $obj->code,
2389 'label' => $obj->label,
2390 'affect' => $obj->affect,
2391 'delay' => $obj->delay,
2392 'newbymonth' => $obj->newbymonth
2393 );
2394 }
2395
2396 return $types;
2397 }
2398 } else {
2399 dol_print_error($this->db);
2400 }
2401
2402 return array();
2403 }
2404
2405
2412 public function info($id)
2413 {
2414 global $conf;
2415
2416 $sql = "SELECT f.rowid, f.statut as status,";
2417 $sql .= " f.date_create as datec,";
2418 $sql .= " f.tms as date_modification,";
2419 $sql .= " f.date_valid as datev,";
2420 $sql .= " f.date_approval as datea,";
2421 $sql .= " f.date_refuse as dater,";
2422 $sql .= " f.fk_user_create as fk_user_creation,";
2423 $sql .= " f.fk_user_modif as fk_user_modification,";
2424 $sql .= " f.fk_user_valid as fk_user_validation,";
2425 $sql .= " f.fk_user_approve as fk_user_approval_done,";
2426 $sql .= " f.fk_validator as fk_user_approval_expected,";
2427 $sql .= " f.fk_user_refuse as fk_user_refuse";
2428 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as f";
2429 $sql .= " WHERE f.rowid = ".((int) $id);
2430 $sql .= " AND f.entity = ".((int) $conf->entity);
2431
2432 $resql = $this->db->query($sql);
2433 if ($resql) {
2434 if ($this->db->num_rows($resql)) {
2435 $obj = $this->db->fetch_object($resql);
2436
2437 $this->id = $obj->rowid;
2438
2439 $this->date_creation = $this->db->jdate($obj->datec);
2440 $this->date_modification = $this->db->jdate($obj->date_modification);
2441 $this->date_validation = $this->db->jdate($obj->datev);
2442 $this->date_approval = $this->db->jdate($obj->datea);
2443
2444 $this->user_creation_id = $obj->fk_user_creation;
2445 $this->user_validation_id = $obj->fk_user_validation;
2446 $this->user_modification_id = $obj->fk_user_modification;
2447
2448 if ($obj->status == Holiday::STATUS_APPROVED || $obj->status == Holiday::STATUS_CANCELED) {
2449 if ($obj->fk_user_approval_done) {
2450 $this->fk_user_approve = $obj->fk_user_approval_done;
2451 }
2452 }
2453 }
2454 $this->db->free($resql);
2455 } else {
2456 dol_print_error($this->db);
2457 }
2458 }
2459
2460
2468 public function initAsSpecimen()
2469 {
2470 global $user, $langs;
2471
2472 // Initialise parameters
2473 $this->id = 0;
2474 $this->specimen = 1;
2475
2476 $this->fk_user = $user->id;
2477 $this->description = 'SPECIMEN description';
2478 $this->date_debut = dol_now();
2479 $this->date_fin = dol_now() + (24 * 3600);
2480 $this->date_valid = dol_now();
2481 $this->fk_validator = $user->id;
2482 $this->halfday = 0;
2483 $this->fk_type = 1;
2485
2486 return 1;
2487 }
2488
2494 public function loadStateBoard()
2495 {
2496 global $user;
2497
2498 $this->nb = array();
2499
2500 $sql = "SELECT count(h.rowid) as nb";
2501 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2502 $sql .= " WHERE h.statut > 1";
2503 $sql .= " AND h.entity IN (".getEntity('holiday').")";
2504 if (!$user->hasRight('holiday', 'readall')) {
2505 $userchildids = $user->getAllChildIds(1);
2506 $sql .= " AND (h.fk_user IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2507 $sql .= " OR h.fk_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2508 }
2509
2510 $resql = $this->db->query($sql);
2511 if ($resql) {
2512 while ($obj = $this->db->fetch_object($resql)) {
2513 $this->nb["holidays"] = $obj->nb;
2514 }
2515 $this->db->free($resql);
2516 return 1;
2517 } else {
2518 dol_print_error($this->db);
2519 $this->error = $this->db->error();
2520 return -1;
2521 }
2522 }
2523
2524 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2531 public function load_board($user)
2532 {
2533 // phpcs:enable
2534 global $conf, $langs;
2535
2536 if ($user->socid) {
2537 return -1; // Protection to prevent calls by external users
2538 }
2539
2540 $now = dol_now();
2541
2542 // The count and the number of late requests are computed by the database instead of reading every request. A request is
2543 // late when its start date is before now minus the warning delay (a request without start date was counted as late,
2544 // this is kept).
2545 $sql = "SELECT COUNT(h.rowid) as nb,";
2546 $sql .= " SUM(CASE WHEN h.date_debut IS NULL OR h.date_debut < '".$this->db->idate($now - $conf->holiday->approve->warning_delay)."' THEN 1 ELSE 0 END) as nblate";
2547 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2548 $sql .= " WHERE h.statut = 2";
2549 $sql .= " AND h.entity IN (".getEntity('holiday').")";
2550 if (!$user->hasRight('holiday', 'read_all')) {
2551 $userchildids = $user->getAllChildIds(1);
2552 $sql .= " AND (h.fk_user IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2553 $sql .= " OR h.fk_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2554 }
2555
2556 $resql = $this->db->query($sql);
2557 if ($resql) {
2558 $langs->load("members");
2559
2560 $response = new WorkboardResponse();
2561 $response->warning_delay = $conf->holiday->approve->warning_delay / 60 / 60 / 24;
2562 $response->label = $langs->trans("HolidaysToApprove");
2563 $response->labelShort = $langs->trans("ToApprove");
2564 $response->url = DOL_URL_ROOT.'/holiday/list.php?search_status=2&amp;mainmenu=hrm&amp;leftmenu=holiday';
2565 $response->img = img_object('', "holiday");
2566
2567 $obj = $this->db->fetch_object($resql);
2568 if ($obj) {
2569 $response->nbtodo = (int) $obj->nb;
2570 $response->nbtodolate = (int) $obj->nblate;
2571 }
2572
2573 return $response;
2574 } else {
2575 dol_print_error($this->db);
2576 $this->error = $this->db->error();
2577 return -1;
2578 }
2579 }
2587 public function getKanbanView($option = '', $arraydata = null)
2588 {
2589 global $langs;
2590
2591 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2592
2593 $return = '<div class="box-flex-item box-flex-grow-zero">';
2594 $return .= '<div class="info-box info-box-sm">';
2595 $return .= '<span class="info-box-icon bg-infobox-action">';
2596 $return .= img_picto('', $this->picto);
2597 $return .= '</span>';
2598 $return .= '<div class="info-box-content">';
2599 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.$this->getNomUrl().'</span>';
2600 if ($selected >= 0) {
2601 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2602 }
2603 if (property_exists($this, 'fk_type')) {
2604 $return .= '<br>';
2605 //$return .= '<span class="opacitymedium">'.$langs->trans("Type").'</span> : ';
2606 $return .= '<div class="info_box-label tdoverflowmax100" title="'.dol_escape_htmltag($arraydata['labeltype']).'">'.dol_escape_htmltag($arraydata['labeltype']).'</div>';
2607 }
2608 if (property_exists($this, 'date_debut') && property_exists($this, 'date_fin')) {
2609 $return .= '<span class="info-box-label small">'.dol_print_date($this->date_debut, 'day').'</span>';
2610 $return .= ' <span class="opacitymedium small">'.$langs->trans("To").'</span> ';
2611 $return .= '<span class="info-box-label small">'.dol_print_date($this->date_fin, 'day').'</span>';
2612 if (!empty($arraydata['nbopenedday'])) {
2613 $return .= ' ('.$arraydata['nbopenedday'].')';
2614 }
2615 }
2616 if (method_exists($this, 'getLibStatut')) {
2617 $return .= '<div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2618 }
2619 $return .= '</div>';
2620 $return .= '</div>';
2621 $return .= '</div>';
2622 return $return;
2623 }
2624
2635 public function sendPreviousMonthHRInformations($mailto = "", $template = "", $newlang = "")
2636 {
2637 global $conf, $langs, $user;
2638
2639 $outputlangs = $langs;
2640
2641 $error = 0;
2642 $this->output = '';
2643 $this->error = '';
2644 $arrayfields = array(
2645 'user' => 'Employee',
2646 'type' => 'Type',
2647 'date_start' => 'DateDebCP',
2648 'date_end' => 'DateFinCP',
2649 'used_days' => 'NbUseDaysCPShort',
2650 );
2651
2652 if (!empty($newlang)) {
2653 $outputlangs = new Translate("", $conf);
2654 $outputlangs->setDefaultLang($newlang);
2655 }
2656 $outputlangs->loadLangs(array('main', 'holiday', 'hrm'));
2657
2658 if (empty($mailto) || !isValidEmail($mailto)) {
2659 $this->errors[] = 'Bad value for parameter mailto. Must be a valid email address.';
2660 return 1;
2661 }
2662
2663 $typeleaves = $this->getTypes(1, -1);
2664 $arraytypeleaves = array();
2665 foreach ($typeleaves as $val) {
2666 $labeltoshow = ($outputlangs->trans($val['code']) != $val['code'] ? $outputlangs->trans($val['code']) : $val['label']);
2667 $arraytypeleaves[$val['rowid']] = $labeltoshow;
2668 }
2669 $listhalfday = array('morning' => $outputlangs->trans("Morning"), "afternoon" => $outputlangs->trans("Afternoon"));
2670
2671 $datenow = dol_getdate(dol_now());
2672 $prev_month = dol_get_prev_month($datenow["mon"], $datenow["year"]);
2673 $year_month = sprintf("%04d", $prev_month["year"]).'-'.sprintf("%02d", $prev_month["month"]);
2674 $arrayleaves = array();
2675
2676 $sql = "SELECT cp.rowid, cp.ref, cp.fk_user, cp.date_debut, cp.date_fin, cp.fk_type, cp.description, cp.halfday, cp.statut as status";
2677 $sql .= " FROM ".MAIN_DB_PREFIX."holiday cp";
2678 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON cp.fk_user = u.rowid";
2679 $sql .= " WHERE cp.entity IN (".getEntity('holiday').") AND cp.rowid > 0";
2680 $sql .= " AND cp.statut = ".Holiday::STATUS_APPROVED;
2681 $sql .= " AND (";
2682 $sql .= " (date_format(cp.date_debut, '%Y-%m') = '".$this->db->escape($year_month)."' OR date_format(cp.date_fin, '%Y-%m') = '".$this->db->escape($year_month)."')";
2683 $sql .= " OR"; // For leave over several months
2684 $sql .= " (date_format(cp.date_debut, '%Y-%m') < '".$this->db->escape($year_month)."' AND date_format(cp.date_fin, '%Y-%m') > '".$this->db->escape($year_month)."') ";
2685 $sql .= " )";
2686 $sql .= $this->db->order("cp.fk_user, cp.date_debut", "ASC");
2687 $resql = $this->db->query($sql);
2688 if (empty($resql)) {
2689 $this->errors[] = $this->db->lasterror();
2690 return 1;
2691 }
2692 $num = $this->db->num_rows($resql);
2693 if ($num > 0) {
2694 $tmpuser = new User($this->db);
2695 while ($obj = $this->db->fetch_object($resql)) {
2696 $tmpuser->fetch($obj->fk_user);
2697
2698 $date_start = $this->db->jdate($obj->date_debut, true);
2699 $date_end = $this->db->jdate($obj->date_fin, true);
2700
2701 $tmpstart = dol_getdate($date_start);
2702 $tmpend = dol_getdate($date_end);
2703
2704 $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning';
2705 $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon';
2706
2707 $halfdayinmonth = $obj->halfday;
2708 $starthalfdayinmonth = $starthalfday;
2709 $endhalfdayinmonth = $endhalfday;
2710
2711 //0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
2712
2713 // Set date_start_gmt and date_end_gmt that are date to show for the selected month
2714 $date_start_inmonth = $this->db->jdate($obj->date_debut, true);
2715 $date_end_inmonth = $this->db->jdate($obj->date_fin, true);
2716 if ($tmpstart['year'] < $prev_month["year"] || $tmpstart['mon'] < $prev_month["month"]) {
2717 $date_start_inmonth = dol_get_first_day($prev_month["year"], $prev_month["month"], true);
2718 $starthalfdayinmonth = 'morning';
2719 if ($halfdayinmonth == 2) {
2720 $halfdayinmonth = 1;
2721 }
2722 if ($halfdayinmonth == -1) {
2723 $halfdayinmonth = 0;
2724 }
2725 }
2726 if ($tmpend['year'] > $prev_month["year"] || $tmpend['mon'] > $prev_month["month"]) {
2727 $date_end_inmonth = dol_get_last_day($prev_month["year"], $prev_month["month"], true) - ((24 * 3600) - 1);
2728 $endhalfdayinmonth = 'afternoon';
2729 if ($halfdayinmonth == 2) {
2730 $halfdayinmonth = -1;
2731 }
2732 if ($halfdayinmonth == 1) {
2733 $halfdayinmonth = 0;
2734 }
2735 }
2736 $arrayleaves[] = array(
2737 "user" => $tmpuser->getNomUrl(0, 'nolink', 0, 0, 24, 1),
2738 "type" => $arraytypeleaves[$obj->fk_type],
2739 "date_start" => dol_print_date($date_start_inmonth, 'day') . ' <span class="opacitymedium">('.$outputlangs->trans($listhalfday[$starthalfdayinmonth]).')</span>',
2740 "date_end" => dol_print_date($date_end_inmonth, 'day') . ' <span class="opacitymedium">('.$outputlangs->trans($listhalfday[$endhalfdayinmonth]).')</span>',
2741 "used_days" => num_open_day($date_start_inmonth, $date_end_inmonth, 0, 1, $halfdayinmonth, $tmpuser->country_id, $obj->fk_user)
2742 );
2743 }
2744 }
2745
2746 $outputarrayleaves = '<br><table style="width: 100%;border-collapse: separate !important;border-spacing: 0px;border-top: 1px solid #b6b6b6;border-left: 1px solid #b6b6b6;border-right: 1px solid #b6b6b6;margin: 0px 0px 20px 0px;">';
2747 $outputarrayleaves .= '<tr>';
2748 foreach ($arrayfields as $key => $label) {
2749 $outputarrayleaves .= '<td style="border-bottom:1px solid #b6b6b6;padding: 6px 10px 6px 12px;">';
2750 $outputarrayleaves .= $outputlangs->trans($label);
2751 if ($key == 'date_end') {
2752 $outputarrayleaves .=" (".$langs->trans("Included").")";
2753 }
2754 $outputarrayleaves .= '</td>';
2755 }
2756 $outputarrayleaves .= '</tr>';
2757
2758 if (!empty($arrayleaves)) {
2759 foreach ($arrayleaves as $fields) {
2760 $outputarrayleaves .= '<tr>';
2761 foreach ($fields as $field => $value) {
2762 $outputarrayleaves .= '<td style="border-bottom:1px solid #b6b6b6;padding: 6px 10px 6px 12px;" id="'.$field.'">';
2763 $outputarrayleaves .= $value;
2764 $outputarrayleaves .= '</td>';
2765 }
2766 $outputarrayleaves .= '</tr>';
2767 }
2768 } else {
2769 $outputarrayleaves .= '<tr>';
2770 $outputarrayleaves .= '<td style="border-bottom:1px solid #b6b6b6;padding: 6px 10px 6px 12px;" colspan="5">';
2771 $outputarrayleaves .= $outputlangs->trans("None");
2772 $outputarrayleaves .= '</td>';
2773 $outputarrayleaves .= '</tr>';
2774 }
2775 $outputarrayleaves .= '</table>';
2776
2777 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2778 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2779
2780 $formmail = new FormMail($this->db);
2781 $templateId = 0;
2782 $templateLabel = '';
2783 if (empty($template) || $template == 'EmailTemplateCode') {
2784 $templateLabel = '(HolidayHrInformationsPreviousMonth)';
2785 } else {
2786 if (is_numeric($template)) {
2787 $templateId = $template;
2788 } else {
2789 $templateLabel = $template;
2790 }
2791 }
2792 $mailtemplate = $formmail->getEMailTemplate($this->db, "holiday", $user, $outputlangs, $templateId, 1, $templateLabel);
2793
2794 if (is_numeric($mailtemplate) || empty($mailtemplate->topic)) {
2795 $this->errors[] = 'No mail template found for code "'.$templateLabel.'" or id "'.$templateId.'".';
2796 $error++;
2797 }
2798
2799 if (!$error) {
2800 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
2801 complete_substitutions_array($substitutionarray, $outputlangs, $this);
2802
2803 $subject = make_substitutions($mailtemplate->topic, $substitutionarray, $outputlangs);
2804 $msg = make_substitutions($mailtemplate->content, $substitutionarray, $outputlangs);
2805 $from = dol_string_nospecial(getDolGlobalString('MAIN_INFO_SOCIETE_NOM'), ' ', array(",")).' <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL').'>';
2806
2807 $msg = preg_replace('/__HOLIDAY_ARRAY_PER_EMPLOYEE_FOR_PERIOD__/', $outputarrayleaves, $msg);
2808 $cmail = new CMailFile($subject, $mailto, $from, $msg, array(), array(), array(), '', '', 0, 1);
2809 $result = $cmail->sendfile();
2810 if (!$result || !empty($cmail->error) || !empty($cmail->errors)) {
2811 $this->errors[] = $cmail->error;
2812 if (is_array($cmail->errors) && count($cmail->errors) > 0) {
2813 $this->errors = array_merge($this->errors, $cmail->errors);
2814 $error++;
2815 }
2816 }
2817 }
2818
2819 if (!empty($this->errors)) {
2820 $this->output .= "\n";
2821 // The $this->errors will be concatenated to the output by the function that call this method.
2822 }
2823 return ($error ? 1 : 0);
2824 }
2825}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:477
$object ref
Definition info.php:90
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class of the module paid holiday.
getTypes($active=-1, $affect=-1)
Return array with list of types.
getNomUrl($withpicto=0, $save_lastsearch_value=-1, $notooltip=0, $morecss='')
Return clickable name (with picto eventually)
verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday=0)
Check if a user is on holiday (partially or completely) into a period.
validate($user=null, $notrigger=0)
Validate leave request.
fetchUsers($stringlist=true, $type=true, $sqlFilters='')
Get list of Users or list of vacation balance.
info($id)
Load information on object.
updateBalance()
Update balance of vacations and check table of users for holidays is complete.
updateConfCP($name, $value)
Update an option of the Holiday module.
const STATUS_VALIDATED
Validated status.
const STATUS_DRAFT
Draft status.
fetchAll($sqlOrder, $sqlFilter)
List all holidays of all users.
fetch($id, $ref='')
Load object in memory from database.
addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
addLogCP
verifNbUsers($userDolibarrWithoutCP, $userCP)
Compare the number of active Dolibarr users to the number of paid leave users.
verifDateHolidayForTimestamp($fk_user, $timestamp, $status='-1')
Check that a user is not on holiday for a particular timestamp.
approve($user=null, $notrigger=0)
Approve leave request.
const STATUS_REFUSED
Refused.
getConfCP($name, $createifnotfound='')
Return value of a conf parameter for leave module TODO Move this into llx_const table.
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
initAsSpecimen()
Initialise an instance with random values.
create($user, $notrigger=0)
Create a paid leave entry in the database.
selectStatutCP($selected=0, $htmlname='select_statut', $morecss='minwidth125')
Show select with list of leave status.
countActiveUsersWithoutCP()
Count number of active users in Dolibarr without Paid leave.
updateSoldeCP($userID=0, $nbHoliday=0, $fk_type=0)
Updates the timestamp of the last CP balance update.
update($user=null, $notrigger=0)
Update database.
getCPforUser($user_id, $fk_type=0)
Return the balance of annual leave of a user.
sendPreviousMonthHRInformations($mailto="", $template="", $newlang="")
Send a mail with previous month Hr information CAN BE A CRON TASK.
fetch_users_approver_holiday()
Return list of people with permission to validate leave requests.
__construct($db)
Constructor.
loadStateBoard()
Load this->nb for dashboard.
getLibStatut($mode=0)
Returns the label status.
const STATUS_CANCELED
Canceled.
fetchLog($sqlorder, $sqlwhere)
List log of leaves.
countActiveUsers()
Count number of active users in Dolibarr.
fetchByUser($user_id, $order='', $filter='')
List holidays for a particular user or list of users.
const STATUS_APPROVED
Approved.
getTooltipContentArray($params)
getTooltipContentArray
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
LibStatut($status, $mode=0, $startdate='')
Returns the label of a status.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:535
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $countryCodeOrId='', $user_id=0)
Function to return number of working days (and text of units) between two dates (working days)
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:616
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:554
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:635
dol_stringtotime($string, $gm=1, $processnotimeasnoon=0)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:442
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:65
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:181