projecttask_ticket.class.php 18.9 KB
Newer Older
1
<?php
2
3
4
/**
 * ---------------------------------------------------------------------
 * GLPI - Gestionnaire Libre de Parc Informatique
5
 * Copyright (C) 2015-2021 Teclib' and contributors.
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 *
 * http://glpi-project.org
 *
 * based on GLPI - Gestionnaire Libre de Parc Informatique
 * Copyright (C) 2003-2014 by the INDEPNET Development Team.
 *
 * ---------------------------------------------------------------------
 *
 * LICENSE
 *
 * This file is part of GLPI.
 *
 * GLPI is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * GLPI is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GLPI. If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------
31
32
33
 */

if (!defined('GLPI_ROOT')) {
Stefan Weil's avatar
Stefan Weil committed
34
   die("Sorry. You can't access this file directly");
35
36
37
38
39
40
}

/**
 * ProjectTask_Ticket Class
 *
 * Relation between ProjectTasks and Tickets
yllen's avatar
yllen committed
41
 *
Anael Mobilia's avatar
Anael Mobilia committed
42
 * @since 0.85
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
**/
class ProjectTask_Ticket extends CommonDBRelation{

   // From CommonDBRelation
   static public $itemtype_1   = 'ProjectTask';
   static public $items_id_1   = 'projecttasks_id';

   static public $itemtype_2   = 'Ticket';
   static public $items_id_2   = 'tickets_id';



   function getForbiddenStandardMassiveAction() {

      $forbidden   = parent::getForbiddenStandardMassiveAction();
moyooo's avatar
moyooo committed
58
      $forbidden[] = 'update';
59
60
61
62
      return $forbidden;
   }


63
   static function getTypeName($nb = 0) {
64
      return _n('Link Ticket/Project task', 'Links Ticket/Project task', $nb);
65
66
   }

yllen's avatar
yllen committed
67

68
   function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
69
70
71
72
73
74

      if (static::canView()) {
         $nb = 0;
         switch ($item->getType()) {
            case 'ProjectTask' :
               if ($_SESSION['glpishow_count_on_tabs']) {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
75
                  $nb = self::countForItem($item);
76
               }
77
               return self::createTabEntry(Ticket::getTypeName(Session::getPluralNumber()), $nb);
78

79
80
            case 'Ticket' :
               if ($_SESSION['glpishow_count_on_tabs']) {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
81
                  $nb = self::countForItem($item);
82
83
               }
               return self::createTabEntry(ProjectTask::getTypeName(Session::getPluralNumber()), $nb);
84
85
86
87
88
89
         }
      }
      return '';
   }


90
   static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
91
92
93
94
95

      switch ($item->getType()) {
         case 'ProjectTask' :
            self::showForProjectTask($item);
            break;
96
97
98
99
100

         case 'Ticket' :
            self::showForTicket($item);
            break;

101
102
103
      }
      return true;
   }
yllen's avatar
yllen committed
104
105


106
   /**
moyooo's avatar
moyooo committed
107
    * Get total duration of tickets linked to a project task
108
    *
yllen's avatar
yllen committed
109
110
    * @param $projecttasks_id    integer    $projecttasks_id ID of the project task
    *
moyooo's avatar
moyooo committed
111
    * @return integer total actiontime
112
   **/
moyooo's avatar
moyooo committed
113
114
115
   static function getTicketsTotalActionTime($projecttasks_id) {
      global $DB;

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
      $iterator = $DB->request([
         'SELECT'       => new QueryExpression('SUM(glpi_tickets.actiontime) AS duration'),
         'FROM'         => self::getTable(),
         'INNER JOIN'   => [
            'glpi_tickets' => [
               'FKEY'   => [
                  self::getTable()  => 'tickets_id',
                  'glpi_tickets'    => 'id'
               ]
            ]
         ],
         'WHERE'        => ['projecttasks_id' => $projecttasks_id]
      ]);

      if ($row = $iterator->next()) {
         return $row['duration'];
moyooo's avatar
moyooo committed
132
133
      }
      return 0;
134
135
   }

yllen's avatar
yllen committed
136

