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 $user_approve_id;
139
143 public $date_refuse = 0;
144
148 public $fk_user_refuse;
149
153 public $date_cancel = 0;
154
158 public $fk_user_cancel;
159
163 public $fk_user_create;
164
168 public $detail_refuse = '';
169
173 public $fk_type;
174
178 public $holiday = array();
179
183 public $events = array();
184
188 public $logs = array();
189
190
194 const STATUS_DRAFT = 1;
210 const STATUS_REFUSED = 5;
211
212
218 public function __construct($db)
219 {
220 $this->db = $db;
221
222 $this->ismultientitymanaged = 0;
223 }
224
225
233 public function getNextNumRef($objsoc)
234 {
235 global $langs, $conf;
236 $langs->load("order");
237
238 if (!getDolGlobalString('HOLIDAY_ADDON')) {
239 $conf->global->HOLIDAY_ADDON = 'mod_holiday_madonna';
240 }
241
242 if (getDolGlobalString('HOLIDAY_ADDON')) {
243 $mybool = false;
244
245 $file = getDolGlobalString('HOLIDAY_ADDON') . ".php";
246 $classname = getDolGlobalString('HOLIDAY_ADDON');
247
248 // Include file with class
249 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
250 foreach ($dirmodels as $reldir) {
251 $dir = dol_buildpath($reldir."core/modules/holiday/");
252
253 // Load file with numbering class (if found)
254 $mybool = ((bool) @include_once $dir.$file) || $mybool;
255 }
256
257 if (!$mybool) {
258 dol_print_error(null, "Failed to include file ".$file);
259 return '';
260 }
261
262 $obj = new $classname();
263 '@phan-var-force ModelNumRefHolidays $obj';
265 $numref = $obj->getNextValue($objsoc, $this);
266
267 if ($numref != "") {
268 return $numref;
269 } else {
270 $this->error = $obj->error;
271 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
272 return "";
273 }
274 } else {
275 print $langs->trans("Error")." ".$langs->trans("Error_HOLIDAY_ADDON_NotDefined");
276 return "";
277 }
278 }
279
285 public function updateBalance()
286 {
287 $this->db->begin();
288
289 // Update sold of vocations
290 $result = $this->updateSoldeCP();
291
292 // Check nb of users into table llx_holiday_users and update with empty lines
293 //if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser'));
294
295 if ($result >= 0) {
296 $this->db->commit();
297 return 0; // for cronjob use (0 is OK, any other value is an error code)
298 } else {
299 $this->db->rollback();
300 return -1;
301 }
302 }
303
311 public function create($user, $notrigger = 0)
312 {
313 global $conf;
314 $error = 0;
315
316 $now = dol_now();
317
318 // Check parameters
319 if (empty($this->fk_user) || !is_numeric($this->fk_user) || $this->fk_user < 0) {
320 $this->error = "ErrorBadParameterFkUser";
321 return -1;
322 }
323 if (empty($this->fk_validator) || !is_numeric($this->fk_validator) || $this->fk_validator < 0) {
324 $this->error = "ErrorBadParameterFkValidator";
325 return -1;
326 }
327 if (empty($this->fk_type) || !is_numeric($this->fk_type) || $this->fk_type < 0) {
328 $this->error = "ErrorBadParameterFkType";
329 return -1;
330 }
331
332 // Insert request
333 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday(";
334 $sql .= "ref,";
335 $sql .= "fk_user,";
336 $sql .= "date_create,";
337 $sql .= "description,";
338 $sql .= "date_debut,";
339 $sql .= "date_fin,";
340 $sql .= "halfday,";
341 $sql .= "statut,";
342 $sql .= "fk_validator,";
343 $sql .= "fk_type,";
344 $sql .= "fk_user_create,";
345 $sql .= "entity";
346 $sql .= ") VALUES (";
347 $sql .= "'(PROV)',";
348 $sql .= " ".((int) $this->fk_user).",";
349 $sql .= " '".$this->db->idate($now)."',";
350 $sql .= " '".$this->db->escape($this->description)."',";
351 $sql .= " '".$this->db->idate($this->date_debut)."',";
352 $sql .= " '".$this->db->idate($this->date_fin)."',";
353 $sql .= " ".((int) $this->halfday).",";
354 $sql .= " '1',";
355 $sql .= " ".((int) $this->fk_validator).",";
356 $sql .= " ".((int) $this->fk_type).",";
357 $sql .= " ".((int) $user->id).",";
358 $sql .= " ".((int) $conf->entity);
359 $sql .= ")";
360
361 $this->db->begin();
362
363 dol_syslog(get_class($this)."::create", LOG_DEBUG);
364 $resql = $this->db->query($sql);
365 if (!$resql) {
366 $error++;
367 $this->errors[] = "Error ".$this->db->lasterror();
368 }
369
370 if (!$error) {
371 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday");
372
373 if ($this->id) {
374 // update ref
375 $initialref = '(PROV'.$this->id.')';
376 if (!empty($this->ref)) {
377 $initialref = $this->ref;
378 }
379
380 $sql = 'UPDATE '.MAIN_DB_PREFIX."holiday SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id);
381 if ($this->db->query($sql)) {
382 $this->ref = $initialref;
383 $result = $this->insertExtraFields();
384 if ($result < 0) {
385 $error++;
386 }
387
388 if (!$error && !$notrigger) {
389 // Call trigger
390 $result = $this->call_trigger('HOLIDAY_CREATE', $user);
391 if ($result < 0) {
392 $error++;
393 }
394 // End call triggers
395 }
396 }
397 }
398 }
399
400 // Commit or rollback
401 if ($error) {
402 foreach ($this->errors as $errmsg) {
403 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
404 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
405 }
406 $this->db->rollback();
407 return -1 * $error;
408 } else {
409 $this->db->commit();
410 return $this->id;
411 }
412 }
413
414
422 public function fetch($id, $ref = '')
423 {
424 $sql = "SELECT";
425 $sql .= " cp.rowid,";
426 $sql .= " cp.ref,";
427 $sql .= " cp.fk_user,";
428 $sql .= " cp.date_create,";
429 $sql .= " cp.description,";
430 $sql .= " cp.date_debut,";
431 $sql .= " cp.date_fin,";
432 $sql .= " cp.halfday,";
433 $sql .= " cp.statut as status,";
434 $sql .= " cp.fk_validator,";
435 $sql .= " cp.date_valid,";
436 $sql .= " cp.fk_user_valid,";
437 $sql .= " cp.date_approval,";
438 $sql .= " cp.fk_user_approve,";
439 $sql .= " cp.date_refuse,";
440 $sql .= " cp.fk_user_refuse,";
441 $sql .= " cp.date_cancel,";
442 $sql .= " cp.fk_user_cancel,";
443 $sql .= " cp.detail_refuse,";
444 $sql .= " cp.note_private,";
445 $sql .= " cp.note_public,";
446 $sql .= " cp.fk_user_create,";
447 $sql .= " cp.fk_type,";
448 $sql .= " cp.entity";
449 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
450 if ($id > 0) {
451 $sql .= " WHERE cp.rowid = ".((int) $id);
452 } else {
453 $sql .= " WHERE cp.ref = '".$this->db->escape($ref)."'";
454 }
455
456 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
457 $resql = $this->db->query($sql);
458 if ($resql) {
459 if ($this->db->num_rows($resql)) {
460 $obj = $this->db->fetch_object($resql);
461
462 $this->id = (int) $obj->rowid;
463 $this->ref = (string) ($obj->ref ? $obj->ref : $obj->rowid);
464 $this->fk_user = (int) $obj->fk_user;
465 $this->date_create = $this->db->jdate($obj->date_create);
466 $this->description = $obj->description;
467
468 $this->date_debut = $this->db->jdate($obj->date_debut);
469 $this->date_fin = $this->db->jdate($obj->date_fin);
470 $this->date_debut_gmt = $this->db->jdate($obj->date_debut, 1);
471 $this->date_fin_gmt = $this->db->jdate($obj->date_fin, 1);
472
473 $this->halfday = (int) $obj->halfday;
474 $this->status = (int) $obj->status;
475 $this->statut = (int) $obj->status; // deprecated
476 $this->fk_validator = $obj->fk_validator;
477 $this->date_valid = $this->db->jdate($obj->date_valid);
478 $this->fk_user_valid = $obj->fk_user_valid;
479 $this->user_validation_id = $obj->fk_user_valid;
480 $this->date_approval = $this->db->jdate($obj->date_approval);
481 $this->fk_user_approve = $obj->fk_user_approve;
482 $this->date_refuse = $this->db->jdate($obj->date_refuse);
483 $this->fk_user_refuse = $obj->fk_user_refuse;
484 $this->date_cancel = $this->db->jdate($obj->date_cancel);
485 $this->fk_user_cancel = $obj->fk_user_cancel;
486 $this->detail_refuse = $obj->detail_refuse;
487 $this->note_private = $obj->note_private;
488 $this->note_public = $obj->note_public;
489 $this->fk_user_create = $obj->fk_user_create;
490 $this->fk_type = $obj->fk_type;
491 $this->entity = $obj->entity;
492
493 $this->fetch_optionals();
494
495 $result = 1;
496 } else {
497 $result = 0;
498 }
499 $this->db->free($resql);
500
501 return $result;
502 } else {
503 $this->error = "Error ".$this->db->lasterror();
504 return -1;
505 }
506 }
507
516 public function fetchByUser($user_id, $order = '', $filter = '')
517 {
518 $this->holiday = [];
519 $sql = "SELECT";
520 $sql .= " cp.rowid,";
521 $sql .= " cp.ref,";
522
523 $sql .= " cp.fk_user,";
524 $sql .= " cp.fk_type,";
525 $sql .= " cp.date_create,";
526 $sql .= " cp.tms as date_modification,";
527 $sql .= " cp.description,";
528 $sql .= " cp.date_debut,";
529 $sql .= " cp.date_fin,";
530 $sql .= " cp.halfday,";
531 $sql .= " cp.statut as status,";
532 $sql .= " cp.fk_validator,";
533 $sql .= " cp.date_valid,";
534 $sql .= " cp.fk_user_valid,";
535 $sql .= " cp.date_approval,";
536 $sql .= " cp.fk_user_approve,";
537 $sql .= " cp.date_refuse,";
538 $sql .= " cp.fk_user_refuse,";
539 $sql .= " cp.date_cancel,";
540 $sql .= " cp.fk_user_cancel,";
541 $sql .= " cp.detail_refuse,";
542
543 $sql .= " uu.lastname as user_lastname,";
544 $sql .= " uu.firstname as user_firstname,";
545 $sql .= " uu.login as user_login,";
546 $sql .= " uu.statut as user_status,";
547 $sql .= " uu.photo as user_photo,";
548 $sql .= " uu.fk_country as country_id,";
549
550 $sql .= " ua.lastname as validator_lastname,";
551 $sql .= " ua.firstname as validator_firstname,";
552 $sql .= " ua.login as validator_login,";
553 $sql .= " ua.statut as validator_status,";
554 $sql .= " ua.photo as validator_photo";
555
556 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
557 $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
558 $sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid"; // Hack needed for search on the list
559 $sql .= " AND cp.fk_user IN (".$this->db->sanitize($user_id).")";
560
561 // Selection filter
562 if (!empty($filter)) {
563 $sql .= $filter; // @phan-suppress-current-line SqlInjection
564 }
565
566 // Order of display of the result
567 if (!empty($order)) {
568 $sql .= $order; // @phan-suppress-current-line SqlInjection
569 }
570
571 dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG);
572 $resql = $this->db->query($sql);
573
574 // If no SQL error
575 if ($resql) {
576 $i = 0;
577 $tab_result = $this->holiday;
578 $num = $this->db->num_rows($resql);
579
580 // If no registration
581 if (!$num) {
582 return 2;
583 }
584
585 // List the records and add them to the table
586 while ($i < $num) {
587 $obj = $this->db->fetch_object($resql);
588
589 $tab_result[$i]['rowid'] = (int) $obj->rowid;
590 $tab_result[$i]['id'] = (int) $obj->rowid;
591 $tab_result[$i]['ref'] = (string) ($obj->ref ? $obj->ref : $obj->rowid);
592
593 $tab_result[$i]['fk_user'] = (int) $obj->fk_user;
594 $tab_result[$i]['fk_type'] = (int) $obj->fk_type;
595 $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
596 $tab_result[$i]['date_modification'] = $this->db->jdate($obj->date_modification);
597 $tab_result[$i]['description'] = (string) $obj->description;
598 $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
599 $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
600 $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
601 $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
602 $tab_result[$i]['halfday'] = (int) $obj->halfday;
603 $tab_result[$i]['statut'] = (int) $obj->status;
604 $tab_result[$i]['status'] = (int) $obj->status;
605 $tab_result[$i]['fk_validator'] = (int) $obj->fk_validator;
606 $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
607 $tab_result[$i]['fk_user_valid'] = (int) $obj->fk_user_valid;
608 $tab_result[$i]['date_approval'] = $this->db->jdate($obj->date_approval);
609 $tab_result[$i]['fk_user_approve'] = (int) $obj->fk_user_approve;
610 $tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
611 $tab_result[$i]['fk_user_refuse'] = (int) $obj->fk_user_refuse;
612 $tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
613 $tab_result[$i]['fk_user_cancel'] = (int) $obj->fk_user_cancel;
614 $tab_result[$i]['detail_refuse'] = (string) $obj->detail_refuse;
615
616 $tab_result[$i]['user_firstname'] = (string) $obj->user_firstname;
617 $tab_result[$i]['user_lastname'] = (string) $obj->user_lastname;
618 $tab_result[$i]['user_login'] = (string) $obj->user_login;
619 $tab_result[$i]['user_statut'] = (int) $obj->user_status;
620 $tab_result[$i]['user_status'] = (int) $obj->user_status;
621 $tab_result[$i]['user_photo'] = (string) $obj->user_photo;
622
623 $tab_result[$i]['validator_firstname'] = (string) $obj->validator_firstname;
624 $tab_result[$i]['validator_lastname'] = (string) $obj->validator_lastname;
625 $tab_result[$i]['validator_login'] = (string) $obj->validator_login;
626 $tab_result[$i]['validator_statut'] = (int) $obj->validator_status;
627 $tab_result[$i]['validator_status'] = (int) $obj->validator_status;
628 $tab_result[$i]['validator_photo'] = (string) $obj->validator_photo;
629
630 $tab_result[$i]['country_id'] = (int) $obj->country_id; // id of country of user
631
632 $i++;
633 }
634
635 // Returns 1 with the filled array
636 $this->holiday = $tab_result;
637 return 1;
638 } else {
639 // SQL Error
640 $this->error = "Error ".$this->db->lasterror();
641 return -1;
642 }
643 }
644
652 public function fetchAll($sqlOrder, $sqlFilter)
653 {
654 $sql = "SELECT";
655 $sql .= " cp.rowid,";
656 $sql .= " cp.ref,";
657 $sql .= " cp.fk_user,";
658 $sql .= " cp.fk_type,";
659 $sql .= " cp.date_create,";
660 $sql .= " cp.tms as date_modification,";
661 $sql .= " cp.description,";
662 $sql .= " cp.date_debut,";
663 $sql .= " cp.date_fin,";
664 $sql .= " cp.halfday,";
665 $sql .= " cp.statut as status,";
666 $sql .= " cp.fk_validator,";
667 $sql .= " cp.date_valid,";
668 $sql .= " cp.fk_user_valid,";
669 $sql .= " cp.date_approval,";
670 $sql .= " cp.fk_user_approve,";
671 $sql .= " cp.date_refuse,";
672 $sql .= " cp.fk_user_refuse,";
673 $sql .= " cp.date_cancel,";
674 $sql .= " cp.fk_user_cancel,";
675 $sql .= " cp.detail_refuse,";
676
677 $sql .= " uu.lastname as user_lastname,";
678 $sql .= " uu.firstname as user_firstname,";
679 $sql .= " uu.login as user_login,";
680 $sql .= " uu.statut as user_status,";
681 $sql .= " uu.photo as user_photo,";
682
683 $sql .= " ua.lastname as validator_lastname,";
684 $sql .= " ua.firstname as validator_firstname,";
685 $sql .= " ua.login as validator_login,";
686 $sql .= " ua.statut as validator_status,";
687 $sql .= " ua.photo as validator_photo";
688
689 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
690 $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
691 $sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack needed for search on the list
692
693 // Selection filtering
694 if (!empty($sqlFilter)) {
695 $sql .= $sqlFilter;
696 }
697
698 // order of display
699 if (!empty($sqlOrder)) {
700 $sql .= $sqlOrder;
701 }
702
703 dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
704 $resql = $this->db->query($sql);
705
706 // If no SQL error
707 if ($resql) {
708 $i = 0;
709 $tab_result = $this->holiday;
710 $num = $this->db->num_rows($resql);
711
712 // If no registration
713 if (!$num) {
714 return 2;
715 }
716
717 // List the records and add them to the table
718 while ($i < $num) {
719 $obj = $this->db->fetch_object($resql);
720
721 $tab_result[$i]['rowid'] = (int) $obj->rowid;
722 $tab_result[$i]['id'] = (int) $obj->rowid;
723 $tab_result[$i]['ref'] = (string) ($obj->ref ? $obj->ref : $obj->rowid);
724
725 $tab_result[$i]['fk_user'] = (int) $obj->fk_user;
726 $tab_result[$i]['fk_type'] = (int) $obj->fk_type;
727 $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
728 $tab_result[$i]['date_modification'] = $this->db->jdate($obj->date_modification);
729 $tab_result[$i]['description'] = (string) $obj->description;
730 $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
731 $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
732 $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
733 $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
734 $tab_result[$i]['halfday'] = (int) $obj->halfday;
735 $tab_result[$i]['statut'] = (int) $obj->status;
736 $tab_result[$i]['status'] = (int) $obj->status;
737 $tab_result[$i]['fk_validator'] = (int) $obj->fk_validator;
738 $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
739 $tab_result[$i]['fk_user_valid'] = (int) $obj->fk_user_valid;
740 $tab_result[$i]['date_approval'] = $this->db->jdate($obj->date_approval);
741 $tab_result[$i]['fk_user_approve'] = (int) $obj->fk_user_approve;
742 $tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
743 $tab_result[$i]['fk_user_refuse'] = (int) $obj->fk_user_refuse;
744 $tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
745 $tab_result[$i]['fk_user_cancel'] = (int) $obj->fk_user_cancel;
746 $tab_result[$i]['detail_refuse'] = (string) $obj->detail_refuse;
747
748 $tab_result[$i]['user_firstname'] = (string) $obj->user_firstname;
749 $tab_result[$i]['user_lastname'] = (string) $obj->user_lastname;
750 $tab_result[$i]['user_login'] = (string) $obj->user_login;
751 $tab_result[$i]['user_statut'] = (int) $obj->user_status;
752 $tab_result[$i]['user_status'] = (int) $obj->user_status;
753 $tab_result[$i]['user_photo'] = (string) $obj->user_photo;
754
755 $tab_result[$i]['validator_firstname'] = (string) $obj->validator_firstname;
756 $tab_result[$i]['validator_lastname'] = (string) $obj->validator_lastname;
757 $tab_result[$i]['validator_login'] = (string) $obj->validator_login;
758 $tab_result[$i]['validator_statut'] = (int) $obj->validator_status;
759 $tab_result[$i]['validator_status'] = (int) $obj->validator_status;
760 $tab_result[$i]['validator_photo'] = (string) $obj->validator_photo;
761
762 $i++;
763 }
764 // Returns 1 and adds the array to the variable
765 $this->holiday = $tab_result;
766 return 1;
767 } else {
768 // SQL Error
769 $this->error = "Error ".$this->db->lasterror();
770 return -1;
771 }
772 }
773
774
782 public function validate($user = null, $notrigger = 0)
783 {
784 global $conf, $langs;
785 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
786 $error = 0;
787
788
789 $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type, true);
790
791 if ($checkBalance > 0) {
792 $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
793
794 // Use the GMT variants: num_public_holiday(), called by num_open_day(), refuses a range whose
795 // length is not a whole number of days, and a range spanning a DST transition is 23h or 25h
796 // long in the server timezone. It then returns a string and the subtraction fatals.
797 $datedebutforcount = !empty($this->date_debut_gmt) ? $this->date_debut_gmt : $this->date_debut;
798 $datefinforcount = !empty($this->date_fin_gmt) ? $this->date_fin_gmt : $this->date_fin;
799 $daysAsked = num_open_day($datedebutforcount, $datefinforcount, 0, 1, (int) $this->halfday, '', $this->fk_user);
800
801 if (($balance - $daysAsked) < 0) {
802 $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
803 return -1;
804 }
805 }
806
807 // Define new ref
808 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref) || $this->ref == $this->id) {
809 $num = $this->getNextNumRef(null);
810 } else {
811 $num = (string) $this->ref;
812 }
813 $this->newref = dol_sanitizeFileName($num);
814
815 // Update status
816 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
817 $sql .= " fk_user_valid = ".((int) $user->id).",";
818 $sql .= " date_valid = '".$this->db->idate(dol_now())."',";
819 if (!empty($this->status) && is_numeric($this->status)) {
820 $sql .= " statut = ".((int) $this->status).",";
821 } else {
822 $this->error = 'Property status must be a numeric value';
823 $error++;
824 }
825 $sql .= " ref = '".$this->db->escape($num)."'";
826 $sql .= " WHERE rowid = ".((int) $this->id);
827
828 $this->db->begin();
829
830 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
831 $resql = $this->db->query($sql);
832 if (!$resql) {
833 $error++;
834 $this->errors[] = "Error ".$this->db->lasterror();
835 }
836
837 if (!$error) {
838 if (!$notrigger) {
839 // Call trigger
840 $result = $this->call_trigger('HOLIDAY_VALIDATE', $user);
841 if ($result < 0) {
842 $error++;
843 }
844 // End call triggers
845 }
846 }
847
848 if (!$error) {
849 $this->oldref = $this->ref;
850
851 // Rename directory if dir was a temporary ref
852 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
853 // Now we rename also files into index
854 $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) . "'";
855 $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%' AND filepath = 'holiday/" . $this->db->escape($this->ref) . "' and entity = " . ((int) $conf->entity);
856 $resql = $this->db->query($sql);
857 if (!$resql) {
858 $error++;
859 $this->error = $this->db->lasterror();
860 }
861 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'holiday/".$this->db->escape($this->newref)."'";
862 $sql .= " WHERE filepath = 'holiday/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
863 $resql = $this->db->query($sql);
864 if (!$resql) {
865 $error++;
866 $this->error = $this->db->lasterror();
867 }
868
869 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
870 $oldref = dol_sanitizeFileName($this->ref);
871 $newref = dol_sanitizeFileName($num);
872 $dirsource = $conf->holiday->multidir_output[$this->entity] . '/' . $oldref;
873 $dirdest = $conf->holiday->multidir_output[$this->entity] . '/' . $newref;
874 if (!$error && file_exists($dirsource)) {
875 dol_syslog(get_class($this) . "::validate rename dir " . $dirsource . " into " . $dirdest);
876 if (@rename($dirsource, $dirdest)) {
877 dol_syslog("Rename ok");
878 // Rename docs starting with $oldref with $newref
879 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^' . preg_quote($oldref, '/'));
880 foreach ($listoffiles as $fileentry) {
881 $dirsource = $fileentry['name'];
882 $dirdest = preg_replace('/^' . preg_quote($oldref, '/') . '/', $newref, $dirsource);
883 $dirsource = $fileentry['path'] . '/' . $dirsource;
884 $dirdest = $fileentry['path'] . '/' . $dirdest;
885 @rename($dirsource, $dirdest);
886 }
887 }
888 }
889 }
890 }
891
892
893 // Commit or rollback
894 if ($error) {
895 foreach ($this->errors as $errmsg) {
896 dol_syslog(get_class($this)."::validate ".$errmsg, LOG_ERR);
897 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
898 }
899 $this->db->rollback();
900 return -1 * $error;
901 } else {
902 $this->db->commit();
903 return 1;
904 }
905 }
906
907
915 public function approve($user = null, $notrigger = 0)
916 {
917 $error = 0;
918
919 $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type, true);
920
921 if ($checkBalance > 0) {
922 $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
923
924 // Use the GMT variants: num_public_holiday(), called by num_open_day(), refuses a range whose
925 // length is not a whole number of days, and a range spanning a DST transition is 23h or 25h
926 // long in the server timezone. It then returns a string and the subtraction fatals.
927 $datedebutforcount = !empty($this->date_debut_gmt) ? $this->date_debut_gmt : $this->date_debut;
928 $datefinforcount = !empty($this->date_fin_gmt) ? $this->date_fin_gmt : $this->date_fin;
929 $daysAsked = num_open_day($datedebutforcount, $datefinforcount, 0, 1, (int) $this->halfday, '', $this->fk_user);
930
931 if (($balance - $daysAsked) < 0) {
932 $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
933 return -1;
934 }
935 }
936
937 // Update request
938 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
939 $sql .= " description= '".$this->db->escape($this->description)."',";
940 if (!empty($this->date_debut)) {
941 $sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
942 } else {
943 $error++;
944 }
945 if (!empty($this->date_fin)) {
946 $sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
947 } else {
948 $error++;
949 }
950 $sql .= " halfday = ".((int) $this->halfday).",";
951 if (!empty($this->status) && is_numeric($this->status)) {
952 $sql .= " statut = ".((int) $this->status).",";
953 } else {
954 $error++;
955 }
956 if (!empty($this->fk_validator)) {
957 $sql .= " fk_validator = ".((int) $this->fk_validator).",";
958 } else {
959 $error++;
960 }
961 if (!empty($this->date_valid)) {
962 $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
963 } else {
964 $sql .= " date_valid = NULL,";
965 }
966 if (!empty($this->fk_user_valid)) {
967 $sql .= " fk_user_valid = ".((int) $this->fk_user_valid).",";
968 } else {
969 $sql .= " fk_user_valid = NULL,";
970 }
971 if (!empty($this->date_approval)) {
972 $sql .= " date_approval = '".$this->db->idate($this->date_approval)."',";
973 } else {
974 $sql .= " date_approval = NULL,";
975 }
976 if (!empty($this->fk_user_approve)) {
977 $sql .= " fk_user_approve = ".((int) $this->fk_user_approve).",";
978 } else {
979 $sql .= " fk_user_approve = NULL,";
980 }
981 if (!empty($this->date_refuse)) {
982 $sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
983 } else {
984 $sql .= " date_refuse = NULL,";
985 }
986 if (!empty($this->fk_user_refuse)) {
987 $sql .= " fk_user_refuse = ".((int) $this->fk_user_refuse).",";
988 } else {
989 $sql .= " fk_user_refuse = NULL,";
990 }
991 if (!empty($this->date_cancel)) {
992 $sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
993 } else {
994 $sql .= " date_cancel = NULL,";
995 }
996 if (!empty($this->fk_user_cancel)) {
997 $sql .= " fk_user_cancel = ".((int) $this->fk_user_cancel).",";
998 } else {
999 $sql .= " fk_user_cancel = NULL,";
1000 }
1001 if (!empty($this->detail_refuse)) {
1002 $sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
1003 } else {
1004 $sql .= " detail_refuse = NULL";
1005 }
1006 $sql .= " WHERE rowid = ".((int) $this->id);
1007
1008 $this->db->begin();
1009
1010 dol_syslog(get_class($this)."::approve", LOG_DEBUG);
1011 $resql = $this->db->query($sql);
1012 if (!$resql) {
1013 $error++;
1014 $this->errors[] = "Error ".$this->db->lasterror();
1015 }
1016
1017 if (!$error) {
1018 if (!$notrigger) {
1019 // Call trigger
1020 $result = $this->call_trigger('HOLIDAY_APPROVE', $user);
1021 if ($result < 0) {
1022 $error++;
1023 }
1024 // End call triggers
1025 }
1026 }
1027
1028 // Commit or rollback
1029 if ($error) {
1030 foreach ($this->errors as $errmsg) {
1031 dol_syslog(get_class($this)."::approve ".$errmsg, LOG_ERR);
1032 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1033 }
1034 $this->db->rollback();
1035 return -1 * $error;
1036 } else {
1037 $this->db->commit();
1038 return 1;
1039 }
1040 }
1041
1047 public function sendApprovalEmail()
1048 {
1049 global $langs;
1050
1051 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1052
1053 $langs->load('holiday');
1054
1055 $recipient = new User($this->db);
1056 $recipient->fetch($this->fk_user);
1057 if (empty($recipient->email)) {
1058 dol_syslog(get_class($this)."::sendApprovalEmail user that requested the leave has no email, so no email is sent");
1059 return 0;
1060 }
1061
1062 $validator = new User($this->db);
1063 $validator->fetch($this->fk_validator);
1064
1065 // Not the validator's own address: it may belong to another company and be refused by the mail server.
1066 $emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
1067
1068 $societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
1069 if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
1070 $societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
1071 }
1072 $subject = '['.$societeName.'] '.$langs->transnoentitiesnoconv("HolidaysValidated");
1073
1074 $link = dol_buildpath('/holiday/card.php', 3).'?id='.$this->id;
1075
1076 $message = "<p>".$langs->transnoentitiesnoconv("Hello")." ".dol_escape_htmltag($recipient->firstname).",</p>\n";
1077 $message .= "<p>".$langs->transnoentities("HolidaysValidatedBody", dol_print_date($this->date_debut, 'day'), dol_print_date($this->date_fin, 'day'))."</p>\n";
1078 $message .= "<ul>\n";
1079 $message .= "<li>".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dol_escape_htmltag(dolGetFirstLastname($validator->firstname, $validator->lastname))."</li>\n";
1080 $message .= "<li>".$langs->transnoentitiesnoconv("Link").' : <a href="'.$link.'" target="_blank">'.$link."</a></li>\n";
1081 $message .= "</ul>\n";
1082
1083 $sendtobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_HOLIDAY_TO');
1084 $trackid = 'leav'.$this->id;
1085
1086 $mail = new CMailFile($subject, $recipient->email, $emailFrom, $message, array(), array(), array(), '', $sendtobcc, 0, 1, '', '', $trackid);
1087 if (!$mail->sendfile()) {
1088 $this->error = $mail->error;
1089 $this->errors = $mail->errors;
1090 dol_syslog(get_class($this)."::sendApprovalEmail id=".$this->id." ".$this->error, LOG_WARNING);
1091 return -1;
1092 }
1093
1094 return 1;
1095 }
1096
1104 public function update($user = null, $notrigger = 0)
1105 {
1106 $error = 0;
1107
1108 $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type, true);
1109 if ($this->status == self::STATUS_REFUSED || $this->status == self::STATUS_APPROVED) {
1110 $checkBalance = 0; // No balance check to refuse a request, nor on an approved request (its days are already debited)
1111 }
1112
1113 if ($checkBalance > 0 && $this->status != self::STATUS_DRAFT && $this->status != self::STATUS_CANCELED) {
1114 $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
1115
1116 // Use the GMT variants: num_public_holiday(), called by num_open_day(), refuses a range whose
1117 // length is not a whole number of days, and a range spanning a DST transition is 23h or 25h
1118 // long in the server timezone. It then returns a string and the subtraction fatals.
1119 $datedebutforcount = !empty($this->date_debut_gmt) ? $this->date_debut_gmt : $this->date_debut;
1120 $datefinforcount = !empty($this->date_fin_gmt) ? $this->date_fin_gmt : $this->date_fin;
1121 $daysAsked = num_open_day($datedebutforcount, $datefinforcount, 0, 1, (int) $this->halfday, '', $this->fk_user);
1122
1123 if (($balance - $daysAsked) < 0) {
1124 $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
1125 return -1;
1126 }
1127 }
1128
1129 // Update request
1130 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
1131
1132 $sql .= " description= '".$this->db->escape($this->description)."',";
1133
1134 if (!empty($this->date_create)) {
1135 $sql .= " date_create = '".$this->db->idate($this->date_create)."',";
1136 } else {
1137 $error++;
1138 }
1139 if (!empty($this->date_debut)) {
1140 $sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
1141 } else {
1142 $error++;
1143 }
1144 if (!empty($this->date_fin)) {
1145 $sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
1146 } else {
1147 $error++;
1148 }
1149 $sql .= " halfday = ".((int) $this->halfday).",";
1150 if (!empty($this->status) && is_numeric($this->status)) {
1151 $sql .= " statut = ".((int) $this->status).",";
1152 } else {
1153 $error++;
1154 }
1155 if (!empty($this->fk_validator)) {
1156 $sql .= " fk_validator = ".((int) $this->fk_validator).",";
1157 } else {
1158 $error++;
1159 }
1160 if (!empty($this->date_valid)) {
1161 $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
1162 } else {
1163 $sql .= " date_valid = NULL,";
1164 }
1165 if (!empty($this->fk_user_valid)) {
1166 $sql .= " fk_user_valid = ".((int) $this->fk_user_valid).",";
1167 } else {
1168 $sql .= " fk_user_valid = NULL,";
1169 }
1170 if (!empty($this->date_approval)) {
1171 $sql .= " date_approval = '".$this->db->idate($this->date_approval)."',";
1172 } else {
1173 $sql .= " date_approval = NULL,";
1174 }
1175 if (!empty($this->fk_user_approve)) {
1176 $sql .= " fk_user_approve = ".((int) $this->fk_user_approve).",";
1177 } else {
1178 $sql .= " fk_user_approve = NULL,";
1179 }
1180 if (!empty($this->date_refuse)) {
1181 $sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
1182 } else {
1183 $sql .= " date_refuse = NULL,";
1184 }
1185 if (!empty($this->fk_user_refuse)) {
1186 $sql .= " fk_user_refuse = ".((int) $this->fk_user_refuse).",";
1187 } else {
1188 $sql .= " fk_user_refuse = NULL,";
1189 }
1190 if (!empty($this->date_cancel)) {
1191 $sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
1192 } else {
1193 $sql .= " date_cancel = NULL,";
1194 }
1195 if (!empty($this->fk_user_cancel)) {
1196 $sql .= " fk_user_cancel = ".((int) $this->fk_user_cancel).",";
1197 } else {
1198 $sql .= " fk_user_cancel = NULL,";
1199 }
1200 if (!empty($this->detail_refuse)) {
1201 $sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
1202 } else {
1203 $sql .= " detail_refuse = NULL";
1204 }
1205
1206 $sql .= " WHERE rowid = ".((int) $this->id);
1207
1208 $this->db->begin();
1209
1210 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1211 $resql = $this->db->query($sql);
1212 if (!$resql) {
1213 $error++;
1214 $this->errors[] = "Error ".$this->db->lasterror();
1215 }
1216
1217 if (!$error) {
1218 $result = $this->insertExtraFields();
1219 if ($result < 0) {
1220 $error++;
1221 }
1222 }
1223
1224 if (!$error) {
1225 if (!$notrigger && $user !== null) {
1226 // Call trigger
1227 $result = $this->call_trigger('HOLIDAY_MODIFY', $user);
1228 if ($result < 0) {
1229 $error++;
1230 }
1231 // End call triggers
1232 }
1233 }
1234
1235 // Commit or rollback
1236 if ($error) {
1237 foreach ($this->errors as $errmsg) {
1238 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1239 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1240 }
1241 $this->db->rollback();
1242 return -1 * $error;
1243 } else {
1244 $this->db->commit();
1245 return 1;
1246 }
1247 }
1248
1249
1257 public function delete($user, $notrigger = 0)
1258 {
1259 global $conf, $langs;
1260 $error = 0;
1261
1262 $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday";
1263 $sql .= " WHERE rowid=".((int) $this->id);
1264
1265 $this->db->begin();
1266
1267 // Delete extrafields before the leave request
1268 $result = $this->deleteExtraFields();
1269 if ($result < 0) {
1270 $error++;
1271 }
1272
1273 if (!$error) {
1274 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1275 $resql = $this->db->query($sql);
1276 if (!$resql) {
1277 $error++;
1278 $this->errors[] = "Error ".$this->db->lasterror();
1279 }
1280 }
1281
1282 if (!$error) {
1283 if (!$notrigger) {
1284 // Call trigger
1285 $result = $this->call_trigger('HOLIDAY_DELETE', $user);
1286 if ($result < 0) {
1287 $error++;
1288 }
1289 // End call triggers
1290 }
1291 }
1292
1293 // Commit or rollback
1294 if ($error) {
1295 foreach ($this->errors as $errmsg) {
1296 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1297 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1298 }
1299 $this->db->rollback();
1300 return -1 * $error;
1301 } else {
1302 $this->db->commit();
1303 return 1;
1304 }
1305 }
1306
1320 public function verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday = 0)
1321 {
1322 $this->fetchByUser($fk_user, '', '');
1323
1324 foreach ($this->holiday as $infos_CP) {
1325 if ($infos_CP['statut'] == Holiday::STATUS_CANCELED) {
1326 continue; // ignore not validated holidays
1327 }
1328 if ($infos_CP['statut'] == Holiday::STATUS_REFUSED) {
1329 continue; // ignore refused holidays
1330 }
1331 //var_dump("--");
1332 //var_dump("old: ".dol_print_date($infos_CP['date_debut'],'dayhour').' '.dol_print_date($infos_CP['date_fin'],'dayhour').' '.$infos_CP['halfday']);
1333 //var_dump("new: ".dol_print_date($dateStart,'dayhour').' '.dol_print_date($dateEnd,'dayhour').' '.$halfday);
1334
1335 // A new leave can fully contain an existing leave, so neither endpoint is inside the existing range.
1336 if ($dateStart < $infos_CP['date_debut'] && $dateEnd > $infos_CP['date_fin']) {
1337 return false;
1338 }
1339
1340 if ($halfday == 0) {
1341 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1342 return false;
1343 }
1344 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1345 return false;
1346 }
1347 } elseif ($halfday == -1) {
1348 // new start afternoon, new end afternoon
1349 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1350 if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1351 return false;
1352 }
1353 }
1354 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1355 if ($dateStart < $dateEnd) {
1356 return false;
1357 }
1358 if ($dateEnd < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1359 return false;
1360 }
1361 }
1362 } elseif ($halfday == 1) {
1363 // new start morning, new end morning
1364 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1365 if ($dateStart < $dateEnd) {
1366 return false;
1367 }
1368 if ($dateStart > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1369 return false;
1370 }
1371 }
1372 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1373 if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1374 return false;
1375 }
1376 }
1377 } elseif ($halfday == 2) {
1378 // new start afternoon, new end morning
1379 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1380 if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1381 return false;
1382 }
1383 }
1384 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1385 if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1386 return false;
1387 }
1388 }
1389 } else {
1390 dol_print_error(null, 'Bad value of parameter halfday when calling function verifDateHolidayCP');
1391 }
1392 }
1393
1394 return true;
1395 }
1396
1397
1407 public function verifDateHolidayForTimestamp($fk_user, $timestamp, $status = '-1')
1408 {
1409 $isavailablemorning = true;
1410 $isavailableafternoon = true;
1411
1412 // Check into leave requests
1413 $sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday, cp.statut as status";
1414 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
1415 $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
1416 $sql .= " AND cp.fk_user = ".(int) $fk_user;
1417 $sql .= " AND cp.date_debut <= '".$this->db->idate($timestamp)."' AND cp.date_fin >= '".$this->db->idate($timestamp)."'";
1418 if ($status != '-1') {
1419 $sql .= " AND cp.statut IN (".$this->db->sanitize($status).")";
1420 }
1421
1422 $resql = $this->db->query($sql);
1423 if ($resql) {
1424 $num_rows = $this->db->num_rows($resql); // Note, we can have 2 records if on is morning and the other one is afternoon
1425 if ($num_rows > 0) {
1426 $arrayofrecord = array();
1427 $i = 0;
1428 while ($i < $num_rows) {
1429 $obj = $this->db->fetch_object($resql);
1430
1431 // Note: $obj->halfday is 0:Full days, 2:Start afternoon end morning, -1:Start afternoon, 1:End morning
1432 $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);
1433 $i++;
1434 }
1435
1436 // We found a record, user is on holiday by default, so is not available is true.
1437 $isavailablemorning = true;
1438 foreach ($arrayofrecord as $record) {
1439 if ($timestamp == $record['date_start'] && $record['halfday'] == 2) {
1440 continue;
1441 }
1442 if ($timestamp == $record['date_start'] && $record['halfday'] == -1) {
1443 continue;
1444 }
1445 $isavailablemorning = false;
1446 break;
1447 }
1448 $isavailableafternoon = true;
1449 foreach ($arrayofrecord as $record) {
1450 if ($timestamp == $record['date_end'] && $record['halfday'] == 2) {
1451 continue;
1452 }
1453 if ($timestamp == $record['date_end'] && $record['halfday'] == 1) {
1454 continue;
1455 }
1456 $isavailableafternoon = false;
1457 break;
1458 }
1459 }
1460 } else {
1461 dol_print_error($this->db);
1462 }
1463
1464 $result = array('morning' => (int) $isavailablemorning, 'afternoon' => (int) $isavailableafternoon);
1465 if (!$isavailablemorning) {
1466 $result['morning_reason'] = 'leave_request';
1467 }
1468 if (!$isavailableafternoon) {
1469 $result['afternoon_reason'] = 'leave_request';
1470 }
1471 return $result;
1472 }
1473
1480 public function getTooltipContentArray($params)
1481 {
1482 global $langs;
1483
1484 $langs->load('holiday');
1485 $nofetch = !empty($params['nofetch']);
1486
1487 $datas = array();
1488 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Holiday").'</u>';
1489 if (isset($this->status)) {
1490 $datas['picto'] .= ' '.$this->getLibStatut(5);
1491 }
1492 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1493 // show type for this record only in ajax to not overload lists
1494 if (!$nofetch && !empty($this->fk_type)) {
1495 $typeleaves = $this->getTypes(1, -1);
1496 if (empty($typeleaves[$this->fk_type])) {
1497 $labeltoshow = $langs->trans("TypeWasDisabledOrRemoved", $this->fk_type);
1498 } else {
1499 $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']);
1500 }
1501 $datas['type'] = '<br><b>'.$langs->trans("Type") . ':</b> ' . $labeltoshow;
1502 }
1503 if (isset($this->halfday) && !empty($this->date_debut) && !empty($this->date_fin)) {
1504 $listhalfday = array(
1505 'morning' => $langs->trans("Morning"),
1506 "afternoon" => $langs->trans("Afternoon")
1507 );
1508 $starthalfday = ($this->halfday == -1 || $this->halfday == 2) ? 'afternoon' : 'morning';
1509 $endhalfday = ($this->halfday == 1 || $this->halfday == 2) ? 'morning' : 'afternoon';
1510 $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>';
1511 $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>';
1512 }
1513
1514
1515 return $datas;
1516 }
1517
1527 public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '')
1528 {
1529 global $conf, $langs, $hookmanager;
1530
1531 if (!empty($conf->dol_no_mouse_hover)) {
1532 $notooltip = 1; // Force disable tooltips
1533 }
1534
1535 $result = '';
1536 $params = [
1537 'id' => $this->id,
1538 'objecttype' => $this->element,
1539 'nofetch' => 1,
1540 ];
1541 $classfortooltip = 'classfortooltip';
1542 $dataparams = '';
1543 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1544 $classfortooltip = 'classforajaxtooltip';
1545 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1546 $label = '';
1547 } else {
1548 $label = implode($this->getTooltipContentArray($params));
1549 }
1550
1551 $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
1552
1553 //if ($option != 'nolink')
1554 //{
1555 // Add param to save lastsearch_values or not
1556 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1557 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1558 $add_save_lastsearch_values = 1;
1559 }
1560 if ($add_save_lastsearch_values) {
1561 $url .= '&save_lastsearch_values=1';
1562 }
1563 //}
1564
1565 $linkclose = '';
1566 if (empty($notooltip)) {
1567 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1568 $label = $langs->trans("ShowMyObject");
1569 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1570 }
1571 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1572 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1573 } else {
1574 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1575 }
1576
1577 $linkstart = '<a href="'.$url.'"';
1578 $linkstart .= $linkclose.'>';
1579 $linkend = '</a>';
1580
1581 $result .= $linkstart;
1582
1583 if ($withpicto) {
1584 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
1585 }
1586 if ($withpicto != 2) {
1587 $result .= $this->ref;
1588 }
1589 $result .= $linkend;
1590
1591 global $action;
1592 $hookmanager->initHooks(array($this->element . 'dao'));
1593 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1594 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1595 if ($reshook > 0) {
1596 $result = $hookmanager->resPrint;
1597 } else {
1598 $result .= $hookmanager->resPrint;
1599 }
1600 return $result;
1601 }
1602
1603
1610 public function getLibStatut($mode = 0)
1611 {
1612 return $this->LibStatut($this->status, $mode, $this->date_debut);
1613 }
1614
1615 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1624 public function LibStatut($status, $mode = 0, $startdate = '')
1625 {
1626 // phpcs:enable
1627 global $langs;
1628
1629 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1630 global $langs;
1631 //$langs->load("mymodule");
1632 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('DraftCP');
1633 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ToReviewCP');
1634 $this->labelStatus[self::STATUS_APPROVED] = $langs->transnoentitiesnoconv('ApprovedCP');
1635 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('CancelCP');
1636 $this->labelStatus[self::STATUS_REFUSED] = $langs->transnoentitiesnoconv('RefuseCP');
1637 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('DraftCP');
1638 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ToReviewCP');
1639 $this->labelStatusShort[self::STATUS_APPROVED] = $langs->transnoentitiesnoconv('ApprovedCP');
1640 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('CancelCP');
1641 $this->labelStatusShort[self::STATUS_REFUSED] = $langs->transnoentitiesnoconv('RefuseCP');
1642 }
1643
1644 $params = array();
1645 $statusType = 'status6';
1646 if (!empty($startdate) && $startdate >= dol_now()) { // If not yet passed, we use a green "in live" color
1647 $statusType = 'status4';
1648 $params = array('tooltip' => $this->labelStatus[$status].' - '.$langs->trans("Forthcoming"));
1649 }
1650 if ($status == self::STATUS_DRAFT) {
1651 $statusType = 'status0';
1652 }
1653 if ($status == self::STATUS_VALIDATED) {
1654 $statusType = 'status1';
1655 }
1656 if ($status == self::STATUS_CANCELED) {
1657 $statusType = 'status9';
1658 }
1659 if ($status == self::STATUS_REFUSED) {
1660 $statusType = 'status9';
1661 }
1662
1663 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode, '', $params);
1664 }
1665
1666
1675 public function selectStatutCP($selected = 0, $htmlname = 'select_statut', $morecss = 'minwidth125')
1676 {
1677 global $langs;
1678
1679 // List of status label
1680 $name = array('DraftCP', 'ToReviewCP', 'ApprovedCP', 'CancelCP', 'RefuseCP');
1681 $nb = count($name) + 1;
1682
1683 // Select HTML
1684 $out = '<select name="'.$htmlname.'" id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'">'."\n";
1685 $out .= '<option value="-1">&nbsp;</option>'."\n";
1686
1687 // Loop on status
1688 for ($i = 1; $i < $nb; $i++) {
1689 if ($i == $selected) {
1690 $out .= '<option value="'.$i.'" selected>'.$langs->trans($name[$i - 1]).'</option>'."\n";
1691 } else {
1692 $out .= '<option value="'.$i.'">'.$langs->trans($name[$i - 1]).'</option>'."\n";
1693 }
1694 }
1695
1696 $out .= "</select>\n";
1697
1698 $showempty = 0;
1699 $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($showempty < 0 ? (string) $showempty : '-1'), $morecss);
1700
1701 return $out;
1702 }
1703
1711 public function updateConfCP($name, $value)
1712 {
1713 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1714 $sql .= " value = '".$this->db->escape($value)."'";
1715 $sql .= " WHERE name = '".$this->db->escape($name)."'";
1716
1717 dol_syslog(get_class($this).'::updateConfCP name='.$name, LOG_DEBUG);
1718 $result = $this->db->query($sql);
1719 if ($result) {
1720 return true;
1721 }
1722
1723 return false;
1724 }
1725
1734 public function getConfCP($name, $createifnotfound = '')
1735 {
1736 $sql = "SELECT value";
1737 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_config";
1738 $sql .= " WHERE name = '".$this->db->escape($name)."'";
1739
1740 dol_syslog(get_class($this).'::getConfCP name='.$name.' createifnotfound='.$createifnotfound, LOG_DEBUG);
1741 $result = $this->db->query($sql);
1742
1743 if ($result) {
1744 $obj = $this->db->fetch_object($result);
1745 // Return value
1746 if (empty($obj)) {
1747 if ($createifnotfound) {
1748 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)";
1749 $sql .= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')";
1750 $result = $this->db->query($sql);
1751 if ($result) {
1752 return $createifnotfound;
1753 } else {
1754 $this->error = $this->db->lasterror();
1755 return -2;
1756 }
1757 } else {
1758 return '';
1759 }
1760 } else {
1761 return $obj->value;
1762 }
1763 } else {
1764 // Erreur SQL
1765 $this->error = $this->db->lasterror();
1766 return -1;
1767 }
1768 }
1769
1778 public function updateSoldeCP($userID = 0, $nbHoliday = 0, $fk_type = 0)
1779 {
1780 global $user, $langs;
1781
1782 $error = 0;
1783
1784 if (empty($userID) && empty($nbHoliday) && empty($fk_type)) {
1785 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
1786 $langs->load("holiday");
1787
1788 $decrease = getDolGlobalInt('HOLIDAY_DECREASE_AT_END_OF_MONTH');
1789
1790 // If updated for everyone at the beginning of the month
1791 $now = dol_now();
1792
1793 // Get month of last update
1794 $stringInDBForLastUpdate = $this->getConfCP('lastUpdate', dol_print_date($now, '%Y%m%d%H%M%S')); // Example '20200101120000'
1795 // The lastUpdate config row is created empty (value NULL) at install, so getConfCP() returns an empty value
1796 // the first time. Treat an empty value as "start from now" instead of a very old date, otherwise the catch-up
1797 // loop below would credit every user with years of monthly accrual at once. Store it, because the loop is the
1798 // only other place that writes it: an empty value would stay empty and no month would ever be credited.
1799 if (empty($stringInDBForLastUpdate)) {
1800 $stringInDBForLastUpdate = dol_print_date($now, '%Y%m%d%H%M%S');
1801
1802 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1803 $sql .= " value = '".$this->db->escape($stringInDBForLastUpdate)."'";
1804 $sql .= " WHERE name = 'lastUpdate'";
1805 $result = $this->db->query($sql);
1806 if (!$result) {
1807 $this->error = $this->db->lasterror();
1808 return -1;
1809 }
1810 }
1811 // Protection when $lastUpdate has a not valid value
1812 if ($stringInDBForLastUpdate < '20000101000000') {
1813 $stringInDBForLastUpdate = '20000101000000';
1814 }
1815 $lastUpdate = dol_stringtotime($stringInDBForLastUpdate);
1816 //print 'lastUpdate:'.$lastUpdate;exit;
1817
1818 $yearMonthLastUpdate = dol_print_date($lastUpdate, '%Y%m');
1819 $yearMonthNow = dol_print_date($now, '%Y%m');
1820 //print 'yearMonthLastUpdate='.$yearMonthLastUpdate.' yearMonthNow='.$yearMonthNow;
1821
1822 // 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,
1823 // catching up to the current month if a gap is detected
1824 while ($yearMonthLastUpdate < $yearMonthNow) {
1825 $this->db->begin();
1826
1827 $year = dol_print_date($lastUpdate, '%Y');
1828 $month = dol_print_date($lastUpdate, '%m');
1829
1830 $users = $this->fetchUsers(false, false, ' AND u.statut > 0');
1831 $nbUser = count($users);
1832
1833 $typeleaves = $this->getTypes(1, 1);
1834
1835 // Update each user counter
1836 foreach ($users as $userCounter) {
1837 $nbDaysToAdd = (isset($typeleaves[$userCounter['type']]['newbymonth']) ? $typeleaves[$userCounter['type']]['newbymonth'] : 0);
1838 if (empty($nbDaysToAdd)) {
1839 continue;
1840 }
1841
1842 dol_syslog("We update leave type id ".$userCounter['type']." for user id ".$userCounter['rowid'], LOG_DEBUG);
1843
1844 $nowHoliday = (float) $userCounter['nb_holiday'];
1845 $newSolde = $nowHoliday + $nbDaysToAdd;
1846
1847 // We add a log for each user when its balance gets increased
1848 $this->addLogCP($user->id, $userCounter['rowid'], $langs->trans('HolidayMonthlyCredit'), $newSolde, $userCounter['type']);
1849
1850 $result = $this->updateSoldeCP($userCounter['rowid'], $newSolde, $userCounter['type']);
1851
1852 if ($result < 0) {
1853 $this->db->rollback();
1854 return -1;
1855 }
1856
1857 if (empty($decrease)) {
1858 continue;
1859 }
1860
1861 // 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
1862 $filter = " AND cp.statut = ".((int) self::STATUS_APPROVED);
1863 $filter .= " AND cp.date_fin >= '".$this->db->idate(dol_stringtotime(dol_print_date($lastUpdate, '%Y-%m-01')))."'";
1864 $filter .= " AND cp.date_debut <= '".$this->db->idate(dol_stringtotime(dol_print_date($lastUpdate, '%Y-%m-t')))."'";
1865 $filter .= " AND cp.fk_type = ".((int) $userCounter['type']);
1866 $this->fetchByUser($userCounter['id'], '', $filter);
1867
1868 if (empty($this->holiday)) {
1869 continue;
1870 }
1871
1872 $startOfMonth = dol_mktime(0, 0, 0, (int) $month, 1, (int) $year, 1);
1873 $endOfMonth = dol_mktime(0, 0, 0, (int) $month, (int) dol_print_date($lastUpdate, 't'), (int) $year, 1);
1874
1875 foreach ($this->holiday as $obj) {
1876 $startDate = $obj['date_debut_gmt'];
1877 $endDate = $obj['date_fin_gmt'];
1878
1879 if ($startDate <= $endOfMonth && $startDate < $startOfMonth) {
1880 $startDate = $startOfMonth;
1881 }
1882
1883 if ($startOfMonth <= $endDate && $endDate > $endOfMonth) {
1884 $endDate = $endOfMonth;
1885 }
1886
1887 $nbDaysToDeduct = (float) num_open_day($startDate, $endDate, 0, 1, $obj['halfday'], $obj['country_id'], $obj['fk_user']);
1888
1889 if ($nbDaysToDeduct <= 0) {
1890 continue;
1891 }
1892
1893 $newSolde -= $nbDaysToDeduct;
1894
1895 // We add a log for each user when its balance gets decreased
1896 $this->addLogCP($user->id, $userCounter['rowid'], $obj['ref'].' - '.$langs->trans('HolidayConsumption'), $newSolde, $userCounter['type']);
1897
1898 $result = $this->updateSoldeCP($userCounter['rowid'], $newSolde, $userCounter['type']);
1899
1900 if ($result < 0) {
1901 $this->db->rollback();
1902 return -1;
1903 }
1904 }
1905 }
1906
1907 // Updating the date of the last monthly balance update
1908 $newMonth = dol_get_next_month((int) dol_print_date($lastUpdate, '%m'), (int) dol_print_date($lastUpdate, '%Y'));
1909 $lastUpdate = dol_mktime(0, 0, 0, (int) $newMonth['month'], 1, (int) $newMonth['year']);
1910
1911 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1912 $sql .= " value = '".$this->db->escape(dol_print_date($lastUpdate, '%Y%m%d%H%M%S'))."'";
1913 $sql .= " WHERE name = 'lastUpdate'";
1914 $result = $this->db->query($sql);
1915
1916 if (!$result) {
1917 $this->db->rollback();
1918 return -1;
1919 }
1920
1921 $this->db->commit();
1922
1923 $yearMonthLastUpdate = dol_print_date($lastUpdate, '%Y%m');
1924 }
1925
1926 return 1;
1927 } else {
1928 // Update for one user
1929 $nbHoliday = price2num($nbHoliday, 5);
1930
1931 $sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users";
1932 $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1933 $resql = $this->db->query($sql);
1934 if ($resql) {
1935 $num = $this->db->num_rows($resql);
1936
1937 if ($num > 0) {
1938 // Update for user
1939 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET";
1940 $sql .= " nb_holiday = ".((float) $nbHoliday);
1941 $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1942 $result = $this->db->query($sql);
1943 if (!$result) {
1944 $error++;
1945 $this->errors[] = $this->db->lasterror();
1946 }
1947 } else {
1948 // Insert for user
1949 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users(nb_holiday, fk_user, fk_type) VALUES (";
1950 $sql .= ((float) $nbHoliday);
1951 $sql .= ", ".(int) $userID.", ".(int) $fk_type.")";
1952 $result = $this->db->query($sql);
1953 if (!$result) {
1954 $error++;
1955 $this->errors[] = $this->db->lasterror();
1956 }
1957 }
1958 } else {
1959 $this->errors[] = $this->db->lasterror();
1960 $error++;
1961 }
1962
1963 if (!$error) {
1964 return 1;
1965 } else {
1966 return -1;
1967 }
1968 }
1969 }
1970
1978 public function getCPforUser($user_id, $fk_type = 0)
1979 {
1980 $sql = "SELECT nb_holiday";
1981 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users";
1982 $sql .= " WHERE fk_user = ".(int) $user_id;
1983 if ($fk_type > 0) {
1984 $sql .= " AND fk_type = ".(int) $fk_type;
1985 }
1986
1987 dol_syslog(get_class($this).'::getCPforUser user_id='.$user_id.' type_id='.$fk_type, LOG_DEBUG);
1988 $result = $this->db->query($sql);
1989 if ($result) {
1990 $obj = $this->db->fetch_object($result);
1991 //return number_format($obj->nb_holiday,2);
1992 if ($obj) {
1993 return $obj->nb_holiday;
1994 } else {
1995 return null;
1996 }
1997 } else {
1998 return null;
1999 }
2000 }
2001
2010 public function fetchUsers($stringlist = true, $type = true, $sqlFilters = '')
2011 {
2012 dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG);
2013
2014 if ($stringlist) {
2015 if ($type) {
2016 // If user of Dolibarr
2017 $sql = "SELECT";
2018 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2019 $sql .= " DISTINCT";
2020 }
2021 $sql .= " u.rowid";
2022 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2023
2024 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2025 $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2026 $sql .= " WHERE ((ug.fk_user = u.rowid";
2027 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
2028 $sql .= " OR u.entity = 0)"; // Show always superadmin
2029 } else {
2030 $sql .= " WHERE u.entity IN (".getEntity('user').")";
2031 }
2032 $sql .= " AND u.statut > 0";
2033 $sql .= " AND u.employee = 1"; // We only want employee users for holidays
2034 if ($sqlFilters) {
2035 $sql .= $sqlFilters;
2036 }
2037
2038 $resql = $this->db->query($sql);
2039
2040 // If no SQL error
2041 if ($resql) {
2042 $i = 0;
2043 $num = $this->db->num_rows($resql);
2044 $stringlist = '';
2045
2046 // User listing loops
2047 while ($i < $num) {
2048 $obj = $this->db->fetch_object($resql);
2049
2050 if ($i == 0) {
2051 $stringlist .= $obj->rowid;
2052 } else {
2053 $stringlist .= ', '.$obj->rowid;
2054 }
2055
2056 $i++;
2057 }
2058 // Returns the user table
2059 return $stringlist;
2060 } else {
2061 // SQL error
2062 $this->error = "Error ".$this->db->lasterror();
2063 return -1;
2064 }
2065 } else {
2066 // We want only list of vacation balance for user ids
2067 $sql = "SELECT DISTINCT cpu.fk_user";
2068 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
2069 $sql .= " WHERE cpu.fk_user = u.rowid";
2070 if ($sqlFilters) {
2071 $sql .= $sqlFilters;
2072 }
2073
2074 $resql = $this->db->query($sql);
2075
2076 // If no SQL error
2077 if ($resql) {
2078 $i = 0;
2079 $num = $this->db->num_rows($resql);
2080 $stringlist = '';
2081
2082 // User listing loops
2083 while ($i < $num) {
2084 $obj = $this->db->fetch_object($resql);
2085
2086 if ($i == 0) {
2087 $stringlist .= $obj->fk_user;
2088 } else {
2089 $stringlist .= ', '.$obj->fk_user;
2090 }
2091
2092 $i++;
2093 }
2094 // Returns the user table
2095 return $stringlist;
2096 } else {
2097 // SQL error
2098 $this->error = "Error ".$this->db->lasterror();
2099 return -1;
2100 }
2101 }
2102 } else {
2103 // If false, return array
2104 // List for Dolibarr users
2105 if ($type) {
2106 // If we need users of Dolibarr
2107 $sql = "SELECT";
2108 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2109 $sql .= " DISTINCT";
2110 }
2111 $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";
2112 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2113
2114 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2115 $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2116 $sql .= " WHERE ((ug.fk_user = u.rowid";
2117 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
2118 $sql .= " OR u.entity = 0)"; // Show always superadmin
2119 } else {
2120 $sql .= " WHERE u.entity IN (".getEntity('user').")";
2121 }
2122
2123 $sql .= " AND u.statut > 0";
2124 $sql .= " AND u.employee = 1"; // We only want employee users for holidays
2125 if ($sqlFilters) {
2126 $sql .= $sqlFilters;
2127 }
2128
2129 $resql = $this->db->query($sql);
2130
2131 // If no SQL error
2132 if ($resql) {
2133 $i = 0;
2134 $tab_result = $this->holiday;
2135 $num = $this->db->num_rows($resql);
2136
2137 // User listing loops
2138 while ($i < $num) {
2139 $obj = $this->db->fetch_object($resql);
2140
2141 $tab_result[$i]['rowid'] = (int) $obj->rowid; // rowid of user
2142 $tab_result[$i]['id'] = (int) $obj->rowid; // id of user
2143 $tab_result[$i]['name'] = $obj->lastname; // deprecated
2144 $tab_result[$i]['lastname'] = $obj->lastname;
2145 $tab_result[$i]['firstname'] = $obj->firstname;
2146 $tab_result[$i]['gender'] = $obj->gender;
2147 $tab_result[$i]['status'] = (int) $obj->status;
2148 $tab_result[$i]['employee'] = (int) $obj->employee;
2149 $tab_result[$i]['photo'] = $obj->photo;
2150 $tab_result[$i]['fk_user'] = (int) $obj->fk_user; // rowid of manager
2151 $tab_result[$i]['country_id'] = (int) $obj->country_id; // id of country of user
2152 //$tab_result[$i]['type'] = $obj->type;
2153 //$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
2154
2155 $i++;
2156 }
2157 // Returns the user table
2158 return $tab_result;
2159 } else {
2160 // SQL error
2161 $this->errors[] = "Error ".$this->db->lasterror();
2162 return -1;
2163 }
2164 } else {
2165 // List of vacation balance users
2166 $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";
2167 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
2168 $sql .= " WHERE cpu.fk_user = u.rowid";
2169 if ($sqlFilters) {
2170 $sql .= $sqlFilters;
2171 }
2172
2173 $resql = $this->db->query($sql);
2174
2175 // If no SQL error
2176 if ($resql) {
2177 $i = 0;
2178 $tab_result = $this->holiday;
2179 $num = $this->db->num_rows($resql);
2180
2181 // User listing loops
2182 while ($i < $num) {
2183 $obj = $this->db->fetch_object($resql);
2184
2185 $tab_result[$i]['rowid'] = $obj->rowid; // rowid of user
2186 $tab_result[$i]['id'] = $obj->rowid; // id of user
2187 $tab_result[$i]['name'] = $obj->lastname; // deprecated
2188 $tab_result[$i]['lastname'] = $obj->lastname;
2189 $tab_result[$i]['firstname'] = $obj->firstname;
2190 $tab_result[$i]['gender'] = $obj->gender;
2191 $tab_result[$i]['status'] = $obj->status;
2192 $tab_result[$i]['employee'] = $obj->employee;
2193 $tab_result[$i]['photo'] = $obj->photo;
2194 $tab_result[$i]['fk_user'] = $obj->fk_user; // rowid of manager
2195
2196 $tab_result[$i]['type'] = $obj->fk_type;
2197 $tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
2198
2199 $i++;
2200 }
2201 // Returns the user table
2202 return $tab_result;
2203 } else {
2204 // SQL error
2205 $this->error = "Error ".$this->db->lasterror();
2206 return -1;
2207 }
2208 }
2209 }
2210 }
2211
2212
2213 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2221 {
2222 // phpcs:enable
2223 $users_validator = array();
2224
2225 $sql = "SELECT DISTINCT ur.fk_user";
2226 $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2227 $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
2228 $sql .= "UNION";
2229 $sql .= " SELECT DISTINCT ugu.fk_user";
2230 $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2231 $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
2232 //print $sql;
2233
2234 dol_syslog(get_class($this)."::fetch_users_approver_holiday sql=".$sql);
2235 $result = $this->db->query($sql);
2236 if ($result) {
2237 $num_rows = $this->db->num_rows($result);
2238 $i = 0;
2239 while ($i < $num_rows) {
2240 $objp = $this->db->fetch_object($result);
2241 array_push($users_validator, $objp->fk_user);
2242 $i++;
2243 }
2244 return $users_validator;
2245 } else {
2246 $this->error = $this->db->lasterror();
2247 dol_syslog(get_class($this)."::fetch_users_approver_holiday Error ".$this->error, LOG_ERR);
2248 return -1;
2249 }
2250 }
2251
2252
2258 public function countActiveUsers()
2259 {
2260 $sql = "SELECT count(u.rowid) as compteur";
2261 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2262 $sql .= " WHERE u.statut > 0";
2263
2264 $result = $this->db->query($sql);
2265 $object = $this->db->fetch_object($result);
2266
2267 return $object->compteur;
2268 }
2275 {
2276 $sql = "SELECT count(u.rowid) as compteur";
2277 $sql .= " FROM ".MAIN_DB_PREFIX."user as u LEFT JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)";
2278 $sql .= " WHERE u.statut > 0 AND hu.fk_user IS NULL";
2279
2280 $result = $this->db->query($sql);
2281 $object = $this->db->fetch_object($result);
2282
2283 return $object->compteur;
2284 }
2285
2293 public function verifNbUsers($userDolibarrWithoutCP, $userCP)
2294 {
2295 if (empty($userCP)) {
2296 $userCP = 0;
2297 }
2298 dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP);
2299 return 1;
2300 }
2301
2302
2313 public function addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
2314 {
2315 $error = 0;
2316
2317 $prev_solde = price2num((float) $this->getCPforUser($fk_user_update, $fk_type), 5);
2318 $new_solde = price2num($new_solde, 5);
2319 //print "$prev_solde == $new_solde";
2320
2321 if ($prev_solde == $new_solde) {
2322 return 0;
2323 }
2324
2325 $this->db->begin();
2326
2327 // Insert request
2328 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_logs (";
2329 $sql .= "date_action,";
2330 $sql .= "fk_user_action,";
2331 $sql .= "fk_user_update,";
2332 $sql .= "type_action,";
2333 $sql .= "prev_solde,";
2334 $sql .= "new_solde,";
2335 $sql .= "fk_type";
2336 $sql .= ") VALUES (";
2337 $sql .= " '".$this->db->idate(dol_now())."',";
2338 $sql .= " ".((int) $fk_user_action).",";
2339 $sql .= " ".((int) $fk_user_update).",";
2340 $sql .= " '".$this->db->escape($label)."',";
2341 $sql .= " ".((float) $prev_solde).",";
2342 $sql .= " ".((float) $new_solde).",";
2343 $sql .= " ".((int) $fk_type);
2344 $sql .= ")";
2345
2346 $resql = $this->db->query($sql);
2347 if (!$resql) {
2348 $error++;
2349 $this->errors[] = "Error ".$this->db->lasterror();
2350 }
2351
2352 $optRowid = 0;
2353 if (!$error) {
2354 $optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs");
2355 }
2356
2357 // Commit or rollback
2358 if ($error) {
2359 foreach ($this->errors as $errmsg) {
2360 dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR);
2361 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2362 }
2363 $this->db->rollback();
2364 return -1 * $error;
2365 } else {
2366 $this->db->commit();
2367 return $optRowid;
2368 }
2369 }
2370
2378 public function fetchLog($sqlorder, $sqlwhere)
2379 {
2380 $sql = "SELECT";
2381 $sql .= " cpl.rowid,";
2382 $sql .= " cpl.date_action,";
2383 $sql .= " cpl.fk_user_action,";
2384 $sql .= " cpl.fk_user_update,";
2385 $sql .= " cpl.type_action,";
2386 $sql .= " cpl.prev_solde,";
2387 $sql .= " cpl.new_solde,";
2388 $sql .= " cpl.fk_type";
2389 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_logs as cpl";
2390 $sql .= " WHERE cpl.rowid > 0"; // To avoid error with other search and criteria
2391
2392 // Filter
2393 if (!empty($sqlwhere)) {
2394 $sql .= " ".$sqlwhere;
2395 }
2396
2397 // Order
2398 if (!empty($sqlorder)) {
2399 $sql .= " ".$sqlorder;
2400 }
2401
2402 dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG);
2403 $resql = $this->db->query($sql);
2404
2405 // If no error SQL
2406 if ($resql) {
2407 $i = 0;
2408 $tab_result = $this->logs;
2409 $num = $this->db->num_rows($resql);
2410
2411 // If no record
2412 if (!$num) {
2413 return 2;
2414 }
2415
2416 // Loop on result to fill the array
2417 while ($i < $num) {
2418 $obj = $this->db->fetch_object($resql);
2419
2420 $tab_result[$i]['rowid'] = (int) $obj->rowid;
2421 $tab_result[$i]['id'] = (int) $obj->rowid;
2422 $tab_result[$i]['date_action'] = (string) $obj->date_action;
2423 $tab_result[$i]['fk_user_action'] = (int) $obj->fk_user_action;
2424 $tab_result[$i]['fk_user_update'] = (int) $obj->fk_user_update;
2425 $tab_result[$i]['type_action'] = (string) $obj->type_action;
2426 $tab_result[$i]['prev_solde'] = (float) $obj->prev_solde;
2427 $tab_result[$i]['new_solde'] = (float) $obj->new_solde;
2428 $tab_result[$i]['fk_type'] = (int) $obj->fk_type;
2429
2430 $i++;
2431 }
2432 // Returns 1 and adds the array to the variable
2433 $this->logs = $tab_result;
2434 return 1;
2435 } else {
2436 // SQL error
2437 $this->error = "Error ".$this->db->lasterror();
2438 return -1;
2439 }
2440 }
2441
2442
2450 public function getTypes($active = -1, $affect = -1)
2451 {
2452 global $mysoc;
2453
2454 $sql = "SELECT rowid, code, label, affect, delay, newbymonth";
2455 $sql .= " FROM ".MAIN_DB_PREFIX."c_holiday_types";
2456 $sql .= " WHERE (fk_country IS NULL OR fk_country = ".((int) $mysoc->country_id).')';
2457 $sql .= " AND entity IN (0, ".getEntity('c_holiday_types').")"; // Need entity 0 (holiday types common to all countries= + current entity).
2458 if ($active >= 0) {
2459 $sql .= " AND active = ".((int) $active);
2460 }
2461 if ($affect >= 0) {
2462 $sql .= " AND affect = ".((int) $affect);
2463 }
2464 $sql .= " ORDER BY sortorder";
2465
2466 $result = $this->db->query($sql);
2467 if ($result) {
2468 $num = $this->db->num_rows($result);
2469 if ($num) {
2470 $types = array();
2471 while ($obj = $this->db->fetch_object($result)) {
2472 $types[$obj->rowid] = array(
2473 'id' => $obj->rowid,
2474 'rowid' => $obj->rowid,
2475 'code' => $obj->code,
2476 'label' => $obj->label,
2477 'affect' => $obj->affect,
2478 'delay' => $obj->delay,
2479 'newbymonth' => $obj->newbymonth
2480 );
2481 }
2482
2483 return $types;
2484 }
2485 } else {
2486 dol_print_error($this->db);
2487 }
2488
2489 return array();
2490 }
2491
2492
2499 public function info($id)
2500 {
2501 global $conf;
2502
2503 $sql = "SELECT f.rowid, f.statut as status,";
2504 $sql .= " f.date_create as datec,";
2505 $sql .= " f.tms as date_modification,";
2506 $sql .= " f.date_valid as datev,";
2507 $sql .= " f.date_approval as datea,";
2508 $sql .= " f.date_refuse as dater,";
2509 $sql .= " f.fk_user_create as fk_user_creation,";
2510 $sql .= " f.fk_user_modif as fk_user_modification,";
2511 $sql .= " f.fk_user_valid as fk_user_validation,";
2512 $sql .= " f.fk_user_approve as fk_user_approval_done,";
2513 $sql .= " f.fk_validator as fk_user_approval_expected,";
2514 $sql .= " f.fk_user_refuse as fk_user_refuse";
2515 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as f";
2516 $sql .= " WHERE f.rowid = ".((int) $id);
2517 $sql .= " AND f.entity = ".((int) $conf->entity);
2518
2519 $resql = $this->db->query($sql);
2520 if ($resql) {
2521 if ($this->db->num_rows($resql)) {
2522 $obj = $this->db->fetch_object($resql);
2523
2524 $this->id = $obj->rowid;
2525
2526 $this->date_creation = $this->db->jdate($obj->datec);
2527 $this->date_modification = $this->db->jdate($obj->date_modification);
2528 $this->date_validation = $this->db->jdate($obj->datev);
2529 $this->date_approval = $this->db->jdate($obj->datea);
2530
2531 $this->user_creation_id = $obj->fk_user_creation;
2532 $this->user_validation_id = $obj->fk_user_validation;
2533 $this->user_modification_id = $obj->fk_user_modification;
2534
2535 if ($obj->status == Holiday::STATUS_APPROVED || $obj->status == Holiday::STATUS_CANCELED) {
2536 if ($obj->fk_user_approval_done) {
2537 $this->fk_user_approve = $obj->fk_user_approval_done;
2538 $this->user_approve_id = $obj->fk_user_approval_done;
2539 }
2540 }
2541 }
2542 $this->db->free($resql);
2543 } else {
2544 dol_print_error($this->db);
2545 }
2546 }
2547
2548
2556 public function initAsSpecimen()
2557 {
2558 global $user, $langs;
2559
2560 // Initialise parameters
2561 $this->id = 0;
2562 $this->specimen = 1;
2563
2564 $this->fk_user = $user->id;
2565 $this->description = 'SPECIMEN description';
2566 $this->date_debut = dol_now();
2567 $this->date_fin = dol_now() + (24 * 3600);
2568 $this->date_valid = dol_now();
2569 $this->fk_validator = $user->id;
2570 $this->halfday = 0;
2571 $this->fk_type = 1;
2573
2574 return 1;
2575 }
2576
2582 public function loadStateBoard()
2583 {
2584 global $user;
2585
2586 $this->nb = array();
2587
2588 $sql = "SELECT count(h.rowid) as nb";
2589 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2590 $sql .= " WHERE h.statut > 1";
2591 $sql .= " AND h.entity IN (".getEntity('holiday').")";
2592 if (!$user->hasRight('holiday', 'readall')) {
2593 $userchildids = $user->getAllChildIds(1);
2594 $sql .= " AND (h.fk_user IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2595 $sql .= " OR h.fk_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2596 }
2597
2598 $resql = $this->db->query($sql);
2599 if ($resql) {
2600 while ($obj = $this->db->fetch_object($resql)) {
2601 $this->nb["holidays"] = $obj->nb;
2602 }
2603 $this->db->free($resql);
2604 return 1;
2605 } else {
2606 dol_print_error($this->db);
2607 $this->error = $this->db->error();
2608 return -1;
2609 }
2610 }
2611
2612 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2619 public function load_board($user)
2620 {
2621 // phpcs:enable
2622 global $conf, $langs;
2623
2624 if ($user->socid) {
2625 return -1; // Protection to prevent calls by external users
2626 }
2627
2628 $now = dol_now();
2629
2630 // The count and the number of late requests are computed by the database instead of reading every request. A request is
2631 // late when its start date is before now minus the warning delay (a request without start date was counted as late,
2632 // this is kept).
2633 $sql = "SELECT COUNT(h.rowid) as nb,";
2634 $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";
2635 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2636 $sql .= " WHERE h.statut = 2";
2637 $sql .= " AND h.entity IN (".getEntity('holiday').")";
2638 if (!$user->hasRight('holiday', 'read_all')) {
2639 $userchildids = $user->getAllChildIds(1);
2640 $sql .= " AND (h.fk_user IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2641 $sql .= " OR h.fk_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2642 }
2643
2644 $resql = $this->db->query($sql);
2645 if ($resql) {
2646 $langs->load("members");
2647
2648 $response = new WorkboardResponse();
2649 $response->warning_delay = $conf->holiday->approve->warning_delay / 60 / 60 / 24;
2650 $response->label = $langs->trans("HolidaysToApprove");
2651 $response->labelShort = $langs->trans("ToApprove");
2652 $response->url = DOL_URL_ROOT.'/holiday/list.php?search_status=2&amp;mainmenu=hrm&amp;leftmenu=holiday';
2653 $response->img = img_object('', "holiday");
2654
2655 $obj = $this->db->fetch_object($resql);
2656 if ($obj) {
2657 $response->nbtodo = (int) $obj->nb;
2658 $response->nbtodolate = (int) $obj->nblate;
2659 }
2660
2661 return $response;
2662 } else {
2663 dol_print_error($this->db);
2664 $this->error = $this->db->error();
2665 return -1;
2666 }
2667 }
2675 public function getKanbanView($option = '', $arraydata = null)
2676 {
2677 global $langs;
2678
2679 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2680
2681 $return = '<div class="box-flex-item box-flex-grow-zero">';
2682 $return .= '<div class="info-box info-box-sm">';
2683 $return .= '<span class="info-box-icon bg-infobox-action">';
2684 $return .= img_picto('', $this->picto);
2685 $return .= '</span>';
2686 $return .= '<div class="info-box-content">';
2687 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.$this->getNomUrl().'</span>';
2688 if ($selected >= 0) {
2689 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2690 }
2691 if (property_exists($this, 'fk_type')) {
2692 $return .= '<br>';
2693 //$return .= '<span class="opacitymedium">'.$langs->trans("Type").'</span> : ';
2694 $return .= '<div class="info_box-label tdoverflowmax100" title="'.dol_escape_htmltag($arraydata['labeltype']).'">'.dol_escape_htmltag($arraydata['labeltype']).'</div>';
2695 }
2696 if (property_exists($this, 'date_debut') && property_exists($this, 'date_fin')) {
2697 $return .= '<span class="info-box-label small">'.dol_print_date($this->date_debut, 'day').'</span>';
2698 $return .= ' <span class="opacitymedium small">'.$langs->trans("To").'</span> ';
2699 $return .= '<span class="info-box-label small">'.dol_print_date($this->date_fin, 'day').'</span>';
2700 if (!empty($arraydata['nbopenedday'])) {
2701 $return .= ' ('.$arraydata['nbopenedday'].')';
2702 }
2703 }
2704 if (method_exists($this, 'getLibStatut')) {
2705 $return .= '<div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2706 }
2707 $return .= '</div>';
2708 $return .= '</div>';
2709 $return .= '</div>';
2710 return $return;
2711 }
2712
2723 public function sendPreviousMonthHRInformations($mailto = "", $template = "", $newlang = "")
2724 {
2725 global $conf, $langs, $user;
2726
2727 $outputlangs = $langs;
2728
2729 $error = 0;
2730 $this->output = '';
2731 $this->error = '';
2732 $arrayfields = array(
2733 'user' => 'Employee',
2734 'type' => 'Type',
2735 'date_start' => 'DateDebCP',
2736 'date_end' => 'DateFinCP',
2737 'used_days' => 'NbUseDaysCPShort',
2738 );
2739
2740 if (!empty($newlang)) {
2741 $outputlangs = new Translate("", $conf);
2742 $outputlangs->setDefaultLang($newlang);
2743 }
2744 $outputlangs->loadLangs(array('main', 'holiday', 'hrm'));
2745
2746 if (empty($mailto) || !isValidEmail($mailto)) {
2747 $this->errors[] = 'Bad value for parameter mailto. Must be a valid email address.';
2748 return 1;
2749 }
2750
2751 $typeleaves = $this->getTypes(1, -1);
2752 $arraytypeleaves = array();
2753 foreach ($typeleaves as $val) {
2754 $labeltoshow = ($outputlangs->trans($val['code']) != $val['code'] ? $outputlangs->trans($val['code']) : $val['label']);
2755 $arraytypeleaves[$val['rowid']] = $labeltoshow;
2756 }
2757 $listhalfday = array('morning' => $outputlangs->trans("Morning"), "afternoon" => $outputlangs->trans("Afternoon"));
2758
2759 $datenow = dol_getdate(dol_now());
2760 $prev_month = dol_get_prev_month($datenow["mon"], $datenow["year"]);
2761 $year_month = sprintf("%04d", $prev_month["year"]).'-'.sprintf("%02d", $prev_month["month"]);
2762 $arrayleaves = array(); // Array of leaves of previous month, grouped by user id
2763
2764 $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";
2765 $sql .= " FROM ".MAIN_DB_PREFIX."holiday cp";
2766 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON cp.fk_user = u.rowid";
2767 $sql .= " WHERE cp.entity IN (".getEntity('holiday').") AND cp.rowid > 0";
2768 $sql .= " AND cp.statut = ".Holiday::STATUS_APPROVED;
2769 $sql .= " AND (";
2770 $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)."')";
2771 $sql .= " OR"; // For leave over several months
2772 $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)."') ";
2773 $sql .= " )";
2774 $sql .= $this->db->order("cp.fk_user, cp.date_debut", "ASC");
2775 $resql = $this->db->query($sql);
2776 if (empty($resql)) {
2777 $this->errors[] = $this->db->lasterror();
2778 return 1;
2779 }
2780 $num = $this->db->num_rows($resql);
2781 if ($num > 0) {
2782 $tmpuser = new User($this->db);
2783 while ($obj = $this->db->fetch_object($resql)) {
2784 $tmpuser->fetch($obj->fk_user);
2785
2786 $date_start = $this->db->jdate($obj->date_debut, true);
2787 $date_end = $this->db->jdate($obj->date_fin, true);
2788
2789 $tmpstart = dol_getdate($date_start);
2790 $tmpend = dol_getdate($date_end);
2791
2792 $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning';
2793 $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon';
2794
2795 $halfdayinmonth = $obj->halfday;
2796 $starthalfdayinmonth = $starthalfday;
2797 $endhalfdayinmonth = $endhalfday;
2798
2799 //0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
2800
2801 // Set date_start_gmt and date_end_gmt that are date to show for the selected month
2802 $date_start_inmonth = $this->db->jdate($obj->date_debut, true);
2803 $date_end_inmonth = $this->db->jdate($obj->date_fin, true);
2804 if ($tmpstart['year'] < $prev_month["year"] || $tmpstart['mon'] < $prev_month["month"]) {
2805 $date_start_inmonth = dol_get_first_day($prev_month["year"], $prev_month["month"], true);
2806 $starthalfdayinmonth = 'morning';
2807 if ($halfdayinmonth == 2) {
2808 $halfdayinmonth = 1;
2809 }
2810 if ($halfdayinmonth == -1) {
2811 $halfdayinmonth = 0;
2812 }
2813 }
2814 if ($tmpend['year'] > $prev_month["year"] || $tmpend['mon'] > $prev_month["month"]) {
2815 $date_end_inmonth = dol_get_last_day($prev_month["year"], $prev_month["month"], true) - ((24 * 3600) - 1);
2816 $endhalfdayinmonth = 'afternoon';
2817 if ($halfdayinmonth == 2) {
2818 $halfdayinmonth = -1;
2819 }
2820 if ($halfdayinmonth == 1) {
2821 $halfdayinmonth = 0;
2822 }
2823 }
2824 $arrayleaves[$obj->fk_user][] = array(
2825 "user" => $tmpuser->getNomUrl(0, 'nolink', 0, 0, 24, 1),
2826 "type" => $arraytypeleaves[$obj->fk_type],
2827 "date_start" => dol_print_date($date_start_inmonth, 'day') . ' <span class="opacitymedium">('.$outputlangs->trans($listhalfday[$starthalfdayinmonth]).')</span>',
2828 "date_end" => dol_print_date($date_end_inmonth, 'day') . ' <span class="opacitymedium">('.$outputlangs->trans($listhalfday[$endhalfdayinmonth]).')</span>',
2829 "used_days" => num_open_day($date_start_inmonth, $date_end_inmonth, 0, 1, $halfdayinmonth, $tmpuser->country_id, $obj->fk_user)
2830 );
2831 }
2832 }
2833
2834 // Get list of active employees, so all of them appear even if they did not take any leave
2835 $arrayemployees = $this->fetchUsers(false, true);
2836 if (!is_array($arrayemployees)) {
2837 return 1; // $this->errors was already filled by fetchUsers
2838 }
2839
2840 // Reorder the array of leaves to show all active employees, and add a line with type = "None" for those without leave
2841 $arrayleavesfinal = array();
2842 $usertmp = new User($this->db);
2843 foreach ($arrayemployees as $employee) {
2844 if (!empty($arrayleaves[$employee['rowid']])) {
2845 $arrayleavesfinal = array_merge($arrayleavesfinal, $arrayleaves[$employee['rowid']]);
2846 unset($arrayleaves[$employee['rowid']]);
2847 } else {
2848 $usertmp->fetch($employee['rowid']);
2849 $arrayleavesfinal[] = array(
2850 "user" => $usertmp->getNomUrl(0, 'nolink', 0, 0, 24, 1),
2851 "type" => $outputlangs->trans("None"),
2852 "date_start" => '',
2853 "date_end" => '',
2854 "used_days" => 0
2855 );
2856 }
2857 }
2858 // Add leaves of users that are no longer active employees
2859 foreach ($arrayleaves as $leavesofuser) {
2860 $arrayleavesfinal = array_merge($arrayleavesfinal, $leavesofuser);
2861 }
2862 $arrayleaves = $arrayleavesfinal;
2863
2864 $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;">';
2865 $outputarrayleaves .= '<tr>';
2866 foreach ($arrayfields as $key => $label) {
2867 $outputarrayleaves .= '<td style="border-bottom:1px solid #b6b6b6;padding: 6px 10px 6px 12px;">';
2868 $outputarrayleaves .= $outputlangs->trans($label);
2869 if ($key == 'date_end') {
2870 $outputarrayleaves .=" (".$langs->trans("Included").")";
2871 }
2872 $outputarrayleaves .= '</td>';
2873 }
2874 $outputarrayleaves .= '</tr>';
2875
2876 if (!empty($arrayleaves)) {
2877 foreach ($arrayleaves as $fields) {
2878 $outputarrayleaves .= '<tr>';
2879 foreach ($fields as $field => $value) {
2880 $outputarrayleaves .= '<td style="border-bottom:1px solid #b6b6b6;padding: 6px 10px 6px 12px;" id="'.$field.'">';
2881 $outputarrayleaves .= $value;
2882 $outputarrayleaves .= '</td>';
2883 }
2884 $outputarrayleaves .= '</tr>';
2885 }
2886 } else {
2887 $outputarrayleaves .= '<tr>';
2888 $outputarrayleaves .= '<td style="border-bottom:1px solid #b6b6b6;padding: 6px 10px 6px 12px;" colspan="5">';
2889 $outputarrayleaves .= $outputlangs->trans("None");
2890 $outputarrayleaves .= '</td>';
2891 $outputarrayleaves .= '</tr>';
2892 }
2893 $outputarrayleaves .= '</table>';
2894
2895 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2896 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2897
2898 $formmail = new FormMail($this->db);
2899 $templateId = 0;
2900 $templateLabel = '';
2901 if (empty($template) || $template == 'EmailTemplateCode') {
2902 $templateLabel = '(HolidayHrInformationsPreviousMonth)';
2903 } else {
2904 if (is_numeric($template)) {
2905 $templateId = $template;
2906 } else {
2907 $templateLabel = $template;
2908 }
2909 }
2910 $mailtemplate = $formmail->getEMailTemplate($this->db, "holiday", $user, $outputlangs, $templateId, 1, $templateLabel);
2911
2912 if (is_numeric($mailtemplate) || empty($mailtemplate->topic)) {
2913 $this->errors[] = 'No mail template found for code "'.$templateLabel.'" or id "'.$templateId.'".';
2914 $error++;
2915 }
2916
2917 if (!$error) {
2918 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
2919 complete_substitutions_array($substitutionarray, $outputlangs, $this);
2920
2921 $subject = make_substitutions($mailtemplate->topic, $substitutionarray, $outputlangs);
2922 $msg = make_substitutions($mailtemplate->content, $substitutionarray, $outputlangs);
2923 $from = dol_string_nospecial(getDolGlobalString('MAIN_INFO_SOCIETE_NOM'), ' ', array(",")).' <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL').'>';
2924
2925 $msg = preg_replace('/__HOLIDAY_ARRAY_PER_EMPLOYEE_FOR_PERIOD__/', $outputarrayleaves, $msg);
2926 $cmail = new CMailFile($subject, $mailto, $from, $msg, array(), array(), array(), '', '', 0, 1);
2927 $result = $cmail->sendfile();
2928 if (!$result || !empty($cmail->error) || !empty($cmail->errors)) {
2929 $this->errors[] = $cmail->error;
2930 if (is_array($cmail->errors) && count($cmail->errors) > 0) {
2931 $this->errors = array_merge($this->errors, $cmail->errors);
2932 $error++;
2933 }
2934 }
2935 }
2936
2937 if (!empty($this->errors)) {
2938 $this->output .= "\n";
2939 // The $this->errors will be concatenated to the output by the function that call this method.
2940 }
2941 return ($error ? 1 : 0);
2942 }
2943}
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:488
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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...
deleteExtraFields()
Delete all extra fields values for the current object.
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.
sendApprovalEmail()
Send the approval email to the user who requested the leave.
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:545
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:626
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:564
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:645
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:452
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.
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:66
$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, $currencycode='')
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.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
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:183