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