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 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->public = $obj->project_public;
1808
1809 $newobj->fk_task = $obj->task_id;
1810 $newobj->task_ref = $obj->task_ref;
1811 $newobj->task_label = $obj->task_label;
1812
1813 $newobj->timespent_line_id = $obj->rowid;
1814 $newobj->timespent_line_ref_ext = $obj->ref_ext;
1815 $newobj->timespent_line_date = $this->db->jdate($obj->task_date);
1816 $newobj->timespent_line_datehour = $this->db->jdate($obj->task_datehour);
1817 $newobj->timespent_line_withhour = $obj->task_date_withhour;
1818 $newobj->timespent_line_duration = $obj->task_duration;
1819 $newobj->timespent_line_fk_user = $obj->fk_user;
1820 $newobj->timespent_line_fk_product = $obj->fk_product;
1821 $newobj->timespent_line_thm = $obj->thm; // hourly rate
1822 $newobj->timespent_line_note = $obj->note;
1823
1824 $arrayres[] = $newobj;
1825
1826 $i++;
1827 }
1828
1829 $this->db->free($resql);
1830
1831 $this->lines = $arrayres;
1832 return 1;
1833 } else {
1834 dol_print_error($this->db);
1835 $this->error = "Error ".$this->db->lasterror();
1836 return -1;
1837 }
1838 }
1839
1840
1848 public function getSummaryOfTimeSpent($userobj = null, $morewherefilter = '')
1849 {
1850 if (is_object($userobj)) {
1851 $userid = $userobj->id;
1852 } else {
1853 $userid = $userobj; // old method
1854 }
1855
1856 $id = $this->id;
1857 if (empty($id) && empty($userid)) {
1858 dol_syslog("getSummaryOfTimeSpent called on a not loaded task without user param defined", LOG_ERR);
1859 return -1;
1860 }
1861
1862 $result = array();
1863
1864 $sql = "SELECT";
1865 $sql .= " MIN(t.element_datehour) as min_date,";
1866 $sql .= " MAX(t.element_datehour) as max_date,";
1867 $sql .= " SUM(t.element_duration) as total_duration,";
1868 $sql .= " SUM(t.element_duration / 3600 * ".$this->db->ifsql("t.thm IS NULL", '0', "t.thm").") as total_amount,";
1869 $sql .= " COUNT(t.rowid) as nblines,";
1870 $sql .= " SUM(".$this->db->ifsql("t.thm IS NULL", '1', '0').") as nblinesnull";
1871 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as t";
1872 $sql .= " WHERE t.elementtype='task'";
1873 if ($morewherefilter) {
1874 $sql .= $morewherefilter;
1875 }
1876 if ($id > 0) {
1877 $sql .= " AND t.fk_element = ".((int) $id);
1878 }
1879 if ($userid > 0) {
1880 $sql .= " AND t.fk_user = ".((int) $userid);
1881 }
1882
1883 dol_syslog(get_class($this)."::getSummaryOfTimeSpent", LOG_DEBUG);
1884 $resql = $this->db->query($sql);
1885 if ($resql) {
1886 $obj = $this->db->fetch_object($resql);
1887
1888 $result['min_date'] = $obj->min_date; // deprecated. use the ->timespent_xxx instead
1889 $result['max_date'] = $obj->max_date; // deprecated. use the ->timespent_xxx instead
1890 $result['total_duration'] = $obj->total_duration; // deprecated. use the ->timespent_xxx instead
1891
1892 $this->timespent_min_date = $this->db->jdate($obj->min_date);
1893 $this->timespent_max_date = $this->db->jdate($obj->max_date);
1894 $this->timespent_total_duration = $obj->total_duration;
1895 $this->timespent_total_amount = $obj->total_amount;
1896 $this->timespent_nblinesnull = ($obj->nblinesnull ? $obj->nblinesnull : 0);
1897 $this->timespent_nblines = ($obj->nblines ? $obj->nblines : 0);
1898
1899 $this->db->free($resql);
1900 } else {
1901 dol_print_error($this->db);
1902 }
1903 return $result;
1904 }
1905
1914 public function getSumOfAmount($fuser = '', $dates = '', $datee = '')
1915 {
1916 $id = $this->id;
1917
1918 $result = array();
1919
1920 $sql = "SELECT";
1921 $sql .= " SUM(t.element_duration) as nbseconds,";
1922 $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";
1923 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as t";
1924 $sql .= " WHERE t.elementtype='task' AND t.fk_element = ".((int) $id);
1925 if (is_object($fuser) && $fuser->id > 0) {
1926 $sql .= " AND fk_user = ".((int) $fuser->id);
1927 }
1928 if ($dates > 0) {
1929 $datefieldname = "element_datehour";
1930 $sql .= " AND (".$datefieldname." >= '".$this->db->idate((int) $dates)."' OR ".$datefieldname." IS NULL)";
1931 }
1932 if ($datee > 0) {
1933 $datefieldname = "element_datehour";
1934 $sql .= " AND (".$datefieldname." <= '".$this->db->idate((int) $datee)."' OR ".$datefieldname." IS NULL)";
1935 }
1936 //print $sql;
1937
1938 dol_syslog(get_class($this)."::getSumOfAmount", LOG_DEBUG);
1939 $resql = $this->db->query($sql);
1940 if ($resql) {
1941 $obj = $this->db->fetch_object($resql);
1942
1943 $result['amount'] = $obj->amount;
1944 $result['nbseconds'] = $obj->nbseconds;
1945 $result['nblinesnull'] = $obj->nblinesnull;
1946
1947 $this->db->free($resql);
1948 return $result;
1949 } else {
1950 dol_print_error($this->db);
1951 return $result;
1952 }
1953 }
1954
1961 public function fetchTimeSpent($id)
1962 {
1963 $timespent = new TimeSpent($this->db);
1964 $timespent->fetch($id);
1965
1966 dol_syslog(get_class($this)."::fetchTimeSpent", LOG_DEBUG);
1967
1968 if ($timespent->id > 0) {
1969 $this->timespent_id = $timespent->id;
1970 $this->id = $timespent->fk_element;
1971 $this->timespent_date = $timespent->element_date;
1972 $this->timespent_datehour = $timespent->element_datehour;
1973 $this->timespent_withhour = $timespent->element_date_withhour;
1974 $this->timespent_duration = $timespent->element_duration;
1975 $this->timespent_fk_user = $timespent->fk_user;
1976 $this->timespent_fk_product = $timespent->fk_product;
1977 $this->timespent_thm = $timespent->thm; // hourly rate
1978 $this->timespent_note = $timespent->note;
1979
1980 return 1;
1981 }
1982
1983 return 0;
1984 }
1985
1993 public function fetchAllTimeSpent(User $userobj, $morewherefilter = '')
1994 {
1995 $arrayres = array();
1996
1997 $sql = "SELECT";
1998 $sql .= " s.rowid as socid,";
1999 $sql .= " s.nom as thirdparty_name,";
2000 $sql .= " s.email as thirdparty_email,";
2001 $sql .= " ptt.rowid,";
2002 $sql .= " ptt.fk_element as fk_task,";
2003 $sql .= " ptt.element_date as task_date,";
2004 $sql .= " ptt.element_datehour as task_datehour,";
2005 $sql .= " ptt.element_date_withhour as task_date_withhour,";
2006 $sql .= " ptt.element_duration as task_duration,";
2007 $sql .= " ptt.fk_user,";
2008 $sql .= " ptt.note,";
2009 $sql .= " ptt.thm,";
2010 $sql .= " pt.rowid as task_id,";
2011 $sql .= " pt.ref as task_ref,";
2012 $sql .= " pt.label as task_label,";
2013 $sql .= " p.rowid as project_id,";
2014 $sql .= " p.ref as project_ref,";
2015 $sql .= " p.title as project_label,";
2016 $sql .= " p.public as public";
2017 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as ptt, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet as p";
2018 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
2019 $sql .= " WHERE ptt.fk_element = pt.rowid AND pt.fk_projet = p.rowid";
2020 $sql .= " AND ptt.elementtype = 'task'";
2021 $sql .= " AND ptt.fk_user = ".((int) $userobj->id);
2022 $sql .= " AND pt.entity IN (".getEntity('project').")";
2023 if ($morewherefilter) {
2024 $sql .= $morewherefilter;
2025 }
2026
2027 dol_syslog(get_class($this)."::fetchAllTimeSpent", LOG_DEBUG);
2028 $resql = $this->db->query($sql);
2029 if ($resql) {
2030 $num = $this->db->num_rows($resql);
2031
2032 $i = 0;
2033 while ($i < $num) {
2034 $obj = $this->db->fetch_object($resql);
2035
2036 $newobj = new stdClass();
2037
2038 $newobj->socid = $obj->socid;
2039 $newobj->thirdparty_name = $obj->thirdparty_name;
2040 $newobj->thirdparty_email = $obj->thirdparty_email;
2041
2042 $newobj->fk_project = $obj->project_id;
2043 $newobj->project_ref = $obj->project_ref;
2044 $newobj->project_label = $obj->project_label;
2045 $newobj->public = $obj->project_public;
2046
2047 $newobj->fk_task = $obj->task_id;
2048 $newobj->task_ref = $obj->task_ref;
2049 $newobj->task_label = $obj->task_label;
2050
2051 $newobj->timespent_id = $obj->rowid;
2052 $newobj->timespent_date = $this->db->jdate($obj->task_date);
2053 $newobj->timespent_datehour = $this->db->jdate($obj->task_datehour);
2054 $newobj->timespent_withhour = $obj->task_date_withhour;
2055 $newobj->timespent_duration = $obj->task_duration;
2056 $newobj->timespent_fk_user = $obj->fk_user;
2057 $newobj->timespent_thm = $obj->thm; // hourly rate
2058 $newobj->timespent_note = $obj->note;
2059
2060 $arrayres[] = $newobj;
2061
2062 $i++;
2063 }
2064
2065 $this->db->free($resql);
2066 } else {
2067 dol_print_error($this->db);
2068 $this->error = "Error ".$this->db->lasterror();
2069 return -1;
2070 }
2071
2072 return $arrayres;
2073 }
2074
2082 public function updateTimeSpent($user, $notrigger = 0)
2083 {
2084 global $conf, $langs;
2085
2086 $ret = 0;
2087
2088 // Check parameters
2089 if ($this->timespent_date == '') {
2090 $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Date"));
2091 return -1;
2092 }
2093
2094 // Clean parameters
2095 if (empty($this->timespent_datehour) || empty($this->timespent_withhour)) {
2096 // Sync datehour from the day-level date when no start hour was provided (withhour = 0), or when
2097 // datehour is empty. When a start hour was entered (withhour = 1), keep datehour untouched so the
2098 // hour is not discarded (#39276). This still resynchronizes datehour when only the day changes.
2099 $this->timespent_datehour = $this->timespent_date;
2100 }
2101 if (isset($this->timespent_note)) {
2102 $this->timespent_note = trim($this->timespent_note);
2103 }
2104
2105 if (getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS')) {
2106 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2107 $restrictBefore = dol_time_plus_duree(dol_now(), - getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'), 'm');
2108
2109 if ($this->timespent_date < $restrictBefore) {
2110 $this->error = $langs->trans('TimeRecordingRestrictedToNMonthsBack', getDolGlobalString('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'));
2111 $this->errors[] = $this->error;
2112 return -1;
2113 }
2114 }
2115
2116 $this->db->begin();
2117
2118 $timespent = new TimeSpent($this->db);
2119 $timespent->fetch($this->timespent_id);
2120 $old_fk_element = $timespent->fk_element; // Store old task ID before potential change
2121
2122 $timespent->element_date = $this->timespent_date;
2123 $timespent->element_datehour = $this->timespent_datehour;
2124 $timespent->element_date_withhour = $this->timespent_withhour;
2125 $timespent->element_duration = $this->timespent_duration;
2126 if ($this->timespent_fk_user > 0) {
2127 $timespent->fk_user = $this->timespent_fk_user;
2128 }
2129 $timespent->fk_product = $this->timespent_fk_product;
2130 $timespent->fk_element = $this->id; // Update task assignment (may be changed)
2131 $timespent->note = $this->timespent_note;
2132 $timespent->invoice_id = $this->timespent_invoiceid;
2133 $timespent->invoice_line_id = $this->timespent_invoicelineid;
2134
2135 dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
2136 if ($timespent->update($user) > 0) {
2137 if (!$notrigger) {
2138 // Call trigger
2139 $result = $this->call_trigger('TASK_TIMESPENT_MODIFY', $user);
2140 if ($result < 0) {
2141 $this->db->rollback();
2142 $ret = -1;
2143 } else {
2144 $ret = 1;
2145 }
2146 // End call triggers
2147 } else {
2148 $ret = 1;
2149 }
2150 } else {
2151 $this->error = $this->db->lasterror();
2152 $this->db->rollback();
2153 $ret = -1;
2154 }
2155
2156 // Propagate trigger handler messages from $this->errors (plural array)
2157 // to $this->error (singular string) so callers like the REST API can
2158 // surface a useful message instead of an empty error tail.
2159 if ($ret < 0 && empty($this->error) && !empty($this->errors)) {
2160 foreach ($this->errors as $errmsg) {
2161 dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
2162 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2163 }
2164 }
2165
2166 if ($ret == 1 && (($this->timespent_old_duration != $this->timespent_duration) || getDolGlobalString('TIMESPENT_ALWAYS_UPDATE_THM'))) {
2167 if ($this->timespent_old_duration != $this->timespent_duration) {
2168 // Recalculate amount of time spent for task and update denormalized field
2169 $sql = "UPDATE " . MAIN_DB_PREFIX . "projet_task";
2170 $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) . ")";
2171 if (isset($this->progress)) {
2172 $sql .= ", progress = " . ((float) $this->progress); // Do not overwrite value if not provided
2173 }
2174 $sql .= " WHERE rowid = " . ((int) $this->id);
2175
2176 dol_syslog(get_class($this) . "::updateTimeSpent", LOG_DEBUG);
2177 if (!$this->db->query($sql)) {
2178 $this->error = $this->db->lasterror();
2179 $this->db->rollback();
2180 $ret = -2;
2181 }
2182 }
2183
2184 // Update hourly rate of this time spent entry, but only if it was not set initially
2185 $res_update = 1;
2186 if (empty($timespent->thm) || getDolGlobalString('TIMESPENT_ALWAYS_UPDATE_THM')) {
2187 $resql_thm_user = $this->db->query("SELECT thm FROM " . MAIN_DB_PREFIX . "user WHERE rowid = " . ((int) $timespent->fk_user));
2188 if (!empty($resql_thm_user)) {
2189 $obj_thm_user = $this->db->fetch_object($resql_thm_user);
2190 $timespent->thm = $obj_thm_user->thm;
2191 }
2192 $res_update = $timespent->update($user);
2193 }
2194
2195 dol_syslog(get_class($this)."::updateTimeSpent", LOG_DEBUG);
2196 if ($res_update <= 0) {
2197 $this->error = $this->db->lasterror();
2198 $ret = -2;
2199 }
2200 }
2201
2202 // If task assignment changed, recalculate duration_effective for both old and new tasks
2203 if ($ret == 1 && $old_fk_element != $this->id) {
2204 // Recalculate duration_effective for the OLD task
2205 $sql = "UPDATE " . MAIN_DB_PREFIX . "projet_task";
2206 $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) . ")";
2207 $sql .= " WHERE rowid = " . ((int) $old_fk_element);
2208 dol_syslog(get_class($this) . "::updateTimeSpent update old task", LOG_DEBUG);
2209 if (!$this->db->query($sql)) {
2210 $this->error = $this->db->lasterror();
2211 $this->db->rollback();
2212 $ret = -2;
2213 }
2214 // Recalculate duration_effective for the NEW task
2215 if ($ret == 1) {
2216 $sql = "UPDATE " . MAIN_DB_PREFIX . "projet_task";
2217 $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) . ")";
2218 $sql .= " WHERE rowid = " . ((int) $this->id);
2219 dol_syslog(get_class($this) . "::updateTimeSpent update new task", LOG_DEBUG);
2220 if (!$this->db->query($sql)) {
2221 $this->error = $this->db->lasterror();
2222 $this->db->rollback();
2223 $ret = -2;
2224 }
2225 }
2226 }
2227
2228 if ($ret >= 0) {
2229 $this->db->commit();
2230 }
2231 return $ret;
2232 }
2233
2241 public function delTimeSpent($user, $notrigger = 0)
2242 {
2243 global $conf, $langs;
2244
2245 $error = 0;
2246
2247 if (getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS')) {
2248 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
2249 $restrictBefore = dol_time_plus_duree(dol_now(), - getDolGlobalInt('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'), 'm');
2250
2251 if ($this->timespent_date < $restrictBefore) {
2252 $this->error = $langs->trans('TimeRecordingRestrictedToNMonthsBack', getDolGlobalString('PROJECT_TIMESHEET_PREVENT_AFTER_MONTHS'));
2253 $this->errors[] = $this->error;
2254 return -1;
2255 }
2256 }
2257
2258 $this->db->begin();
2259
2260 if (!$notrigger) {
2261 // Call trigger
2262 $result = $this->call_trigger('TASK_TIMESPENT_DELETE', $user);
2263 if ($result < 0) {
2264 $error++;
2265 }
2266 // End call triggers
2267 }
2268
2269 if (!$error) {
2270 $timespent = new TimeSpent($this->db);
2271 $timespent->fetch($this->timespent_id);
2272
2273 $res_del = $timespent->delete($user);
2274
2275 if ($res_del < 0) {
2276 $error++;
2277 $this->errors[] = "Error ".$this->db->lasterror();
2278 }
2279 }
2280
2281 if (!$error) {
2282 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task";
2283 $sql .= " SET duration_effective = duration_effective - ".((int) $this->timespent_duration);
2284 $sql .= " WHERE rowid = ".((int) $this->id);
2285
2286 dol_syslog(get_class($this)."::delTimeSpent", LOG_DEBUG);
2287 if ($this->db->query($sql)) {
2288 $result = 0;
2289 } else {
2290 $this->error = $this->db->lasterror();
2291 $result = -2;
2292 }
2293 }
2294
2295 // Commit or rollback
2296 if ($error) {
2297 foreach ($this->errors as $errmsg) {
2298 dol_syslog(get_class($this)."::delTimeSpent ".$errmsg, LOG_ERR);
2299 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2300 }
2301 $this->db->rollback();
2302 return -1 * $error;
2303 } else {
2304 $this->db->commit();
2305 return 1;
2306 }
2307 }
2308
2323 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)
2324 {
2325 global $langs, $conf;
2326
2327 $error = 0;
2328
2329 //Use 00:00 of today if time is use on task.
2330 $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'));
2331
2332 $datec = $now;
2333
2334 $clone_task = new Task($this->db);
2335 $origin_task = new Task($this->db);
2336
2337 $clone_task->context['createfromclone'] = 'createfromclone';
2338
2339 $this->db->begin();
2340
2341 // Load source object
2342 $clone_task->fetch($fromid);
2343 $clone_task->fetch_optionals();
2344 //var_dump($clone_task->array_options);exit;
2345
2346 $origin_task->fetch($fromid);
2347
2348 $clone_task->date_c = $datec; // Set the new creation date before computing the ref, else the numbering mask uses the source task year
2349
2350 $defaultref = '';
2351 $obj = !getDolGlobalString('PROJECT_TASK_ADDON') ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
2352 if (getDolGlobalString('PROJECT_TASK_ADDON') && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON').".php")) {
2353 require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON').'.php';
2354 $modTask = new $obj();
2355 '@phan-var-force ModeleNumRefTask $modTask';
2356 $defaultref = $modTask->getNextValue(null, $clone_task);
2357 }
2358
2359 $ori_project_id = $clone_task->fk_project;
2360
2361 $clone_task->id = 0;
2362 $clone_task->ref = $defaultref;
2363 $clone_task->fk_project = $project_id;
2364 $clone_task->fk_task_parent = $parent_task_id;
2365 $clone_task->planned_workload = $origin_task->planned_workload;
2366 $clone_task->rang = $origin_task->rang;
2367 $clone_task->priority = $origin_task->priority;
2368
2369 //Manage Task Date
2370 if ($clone_change_dt) {
2371 $projectstatic = new Project($this->db);
2372 $projectstatic->fetch($ori_project_id);
2373
2374 // Origin project start date
2375 $orign_project_dt_start = (!isset($projectstatic->date_start) || $projectstatic->date_start == '') ? $projectstatic->date_c : $projectstatic->date_start;
2376
2377 // Calculate new task start date with difference between origin proj start date and origin task start date
2378 if (!empty($clone_task->date_start)) {
2379 $clone_task->date_start = $now + $clone_task->date_start - $orign_project_dt_start;
2380 }
2381
2382 // Calculate new task end date with difference between origin proj start date and origin task end date
2383 if (!empty($clone_task->date_end)) {
2384 $clone_task->date_end = $now + $clone_task->date_end - $orign_project_dt_start;
2385 }
2386 }
2387
2388 if (!$clone_prog) {
2389 $clone_task->progress = 0;
2390 }
2391
2392 // Create clone
2393 $result = $clone_task->create($user);
2394
2395 // Other options
2396 if ($result < 0) {
2397 $this->error = $clone_task->error;
2398 $error++;
2399 }
2400 // End
2401 if ($error) {
2402 $clone_task_id = 0; // For static tool check
2403 } else {
2404 $clone_task_id = $clone_task->id;
2405 $clone_task_ref = $clone_task->ref;
2406
2407 //Note Update
2408 if (!$clone_note) {
2409 $clone_task->note_private = '';
2410 $clone_task->note_public = '';
2411 } else {
2412 $this->db->begin();
2413 $res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES | ENT_HTML5), '_public');
2414 if ($res < 0) {
2415 $this->error .= $clone_task->error;
2416 $error++;
2417 $this->db->rollback();
2418 } else {
2419 $this->db->commit();
2420 }
2421
2422 $this->db->begin();
2423 $res = $clone_task->update_note(dol_html_entity_decode($clone_task->note_private, ENT_QUOTES | ENT_HTML5), '_private');
2424 if ($res < 0) {
2425 $this->error .= $clone_task->error;
2426 $error++;
2427 $this->db->rollback();
2428 } else {
2429 $this->db->commit();
2430 }
2431 }
2432
2433 //Duplicate file
2434 if ($clone_file) {
2435 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2436
2437 //retrieve project origin ref to know folder to copy
2438 $projectstatic = new Project($this->db);
2439 $projectstatic->fetch($ori_project_id);
2440 $ori_project_ref = $projectstatic->ref;
2441
2442 if ($ori_project_id != $project_id) {
2443 $projectstatic->fetch($project_id);
2444 $clone_project_ref = $projectstatic->ref;
2445 } else {
2446 $clone_project_ref = $ori_project_ref;
2447 }
2448
2449 $clone_task_dir = $conf->project->dir_output."/".dol_sanitizeFileName($clone_project_ref)."/".dol_sanitizeFileName($clone_task_ref);
2450 $ori_task_dir = $conf->project->dir_output."/".dol_sanitizeFileName($ori_project_ref)."/".dol_sanitizeFileName((string) $fromid);
2451
2452 $filearray = dol_dir_list($ori_task_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1);
2453 foreach ($filearray as $file) {
2454 if (!file_exists($clone_task_dir)) {
2455 if (dol_mkdir($clone_task_dir) < 0) {
2456 $this->error .= $langs->trans('ErrorInternalErrorDetected').':dol_mkdir';
2457 $error++;
2458 }
2459 }
2460
2461 $rescopy = dol_copy($ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name'], '0', 1);
2462 if (is_numeric($rescopy) && $rescopy < 0) {
2463 $this->error .= $langs->trans("ErrorFailToCopyFile", $ori_task_dir.'/'.$file['name'], $clone_task_dir.'/'.$file['name']);
2464 $error++;
2465 }
2466 }
2467 }
2468
2469 // clone affectation
2470 if ($clone_affectation) {
2471 $origin_task = new Task($this->db);
2472 $origin_task->fetch($fromid);
2473
2474 foreach (array('internal', 'external') as $source) {
2475 $tab = $origin_task->liste_contact(-1, $source);
2476 $num = count($tab);
2477 $i = 0;
2478 while ($i < $num) {
2479 $clone_task->add_contact($tab[$i]['id'], $tab[$i]['code'], $tab[$i]['source']);
2480 if ($clone_task->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2481 $langs->load("errors");
2482 $this->error .= $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType");
2483 $error++;
2484 } else {
2485 if ($clone_task->error != '') {
2486 $this->error .= $clone_task->error;
2487 $error++;
2488 }
2489 }
2490 $i++;
2491 }
2492 }
2493 }
2494
2495 if ($clone_time) {
2496 //TODO clone time of affectation
2497 }
2498 }
2499
2500 unset($clone_task->context['createfromclone']);
2501
2502 if (!$error) {
2503 $this->db->commit();
2504 return $clone_task_id;
2505 } else {
2506 $this->db->rollback();
2507 dol_syslog(get_class($this)."::createFromClone nbError: ".$error." error : ".$this->error, LOG_ERR);
2508 return -1;
2509 }
2510 }
2511
2512
2519 public function getLibStatut($mode = 0)
2520 {
2521 return $this->LibStatut($this->status, $mode);
2522 }
2523
2524 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2532 public function LibStatut($status, $mode = 0)
2533 {
2534 // phpcs:enable
2535 global $langs;
2536
2537 if ($mode == 0) {
2538 return $langs->trans($this->labelStatus[$status]);
2539 } elseif ($mode == 1) {
2540 return $langs->trans($this->labelStatusShort[$status]);
2541 } elseif ($mode == 2) {
2542 switch ($status) {
2543 case 0: // draft
2544 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut0').' '.$langs->trans($this->labelStatusShort[$status]);
2545 case 1: // validated
2546 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut1').' '.$langs->trans($this->labelStatusShort[$status]);
2547 case 2: // in progress
2548 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut3').' '.$langs->trans($this->labelStatusShort[$status]);
2549 case 3: // closed
2550 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut6').' '.$langs->trans($this->labelStatusShort[$status]);
2551 case 4: // transferred ?
2552 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut6').' '.$langs->trans($this->labelStatusShort[$status]);
2553 case 5: // ???
2554 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut5').' '.$langs->trans($this->labelStatusShort[$status]);
2555 }
2556 } elseif ($mode == 3) {
2557 switch ($status) {
2558 case 0:
2559 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut0');
2560 case 1:
2561 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut1');
2562 case 2:
2563 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut3');
2564 case 3:
2565 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut6');
2566 case 4:
2567 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut6');
2568 case 5:
2569 return img_picto($langs->trans($this->labelStatusShort[$status]), 'statut5');
2570 }
2571 } elseif ($mode == 4) {
2572 switch ($status) {
2573 case 0:
2574 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status0', $mode);
2575 case 1:
2576 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status1', $mode);
2577 case 2:
2578 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status3', $mode);
2579 case 3:
2580 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status6', $mode);
2581 case 4:
2582 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status6', $mode);
2583 case 5:
2584 return dolGetStatus($langs->trans($this->labelStatus[$status]), $langs->trans($this->labelStatusShort[$status]), '', 'status5', $mode);
2585 }
2586 } elseif ($mode == 5) {
2587 /*if ($status==0) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut0');
2588 elseif ($status==1) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut1');
2589 elseif ($status==2) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut3');
2590 elseif ($status==3) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut6');
2591 elseif ($status==4) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut6');
2592 elseif ($status==5) return $langs->trans($this->labelStatusShort[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut5');
2593 */
2594 //else return $this->progress.' %';
2595 return '&nbsp;';
2596 } elseif ($mode == 6) {
2597 /*if ($status==0) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut0');
2598 elseif ($status==1) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut1');
2599 elseif ($status==2) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut3');
2600 elseif ($status==3) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut6');
2601 elseif ($status==4) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut6');
2602 elseif ($status==5) return $langs->trans($this->labelStatus[$status]).' '.img_picto($langs->trans($this->labelStatusShort[$status]),'statut5');
2603 */
2604 //else return $this->progress.' %';
2605 return '&nbsp;';
2606 }
2607 return "";
2608 }
2609
2620 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
2621 {
2622 $outputlangs->load("projects");
2623
2624 if (!dol_strlen($modele)) {
2625 $modele = 'nodefault';
2626
2627 if (!empty($this->model_pdf)) {
2628 $modele = $this->model_pdf;
2629 } elseif (getDolGlobalString('PROJECT_TASK_ADDON_PDF')) {
2630 $modele = getDolGlobalString('PROJECT_TASK_ADDON_PDF');
2631 }
2632 }
2633
2634 $modelpath = "core/modules/project/task/doc/";
2635
2636 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
2637 }
2638
2639
2640 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2647 public function load_board($user)
2648 {
2649 // phpcs:enable
2650 global $conf, $langs;
2651
2652 // For external user, no check is done on company because readability is managed by public status of project and assignment.
2653 //$socid = $user->socid;
2654 $socid = 0;
2655
2656 $projectstatic = new Project($this->db);
2657 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid);
2658
2659 // List of tasks (does not care about permissions. Filtering will be done later)
2660 $sql = "SELECT p.rowid as projectid, p.fk_statut as projectstatus,";
2661 $sql .= " t.rowid as taskid, t.progress as progress, t.fk_statut as status,";
2662 $sql .= " t.dateo as date_start, t.datee as date_end";
2663 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2664 //$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
2665 //if (! $user->rights->societe->client->voir && ! $socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
2666 $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
2667 $sql .= " WHERE p.entity IN (".getEntity('project', 0).')';
2668 $sql .= " AND p.fk_statut = 1";
2669 $sql .= " AND t.fk_projet = p.rowid";
2670 $sql .= " AND (t.progress IS NULL OR t.progress < 100)"; // tasks to do
2671 if (!$user->hasRight('projet', 'all', 'lire')) {
2672 $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2673 }
2674 // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2675 //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).")";
2676 // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2677 // 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))";
2678
2679 //print $sql;
2680 $resql = $this->db->query($sql);
2681 if ($resql) {
2682 $task_static = new Task($this->db);
2683
2684 $response = new WorkboardResponse();
2685 $response->warning_delay = $conf->project->task->warning_delay / 60 / 60 / 24;
2686 $response->label = $langs->trans("OpenedTasks");
2687 if ($user->hasRight("projet", "all", "lire")) {
2688 $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mainmenu=project';
2689 } else {
2690 $response->url = DOL_URL_ROOT.'/projet/tasks/list.php?mode=mine&amp;mainmenu=project';
2691 }
2692 $response->img = img_object('', "task");
2693
2694 // This assignment in condition is not a bug. It allows walking the results.
2695 while ($obj = $this->db->fetch_object($resql)) {
2696 $response->nbtodo++;
2697
2698 $task_static->projectstatus = $obj->projectstatus;
2699 $task_static->progress = $obj->progress;
2700 $task_static->fk_statut = $obj->status;
2701 $task_static->status = $obj->status;
2702 $task_static->date_start = $this->db->jdate($obj->date_start);
2703 $task_static->date_end = $this->db->jdate($obj->date_end);
2704
2705 if ($task_static->hasDelay()) {
2706 $response->nbtodolate++;
2707 }
2708 }
2709
2710 return $response;
2711 } else {
2712 $this->error = $this->db->error();
2713 return -1;
2714 }
2715 }
2716
2717
2723 public function loadStateBoard()
2724 {
2725 global $user;
2726
2727 $mine = 0;
2728 $socid = $user->socid;
2729
2730 $projectstatic = new Project($this->db);
2731 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, $mine, 1, $socid);
2732
2733 // List of tasks (does not care about permissions. Filtering will be done later)
2734 $sql = "SELECT count(p.rowid) as nb";
2735 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
2736 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
2737 if (!$user->hasRight('societe', 'client', 'voir')) {
2738 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid";
2739 }
2740 $sql .= ", ".MAIN_DB_PREFIX."projet_task as t";
2741 $sql .= " WHERE p.entity IN (".getEntity('project', 0).')';
2742 $sql .= " AND t.fk_projet = p.rowid"; // tasks to do
2743 if ($mine || !$user->hasRight('projet', 'all', 'lire')) {
2744 $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
2745 }
2746 // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser
2747 //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).")";
2748 if ($socid) {
2749 $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".((int) $socid).")";
2750 }
2751 if (!$user->hasRight('societe', 'client', 'voir')) {
2752 $sql .= " AND ((s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id).") OR (s.rowid IS NULL))";
2753 }
2754
2755 $resql = $this->db->query($sql);
2756 if ($resql) {
2757 // This assignment in condition is not a bug. It allows walking the results.
2758 while ($obj = $this->db->fetch_object($resql)) {
2759 $this->nb["tasks"] = $obj->nb;
2760 }
2761 $this->db->free($resql);
2762 return 1;
2763 } else {
2764 dol_print_error($this->db);
2765 $this->error = $this->db->error();
2766 return -1;
2767 }
2768 }
2769
2775 public function hasDelay()
2776 {
2777 global $conf;
2778
2779 if (!($this->progress >= 0 && $this->progress < 100)) {
2780 return false;
2781 }
2782
2783 $now = dol_now();
2784
2785 $datetouse = ($this->date_end > 0) ? $this->date_end : ((isset($this->datee) && $this->datee > 0) ? $this->datee : 0);
2786
2787 return ($datetouse > 0 && ($datetouse < ($now - $conf->project->task->warning_delay)));
2788 }
2789
2797 public function getKanbanView($option = '', $arraydata = null)
2798 {
2799 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2800
2801 $return = '<div class="box-flex-item box-flex-grow-zero">';
2802 $return .= '<div class="info-box info-box-sm info-box-kanban">';
2803 $return .= '<span class="info-box-icon bg-infobox-action">';
2804 $return .= img_picto('', $this->picto);
2805 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
2806 $return .= '</span>';
2807 $return .= '<div class="info-box-content">';
2808 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
2809 if ($selected >= 0) {
2810 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2811 }
2812 if (!empty($arraydata['projectlink'])) {
2813 //$tmpproject = $arraydata['project'];
2814 //$return .= '<br><span class="info-box-status ">'.$tmpproject->getNomProject().'</span>';
2815 $return .= '<br><span class="info-box-status ">'.$arraydata['projectlink'].'</span>';
2816 }
2817 //if (property_exists($this, 'budget_amount')) {
2818 //$return .= '<br><span class="info-box-label amount">'.$langs->trans("Budget").' : '.price($this->budget_amount, 0, $langs, 1, 0, 0, $conf->currency).'</span>';
2819 //}
2820 if (property_exists($this, 'duration_effective')) {
2821 $return .= '<br><div class="info-box-label progressinkanban paddingtop">'.getTaskProgressView($this, false, true).'</div>';
2822 }
2823 $return .= '</div>';
2824 $return .= '</div>';
2825 $return .= '</div>';
2826
2827 return $return;
2828 }
2829
2837 public function mergeTask($task_origin_id)
2838 {
2839 global $langs, $hookmanager, $user, $action;
2840
2841 $error = 0;
2842 $task_origin = new Task($this->db); // The thirdparty that we will delete
2843
2844 dol_syslog("mergeTask merge task id=".$task_origin_id." (will be deleted) into the task id=".$this->id);
2845
2846 $langs->load('error');
2847
2848 if (!$error && $task_origin->fetch($task_origin_id) < 1) {
2849 $this->error = $langs->trans('ErrorRecordNotFound');
2850 $error++;
2851 }
2852
2853 if (!$error) {
2854 $this->db->begin();
2855
2856 // Recopy some data
2857 $listofproperties = array(
2858 'label', 'description', 'duration_effective', 'planned_workload', 'datec', 'date_start',
2859 'date_end', 'fk_user_creat', 'fk_user_valid', 'fk_statut', 'progress', 'budget_amount',
2860 'priority', 'rang', 'fk_projet', 'fk_task_parent'
2861 );
2862 foreach ($listofproperties as $property) {
2863 if (empty($this->$property)) {
2864 $this->$property = $task_origin->$property;
2865 }
2866 }
2867
2868 // Concat some data
2869 $listofproperties = array(
2870 'note_public', 'note_private'
2871 );
2872 foreach ($listofproperties as $property) {
2873 $this->$property = dol_concatdesc($this->$property, $task_origin->$property);
2874 }
2875
2876 // Merge extrafields
2877 if (is_array($task_origin->array_options)) {
2878 foreach ($task_origin->array_options as $key => $val) {
2879 if (empty($this->array_options[$key])) {
2880 $this->array_options[$key] = $val;
2881 }
2882 }
2883 }
2884
2885 // Update
2886 $result = $this->update($user);
2887
2888 if ($result < 0) {
2889 $error++;
2890 }
2891
2892 // Merge time spent
2893 if (!$error) {
2894 $result = $this->mergeTimeSpentTask($task_origin_id, $this->id);
2895 if ($result != true) {
2896 $error++;
2897 }
2898 }
2899
2900 // Merge contacts
2901 if (!$error) {
2902 $result = $this->mergeContactTask($task_origin_id, $this->id);
2903 if ($result != true) {
2904 $error++;
2905 }
2906 }
2907
2908 // External modules should update their ones too
2909 if (!$error) {
2910 $parameters = array('task_origin' => $task_origin->id, 'task_dest' => $this->id);
2911 $reshook = $hookmanager->executeHooks('replaceThirdparty', $parameters, $this, $action);
2912
2913 if ($reshook < 0) {
2914 $this->error = $hookmanager->error;
2915 $this->errors = $hookmanager->errors;
2916 $error++;
2917 }
2918 }
2919
2920
2921 if (!$error) {
2922 $this->context = array('merge' => 1, 'mergefromid' => $task_origin->id, 'mergefromref' => $task_origin->ref);
2923
2924 // Call trigger
2925 $result = $this->call_trigger('TASK_MODIFY', $user);
2926 if ($result < 0) {
2927 $error++;
2928 }
2929 // End call triggers
2930 }
2931
2932 if (!$error) {
2933 // We finally remove the old task
2934 if ($task_origin->delete($user) < 1) {
2935 $this->error = $task_origin->error;
2936 $this->errors = $task_origin->errors;
2937 $error++;
2938 }
2939 }
2940
2941 if (!$error) {
2942 $this->db->commit();
2943 return 0;
2944 } else {
2945 $langs->load("errors");
2946 $this->error = $langs->trans('ErrorsTaskMerge');
2947 $this->db->rollback();
2948 return -1;
2949 }
2950 }
2951
2952 return -1;
2953 }
2954}
$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