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