137
138
139
140
141
142
143
144
145
146
147
148
149
150
   /**
    * Show tickets for a projecttask
    *
    * @param $projecttask ProjectTask object
   **/
   static function showForProjectTask(ProjectTask $projecttask) {
      $ID = $projecttask->getField('id');
      if (!$projecttask->can($ID, READ)) {
         return false;
      }

      $canedit = $projecttask->canEdit($ID);
      $rand    = mt_rand();

151
      $iterator = self::getListForItem($projecttask);
Johan Cwiklinski's avatar
Johan Cwiklinski committed
152
      $numrows = count($iterator);
153

154
155
      $tickets = [];
      $used    = [];
Johan Cwiklinski's avatar
Johan Cwiklinski committed
156
157
158
      while ($data = $iterator->next()) {
         $tickets[$data['id']] = $data;
         $used[$data['id']]    = $data['id'];
159
160
161
162
      }

      if ($canedit) {
         echo "<div class='firstbloc'>";
yllen's avatar
yllen committed
163
164
         echo "<form name='projecttaskticket_form$rand' id='projecttaskticket_form$rand'
                method='post' action='".Toolbox::getItemTypeFormURL(__CLASS__)."'>";
165
166
167
168
169
170

         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_2'><th colspan='3'>".__('Add a ticket')."</th></tr>";

         echo "<tr class='tab_bg_2'><td class='right'>";
         echo "<input type='hidden' name='projecttasks_id' value='$ID'>";
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
         $condition = [
            'NOT' => [
               'glpi_tickets.status'    => array_merge(
                  Ticket::getSolvedStatusArray(),
                  Ticket::getClosedStatusArray()
               )
            ]
         ];
         Ticket::dropdown([
            'used'        => $used,
            'entity'      => $projecttask->getEntityID(),
            'entity_sons' => $projecttask->isRecursive(),
            'condition'   => $condition,
            'displaywith' => ['id']
         ]);
yllen's avatar
yllen committed
186

187
         echo "</td><td width='20%'>";
188
         echo "<a href='".Toolbox::getItemTypeFormURL('Ticket')."?_projecttasks_id=$ID'>";
189
         echo __('Create a ticket from this task');
190
191
192
193
194
195
196
197
198
199
200
201
202
         echo "</a>";
         echo "</td><td class='center'>";
         echo "<input type='submit' name='add' value=\""._sx('button', 'Add')."\" class='submit'>";
         echo "</td></tr>";

         echo "</table>";
         Html::closeForm();
         echo "</div>";
      }

      echo "<div class='spaced'>";
      if ($canedit && $numrows) {
         Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
203
204
         $massiveactionparams = ['num_displayed'    => min($_SESSION['glpilist_limit'], $numrows),
                                      'container'        => 'mass'.__CLASS__.$rand];
205
206
207
208
209
210
211
         Html::showMassiveActions($massiveactionparams);
      }

      echo "<table class='tab_cadre_fixehov'>";
      echo "<tr><th colspan='12'>".Ticket::getTypeName($numrows)."</th>";
      echo "</tr>";
      if ($numrows) {
212
         Ticket::commonListHeader(Search::HTML_OUTPUT, 'mass'.__CLASS__.$rand);
213
214
215
         Session::initNavigateListItems('Ticket',
                                 //TRANS : %1$s is the itemtype name,
                                 //        %2$s is the name of the item (used for headings of a list)
moyooo's avatar
moyooo committed
216
                                         sprintf(__('%1$s = %2$s'), ProjectTask::getTypeName(1),
217
218
219
220
221
                                                 $projecttask->fields["name"]));

         $i = 0;
         foreach ($tickets as $data) {
            Session::addToNavigateListItems('Ticket', $data["id"]);
Cédric Anne's avatar
Cédric Anne committed
222
223
224
225
226
227
228
229
            Ticket::showShort(
               $data['id'],
               [
                  'row_num'                => $i,
                  'type_for_massiveaction' => __CLASS__,
                  'id_for_massiveaction'   => $data['linkid']
               ]
            );
230
231
232
233
234
235
236
237
238
239
240
241
            $i++;
         }
      }
      echo "</table>";
      if ($canedit && $numrows) {
         $massiveactionparams['ontop'] = false;
         Html::showMassiveActions($massiveactionparams);
         Html::closeForm();
      }
      echo "</div>";
   }

