dolibarr 22.0.5
task.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2008-2014 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2010-2012 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2014 Marcos García <marcosgdf@gmail.com>
5 * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2020 Juanjo Menent <jmenent@2byte.es>
7 * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
8 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
9 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
10 * Copyright (C) 2024 Vincent de Grandpré <vincent@de-grandpre.quebec>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24 */
25
32require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
33require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
34require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
35require_once DOL_DOCUMENT_ROOT.'/core/class/timespent.class.php';
36
37
42{
46 public $element = 'project_task';
47
51 public $table_element = 'projet_task';
52
56 public $fk_element = 'fk_element';
57
61 public $picto = 'projecttask';
62
66 protected $childtables = array(
67 'element_time' => array('name' => 'Task', 'parent' => 'projet_task', 'parentkey' => 'fk_element', 'parenttypefield' => 'elementtype', 'parenttypevalue' => 'task')
68 );
69
73 public $fk_task_parent = 0;
74
78 public $label;
79
83 public $description;
84
88 public $duration_effective;
89
93 public $planned_workload;
94
99 public $date_c;
100
104 public $progress;
105
111 public $dateo;
112
117 public $date_start;
118
124 public $datee;
125
130 public $date_end;
131
137 public $fk_statut;
138
142 public $status;
143
147 public $priority;
148
152 public $fk_user_creat;
153
157 public $fk_user_valid;
158
162 public $rang;
163
167 public $timespent_min_date;
171 public $timespent_max_date;
175 public $timespent_total_duration;
179 public $timespent_total_amount;
183 public $timespent_nblinesnull;
187 public $timespent_nblines;
188 // For detail of lines of timespent record, there is the property ->lines in common
189
190 // Var used to call method addTimeSpent(). Bad practice.
194 public $timespent_id;
198 public $timespent_duration;
202 public $timespent_old_duration;
206 public $timespent_date;
210 public $timespent_datehour; // More accurate start date (same than timespent_date but includes hours, minutes and seconds)
211
215 public $timespent_withhour; // 0 or 1 = we have entered also start hours for timesheet line
220 public $timespent_fk_user;
224 public $timespent_thm;
228 public $timespent_note;
232 public $timespent_fk_product;
236 public $timespent_invoiceid;
240 public $timespent_invoicelineid;
241
242 public $comments = array();
243
244 // Properties calculated from sum of llx_element_time linked to task
248 public $tobill;
249
253 public $billed;
254
255 // Properties to store project information
259 public $projectref;
260
264 public $projectstatus;
265
269 public $projectlabel;
270
274 public $opp_amount;
275
279 public $opp_percent;
280
284 public $fk_opp_status;
285
289 public $usage_bill_time;
290
294 public $public;
295
299 public $array_options_project;
300
301 // Properties to store thirdparty of project information
302
308 public $socid;
309
313 public $thirdparty_id;
314
318 public $thirdparty_name;
319
323 public $thirdparty_email;
324
325 // store parent ref and position
329 public $task_parent_ref;
330
334 public $task_parent_position;
335
340 public $billable = 1;
341
345 public $budget_amount;
346
350 public $project_budget_amount;
351
355 const STATUS_DRAFT = 0;
356
361
365 const STATUS_ONGOING = 2;
366
370 const STATUS_CLOSED = 3;
371
376
381
382
388 public function __construct($db)
389 {
390 $this->db = $db;
391 // list of status of the task
392 $this->labelStatus = array(
393 0 => 'Draft',
394 1 => 'Validated',
395 2 => 'InProgress',
396 3 => 'Closed',
397 //4 => 'Transferred',
398 );
399 $this->labelStatusShort = array(
400 0 => 'Draft',
401 1 => 'Validated',
402 2 => 'InProgress',
403 3 => 'Closed',
404 //4 => 'Transferred',
405 );
406 }
407
408
416 public function create($user, $notrigger = 0)
417 {
418 global $conf, $langs;
419
420 //For the date
421 $now = dol_now();
422
423 $error = 0;
424
425 // Clean parameters
426 $this->label = trim($this->label);
427 $this->description = trim($this->description);
428 $this->note_public = trim($this->note_public);
429 $this->note_private = trim($this->note_private);
430
431 if (!empty($this->date_start) && !empty($this->date_end) && $this->date_start > $this->date_end) {
432 $this->errors[] = $langs->trans('StartDateCannotBeAfterEndDate');
433 return -1;
434 }
435
436 // Insert request
437 $sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task (";
438 $sql .= "entity";
439 $sql .= ", fk_projet";
440 $sql .= ", ref";
441 $sql .= ", fk_task_parent";
442 $sql .= ", label";
443 $sql .= ", description";
444 $sql .= ", note_public";
445 $sql .= ", note_private";
446 $sql .= ", datec";
447 $sql .= ", fk_user_creat";
448 $sql .= ", dateo";
449 $sql .= ", datee";
450 $sql .= ", planned_workload";
451 $sql .= ", progress";
452 $sql .= ", budget_amount";
453 $sql .= ", priority";
454 $sql .= ", billable";
455 $sql .= ", fk_statut";
456 $sql .= ") VALUES (";
457 $sql .= (!empty($this->entity) ? (int) $this->entity : (int) $conf->entity);
458 $sql .= ", ".((int) $this->fk_project);
459 $sql .= ", ".(!empty($this->ref) ? "'".$this->db->escape($this->ref)."'" : 'null');
460 $sql .= ", ".((int) $this->fk_task_parent);
461 $sql .= ", '".$this->db->escape($this->label)."'";
462 $sql .= ", '".$this->db->escape($this->description)."'";
463 $sql .= ", '".$this->db->escape($this->note_public)."'";
464 $sql .= ", '".$this->db->escape($this->note_private)."'";
465 $sql .= ", '".$this->db->idate($now)."'";
466 $sql .= ", ".((int) $user->id);
467 $sql .= ", ".(isDolTms($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : 'null');
468 $sql .= ", ".(isDolTms($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : 'null');
469 $sql .= ", ".(($this->planned_workload != '' && $this->planned_workload >= 0) ? ((int) $this->planned_workload) : 'null');
470 $sql .= ", ".(($this->progress != '' && $this->progress >= 0) ? ((int) $this->progress) : 'null');
471 $sql .= ", ".(($this->budget_amount != '' && $this->budget_amount >= 0) ? ((int) $this->budget_amount) : 'null');
472 $sql .= ", ".(($this->priority != '' && $this->priority >= 0) ? (int) $this->priority : 'null');
473 $sql .= ", ".((int) $this->billable);
474 $sql .= ", ".((int) $this->status);
475 $sql .= ")";
476
477 $this->db->begin();
478
479 dol_syslog(get_class($this)."::create", LOG_DEBUG);
480 $resql = $this->db->query($sql);
481 if (!$resql) {
482 $error++;
483 $this->errors[] = "Error ".$this->db->lasterror();
484 }
485
486 if (!$error) {
487 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task");
488 // Update extrafield
489 $result = $this->insertExtraFields();
490 if ($result < 0) {
491 $error++;
492 }
493 }
494
495 if (!$error) {
496 if (!$notrigger) {
497 // Call trigger
498 $result = $this->call_trigger('TASK_CREATE', $user);
499 if ($result < 0) {
500 $error++;
501 }
502 // End call triggers
503 }
504 }
505
506 // Commit or rollback
507 if ($error) {
508 foreach ($this->errors as $errmsg) {
509 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
510 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
511 }
512 $this->db->rollback();
513 return -1 * $error;
514 } else {
515 $this->db->commit();
516 return $this->id;
517 }
518 }
519
520
529 public function fetch($id, $ref = '', $loadparentdata = 0)
530 {
531 $sql = "SELECT";
532 $sql .= " t.rowid,";
533 $sql .= " t.ref,";
534 $sql .= " t.entity,";
535 $sql .= " t.fk_projet as fk_project,";
536 $sql .= " t.fk_task_parent,";
537 $sql .= " t.label,";
538 $sql .= " t.description,";
539 $sql .= " t.duration_effective,";
540 $sql .= " t.planned_workload,";
541 $sql .= " t.datec,";
542 $sql .= " t.dateo as date_start,";
543 $sql .= " t.datee as date_end,";
544 $sql .= " t.fk_user_creat,";
545 $sql .= " t.fk_user_valid,";
546 $sql .= " t.fk_statut as status,";
547 $sql .= " t.progress,";
548 $sql .= " t.budget_amount,";
549 $sql .= " t.priority,";
550 $sql .= " t.note_private,";
551 $sql .= " t.note_public,";
552 $sql .= " t.rang,";
553 $sql .= " t.billable";
554 if (!empty($loadparentdata)) {
555 $sql .= ", t2.ref as task_parent_ref";
556 $sql .= ", t2.rang as task_parent_position";
557 }
558 $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t";
559 if (!empty($loadparentdata)) {
560 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t2 ON t.fk_task_parent = t2.rowid";
561 }
562 $sql .= " WHERE ";
563 if (!empty($ref)) {
564 $sql .= "entity IN (".getEntity('project').")";
565 $sql .= " AND t.ref = '".$this->db->escape($ref)."'";
566 } else {
567 $sql .= "t.rowid = ".((int) $id);
568 }
569
570 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
571 $resql = $this->db->query($sql);
572 if ($resql) {
573 $num_rows = $this->db->num_rows($resql);
574
575 if ($num_rows) {
576 $obj = $this->db->fetch_object($resql);
577
578 $this->id = $obj->rowid;
579 $this->ref = $obj->ref;
580 $this->entity = $obj->entity;
581 $this->fk_project = $obj->fk_project;
582 $this->fk_task_parent = $obj->fk_task_parent;
583 $this->label = $obj->label;
584 $this->description = $obj->description;
585 $this->duration_effective = $obj->duration_effective;
586 $this->planned_workload = $obj->planned_workload;
587 $this->date_c = $this->db->jdate($obj->datec);
588 $this->date_start = $this->db->jdate($obj->date_start);
589 $this->date_end = $this->db->jdate($obj->date_end);
590 $this->fk_user_creat = $obj->fk_user_creat;
591 $this->fk_user_valid = $obj->fk_user_valid;
592 $this->status = $obj->status;
593 $this->progress = $obj->progress;
594 $this->budget_amount = $obj->budget_amount;
595 $this->priority = $obj->priority;
596 $this->note_private = $obj->note_private;
597 $this->note_public = $obj->note_public;
598 $this->rang = $obj->rang;
599
600 if (!empty($loadparentdata)) {
601 $this->task_parent_ref = $obj->task_parent_ref;
602 $this->task_parent_position = $obj->task_parent_position;
603 }
604 $this->billable = $obj->billable;
605
606 // Retrieve all extrafield
607 $this->fetch_optionals();
608 }
609
610 $this->db->free($resql);
611
612 if ($num_rows) {
613 return 1;
614 } else {
615 return 0;
616 }
617 } else {
618 $this->error = "Error ".$this->db->lasterror();
619 return -1;
620 }
621 }
622
623
631 public function update($user = null, $notrigger = 0)
632 {
633 global $conf, $langs;
634 $error = 0;
635
636 // Clean parameters
637 if (isset($this->fk_project)) {
638 $this->fk_project = (int) $this->fk_project;
639 }
640 if (isset($this->ref)) {
641 $this->ref = trim($this->ref);
642 }
643 if (isset($this->fk_task_parent)) {
644 $this->fk_task_parent = (int) $this->fk_task_parent;
645 }
646 if (isset($this->label)) {
647 $this->label = trim($this->label);
648 }
649 if (isset($this->description)) {
650 $this->description = trim($this->description);
651 }
652 if (isset($this->note_public)) {
653 $this->note_public = trim($this->note_public);
654 }
655 if (isset($this->note_private)) {
656 $this->note_private = trim($this->note_private);
657 }
658 if (isset($this->duration_effective)) {
659 $this->duration_effective = trim($this->duration_effective);
660 }
661 if (isset($this->planned_workload)) {
662 $this->planned_workload = trim($this->planned_workload);
663 }
664 if (isset($this->budget_amount)) {
665 $this->budget_amount = (float) $this->budget_amount;
666 }
667
668 if (!empty($this->date_start) && !empty($this->date_end) && $this->date_start > $this->date_end) {
669 $this->errors[] = $langs->trans('StartDateCannotBeAfterEndDate');
670 return -1;
671 }
672
673 // Check parameters
674 // Put here code to add control on parameters values
675
676 // Update request
677 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
678 $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
679 $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "'".$this->db->escape((string) $this->id)."'").",";
680 $sql .= " fk_task_parent=".(isset($this->fk_task_parent) ? $this->fk_task_parent : "null").",";
681 $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
682 $sql .= " description=".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").",";
683 $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
684 $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
685 $sql .= " duration_effective=".(isset($this->duration_effective) ? $this->duration_effective : "null").",";
686 $sql .= " planned_workload=".((isset($this->planned_workload) && $this->planned_workload != '') ? $this->planned_workload : "null").",";
687 $sql .= " dateo=".(isDolTms($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : 'null').",";
688 $sql .= " datee=".(isDolTms($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : 'null').",";
689 $sql .= " progress=".(($this->progress != '' && $this->progress >= 0) ? $this->progress : 'null').",";
690 $sql .= " budget_amount=".(($this->budget_amount != '' && $this->budget_amount >= 0) ? $this->budget_amount : 'null').",";
691 $sql .= " rang=".((!empty($this->rang)) ? ((int) $this->rang) : "0").",";
692 $sql .= " priority=".((!empty($this->priority)) ? ((int) $this->priority) : "0").",";
693 $sql .= " billable=".((int) $this->billable).",";
694 $sql .= " fk_statut=".((int) $this->status);
695 $sql .= " WHERE rowid=".((int) $this->id);
696
697 $this->db->begin();
698
699 dol_syslog(get_class($this)."::update", LOG_DEBUG);
700 $resql = $this->db->query($sql);
701 if (!$resql) {
702 $error++;
703 $this->errors[] = "Error ".$this->db->lasterror();
704 }
705
706 // Update extrafield
707 if (!$error) {
708 $result = $this->insertExtraFields();
709 if ($result < 0) {
710 $error++;
711 }
712 }
713
714 if (!$error && getDolGlobalString('PROJECT_CLASSIFY_CLOSED_WHEN_ALL_TASKS_DONE')) {
715 // Close the parent project if it is open (validated) and its tasks are 100% completed
716 $project = new Project($this->db);
717 if ($project->fetch($this->fk_project) > 0) {
718 if ($project->statut == Project::STATUS_VALIDATED) {
719 $project->getLinesArray(null); // this method does not return <= 0 if fails
720 $projectCompleted = array_reduce(
721 $project->lines,
727 static function ($allTasksCompleted, $task) {
728 return $allTasksCompleted && $task->progress >= 100;
729 },
730 1
731 );
732 if ($projectCompleted) {
733 if ($project->setClose($user) <= 0) {
734 $error++;
735 }
736 }
737 }
738 } else {
739 $error++;
740 }
741 if ($error) {
742 $this->errors[] = $project->error;
743 }
744 }
745
746 if (!$error) {
747 if (!$notrigger) {
748 // Call trigger
749 $result = $this->call_trigger('TASK_MODIFY', $user);
750 if ($result < 0) {
751 $error++;
752 }
753 // End call triggers
754 }
755 }
756
757 if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
758 // We remove directory
759 if ($conf->project->dir_output) {
760 $project = new Project($this->db);
761 $project->fetch($this->fk_project);
762
763 $olddir = $conf->project->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->oldcopy->ref);
764 $newdir = $conf->project->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref);
765 if (file_exists($olddir)) {
766 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
767 $res = dol_move_dir($olddir, $newdir);
768 if (!$res) {
769 $langs->load("errors");
770 $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
771 $error++;
772 }
773 }
774 }
775 }
776
777 // Commit or rollback
778 if ($error) {
779 foreach ($this->errors as $errmsg) {
780 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
781 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
782 }
783 $this->db->rollback();
784 return -1 * $error;
785 } else {
786 $this->db->commit();
787 return 1;
788 }
789 }
790
798 public function delete($user, $notrigger = 0)
799 {
800 global $conf;
801 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
802
803 $error = 0;
804
805 $this->db->begin();
806
807 if ($this->hasChildren() > 0) {
808 dol_syslog(get_class($this)."::delete Can't delete record as it has some sub tasks", LOG_WARNING);
809 $this->error = 'ErrorRecordHasSubTasks';
810 $this->db->rollback();
811 return 0;
812 }
813
814 $objectisused = $this->isObjectUsed($this->id);
815 if (!empty($objectisused)) {
816 dol_syslog(get_class($this)."::delete Can't delete record as it has some child", LOG_WARNING);
817 $this->error = 'ErrorRecordHasChildren';
818 $this->db->rollback();
819 return 0;
820 }
821
822 if (!$error) {
823 // Delete linked contacts
824 $res = $this->delete_linked_contact();
825 if ($res < 0) {
826 $this->error = 'ErrorFailToDeleteLinkedContact';
827 //$error++;
828 $this->db->rollback();
829 return 0;
830 }
831 }
832
833 if (!$error) {
834 $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_time";
835 $sql .= " WHERE fk_element = ".((int) $this->id)." AND elementtype = 'task'";
836
837 $resql = $this->db->query($sql);
838 if (!$resql) {
839 $error++;
840 $this->errors[] = "Error ".$this->db->lasterror();
841 }
842 }
843
844 if (!$error) {
845 $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task_extrafields";
846 $sql .= " WHERE fk_object = ".((int) $this->id);
847
848 $resql = $this->db->query($sql);
849 if (!$resql) {
850 $error++;
851 $this->errors[] = "Error ".$this->db->lasterror();
852 }
853 }
854
855 if (!$error) {
856 $sql = "DELETE FROM ".MAIN_DB_PREFIX."projet_task";
857 $sql .= " WHERE rowid=".((int) $this->id);
858
859 $resql = $this->db->query($sql);
860 if (!$resql) {
861 $error++;
862 $this->errors[] = "Error ".$this->db->lasterror();
863 }
864 }
865
866 if (!$error) {
867 if (!$notrigger) {
868 // Call trigger
869 $result = $this->call_trigger('TASK_DELETE', $user);
870 if ($result < 0) {
871 $error++;
872 }
873 // End call triggers
874 }
875 }
876
877 // Commit or rollback
878 if ($error) {
879 foreach ($this->errors as $errmsg) {
880 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
881 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
882 }
883 $this->db->rollback();
884 return -1 * $error;
885 } else {
886 //Delete associated link file
887 if ($conf->project->dir_output) {
888 $projectstatic = new Project($this->db);
889 $projectstatic->fetch($this->fk_project);
890
891 $dir = $conf->project->dir_output."/".dol_sanitizeFileName($projectstatic->ref).'/'.dol_sanitizeFileName((string) $this->id);
892 dol_syslog(get_class($this)."::delete dir=".$dir, LOG_DEBUG);
893 if (file_exists($dir)) {
894 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
895 $res = @dol_delete_dir_recursive($dir);
896 if (!$res) {
897 $this->error = 'ErrorFailToDeleteDir';
898 $this->db->rollback();
899 return 0;
900 }
901 }
902 }
903
904 $this->db->commit();
905
906 return 1;
907 }
908 }
909
915 public function hasChildren()
916 {
917 $error = 0;
918 $ret = 0;
919
920 $sql = "SELECT COUNT(*) as nb";
921 $sql .= " FROM ".MAIN_DB_PREFIX."projet_task";
922 $sql .= " WHERE fk_task_parent = ".((int) $this->id);
923
924 dol_syslog(get_class($this)."::hasChildren", LOG_DEBUG);
925 $resql = $this->db->query($sql);
926 if (!$resql) {
927 $error++;
928 $this->errors[] = "Error ".$this->db->lasterror();
929 } else {
930 $obj = $this->db->fetch_object($resql);
931 if ($obj) {
932 $ret = $obj->nb;
933 }
934 $this->db->free($resql);
935 }
936
937 if (!$error) {
938 return $ret;
939 } else {
940 return -1;
941 }
942 }
943
949 public function hasTimeSpent()
950 {
951 $error = 0;
952 $ret = 0;
953
954 $sql = "SELECT COUNT(*) as nb";
955 $sql .= " FROM ".MAIN_DB_PREFIX."element_time";
956 $sql .= " WHERE fk_element = ".((int) $this->id);
957 $sql .= " AND elementtype = 'task'";
958
959 dol_syslog(get_class($this)."::hasTimeSpent", LOG_DEBUG);
960 $resql = $this->db->query($sql);
961 if (!$resql) {
962 $error++;
963 $this->errors[] = "Error ".$this->db->lasterror();
964 } else {
965 $obj = $this->db->fetch_object($resql);
966 if ($obj) {
967 $ret = $obj->nb;
968 }
969 $this->db->free($resql);
970 }
971
972 if (!$error) {
973 return $ret;
974 } else {
975 return -1;
976 }
977 }
978
979
986 public function getTooltipContentArray($params)
987 {
988 global $langs;
989
990 $langs->load('projects');
991
992 $datas = [];
993 $datas['picto'] = img_picto('', $this->picto).' <u>'.$langs->trans("Task").'</u>';
994 if (!empty($this->ref)) {
995 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
996 }
997 if (!empty($this->label)) {
998 $datas['label'] = '<br><b>'.$langs->trans('LabelTask').':</b> '.$this->label;
999 }
1000 if ($this->date_start || $this->date_end) {
1001 $datas['range'] = "<br>".get_date_range($this->date_start, $this->date_end, '', $langs, 0);
1002 }
1003
1004 return $datas;
1005 }
1006
1019 public function getNomUrl($withpicto = 0, $option = '', $mode = 'task', $addlabel = 0, $sep = ' - ', $notooltip = 0, $save_lastsearch_value = -1)
1020 {
1021 global $action, $conf, $hookmanager, $langs;
1022
1023 if (!empty($conf->dol_no_mouse_hover)) {
1024 $notooltip = 1; // Force disable tooltips
1025 }
1026
1027 $result = '';
1028 $params = [
1029 'id' => $this->id,
1030 'objecttype' => $this->element,
1031 ];
1032 $classfortooltip = 'classfortooltip';
1033 $dataparams = '';
1034 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1035 $classfortooltip = 'classforajaxtooltip';
1036 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1037 $label = '';
1038 } else {
1039 $label = implode($this->getTooltipContentArray($params));
1040 }
1041
1042 $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option == 'withproject' ? '&withproject=1' : '');
1043 // Add param to save lastsearch_values or not
1044 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1045 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1046 $add_save_lastsearch_values = 1;
1047 }
1048 if ($add_save_lastsearch_values) {
1049 $url .= '&save_lastsearch_values=1';
1050 }
1051
1052 $linkclose = '';
1053 if (empty($notooltip)) {
1054 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1055 $label = $langs->trans("ShowTask");
1056 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1057 }
1058 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1059 $linkclose .= $dataparams.' class="'.$classfortooltip.' nowraponall"';
1060 } else {
1061 $linkclose .= ' class="nowraponall"';
1062 }
1063
1064 $linkstart = '<a href="'.$url.'"';
1065 $linkstart .= $linkclose.'>';
1066 $linkend = '</a>';
1067
1068 $picto = 'projecttask';
1069
1070 $result .= $linkstart;
1071 if ($withpicto) {
1072 $result .= img_object(($notooltip ? '' : $label), $picto, 'class="paddingright"', 0, 0, $notooltip ? 0 : 1);
1073 }
1074 if ($withpicto != 2) {
1075 if ($addlabel >= 0) {
1076 $result .= $this->ref;
1077 } else {
1078 $result .= $this->label;
1079 }
1080 }
1081 $result .= $linkend;
1082 if ($withpicto != 2) {
1083 $result .= (($addlabel > 0 && $this->label) ? '<span class="opacitymedium">'.$sep.dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)).'</span>' : '');
1084 }
1085
1086 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1087 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1088 if ($reshook > 0) {
1089 $result = $hookmanager->resPrint;
1090 } else {
1091 $result .= $hookmanager->resPrint;
1092 }
1093
1094 return $result;
1095 }
1096
1104 public function initAsSpecimen()
1105 {
1106 global $user;
1107
1108 $this->id = 0;
1109
1110 $this->fk_project = 0;
1111 $this->ref = 'TK01';
1112 $this->fk_task_parent = 0;
1113 $this->label = 'Specimen task TK01';
1114 $this->duration_effective = '';
1115 $this->fk_user_creat = $user->id;
1116 $this->progress = 25;
1117 $this->status = 0;
1118 $this->priority = 0;
1119 $this->note_private = 'This is a specimen private note';
1120 $this->note_public = 'This is a specimen public note';
1121 $this->billable = 1;
1122
1123 return 1;
1124 }
1125
1149 public function getTasksArray($usert = null, $userp = null, $projectid = 0, $socid = 0, $mode = 0, $filteronproj = '', $filteronprojstatus = '-1', $morewherefilter = '', $filteronprojuser = 0, $filterontaskuser = 0, $extrafields = null, $includebilltime = 0, $search_array_options = array(), $loadextras = 0, $loadRoleMode = 1, $sortfield = '', $sortorder = '')
1150 {
1151 global $hookmanager;
1152
1153 $tasks = array();
1154
1155 //print $usert.'-'.$userp.'-'.$projectid.'-'.$socid.'-'.$mode.'<br>';
1156
1157 // List of tasks (does not care about permissions. Filtering will be done later)
1158 $sql = "SELECT ";
1159 if ($filteronprojuser > 0 || $filterontaskuser > 0) {
1160 $sql .= " DISTINCT"; // We may get several time the same record if user has several roles on same project/task
1161 }
1162 $sql .= " p.rowid as projectid, p.ref, p.title as plabel, p.public, p.fk_statut as projectstatus, p.usage_bill_time,";
1163 $sql .= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,";
1164 $sql .= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang, t.priority,";
1165 $sql .= " t.budget_amount, t.billable,";
1166 $sql .= " t.note_public, t.note_private,";
1167 $sql .= " s.rowid as thirdparty_id, s.nom as thirdparty_name, s.email as thirdparty_email,";
1168 $sql .= " p.fk_opp_status, p.opp_amount, p.opp_percent, p.budget_amount as project_budget_amount";
1169 if ($loadextras) { // TODO Replace this with a fetch_optionnal() on the project after the fetch_object of line.
1170 if (!empty($extrafields->attributes['projet']['label'])) {
1171 foreach ($extrafields->attributes['projet']['label'] as $key => $val) {
1172 $sql .= ($extrafields->attributes['projet']['type'][$key] != 'separate' ? ",efp.".$key." as options_".$key : '');
1173 }
1174 }
1175 if (!empty($extrafields->attributes['projet_task']['label'])) {
1176 foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) {
1177 $sql .= ($extrafields->attributes['projet_task']['type'][$key] != 'separate' ? ",efpt.".$key." as options_".$key : '');
1178 }
1179 }
1180 }
1181 if ($includebilltime) {
1182 $sql .= ", SUM(tt.element_duration * ".$this->db->ifsql("invoice_id IS NULL", "1", "0").") as tobill, SUM(tt.element_duration * ".$this->db->ifsql("invoice_id IS NULL", "0", "1").") as billed";
1183 }
1184
1185 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
1186 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
1187 if ($loadextras) {
1188 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_extrafields as efp ON (p.rowid = efp.fk_object)";
1189 }
1190
1191 if ($mode == 0) {
1192 if ($filteronprojuser > 0) {
1193 $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
1194 $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
1195 }
1196 $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
1197 if ($loadextras) {
1198 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_extrafields as efpt ON (t.rowid = efpt.fk_object)";
1199 }
1200 if ($includebilltime) {
1201 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_time as tt ON (tt.fk_element = t.rowid AND tt.elementtype='task')";
1202 }
1203 if ($filterontaskuser > 0) {
1204 $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec2";
1205 $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
1206 }
1207 $sql .= " WHERE p.entity IN (".getEntity('project').")";
1208 $sql .= " AND t.fk_projet = p.rowid";
1209 } elseif ($mode == 1) {
1210 if ($filteronprojuser > 0) {
1211 $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
1212 $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
1213 }
1214 if ($filterontaskuser > 0) {
1215 $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
1216 if ($includebilltime) {
1217 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_time as tt ON (tt.fk_element = t.rowid AND tt.elementtype='task')";
1218 }
1219 $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec2";
1220 $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc2";
1221 } else {
1222 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid";
1223 if ($includebilltime) {
1224 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_time as tt ON (tt.fk_element = t.rowid AND tt.elementtype = 'task')";
1225 }
1226 }
1227 $sql .= " WHERE p.entity IN (".getEntity('project').")";
1228 } else {
1229 return 'BadValueForParameterMode';
1230 }
1231
1232 if ($filteronprojuser > 0) {
1233 $sql .= " AND p.rowid = ec.element_id";
1234 $sql .= " AND ctc.rowid = ec.fk_c_type_contact";
1235 $sql .= " AND ctc.element = 'project'";
1236 $sql .= " AND ec.fk_socpeople = ".((int) $filteronprojuser);
1237 $sql .= " AND ec.statut = 4";
1238 $sql .= " AND ctc.source = 'internal'";
1239 }
1240 if ($filterontaskuser > 0) {
1241 $sql .= " AND t.fk_projet = p.rowid";
1242 $sql .= " AND p.rowid = ec2.element_id";
1243 $sql .= " AND ctc2.rowid = ec2.fk_c_type_contact";
1244 $sql .= " AND ctc2.element = 'project_task'";
1245 $sql .= " AND ec2.fk_socpeople = ".((int) $filterontaskuser);
1246 $sql .= " AND ec2.statut = 4";
1247 $sql .= " AND ctc2.source = 'internal'";
1248 }
1249 if ($socid) {
1250 $sql .= " AND p.fk_soc = ".((int) $socid);
1251 }
1252 if ($projectid) {
1253 $sql .= " AND p.rowid IN (".$this->db->sanitize((string) $projectid).")";
1254 }
1255 if ($filteronproj) {
1256 $sql .= natural_search(array("p.ref", "p.title"), $filteronproj);
1257 }
1258 if ($filteronprojstatus && (int) $filteronprojstatus != '-1') {
1259 $sql .= " AND p.fk_statut IN (".$this->db->sanitize($filteronprojstatus).")";
1260 }
1261 if ($morewherefilter) {
1262 $sql .= $morewherefilter;
1263 }
1264
1265 // Add where from extra fields
1266 $extrafieldsobjectkey = 'projet_task';
1267 $extrafieldsobjectprefix = 'efpt.';
1268 global $db, $conf; // needed for extrafields_list_search_sql.tpl
1269 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
1270
1271 // Add where from hooks
1272 $parameters = array();
1273 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
1274 $sql .= $hookmanager->resPrint;
1275 if ($includebilltime) {
1276 $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public, p.fk_statut, p.usage_bill_time,";
1277 $sql .= " t.datec, t.dateo, t.datee, t.tms,";
1278 $sql .= " t.rowid, t.ref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut,";
1279 $sql .= " t.dateo, t.datee, t.planned_workload, t.rang, t.priority,";
1280 $sql .= " t.budget_amount, t.billable,";
1281 $sql .= " t.note_public, t.note_private,";
1282 $sql .= " s.rowid, s.nom, s.email,";
1283 $sql .= " p.fk_opp_status, p.opp_amount, p.opp_percent, p.budget_amount";
1284 if ($loadextras) {
1285 if (!empty($extrafields->attributes['projet']['label'])) {
1286 foreach ($extrafields->attributes['projet']['label'] as $key => $val) {
1287 $sql .= ($extrafields->attributes['projet']['type'][$key] != 'separate' ? ",efp.".$key : '');
1288 }
1289 }
1290 if (!empty($extrafields->attributes['projet_task']['label'])) {
1291 foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) {
1292 $sql .= ($extrafields->attributes['projet_task']['type'][$key] != 'separate' ? ",efpt.".$key : '');
1293 }
1294 }
1295 }
1296 }
1297
1298 if ($sortfield && $sortorder) {
1299 $sql .= $this->db->order($sortfield, $sortorder);
1300 } else {
1301 $sql .= " ORDER BY p.ref, t.rang, t.dateo";
1302 }
1303
1304 //print $sql;exit;
1305 dol_syslog(get_class($this)."::getTasksArray", LOG_DEBUG);
1306 $resql = $this->db->query($sql);
1307 if ($resql) {
1308 $num = $this->db->num_rows($resql);
1309 $i = 0;
1310 // Loop on each record found, so each couple (project id, task id)
1311 while ($i < $num) {
1312 $error = 0;
1313
1314 $obj = $this->db->fetch_object($resql);
1315
1316 if ($loadRoleMode) {
1317 if ((!$obj->public) && (is_object($userp))) { // If not public project and we ask a filter on project owned by a user
1318 if (!$this->getUserRolesForProjectsOrTasks($userp, null, $obj->projectid, 0)) {
1319 $error++;
1320 }
1321 }
1322 if (is_object($usert)) { // If we ask a filter on a user affected to a task
1323 if (!$this->getUserRolesForProjectsOrTasks(null, $usert, $obj->projectid, $obj->taskid)) {
1324 $error++;
1325 }
1326 }
1327 }
1328
1329 if (!$error) {
1330 $tasks[$i] = new Task($this->db);
1331 $tasks[$i]->id = $obj->taskid;
1332 $tasks[$i]->ref = $obj->taskref;
1333 $tasks[$i]->fk_project = $obj->projectid;
1334
1335 // Data from project
1336 $tasks[$i]->projectref = $obj->ref;
1337 $tasks[$i]->projectlabel = $obj->plabel;
1338 $tasks[$i]->projectstatus = $obj->projectstatus;
1339 $tasks[$i]->fk_opp_status = $obj->fk_opp_status;
1340 $tasks[$i]->opp_amount = $obj->opp_amount;
1341 $tasks[$i]->opp_percent = $obj->opp_percent;
1342 $tasks[$i]->budget_amount = $obj->budget_amount;
1343 $tasks[$i]->project_budget_amount = $obj->project_budget_amount;
1344 $tasks[$i]->usage_bill_time = $obj->usage_bill_time;
1345
1346 $tasks[$i]->label = $obj->label;
1347 $tasks[$i]->description = $obj->description;
1348
1349 $tasks[$i]->fk_task_parent = $obj->fk_task_parent;
1350 $tasks[$i]->note_public = $obj->note_public;
1351 $tasks[$i]->note_private = $obj->note_private;
1352 $tasks[$i]->duration_effective = $obj->duration_effective;
1353 $tasks[$i]->planned_workload = $obj->planned_workload;
1354
1355 if ($includebilltime) {
1356 // Data summed from element_time linked to task
1357 $tasks[$i]->tobill = $obj->tobill;
1358 $tasks[$i]->billed = $obj->billed;
1359 }
1360
1361 $tasks[$i]->progress = $obj->progress;
1362 $tasks[$i]->fk_statut = $obj->status;
1363 $tasks[$i]->status = $obj->status;
1364 $tasks[$i]->public = $obj->public;
1365 $tasks[$i]->date_start = $this->db->jdate($obj->date_start);
1366 $tasks[$i]->date_end = $this->db->jdate($obj->date_end);
1367 $tasks[$i]->rang = $obj->rang;
1368 $tasks[$i]->priority = $obj->priority;
1369
1370 $tasks[$i]->socid = $obj->thirdparty_id; // For backward compatibility
1371 $tasks[$i]->thirdparty_id = $obj->thirdparty_id;
1372 $tasks[$i]->thirdparty_name = $obj->thirdparty_name;
1373 $tasks[$i]->thirdparty_email = $obj->thirdparty_email;
1374
1375 $tasks[$i]->billable = $obj->billable;
1376
1377 if ($loadextras) {
1378 if (!empty($extrafields->attributes['projet']['label'])) {
1379 foreach ($extrafields->attributes['projet']['label'] as $key => $val) {
1380 if ($extrafields->attributes['projet']['type'][$key] != 'separate') {
1381 $tmpvar = 'options_'.$key;
1382 $tasks[$i]->array_options_project['options_'.$key] = $obj->$tmpvar;
1383 }
1384 }
1385 }
1386 }
1387
1388 if ($loadextras) {
1389 $tasks[$i]->fetch_optionals();
1390 }
1391 }
1392
1393 $i++;
1394 }
1395 $this->db->free($resql);
1396 } else {
1397 dol_print_error($this->db);
1398 }
1399
1400 return $tasks;
1401 }
1402
1413 public function getUserRolesForProjectsOrTasks($userp, $usert, $projectid = '', $taskid = 0, $filteronprojstatus = -1)
1414 {
1415 $arrayroles = array();
1416
1417 dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks userp=".json_encode(is_object($userp))." usert=".json_encode(is_object($usert))." projectid=".$projectid." taskid=".$taskid);
1418
1419 // We want role of user for a projet or role of user for a task. Both are not possible.
1420 if (empty($userp) && empty($usert)) {
1421 $this->error = "CallWithWrongParameters";
1422 return -1;
1423 }
1424 if (!empty($userp) && !empty($usert)) {
1425 $this->error = "CallWithWrongParameters";
1426 return -1;
1427 }
1428
1429 /* Liste des taches et role sur les projects ou taches */
1430 $sql = "SELECT ";
1431 if ($userp) {
1432 $sql .= " p.rowid as pid,";
1433 } else {
1434 $sql .= " pt.rowid as pid,";
1435 }
1436 $sql .= " ec.element_id, ctc.code, ctc.source";
1437 if ($userp) {
1438 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
1439 }
1440 if ($usert && $filteronprojstatus > -1) {
1441 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p, ".MAIN_DB_PREFIX."projet_task as pt";
1442 }
1443 if ($usert && $filteronprojstatus <= -1) {
1444 $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as pt";
1445 }
1446 $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
1447 $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
1448 if ($userp) {
1449 $sql .= " WHERE p.rowid = ec.element_id";
1450 } else {
1451 $sql .= " WHERE pt.rowid = ec.element_id";
1452 }
1453 if ($userp && $filteronprojstatus > -1) {
1454 $sql .= " AND p.fk_statut = ".((int) $filteronprojstatus);
1455 }
1456 if ($usert && $filteronprojstatus > -1) {
1457 $sql .= " AND pt.fk_projet = p.rowid AND p.fk_statut = ".((int) $filteronprojstatus);
1458 }
1459 if ($userp) {
1460 $sql .= " AND ctc.element = 'project'";
1461 }
1462 if ($usert) {
1463 $sql .= " AND ctc.element = 'project_task'";
1464 }
1465 $sql .= " AND ctc.rowid = ec.fk_c_type_contact";
1466 if ($userp) {
1467 $sql .= " AND ec.fk_socpeople = ".((int) $userp->id);
1468 }
1469 if ($usert) {
1470 $sql .= " AND ec.fk_socpeople = ".((int) $usert->id);
1471 }
1472 $sql .= " AND ec.statut = 4";
1473 $sql .= " AND ctc.source = 'internal'";
1474 if ($projectid) {
1475 if ($userp) {
1476 $sql .= " AND p.rowid IN (".$this->db->sanitize($projectid).")";
1477 }
1478 if ($usert) {
1479 $sql .= " AND pt.fk_projet IN (".$this->db->sanitize($projectid).")";
1480 }
1481 }
1482 if ($taskid) {
1483 if ($userp) {
1484 $sql .= " ERROR SHOULD NOT HAPPENS";
1485 }
1486 if ($usert) {
1487 $sql .= " AND pt.rowid = ".((int) $taskid);
1488 }
1489 }
1490 //print $sql;
1491
1492 dol_syslog(get_class($this)."::getUserRolesForProjectsOrTasks execute request", LOG_DEBUG);
1493 $resql = $this->db->query($sql);
1494 if ($resql) {
1495 $num = $this->db->num_rows($resql);
1496 $i = 0;
1497 while ($i < $num) {
1498 $obj = $this->db->fetch_object($resql);
1499 if (empty($arrayroles[$obj->pid])) {
1500 $arrayroles[$obj->pid] = $obj->code;
1501 } else {
1502 $arrayroles[$obj->pid] .= ','.$obj->code;
1503 }
1504 $i++;
1505 }
1506 $this->db->free($resql);
1507 } else {
1508 dol_print_error($this->db);
1509 }
1510
1511 return $arrayroles;
1512 }
1513
1514
1521 public function getListContactId($source = 'internal')
1522 {
1523 $contactAlreadySelected = array();
1524 $tab = $this->liste_contact(-1, $source);
1525 //var_dump($tab);
1526 $num = count($tab);
1527 $i = 0;
1528 while ($i < $num) {
1529 if ($source == 'thirdparty') {
1530 $contactAlreadySelected[$i] = $tab[$i]['socid'];
1531 } else {
1532 $contactAlreadySelected[$i] = $tab[$i]['id'];
1533 }
1534 $i++;
1535 }
1536 return $contactAlreadySelected;
1537 }
1538
1546 public function mergeContactTask($origin_id, $dest_id)
1547 {
1548 $error = 0;
1549 $origintask = new Task($this->db);
1550 $result = $origintask->fetch($origin_id);
1551 if ($result <= 0) {
1552 return false;
1553 }
1554
1555 //Get list of origin contacts
1556 $arraycontactorigin = array_merge($origintask->liste_contact(-1, 'internal'), $origintask->liste_contact(-1, 'external'));
1557 if (is_array($arraycontactorigin)) {
1558 foreach ($arraycontactorigin as $key => $contact) {
1559 $result = $this->add_contact($contact["id"], $contact["fk_c_type_contact"], $contact["source"]);
1560 if ($result < 0) {
1561 return false;
1562 }
1563 }
1564 }
1565 return true;
1566 }
1567
1575 public function mergeTimeSpentTask($origin_id, $dest_id)
1576 {
1577 $ret = true;
1578
1579 $this->db->begin();
1580
1581 $sql = "UPDATE ".MAIN_DB_PREFIX."element_time as et";
1582 $sql .= " SET et.fk_element = ".((int) $dest_id);
1583 $sql .= " WHERE et.elementtype = 'task'";
1584 $sql .= " AND et.fk_element = ".((int) $origin_id);
1585
1586 dol_syslog(get_class($this)."::mergeTimeSpentTask", LOG_DEBUG);
1587 if (!$this->db->query($sql)) {
1588 $this->error = $this->db->lasterror();
1589 $ret = false;
1590 }
1591
1592 if ($ret) {
1593 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
1594 $sql .= " SET duration_effective = (SELECT SUM(element_duration) FROM ".MAIN_DB_PREFIX."element_time as ptt where ptt.elementtype = 'task' AND ptt.fk_element = ".((int) $dest_id).")";
1595 $sql .= " WHERE rowid = ".((int) $dest_id);
1596
1597 dol_syslog(get_class($this)."::mergeTimeSpentTask update project_task", LOG_DEBUG);
1598 if (!$this->db->query($sql)) {
1599 $this->error = $this->db->lasterror();
1600 $ret = false;
1601 }
1602 }
1603
1604 if ($ret) {
1605 $this->db->commit();
1606 } else {
1607 $this->db->rollback();
1608 }
1609 return $ret;
1610 }
1611
1619 public function addTimeSpent($user, $notrigger = 0)
1620 {
1621 global $langs;
1622
1623 dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
1624
1625 $ret = 0;
1626 $now = dol_now();
1627
1628 // Check parameters
1629 if (!is_object($user)) {
1630 dol_print_error(null, "Method addTimeSpent was called with wrong parameter user");
1631 return -1;
1632 }
1633
1634 // Clean parameters
1635 if (isset($this->timespent_note)) {
1636 $this->timespent_note = trim($this->timespent_note);
1637 }
1638 if (empty($this->timespent_datehour) || empty($this->timespent_withhour)) {
1639 // Sync datehour from the day-level date when no start hour was provided (withhour = 0), or when
1640 // datehour is empty. When a start hour was entered (withhour = 1), keep datehour untouched so the
1641 // hour is not discarded (#39276). This still resynchronizes datehour when only the day changes.
1642 $this->timespent_datehour = $this->timespent_date;
1643 }
1644
1645 if (getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS')) {
1646 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
1647 $restrictBefore = dol_time_plus_duree(dol_now(), - getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'), 'm');
1648
1649 if ($this->timespent_date < $restrictBefore) {
1650 $this->error = $langs->trans('TimeRecordingRestrictedToNMonthsBack', getDolGlobalString('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'));
1651 $this->errors[] = $this->error;
1652 return -1;
1653 }
1654 }
1655
1656 $this->db->begin();
1657
1658 $timespent = new TimeSpent($this->db);
1659 $timespent->fk_element = $this->id;
1660 $timespent->elementtype = 'task';
1661 $timespent->element_date = $this->timespent_date;
1662 $timespent->element_datehour = $this->timespent_datehour;
1663 $timespent->element_date_withhour = $this->timespent_withhour;
1664 $timespent->element_duration = $this->timespent_duration;
1665 $timespent->fk_user = $this->timespent_fk_user;
1666 $timespent->fk_product = $this->timespent_fk_product;
1667 $timespent->note = $this->timespent_note;
1668 $timespent->datec = $now;
1669
1670 $result = $timespent->create($user);
1671 if ($result > 0) {
1672 $ret = $result;
1673 $this->timespent_id = $result;
1674
1675 if (!$notrigger) {
1676 // Call trigger
1677 $result = $this->call_trigger('TASK_TIMESPENT_CREATE', $user);
1678 if ($result < 0) {
1679 $ret = -1;
1680 }
1681 // End call triggers
1682 }
1683 } else {
1684 $this->error = $this->db->lasterror();
1685 $ret = -1;
1686 }
1687
1688 // Propagate trigger handler messages from $this->errors (plural array)
1689 // to $this->error (singular string) so callers like the REST API can
1690 // surface a useful message instead of an empty error tail.
1691 if ($ret <= 0 && empty($this->error) && !empty($this->errors)) {
1692 foreach ($this->errors as $errmsg) {
1693 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
1694 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1695 }
1696 }
1697
1698 if ($ret > 0) {
1699 // Recalculate amount of time spent for task and update denormalized field
1700 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
1701 $sql .= " SET duration_effective = (SELECT SUM(element_duration) FROM ".MAIN_DB_PREFIX."element_time as ptt where ptt.elementtype = 'task' AND ptt.fk_element = ".((int) $this->id).")";
1702 if (isset($this->progress)) {
1703 $sql .= ", progress = ".((float) $this->progress); // Do not overwrite value if not provided
1704 if ($this->progress == 100) {
1705 $this->status = Task::STATUS_CLOSED;
1706 } elseif ($this->progress != 0) {
1708 } else {
1710 }
1711 $sql .= ", fk_statut = ".((int) $this->status);
1712 } else {
1714 $sql .= ", fk_statut = ".((int) $this->status);
1715 }
1716 $sql .= " WHERE rowid = ".((int) $this->id);
1717
1718 dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
1719 if (!$this->db->query($sql)) {
1720 $this->error = $this->db->lasterror();
1721 $ret = -2;
1722 }
1723
1724 // Update hourly rate of this time spent entry
1725 $resql_thm_user = $this->db->query("SELECT thm FROM " . MAIN_DB_PREFIX . "user WHERE rowid = " . ((int) $timespent->fk_user));
1726 if (!empty($resql_thm_user)) {
1727 $obj_thm_user = $this->db->fetch_object($resql_thm_user);
1728 $timespent->thm = $obj_thm_user->thm;
1729 }
1730 $res_update = $timespent->update($user);
1731
1732 dol_syslog(get_class($this)."::addTimeSpent", LOG_DEBUG);
1733 if ($res_update <= 0) {
1734 $this->error = $this->db->lasterror();
1735 $ret = -2;
1736 }
1737 }
1738
1739 if ($ret > 0) {
1740 $this->db->commit();
1741 } else {
1742 $this->db->rollback();
1743 }
1744 return $ret;
1745 }
1746
1753 public function fetchTimeSpentOnTask($morewherefilter = '')
1754 {
1755 $arrayres = array();
1756
1757 $sql = "SELECT";
1758 $sql .= " s.rowid as socid,";
1759 $sql .= " s.nom as thirdparty_name,";
1760 $sql .= " s.email as thirdparty_email,";
1761 $sql .= " ptt.rowid,";
1762 $sql .= " ptt.ref_ext,";
1763 $sql .= " ptt.fk_element as fk_task,";
1764 $sql .= " ptt.element_date as task_date,";
1765 $sql .= " ptt.element_datehour as task_datehour,";
1766 $sql .= " ptt.element_date_withhour as task_date_withhour,";
1767 $sql .= " ptt.element_duration as task_duration,";
1768 $sql .= " ptt.fk_user,";
1769 $sql .= " ptt.fk_product,";
1770 $sql .= " ptt.note,";
1771 $sql .= " ptt.thm,";
1772 $sql .= " pt.rowid as task_id,";
1773 $sql .= " pt.ref as task_ref,";
1774 $sql .= " pt.label as task_label,";
1775 $sql .= " p.rowid as project_id,";
1776 $sql .= " p.ref as project_ref,";
1777 $sql .= " p.title as project_label,";
1778 $sql .= " p.public as project_public";
1779 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as ptt, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet as p";
1780 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
1781 $sql .= " WHERE ptt.fk_element = pt.rowid AND pt.fk_projet = p.rowid";
1782 $sql .= " AND ptt.elementtype = 'task'";
1783 $sql .= " AND pt.rowid = ".((int) $this->id);
1784 $sql .= " AND pt.entity IN (".getEntity('project').")";
1785 if ($morewherefilter) {
1786 $sql .= $morewherefilter;
1787 }
1788
1789 dol_syslog(get_class($this)."::fetchAllTimeSpent", LOG_DEBUG);
1790 $resql = $this->db->query($sql);
1791 if ($resql) {
1792 $num = $this->db->num_rows($resql);
1793
1794 $i = 0;
1795 while ($i < $num) {
1796 $obj = $this->db->fetch_object($resql);
1797
1798 $newobj = new stdClass();
1799
1800 $newobj->socid = $obj->socid;
1801 $newobj->thirdparty_name = $obj->thirdparty_name;
1802 $newobj->thirdparty_email = $obj->thirdparty_email;
1803
1804 $newobj->fk_project = $obj->project_id;
1805 $newobj->project_ref = $obj->project_ref;
1806 $newobj->project_label = $obj->project_label;
1807 $newobj->project_public = $obj->project_public;
1808 $newobj->public = $obj->project_public; // deprecated
1809
1810 $newobj->fk_task = $obj->task_id;
1811 $newobj->task_ref = $obj->task_ref;
1812 $newobj->task_label = $obj->task_label;
1813
1814 $newobj->timespent_line_id = $obj->rowid;
1815 $newobj->timespent_line_ref_ext = $obj->ref_ext;
1816 $newobj->timespent_line_date = $this->db->jdate($obj->task_date);
1817 $newobj->timespent_line_datehour = $this->db->jdate($obj->task_datehour);
1818 $newobj->timespent_line_withhour = $obj->task_date_withhour;
1819 $newobj->timespent_line_duration = $obj->task_duration;
1820 $newobj->timespent_line_fk_user = $obj->fk_user;
1821 $newobj->timespent_line_fk_product = $obj->fk_product;
1822 $newobj->timespent_line_thm = $obj->thm; // hourly rate
1823 $newobj->timespent_line_note = $obj->note;
1824
1825 $arrayres[] = $newobj;
1826
1827 $i++;
1828 }
1829
1830 $this->db->free($resql);
1831
1832 $this->lines = $arrayres;
1833 return 1;
1834 } else {
1835 dol_print_error($this->db);
1836 $this->error = "Error ".$this->db->lasterror();
1837 return -1;
1838 }
1839 }
1840
1841
1849 public function getSummaryOfTimeSpent($userobj = null, $morewherefilter = '')
1850 {
1851 if (is_object($userobj)) {
1852 $userid = $userobj->id;
1853 } else {
1854 $userid = $userobj; // old method
1855 }
1856
1857 $id = $this->id;
1858 if (empty($id) && empty($userid)) {
1859 dol_syslog("getSummaryOfTimeSpent called on a not loaded task without user param defined", LOG_ERR);
1860 return -1;
1861 }
1862
1863 $result = array();
1864
1865 $sql = "SELECT";
1866 $sql .= " MIN(t.element_datehour) as min_date,";
1867 $sql .= " MAX(t.element_datehour) as max_date,";
1868 $sql .= " SUM(t.element_duration) as total_duration,";
1869 $sql .= " SUM(t.element_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", '0', "t.thm").") as total_amount,";
1870 $sql .= " COUNT(t.rowid) as nblines,";
1871 $sql .= " SUM(".$this->db->ifsql("t.thm IS NULL", '1', '0').") as nblinesnull";
1872 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as t";
1873 $sql .= " WHERE t.elementtype='task'";
1874 if ($morewherefilter) {
1875 $sql .= $morewherefilter;
1876 }
1877 if ($id > 0) {
1878 $sql .= " AND t.fk_element = ".((int) $id);
1879 }
1880 if ($userid > 0) {
1881 $sql .= " AND t.fk_user = ".((int) $userid);
1882 }
1883
1884 dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG);
1885 $resql = $this->db->query($sql);
1886 if ($resql) {
1887 $obj = $this->db->fetch_object($resql);
1888
1889 $result['min_date'] = $obj->min_date; // deprecated. use the ->timespent_xxx instead
1890 $result['max_date'] = $obj->max_date; // deprecated. use the ->timespent_xxx instead
1891 $result['total_duration'] = $obj->total_duration; // deprecated. use the ->timespent_xxx instead
1892
1893 $this->timespent_min_date = $this->db->jdate($obj->min_date);
1894 $this->timespent_max_date = $this->db->jdate($obj->max_date);
1895 $this->timespent_total_duration = $obj->total_duration;
1896 $this->timespent_total_amount = $obj->total_amount;
1897 $this->timespent_nblinesnull = ($obj->nblinesnull ? $obj->nblinesnull : 0);
1898 $this->timespent_nblines = ($obj->nblines ? $obj->nblines : 0);
1899
1900 $this->db->free($resql);
1901 } else {
1902 dol_print_error($this->db);
1903 }
1904 return $result;
1905 }
1906
1915 public function getSumOfAmount($fuser = '', $dates = '', $datee = '')
1916 {
1917 $id = $this->id;
1918
1919 $result = array();
1920
1921 $sql = "SELECT";
1922 $sql .= " SUM(t.element_duration) as nbseconds,";
1923 $sql .= " SUM(t.element_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", '0', "t.thm").") as amount, SUM(".$this->db->ifsql("t.thm IS NULL", '1', '0').") as nblinesnull";
1924 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as t";
1925 $sql .= " WHERE t.elementtype='task' AND t.fk_element = ".((int) $id);
1926 if (is_object($fuser) && $fuser->id > 0) {
1927 $sql .= " AND fk_user = ".((int) $fuser->id);
1928 }
1929 if ($dates > 0) {
1930 $datefieldname = "element_datehour";
1931 $sql .= " AND (".$datefieldname." >= '".$this->db->idate((int) $dates)."' OR ".$datefieldname." IS NULL)";
1932 }
1933 if ($datee > 0) {
1934 $datefieldname = "element_datehour";
1935 $sql .= " AND (".$datefieldname." <= '".$this->db->idate((int) $datee)."' OR ".$datefieldname." IS NULL)";
1936 }
1937 //print $sql;
1938
1939 dol_syslog(get_class($this)."::getSumOfAmount", LOG_DEBUG);
1940 $resql = $this->db->query($sql);
1941 if ($resql) {
1942 $obj = $this->db->fetch_object($resql);
1943
1944 $result['amount'] = $obj->amount;
1945 $result['nbseconds'] = $obj->nbseconds;
1946 $result['nblinesnull'] = $obj->nblinesnull;
1947
1948 $this->db->free($resql);
1949 return $result;
1950 } else {
1951 dol_print_error($this->db);
1952 return $result;
1953 }
1954 }
1955
1962 public function fetchTimeSpent($id)
1963 {
1964 $timespent = new TimeSpent($this->db);
1965 $timespent->fetch($id);
1966
1967 dol_syslog(get_class($this)."::fetchTimeSpent", LOG_DEBUG);
1968
1969 if ($timespent->id > 0) {
1970 $this->timespent_id = $timespent->id;
1971 $this->id = $timespent->fk_element;
1972 $this->timespent_date = $timespent->element_date;
1973 $this->timespent_datehour = $timespent->element_datehour;
1974 $this->timespent_withhour = $timespent->element_date_withhour;
1975 $this->timespent_duration = $timespent->element_duration;
1976 $this->timespent_fk_user = $timespent->fk_user;
1977 $this->timespent_fk_product = $timespent->fk_product;
1978 $this->timespent_thm = $timespent->thm; // hourly rate
1979 $this->timespent_note = $timespent->note;
1980
1981 return 1;
1982 }
1983
1984 return 0;
1985 }
1986
1994 public function fetchAllTimeSpent(User $userobj, $morewherefilter = '')
1995 {
1996 $arrayres = array();
1997
1998 $sql = "SELECT";
1999 $sql .= " s.rowid as socid,";
2000 $sql .= " s.nom as thirdparty_name,";
2001 $sql .= " s.email as thirdparty_email,";
2002 $sql .= " ptt.rowid,";
2003 $sql .= " ptt.fk_element as fk_task,";
2004 $sql .= " ptt.element_date as task_date,";
2005 $sql .= " ptt.element_datehour as task_datehour,";
2006 $sql .= " ptt.element_date_withhour as task_date_withhour,";
2007 $sql .= " ptt.element_duration as task_duration,";
2008 $sql .= " ptt.fk_user,";
2009 $sql .= " ptt.note,";
2010 $sql .= " ptt.thm,";
2011 $sql .= " pt.rowid as task_id,";
2012 $sql .= " pt.ref as task_ref,";
2013 $sql .= " pt.label as task_label,";
2014 $sql .= " p.rowid as project_id,";
2015 $sql .= " p.ref as project_ref,";
2016 $sql .= " p.title as project_label,";
2017 $sql .= " p.public as project_public";
2018 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as ptt, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet as p";
2019 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
2020 $sql .= " WHERE ptt.fk_element = pt.rowid AND pt.fk_projet = p.rowid";
2021 $sql .= " AND ptt.elementtype = 'task'";
2022 $sql .= " AND ptt.fk_user = ".((int) $userobj->id);
2023 $sql .= " AND pt.entity IN (".getEntity('project').")";
2024 if ($morewherefilter) {
2025 $sql .= $morewherefilter;
2026 }
2027
2028 dol_syslog(get_class($this)."::fetchAllTimeSpent", LOG_DEBUG);
2029 $resql = $this->db->query($sql);
2030 if ($resql) {
2031 $num = $this->db->num_rows($resql);
2032
2033 $i = 0;
2034 while ($i < $num) {
2035 $obj = $this->db->fetch_object($resql);
2036
2037 $newobj = new stdClass();
2038
2039 $newobj->socid = $obj->socid;
2040 $newobj->thirdparty_name = $obj->thirdparty_name;
2041 $newobj->thirdparty_email = $obj->thirdparty_email;
2042
2043 $newobj->fk_project = $obj->project_id;
2044 $newobj->project_ref = $obj->project_ref;
2045 $newobj->project_label = $obj->project_label;
2046 $newobj->project_public = $obj->project_public;
2047 $newobj->public = $obj->project_public; // deprecated
2048
2049 $newobj->fk_task = $obj->task_id;
2050 $newobj->task_ref = $obj->task_ref;
2051 $newobj->task_label = $obj->task_label;
2052
2053 $newobj->timespent_id = $obj->rowid;
2054 $newobj->timespent_date = $this->db->jdate($obj->task_date);
2055 $newobj->timespent_datehour = $this->db->jdate($obj->task_datehour);
2056 $newobj->timespent_withhour = $obj->task_date_withhour;
2057 $newobj->timespent_duration = $obj->task_duration;
2058 $newobj->timespent_fk_user = $obj->fk_user;
2059 $newobj->timespent_thm = $obj->thm; // hourly rate
2060 $newobj->timespent_note = $obj->note;
2061
2062 $arrayres[] = $newobj;
2063
2064 $i++;
2065 }
2066
2067 $this->db->free($resql);
2068 } else {
2069 dol_print_error($this->db);
2070 $this->error = "Error ".$this->db->lasterror();
2071 return -1;
2072 }
2073
2074 return $arrayres;
2075 }
2076
2084 public function updateTimeSpent($user, $notrigger = 0)
2085 {
2086 global $conf, $langs;
2087
2088 $ret = 0;
2089
2090 // Check parameters
2091 if ($this->timespent_date == '') {
2092 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Date"));
2093 return -1;
2094 }
2095
2096 // Clean parameters
2097 if (empty($this->timespent_datehour) || empty($this->timespent_withhour)) {
2098 // Sync datehour from the day-level date when no start hour was provided (withhour = 0), or when
2099 // datehour is empty. When a start hour was entered (withhour = 1), keep datehour untouched so the
2100 // hour is not discarded (#39276). This still resynchronizes datehour when only the day changes.
2101 $this->timespent_datehour = $this->timespent_date;
2102 }
2103 if (isset($this->timespent_note)) {
2104 $this->timespent_note = trim($this->timespent_note);
2105 }
2106
2107 if (getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS')) {
2108 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2109 $restrictBefore = dol_time_plus_duree(dol_now(), - getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'), 'm');
2110
2111 if ($this->timespent_date < $restrictBefore) {
2112 $this->error = $langs->trans('TimeRecordingRestrictedToNMonthsBack', getDolGlobalString('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'));
2113 $this->errors[] = $this->error;
2114 return -1;
2115 }
2116 }
2117
2118 $this->db->begin();
2119
2120 $timespent = new TimeSpent($this->db);
2121 $timespent->fetch($this->timespent_id);
2122 $old_fk_element = $timespent->fk_element; // Store old task ID before potential change
2123
2124 $timespent->element_date = $this->timespent_date;
2125 $timespent->element_datehour = $this->timespent_datehour;
2126 $timespent->element_date_withhour = $this->timespent_withhour;
2127 $timespent->element_duration = $this->timespent_duration;
2128 if ($this->timespent_fk_user > 0) {
2129 $timespent->fk_user = $this->timespent_fk_user;
2130 }
2131 $timespent->fk_product = $this->timespent_fk_product;
2132 $timespent->fk_element = $this->id; // Update task assignment (may be changed)
2133 $timespent->note = $this->timespent_note;
2134 $timespent->invoice_id = $this->timespent_invoiceid;
2135 $timespent->invoice_line_id = $this->timespent_invoicelineid;
2136
2137 dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
2138 if ($timespent->update($user) > 0) {
2139 if (!$notrigger) {
2140 // Call trigger
2141 $result = $this->call_trigger('TASK_TIMESPENT_MODIFY', $user);
2142 if ($result < 0) {
2143 $this->db->rollback();
2144 $ret = -1;
2145 } else {
2146 $ret = 1;
2147 }
2148 // End call triggers
2149 } else {
2150 $ret = 1;
2151 }
2152 } else {
2153 $this->error = $this->db->lasterror();
2154 $this->db->rollback();
2155 $ret = -1;
2156 }
2157
2158 // Propagate trigger handler messages from $this->errors (plural array)
2159 // to $this->error (singular string) so callers like the REST API can
2160 // surface a useful message instead of an empty error tail.
2161 if ($ret < 0 && empty($this->error) && !empty($this->errors)) {
2162 foreach ($this->errors as $errmsg) {
2163 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2164 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2165 }
2166 }
2167
2168 if ($ret == 1 && (($this->timespent_old_duration != $this->timespent_duration) || getDolGlobalString('TIMESPENT_ALWAYS_UPDATE_THM'))) {
2169 if ($this->timespent_old_duration != $this->timespent_duration) {
2170 // Recalculate amount of time spent for task and update denormalized field
2171 $sql = "UPDATE " . MAIN_DB_PREFIX . "projet_task";
2172 $sql .= " SET duration_effective = (SELECT SUM(element_duration) FROM " . MAIN_DB_PREFIX . "element_time as ptt where ptt.elementtype = 'task' AND ptt.fk_element = " . ((int) $this->id) . ")";
2173 if (isset($this->progress)) {
2174 $sql .= ", progress = " . ((float) $this->progress); // Do not overwrite value if not provided
2175 }
2176 $sql .= " WHERE rowid = " . ((int) $this->id);
2177
2178 dol_syslog(get_class($this) . "::updateTimeSpent", LOG_DEBUG);
2179 if (!$this->db->query($sql)) {
2180 $this->error = $this->db->lasterror();
2181 $this->db->rollback();
2182 $ret = -2;
2183 }
2184 }
2185
2186 // Update hourly rate of this time spent entry, but only if it was not set initially
2187 $res_update = 1;
2188 if (empty($timespent->thm) || getDolGlobalString('TIMESPENT_ALWAYS_UPDATE_THM')) {
2189 $resql_thm_user = $this->db->query("SELECT thm FROM " . MAIN_DB_PREFIX . "user WHERE rowid = " . ((int) $timespent->fk_user));
2190 if (!empty($resql_thm_user)) {
2191 $obj_thm_user = $this->db->fetch_object($resql_thm_user);
2192 $timespent->thm = $obj_thm_user->thm;
2193 }
2194 $res_update = $timespent->update($user);
2195 }
2196
2197 dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
2198 if ($res_update <= 0) {
2199 $this->error = $this->db->lasterror();
2200 $ret = -2;
2201 }
2202 }
2203
2204 // If task assignment changed, recalculate duration_effective for both old and new tasks
2205 if ($ret == 1 && $old_fk_element != $this->id) {
2206 // Recalculate duration_effective for the OLD task
2207 $sql = "UPDATE " . MAIN_DB_PREFIX . "projet_task";
2208 $sql .= " SET duration_effective = (SELECT COALESCE(SUM(element_duration), 0) FROM " . MAIN_DB_PREFIX . "element_time as ptt where ptt.elementtype = 'task' AND ptt.fk_element = " . ((int) $old_fk_element) . ")";
2209 $sql .= " WHERE rowid = " . ((int) $old_fk_element);
2210 dol_syslog(get_class($this) . "::updateTimeSpent update old task", LOG_DEBUG);
2211 if (!$this->db->query($sql)) {
2212 $this->error = $this->db->lasterror();
2213 $this->db->rollback();
2214 $ret = -2;
2215 }
2216 // Recalculate duration_effective for the NEW task
2217 if ($ret == 1) {
2218 $sql = "UPDATE " . MAIN_DB_PREFIX . "projet_task";
2219 $sql .= " SET duration_effective = (SELECT COALESCE(SUM(element_duration), 0) FROM " . MAIN_DB_PREFIX . "element_time as ptt where ptt.elementtype = 'task' AND ptt.fk_element = " . ((int) $this->id) . ")";
2220 $sql .= " WHERE rowid = " . ((int) $this->id);
2221 dol_syslog(get_class($this) . "::updateTimeSpent update new task", LOG_DEBUG);
2222 if (!$this->db->query($sql)) {
2223 $this->error = $this->db->lasterror();
2224 $this->db->rollback();
2225 $ret = -2;
2226 }
2227 }
2228 }
2229
2230 if ($ret >= 0) {
2231 $this->db->commit();
2232 }
2233 return $ret;
2234 }
2235
2243 public function delTimeSpent($user, $notrigger = 0)
2244 {
2245 global $conf, $langs;
2246
2247 $error = 0;
2248
2249 if (getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS')) {
2250 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2251 $restrictBefore = dol_time_plus_duree(dol_now(), - getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'), 'm');
2252
2253 if ($this->timespent_date < $restrictBefore) {
2254 $this->error = $langs->trans('TimeRecordingRestrictedToNMonthsBack', getDolGlobalString('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'));
2255 $this->errors[] = $this->error;
2256 return -1;
2257 }
2258 }
2259
2260 $this->db->begin();
2261
2262 if (!$notrigger) {
2263 // Call trigger
2264 $result = $this->call_trigger('TASK_TIMESPENT_DELETE', $user);
2265 if ($result < 0) {
2266 $error++;
2267 }
2268 // End call triggers
2269 }
2270
2271 if (!$error) {
2272 $timespent = new TimeSpent($this->db);
2273 $timespent->fetch($this->timespent_id);
2274
2275 $res_del = $timespent->delete($user);
2276
2277 if ($res_del < 0) {
2278 $error++;
2279 $this->errors[] = "Error ".$this->db->lasterror();
2280 }
2281 }
2282
2283 if (!$error) {
2284 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
2285 $sql .= " SET duration_effective = duration_effective - ".((int) $this->timespent_duration);
2286 $sql .= " WHERE rowid = ".((int) $this->id);
2287
2288 dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
2289 if ($this->db->query($sql)) {
2290 $result = 0;
2291 } else {
2292 $this->error = $this->db->lasterror();
2293 $result = -2;
2294 }
2295 }
2296
2297 // Commit or rollback
2298 if ($error) {
2299 foreach ($this->errors as $errmsg) {
2300 dol_syslog(get_class($this)."::delTimeSpent ".$errmsg, LOG_ERR);
2301 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2302 }
2303 $this->db->rollback();
2304 return -1 * $error;
2305 } else {
2306 $this->db->commit();
2307 return 1;
2308 }
2309 }
2310
2325 public function createFromClone(User $user, $fromid, $project_id, $parent_task_id, $clone_change_dt = false, $clone_affectation = false, $clone_time = false, $clone_file = false, $clone_note = false, $clone_prog = false)
2326 {
2327 global $langs, $conf;
2328
2329 $error = 0;
2330
2331 //Use 00:00 of today if time is use on task.
2332 $now = dol_mktime(0, 0, 0, (int) dol_print_date(dol_now(), '%m'), (int) dol_print_date(dol_now(), '%d'), (int) dol_print_date(dol_now(), '%Y'));
2333
2334 $datec = $now;
2335
2336 $clone_task = new Task($this->db);
2337 $origin_task = new Task($this->db);
2338
2339 $clone_task->context['createfromclone'] = 'createfromclone';
2340
2341 $this->db->begin();
2342
2343 // Load source object
2344 $clone_task->fetch($fromid);
2345 $clone_task->fetch_optionals();
2346 //var_dump($clone_task->array_options);exit;
2347
2348 $origin_task->fetch($fromid);
2349
2350 $clone_task->date_c = $datec; // Set the new creation date before computing the ref, else the numbering mask uses the source task year
2351
2352 $defaultref = '';
2353 $obj = !getDolGlobalString('PROJECT_TASK_ADDON') ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
2354 if (getDolGlobalString('PROJECT_TASK_ADDON') && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON').".php")) {
2355 require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON').'.php';
2356 $modTask = new $obj();
2357 '@phan-var-force ModeleNumRefTask $modTask';
2358 $defaultref = $modTask->getNextValue(null, $clone_task);
2359 }
2360
2361 $ori_project_id = $clone_task->fk_project;
2362
2363 $clone_task->id = 0;
2364 $clone_task->ref = $defaultref;
2365 $clone_task->fk_project = $project_id;
2366 $clone_task->fk_task_parent = $parent_task_id;
2367 $clone_task->planned_workload = $origin_task->planned_workload;
2368 $clone_task->rang = $origin_task->rang;
2369 $clone_task->priority = $origin_task->priority;
2370
2371 //Manage Task Date
2372 if ($clone_change_dt) {
2373 $projectstatic = new Project($this->db);
2374 $projectstatic->fetch($ori_project_id);
2375
2376 // Origin project start date
2377 $orign_project_dt_start = (!isset($projectstatic->date_start) || $projectstatic->date_start == '') ? $projectstatic->date_c : $projectstatic->date_start;
2378
2379 // Calculate new task start date with difference between origin proj start date and origin task start date
2380 if (!empty($clone_task->date_start)) {
2381 $clone_task->date_start = $now + $clone_task->date_start - $orign_project_dt_start;
2382 }
2383
2384 // Calculate new task end date with difference between origin proj start date and origin task end date
2385 if (!empty($clone_task->date_end)) {
2386 $clone_task->date_end = $now + $clone_task->date_end - $orign_project_dt_start;
2387 }
2388 }
2389
2390 if (!$clone_prog) {
2391 $clone_task->progress = 0;
2392 }
2393
2394 // Create clone
2395 $result = $clone_task->create($user);
2396
2397 // Other options
2398 if ($result < 0) {
2399 $this->error = $clone_task->error;
2400 $error++;
2401 }
2402 // End
2403 if ($error) {
2404 $clone_task_id = 0; // For static tool check
2405 } else {
2406 $clone_task_id = $clone_task->id;
2407 $clone_task_ref = $clone_task->ref;
2408
2409 //Note Update
2410 if (!$clone_note) {
2411 $clone_task->note_private = '';
2412 $clone_task->note_public = '';
2413 } else {
2414 $this->db->begin();
2415 $res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES | ENT_HTML5), '_public');
2416 if ($res < 0) {
2417 $this->error .= $clone_task->error;
2418 $error++;
2419 $this->db->rollback();
2420 } else {
2421 $this->db->commit();
2422 }
2423
2424 $this->db->begin();
2425 $res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_private, ENT_QUOTES | ENT_HTML5), '_private');
2426 if ($res < 0) {
2427 $this->error .= $clone_task->error;
2428 $error++;
2429 $this->db->rollback();
2430 } else {
2431 $this->db->commit();
2432 }
2433 }
2434
2435 //Duplicate file
2436 if ($clone_file) {
2437 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2438
2439 //retrieve project origin ref to know folder to copy
2440 $projectstatic = new Project($this->db);
2441 $projectstatic->fetch($ori_project_id);
2442 $ori_project_ref = $projectstatic->ref;
2443
2444 if ($ori_project_id != $project_id) {
2445 $projectstatic->fetch($project_id);
2446 $clone_project_ref = $projectstatic->ref;
2447 } else {
2448 $clone_project_ref = $ori_project_ref;
2449 }
2450
2451 $clone_task_dir = $conf->project->dir_output."/".dol_sanitizeFileName($clone_project_ref)."/".dol_sanitizeFileName($clone_task_ref);
2452 $ori_task_dir = $conf->project->dir_output."/".dol_sanitizeFileName($ori_project_ref)."/".dol_sanitizeFileName((string) $fromid);
2453
2454 $filearray = dol_dir_list($ori_task_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
2455 foreach ($filearray as $file) {
2456 if (!file_exists($clone_task_dir)) {
2457 if (dol_mkdir($clone_task_dir) < 0) {
2458 $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
2459 $error++;
2460 }
2461 }
2462
2463 $rescopy = dol_copy($ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name'], '0', 1);
2464 if (is_numeric($rescopy) && $rescopy < 0) {
2465 $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name']);
2466 $error++;
2467 }
2468 }
2469 }
2470
2471 // clone affectation
2472 if ($clone_affectation) {
2473 $origin_task = new Task($this->db);
2474 $origin_task->fetch($fromid);
2475
2476 foreach (array('internal', 'external') as $source) {
2477 $tab = $origin_task->liste_contact(-1, $source);
2478 $num = count($tab);
2479 $i = 0;
2480 while ($i < $num) {
2481 $clone_task->add_contact($tab[$i]['id'], $tab[$i]['code'], $tab[$i]['source']);
2482 if ($clone_task->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2483 $langs->load("errors");
2484 $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
2485 $error++;
2486 } else {
2487 if ($clone_task->error != '') {
2488 $this->error .= $clone_task->error;
2489 $error++;
2490 }
2491 }
2492 $i++;
2493 }
2494 }
2495 }
2496
2497 if ($clone_time) {
2498 //TODO clone time of affectation
2499 }
2500 }
2501
2502 unset($clone_task->context['createfromclone']);
2503
2504 if (!$error) {
2505 $this->db->commit();
2506 return $clone_task_id;
2507 } else {
2508 $this->db->rollback();
2509 dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
2510 return -1;
2511 }
2512 }
2513
2514
2521 public function getLibStatut($mode = 0)
2522 {
2523 return $this->LibStatut($this->status, $mode);
2524 }
2525
2526 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2534 public function LibStatut($status, $mode = 0)
2535 {
2536 // phpcs:enable
2537 global $langs;
2538
2539 if ($mode == 0) {
2540 return $langs->trans($this->labelStatus[$status]);
2541 } elseif ($mode == 1) {
2542 return $langs->trans($this->labelStatusShort[$status]);
2543 } elseif ($mode == 2) {
2544 switch ($status) {
2545 case 0: // draft
2546 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut0').' '.$langs->trans($this->labelStatusShort[$status]);
2547 case 1: // validated
2548 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut1').' '.$langs->trans($this->labelStatusShort[$status]);
2549 case 2: // in progress
2550 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut3').' '.$langs->trans($this->labelStatusShort[$status]);
2551 case 3: // closed
2552 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut6').' '.$langs->trans($this->labelStatusShort[$status]);
2553 case 4: // transferred ?
2554 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut6').' '.$langs->trans($this->labelStatusShort[$status]);
2555 case 5: // ???
2556 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut5').' '.$langs->trans($this->labelStatusShort[$status]);
2557 }
2558 } elseif ($mode == 3) {
2559 switch ($status) {
2560 case 0:
2561 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut0');
2562 case 1:
2563 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut1');
2564 case 2:
2565 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut3');
2566 case 3:
2567 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut6');
2568 case 4:
2569 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut6');
2570 case 5:
2571 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut5');
2572 }
2573 } elseif ($mode == 4) {
2574 switch ($status) {
2575 case 0:
2576 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status0', $mode);
2577 case 1:
2578 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status1', $mode);
2579 case 2:
2580 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status3', $mode);
2581 case 3:
2582 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status6', $mode);
2583 case 4:
2584 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status6', $mode);
2585 case 5:
2586 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status5', $mode);
2587 }
2588 } elseif ($mode == 5) {
2589 /*if ($status==0) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut0');
2590 elseif ($status==1) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut1');
2591 elseif ($status==2) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut3');
2592 elseif ($status==3) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut6');
2593 elseif ($status==4) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut6');
2594 elseif ($status==5) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut5');
2595 */
2596 //else return $this->progress.' %';
2597 return '&nbsp;';
2598 } elseif ($mode == 6) {
2599 /*if ($status==0) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut0');
2600 elseif ($status==1) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut1');
2601 elseif ($status==2) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut3');
2602 elseif ($status==3) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut6');
2603 elseif ($status==4) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut6');
2604 elseif ($status==5) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut5');
2605 */
2606 //else return $this->progress.' %';
2607 return '&nbsp;';
2608 }
2609 return "";
2610 }
2611
2622 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
2623 {
2624 $outputlangs->load("projects");
2625
2626 if (!dol_strlen($modele)) {
2627 $modele = 'nodefault';
2628
2629 if (!empty($this->model_pdf)) {
2630 $modele = $this->model_pdf;
2631 } elseif (getDolGlobalString('PROJECT_TASK_ADDON_PDF')) {
2632 $modele = getDolGlobalString('PROJECT_TASK_ADDON_PDF');
2633 }
2634 }
2635
2636 $modelpath = "core/modules/project/task/doc/";
2637
2638 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
2639 }
2640
2641
2642 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2649 public function load_board($user)
2650 {
2651 // phpcs:enable
2652 global $conf, $langs;
2653
2654 // For external user, no check is done on company because readability is managed by public status of project and assignment.
2655 //$socid = $user->socid;
2656 $socid = 0;
2657
2658 $projectstatic = new Project($this->db);
2659 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid);
2660
2661 // List of tasks (does not care about permissions. Filtering will be done later)
2662 $sql = "SELECT p.rowid as projectid, p.fk_statut as projectstatus,";
2663 $sql .= " t.rowid as taskid, t.progress as progress, t.fk_statut as status,";
2664 $sql .= " t.dateo as date_start, t.datee as date_end";
2665 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2666 //$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
2667 //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
2668 $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
2669 $sql .= " WHERE p.entity IN (".getEntity('project', 0).')';
2670 $sql .= " AND p.fk_statut = 1";
2671 $sql .= " AND t.fk_projet = p.rowid";
2672 $sql .= " AND (t.progress IS NULL OR t.progress < 100)"; // tasks to do
2673 if (!$user->hasRight('projet', 'all', 'lire')) {
2674 $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2675 }
2676 // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2677 //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
2678 // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2679 // if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id).") OR (s.rowid IS NULL))";
2680
2681 //print $sql;
2682 $resql = $this->db->query($sql);
2683 if ($resql) {
2684 $task_static = new Task($this->db);
2685
2686 $response = new WorkboardResponse();
2687 $response->warning_delay = $conf->project->task->warning_delay / 60 / 60 / 24;
2688 $response->label = $langs->trans("OpenedTasks");
2689 if ($user->hasRight("projet", "all", "lire")) {
2690 $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project';
2691 } else {
2692 $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&amp;mainmenu=project';
2693 }
2694 $response->img = img_object('', "task");
2695
2696 // This assignment in condition is not a bug. It allows walking the results.
2697 while ($obj = $this->db->fetch_object($resql)) {
2698 $response->nbtodo++;
2699
2700 $task_static->projectstatus = $obj->projectstatus;
2701 $task_static->progress = $obj->progress;
2702 $task_static->fk_statut = $obj->status;
2703 $task_static->status = $obj->status;
2704 $task_static->date_start = $this->db->jdate($obj->date_start);
2705 $task_static->date_end = $this->db->jdate($obj->date_end);
2706
2707 if ($task_static->hasDelay()) {
2708 $response->nbtodolate++;
2709 }
2710 }
2711
2712 return $response;
2713 } else {
2714 $this->error = $this->db->error();
2715 return -1;
2716 }
2717 }
2718
2719
2725 public function loadStateBoard()
2726 {
2727 global $user;
2728
2729 $mine = 0;
2730 $socid = $user->socid;
2731
2732 $projectstatic = new Project($this->db);
2733 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, $mine, 1, $socid);
2734
2735 // List of tasks (does not care about permissions. Filtering will be done later)
2736 $sql = "SELECT count(p.rowid) as nb";
2737 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2738 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
2739 if (!$user->hasRight('societe', 'client', 'voir')) {
2740 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
2741 }
2742 $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
2743 $sql .= " WHERE p.entity IN (".getEntity('project', 0).')';
2744 $sql .= " AND t.fk_projet = p.rowid"; // tasks to do
2745 if ($mine || !$user->hasRight('projet', 'all', 'lire')) {
2746 $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2747 }
2748 // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2749 //if ($socid || ! $user->rights->societe->client->voir) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
2750 if ($socid) {
2751 $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
2752 }
2753 if (!$user->hasRight('societe', 'client', 'voir')) {
2754 $sql .= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id).") OR (s.rowid IS NULL))";
2755 }
2756
2757 $resql = $this->db->query($sql);
2758 if ($resql) {
2759 // This assignment in condition is not a bug. It allows walking the results.
2760 while ($obj = $this->db->fetch_object($resql)) {
2761 $this->nb["tasks"] = $obj->nb;
2762 }
2763 $this->db->free($resql);
2764 return 1;
2765 } else {
2766 dol_print_error($this->db);
2767 $this->error = $this->db->error();
2768 return -1;
2769 }
2770 }
2771
2777 public function hasDelay()
2778 {
2779 global $conf;
2780
2781 if (!($this->progress >= 0 && $this->progress < 100)) {
2782 return false;
2783 }
2784
2785 $now = dol_now();
2786
2787 $datetouse = ($this->date_end > 0) ? $this->date_end : ((isset($this->datee) && $this->datee > 0) ? $this->datee : 0);
2788
2789 return ($datetouse > 0 && ($datetouse < ($now - $conf->project->task->warning_delay)));
2790 }
2791
2799 public function getKanbanView($option = '', $arraydata = null)
2800 {
2801 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2802
2803 $return = '<div class="box-flex-item box-flex-grow-zero">';
2804 $return .= '<div class="info-box info-box-sm info-box-kanban">';
2805 $return .= '<span class="info-box-icon bg-infobox-action">';
2806 $return .= img_picto('', $this->picto);
2807 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
2808 $return .= '</span>';
2809 $return .= '<div class="info-box-content">';
2810 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
2811 if ($selected >= 0) {
2812 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2813 }
2814 if (!empty($arraydata['projectlink'])) {
2815 //$tmpproject = $arraydata['project'];
2816 //$return .= '<br><span class="info-box-status ">'.$tmpproject->getNomProject().'</span>';
2817 $return .= '<br><span class="info-box-status ">'.$arraydata['projectlink'].'</span>';
2818 }
2819 //if (property_exists($this, 'budget_amount')) {
2820 //$return .= '<br><span class="info-box-label amount">'.$langs->trans("Budget").' : '.price($this->budget_amount, 0, $langs, 1, 0, 0, $conf->currency).'</span>';
2821 //}
2822 if (property_exists($this, 'duration_effective')) {
2823 $return .= '<br><div class="info-box-label progressinkanban paddingtop">'.getTaskProgressView($this, false, true).'</div>';
2824 }
2825 $return .= '</div>';
2826 $return .= '</div>';
2827 $return .= '</div>';
2828
2829 return $return;
2830 }
2831
2839 public function mergeTask($task_origin_id)
2840 {
2841 global $langs, $hookmanager, $user, $action;
2842
2843 $error = 0;
2844 $task_origin = new Task($this->db); // The thirdparty that we will delete
2845
2846 dol_syslog("mergeTask merge task id=".$task_origin_id." (will be deleted) into the task id=".$this->id);
2847
2848 $langs->load('error');
2849
2850 if (!$error && $task_origin->fetch($task_origin_id) < 1) {
2851 $this->error = $langs->trans('ErrorRecordNotFound');
2852 $error++;
2853 }
2854
2855 if (!$error) {
2856 $this->db->begin();
2857
2858 // Recopy some data
2859 $listofproperties = array(
2860 'label', 'description', 'duration_effective', 'planned_workload', 'datec', 'date_start',
2861 'date_end', 'fk_user_creat', 'fk_user_valid', 'fk_statut', 'progress', 'budget_amount',
2862 'priority', 'rang', 'fk_projet', 'fk_task_parent'
2863 );
2864 foreach ($listofproperties as $property) {
2865 if (empty($this->$property)) {
2866 $this->$property = $task_origin->$property;
2867 }
2868 }
2869
2870 // Concat some data
2871 $listofproperties = array(
2872 'note_public', 'note_private'
2873 );
2874 foreach ($listofproperties as $property) {
2875 $this->$property = dol_concatdesc($this->$property, $task_origin->$property);
2876 }
2877
2878 // Merge extrafields
2879 if (is_array($task_origin->array_options)) {
2880 foreach ($task_origin->array_options as $key => $val) {
2881 if (empty($this->array_options[$key])) {
2882 $this->array_options[$key] = $val;
2883 }
2884 }
2885 }
2886
2887 // Update
2888 $result = $this->update($user);
2889
2890 if ($result < 0) {
2891 $error++;
2892 }
2893
2894 // Merge time spent
2895 if (!$error) {
2896 $result = $this->mergeTimeSpentTask($task_origin_id, $this->id);
2897 if ($result != true) {
2898 $error++;
2899 }
2900 }
2901
2902 // Merge contacts
2903 if (!$error) {
2904 $result = $this->mergeContactTask($task_origin_id, $this->id);
2905 if ($result != true) {
2906 $error++;
2907 }
2908 }
2909
2910 // External modules should update their ones too
2911 if (!$error) {
2912 $parameters = array('task_origin' => $task_origin->id, 'task_dest' => $this->id);
2913 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
2914
2915 if ($reshook < 0) {
2916 $this->error = $hookmanager->error;
2917 $this->errors = $hookmanager->errors;
2918 $error++;
2919 }
2920 }
2921
2922
2923 if (!$error) {
2924 $this->context = array('merge' => 1, 'mergefromid' => $task_origin->id, 'mergefromref' => $task_origin->ref);
2925
2926 // Call trigger
2927 $result = $this->call_trigger('TASK_MODIFY', $user);
2928 if ($result < 0) {
2929 $error++;
2930 }
2931 // End call triggers
2932 }
2933
2934 if (!$error) {
2935 // We finally remove the old task
2936 if ($task_origin->delete($user) < 1) {
2937 $this->error = $task_origin->error;
2938 $this->errors = $task_origin->errors;
2939 $error++;
2940 }
2941 }
2942
2943 if (!$error) {
2944 $this->db->commit();
2945 return 0;
2946 } else {
2947 $langs->load("errors");
2948 $this->error = $langs->trans('ErrorsTaskMerge');
2949 $this->db->rollback();
2950 return -1;
2951 }
2952 }
2953
2954 return -1;
2955 }
2956}
$object ref
Definition info.php:90
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...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
call_trigger($triggerName, $user)
Call trigger based on this instance.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Class to manage projects.
const STATUS_VALIDATED
Open/Validated status.
Class to manage tasks.
create($user, $notrigger=0)
Create into database.
fetch($id, $ref='', $loadparentdata=0)
Load object in memory from database.
getLibStatut($mode=0)
Return status label of object.
mergeContactTask($origin_id, $dest_id)
Merge contact of tasks.
const STATUS_TRANSFERRED
Transferred status.
getSumOfAmount($fuser='', $dates='', $datee='')
Calculate quantity and value of time consumed using the thm (hourly amount value of work for user ent...
mergeTask($task_origin_id)
Merge a task with another one, deleting the given task.
__construct($db)
Constructor.
fetchTimeSpentOnTask($morewherefilter='')
Fetch records of time spent of this task.
const STATUS_VALIDATED
Validated status (To do).
hasTimeSpent()
Return nb of time spent.
getNomUrl($withpicto=0, $option='', $mode='task', $addlabel=0, $sep=' - ', $notooltip=0, $save_lastsearch_value=-1)
Return clickable name (with picto eventually)
getListContactId($source='internal')
Return list of id of contacts of task.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
delTimeSpent($user, $notrigger=0)
Delete time spent.
mergeTimeSpentTask($origin_id, $dest_id)
Merge time spent of tasks.
const STATUS_DRAFT
Draft status.
fetchAllTimeSpent(User $userobj, $morewherefilter='')
Load all records of time spent.
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getUserRolesForProjectsOrTasks($userp, $usert, $projectid='', $taskid=0, $filteronprojstatus=-1)
Return list of roles for a user for each projects or each tasks (or a particular project or a particu...
update($user=null, $notrigger=0)
Update database.
getSummaryOfTimeSpent($userobj=null, $morewherefilter='')
Calculate total of time spent for task.
getTooltipContentArray($params)
getTooltipContentArray
const STATUS_CANCELED
status canceled
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create an intervention document on disk using template defined into PROJECT_TASK_ADDON_PDF.
fetchTimeSpent($id)
Load properties of timespent of a task from the time spent ID.
updateTimeSpent($user, $notrigger=0)
Update time spent line with id $this->timespent_id.
createFromClone(User $user, $fromid, $project_id, $parent_task_id, $clone_change_dt=false, $clone_affectation=false, $clone_time=false, $clone_file=false, $clone_note=false, $clone_prog=false)
Load an object from its id and create a new one in database.
loadStateBoard()
Load indicators this->nb for state board.
const STATUS_ONGOING
Ongoing status (In progress).
initAsSpecimen()
Initialise an instance with random values.
getTasksArray($usert=null, $userp=null, $projectid=0, $socid=0, $mode=0, $filteronproj='', $filteronprojstatus='-1', $morewherefilter='', $filteronprojuser=0, $filterontaskuser=0, $extrafields=null, $includebilltime=0, $search_array_options=array(), $loadextras=0, $loadRoleMode=1, $sortfield='', $sortorder='')
Return list of tasks for all projects or for one particular project Sort order is on project,...
addTimeSpent($user, $notrigger=0)
Add time spent.
hasDelay()
Is the task delayed?
LibStatut($status, $mode=0)
Return status label for an object.
const STATUS_CLOSED
Finished status.
hasChildren()
Return nb of children.
Class for TimeSpent.
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:171
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
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_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_move_dir($srcdir, $destdir, $overwriteifexists=1, $indexdatabase=1, $renamedircontent=1)
Move a directory into another name.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
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:63
dol_html_entity_decode($a, $b, $c='UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
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...
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
natural_search($fields, $value, $mode=0, $nofirstand=0)
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79