242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258

   /**
    * Show projecttasks for a ticket
    *
    * @param $ticket Ticket object
    **/
   static function showForTicket(Ticket $ticket) {
      global $DB, $CFG_GLPI;

      $ID = $ticket->getField('id');
      if (!$ticket->can($ID, READ)) {
         return false;
      }

      $canedit = $ticket->canEdit($ID);
      $rand    = mt_rand();

Johan Cwiklinski's avatar
Johan Cwiklinski committed
259
260
      $iterator = self::getListForItem($ticket);
      $numrows = count($iterator);
261

262
263
      $pjtasks = [];
      $used    = [];
Johan Cwiklinski's avatar
Johan Cwiklinski committed
264
265
266
      while ($data = $iterator->next()) {
         $pjtasks[$data['id']] = $data;
         $used[$data['id']]    = $data['id'];
267
268
      }

yllen's avatar
yllen committed
269
270
271
      if ($canedit
          && !in_array($ticket->fields['status'], array_merge($ticket->getClosedStatusArray(),
                                                              $ticket->getSolvedStatusArray()))) {
272
273
274
275
276
277
278
279
280
         echo "<div class='firstbloc'>";
         echo "<form name='projecttaskticket_form$rand' id='projecttaskticket_form$rand'
                 method='post' action='".Toolbox::getItemTypeFormURL(__CLASS__)."'>";

         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_2'><th colspan='4'>".__('Add a project task')."</th></tr>";

         $rand = mt_rand();

281
282
283
284
285
286
287
288
289
290
291
292
293
294
         $finished_states_it = $DB->request(
            [
               'SELECT' => ['id'],
               'FROM'   => ProjectState::getTable(),
               'WHERE'  => [
                  'is_finished' => 1
               ],
            ]
         );
         $finished_states_ids = [];
         foreach ($finished_states_it as $finished_state) {
            $finished_states_ids[] = $finished_state['id'];
         }

295
296
         echo "<tr class='tab_bg_2'><td class='right'>";
         echo Html::hidden('tickets_id', ['value' => $ID]);
297
298
299
300
301
302
         Project::dropdown([
            'entity'      => $ticket->getEntityID(),
            'entity_sons' => $ticket->isRecursive(),
            'condition'   => ['NOT' => ['glpi_projects.projectstates_id' => $finished_states_ids]],
            'rand'        => $rand
         ]);
303
304
305
306
307
308
309
310
311
312
313
314
315

         $p = ['projects_id'     => '__VALUE__',
               'entity_restrict' => $ticket->getEntityID(),
               'used'            => $used,
               'rand'            => $rand,
               'myname'          => "projects"];

         Ajax::updateItemOnSelectEvent("dropdown_projects_id$rand", "results_projects$rand",
                                       $CFG_GLPI["root_doc"].
                                       "/ajax/dropdownProjectTaskTicket.php",
                                       $p);

         echo "</td>";
316

317
318
319
320
321
322
323
324
325
326
327
         if (count($finished_states_ids)) {
            $where = [
               'OR'  => [
                  'projectstates_id'   => $finished_states_ids,
                  'is_template'        => 1
               ]
            ];
         } else {
            $where = ['is_template' => 1];
         }

328
329
330
331
         $excluded_projects_it = $DB->request(
            [
               'SELECT' => ['id'],
               'FROM'   => Project::getTable(),
332
               'WHERE'  => $where
333
334
            ]
         );
335
336
337
         $excluded_projects_ids = [];
         foreach ($excluded_projects_it as $excluded_project) {
            $excluded_projects_ids[] = $excluded_project['id'];
338
         }
339
340
         echo "<td class='right'>";
         echo "<span id='results_projects$rand'>";
341
342

         $dd_params = [
343
344
345
346
            'used'        => $used,
            'entity'      => $ticket->getEntityID(),
            'entity_sons' => $ticket->isRecursive(),
            'displaywith' => ['id']
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
         ];

         $condition = [];
         if (count($finished_states_ids)) {
            $condition['glpi_projecttasks.projectstates_id'] = $finished_states_ids;
         }
         if (count($excluded_projects_ids)) {
            $condition['glpi_projecttasks.projects_id'] = $excluded_projects_ids;
         }

         if (count($condition)) {
            $dd_params['condition'] = ['NOT' => $condition];
         }

         ProjectTask::dropdown($dd_params);
362
363
364
365
366
367
368
369
370
371
372
373
         echo "</span>";

         echo "</td><td width='20%'>";
         echo "</td><td class='center'>";
         echo Html::submit(_sx('button', 'Add'), ['name' => 'add']);
         echo "</td></tr>";

         echo "</table>";
         Html::closeForm();
         echo "</div>";
      }

374
      echo "<div class='spaced'>";
moyooo's avatar
moyooo committed
375

376
      if ($numrows) {
377
         $columns = ['projectname'      => Project::getTypeName(Session::getPluralNumber()),
moyooo's avatar
moyooo committed
378
                          'name'             => ProjectTask::getTypeName(Session::getPluralNumber()),
379
                          'tname'            => _n('Type', 'Types', 1),
380
381
382
383
384
385
                          'sname'            => __('Status'),
                          'percent_done'     => __('Percent done'),
                          'plan_start_date'  => __('Planned start date'),
                          'plan_end_date'    => __('Planned end date'),
                          'planned_duration' => __('Planned duration'),
                          '_effect_duration' => __('Effective duration'),
386
                          'fname'            => __('Father'),];
387

388
389
390
391
392
         if (isset($_GET["order"]) && ($_GET["order"] == "DESC")) {
            $order = "DESC";
         } else {
            $order = "ASC";
         }
393

394
395
396
         if (!isset($_GET["sort"]) || empty($_GET["sort"])) {
            $_GET["sort"] = "plan_start_date";
         }
397

398
         if (isset($_GET["sort"]) && !empty($_GET["sort"]) && isset($columns[$_GET["sort"]])) {
399
            $sort = $_GET["sort"];
400
         } else {
401
            $sort = ["plan_start_date $order", 'name'];
402
         }
Johan Cwiklinski's avatar
Johan Cwiklinski committed
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
         $iterator = $DB->request([
            'SELECT'    => [
               'glpi_projecttasks.*',
               'glpi_projecttasktypes.name AS tname',
               'glpi_projectstates.name AS sname',
               'glpi_projectstates.color',
               'father.name AS fname',
               'father.id AS fID',
               'glpi_projects.name AS projectname',
               'glpi_projects.content AS projectcontent'
            ],
            'FROM'      => 'glpi_projecttasks',
            'LEFT JOIN' => [
               'glpi_projecttasktypes' => [
                  'ON' => [
                     'glpi_projecttasktypes' => 'id',
                     'glpi_projecttasks'     => 'projecttasktypes_id'
                  ]
               ],
               'glpi_projectstates'    => [
                  'ON' => [
                     'glpi_projectstates' => 'id',
                     'glpi_projecttasks'  => 'projectstates_id'
                  ]
               ],
               'glpi_projecttasks AS father' => [
                  'ON' => [
                     'father'             => 'id',
                     'glpi_projecttasks'  => 'projecttasks_id'
                  ]
               ],
               'glpi_projecttasks_tickets'   => [
                  'ON' => [
                     'glpi_projecttasks_tickets'   => 'projecttasks_id',
                     'glpi_projecttasks'           => 'id'
                  ]
               ],
               'glpi_projects'               => [
                  'ON' => [
                     'glpi_projecttasks'  => 'projects_id',
                     'glpi_projects'      => 'id'
                  ]
               ]
            ],
            'WHERE'     => [
               'glpi_projecttasks_tickets.tickets_id' => $ID
            ],
            'ORDERBY'   => [
               "$sort $order"
            ]
         ]);
454
455
456
457
458
459
460

         Session::initNavigateListItems('ProjectTask',
                                        //TRANS : %1$s is the itemtype name,
                                        //       %2$s is the name of the item (used for headings of a list)
                                        sprintf(__('%1$s = %2$s'), $ticket::getTypeName(1),
                                                $ticket->getName()));

Johan Cwiklinski's avatar
Johan Cwiklinski committed
461
462
463
464
465
466
467
468
469
470
471
         if (count($iterator)) {
            echo "<table class='tab_cadre_fixehov'>";
            echo "<tr><th colspan='10'>".ProjectTask::getTypeName($numrows)."</th>";
            echo "</tr>";

            $header = '<tr>';
            foreach ($columns as $key => $val) {
               // Non order column
               if ($key[0] == '_') {
                  $header .= "<th>$val</th>";
               } else {
472
                  $header .= "<th".($sort == "$key" ? " class='order_$order'" : '').">".
Johan Cwiklinski's avatar
Johan Cwiklinski committed
473
474
                              "<a href='javascript:reloadTab(\"sort=$key&amp;order=".
                                 (($order == "ASC") ?"DESC":"ASC")."&amp;start=0\");'>$val</a></th>";
475
               }
Johan Cwiklinski's avatar
Johan Cwiklinski committed
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
            }
            $header .= "</tr>\n";
            echo $header;

            while ($data = $iterator->next()) {
               Session::addToNavigateListItems('ProjectTask', $data['id']);
               $rand = mt_rand();
               echo "<tr class='tab_bg_2'>";
               echo "<td>";
               $link = "<a id='Project".$data["projects_id"].$rand."' href='".
                           Project::getFormURLWithID($data['projects_id'])."'>".$data['projectname'].
                           (empty($data['projectname'])?"(".$data['projects_id'].")":"")."</a>";
               echo sprintf(__('%1$s %2$s'), $link,
                              Html::showToolTip($data['projectcontent'],
                                                ['display' => false,
                                                      'applyto' => "Project".$data["projects_id"].$rand]));
               echo "</td>";
               echo "<td>";
               $link = "<a id='ProjectTask".$data["id"].$rand."' href='".
                           ProjectTask::getFormURLWithID($data['id'])."'>".$data['name'].
                           (empty($data['name'])?"(".$data['id'].")":"")."</a>";
               echo sprintf(__('%1$s %2$s'), $link,
                              Html::showToolTip($data['content'],
                                                ['display' => false,
                                                      'applyto' => "ProjectTask".$data["id"].$rand]));
               echo "</td>";
               echo "<td>".$data['tname']."</td>";
               echo "<td";
               echo " style=\"background-color:".$data['color']."\"";
               echo ">".$data['sname']."</td>";
               echo "<td>";
               echo Dropdown::getValueWithUnit($data["percent_done"], "%");
               echo "</td>";
               echo "<td>".Html::convDateTime($data['plan_start_date'])."</td>";
               echo "<td>".Html::convDateTime($data['plan_end_date'])."</td>";
               echo "<td>".Html::timestampToString($data['planned_duration'], false)."</td>";
               echo "<td>".Html::timestampToString(ProjectTask::getTotalEffectiveDuration($data['id']),
                                                   false)."</td>";
               echo "<td>";
               if ($data['projecttasks_id']>0) {
                  $father = Dropdown::getDropdownName('glpi_projecttasks', $data['projecttasks_id']);
                  echo "<a id='ProjectTask".$data["projecttasks_id"].$rand."' href='".
                        ProjectTask::getFormURLWithID($data['projecttasks_id'])."'>".$father.
                        (empty($father)?"(".$data['projecttasks_id'].")":"")."</a>";
520
               }
Johan Cwiklinski's avatar
Johan Cwiklinski committed
521
               echo "</td></tr>";
522
            }
Johan Cwiklinski's avatar
Johan Cwiklinski committed
523
524
525
526
527
528
            echo $header;
            echo "</table>\n";
         } else {
            echo "<table class='tab_cadre_fixe'>";
            echo "<tr><th>".__('No item found')."</th></tr>";
            echo "</table>\n";
529
         }
530
         echo "</div>";
531
532
533
      }
   }

534
}