Debian Codegraph @

src/plugins/schedulers/tj/taskjuggler/Task.cpp

raw
1 /*
2 * Task.cpp - TaskJuggler
3 *
4 * Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006
5 * Chris Schlaeger <[email protected]>
6 * SPDX-FileCopyrightText: 2011 Dag Andersen <[email protected]>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of version 2 of the GNU General Public License as
10 * published by the Free Software Foundation.
11 *
12 * $Id$
13 */
14
15 // clazy:excludeall=qstring-arg
16 #include "Task.h"
17
18 #include <KLocalizedString>
19
20 #include <stdlib.h>
21 #include <math.h>
22 #include <assert.h>
23
24 #include "TjMessageHandler.h"
25 #include "tjlib-internal.h"
26 #include "Resource.h"
27 // #include "Account.h"
28 #include "Project.h"
29 #include "ResourceTreeIterator.h"
30 #include "Allocation.h"
31 #include "Booking.h"
32 // #include "ReportXML.h"
33 #include "Scenario.h"
34 #include "CustomAttributeDefinition.h"
35 #include "UsageLimits.h"
36 #include "Shift.h"
37 #include "ShiftSelection.h"
38
39 #include <QExplicitlySharedDataPointer>
40
41 namespace TJ
42 {
43
44 Task::Task(Project* proj, const QString& id_, const QString& n, Task* p,
45 const QString& df, int dl) :
46 CoreAttributes(proj, id_, n, p, df, dl),
47 note(),
48 // journal(),
49 ref(),
50 refLabel(),
51 depends(),
52 precedes(),
53 predecessors(),
54 successors(),
55 previous(),
56 followers(),
57 projectId(),
58 milestone(false),
59 priority(0),
60 scheduling(ASAP),
61 responsible(nullptr),
62 shifts(),
63 allocations(),
64 // account(0),
65 scenarios(new TaskScenario[proj->getMaxScenarios()]),
66 start(0),
67 end(0),
68 length(0.0),
69 effort(0.0),
70 duration(0.0),
71 doneEffort(0.0),
72 doneLength(0.0),
73 doneDuration(0.0),
74 workStarted(false),
75 tentativeStart(0),
76 tentativeEnd(0),
77 lastSlot(0),
78 schedulingDone(false),
79 runAway(false),
80 bookedResources()
81 {
82 // qDebug()<<"Task:"<<this;
83 Q_ASSERT(proj->getMaxScenarios() > 0);
84 // allocations.setAutoDelete(true);
85 // shifts.setAutoDelete(true);
86 // depends.setAutoDelete(true);
87 // precedes.setAutoDelete(true);
88
89 proj->addTask(this);
90
91 for (int i = 0; i < proj->getMaxScenarios(); i++)
92 {
93 scenarios[i].task = this;
94 scenarios[i].index = i;
95 }
96
97 scenarios[0].startBuffer = 0.0;
98 scenarios[0].endBuffer = 0.0;
99 scenarios[0].startCredit = 0.0;
100 scenarios[0].endCredit = 0.0;
101
102 for (int sc = 0; sc < project->getMaxScenarios(); ++sc)
103 {
104 scenarios[sc].minStart = scenarios[sc].minEnd = 0;
105 scenarios[sc].maxStart = scenarios[sc].maxEnd = 0;
106 }
107 Q_ASSERT(duration == 0.0);
108 Q_ASSERT(length == 0.0);
109 Q_ASSERT(effort == 0.0);
110 }
111
112 Task::~Task()
113 {
114 // qDebug()<<"~Task:"<<this;
115 project->deleteTask(this);
116 delete [] scenarios;
117 qDeleteAll(depends);
118 qDeleteAll(precedes);
119 qDeleteAll(allocations);
120 }
121
122 void
123 Task::inheritValues()
124 {
125 Task* p = static_cast<Task*>(parent);
126 if (p)
127 {
128 // Inherit flags from parent task.
129 for (QStringList::ConstIterator it = p->flags.constBegin();
130 it != p->flags.constEnd(); ++it)
131 addFlag(*it);
132
133 // Set attributes that are inherited from parent task.
134 projectId = p->projectId;
135 priority = p->priority;
136 responsible = p->responsible;
137 // account = p->account;
138 scheduling = p->scheduling;
139
140 for (int sc = 0; sc < project->getMaxScenarios(); ++sc)
141 {
142 scenarios[sc].minStart = p->scenarios[sc].minStart;
143 scenarios[sc].maxStart = p->scenarios[sc].maxEnd;
144 scenarios[sc].minEnd = p->scenarios[sc].minStart;
145 scenarios[sc].maxEnd = p->scenarios[sc].maxEnd;
146 }
147 // Inherit depends from parent. Relative IDs need to get another '!'.
148 for (QListIterator<TaskDependency*> tdi(p->depends); tdi.hasNext();)
149 {
150 TaskDependency *tdc = static_cast<TaskDependency*>(tdi.next());
151 QString id = tdc->getTaskRefId();
152 if (id[0] == '!')
153 id = '!' + id;
154 TaskDependency* td = new TaskDependency(id,
155 project->getMaxScenarios());
156 for (int sc = 0; sc < project->getMaxScenarios(); ++sc)
157 {
158 td->setGapDuration(sc, tdc->getGapDurationNR(sc));
159 td->setGapLength(sc, tdc->getGapLengthNR(sc));
160 }
161 depends.append(td);
162 }
163
164 // Inherit precedes from parent. Relative IDs need to get another '!'.
165 for (QListIterator<TaskDependency*> tdi(p->precedes); tdi.hasNext();)
166 {
167 TaskDependency *tdc = static_cast<TaskDependency*>(tdi.next());
168 QString id = tdc->getTaskRefId();
169 if (id[0] == '!')
170 id = '!' + id;
171 TaskDependency* td = new TaskDependency(id,
172 project->getMaxScenarios());
173 for (int sc = 0; sc < project->getMaxScenarios(); ++sc)
174 {
175 td->setGapDuration(sc, tdc->getGapDurationNR(sc));
176 td->setGapLength(sc, tdc->getGapLengthNR(sc));
177 }
178 precedes.append(td);
179 }
180
181 // Inherit allocations from parent.
182 for (QListIterator<Allocation*> ali(p->allocations); ali.hasNext();) {
183 allocations.append(new Allocation(*(ali.next())));
184 }
185
186 // Inherit inheritable custom attributes
187 inheritCustomAttributes(project->getTaskAttributeDict());
188 }
189 else
190 {
191 // Set attributes that are inherited from global attributes.
192 projectId = project->getCurrentId();
193 priority = project->getPriority();
194 for (int sc = 0; sc < project->getMaxScenarios(); ++sc)
195 {
196 scenarios[sc].minStart = scenarios[sc].minEnd = 0;
197 scenarios[sc].maxStart = scenarios[sc].maxEnd = 0;
198 }
199 }
200 }
201
202 // void
203 // Task::addJournalEntry(JournalEntry* entry)
204 // {
205 // journal.inSort(entry);
206 // }
207 //
208 // Journal::Iterator
209 // Task::getJournalIterator() const
210 // {
211 // return Journal::Iterator(journal);
212 // }
213
214 TaskDependency*
215 Task::addDepends(const QString& rid)
216 {
217 for (TaskDependency *d : std::as_const(depends)) {
218 if (rid == d->getTaskRefId()) {
219 return d;
220 }
221 }
222 TaskDependency* td = new TaskDependency(rid, project->getMaxScenarios());
223 depends.append(td);
224 return td;
225 }
226
227 TaskDependency*
228 Task::addPrecedes(const QString& rid)
229 {
230 for (TaskDependency *d : std::as_const(precedes)) {
231 if (rid == d->getTaskRefId()) {
232 return d;
233 }
234 }
235 TaskDependency* td = new TaskDependency(rid, project->getMaxScenarios());
236 precedes.append(td);
237 return td;
238 }
239
240 bool
241 Task::addShift(const Interval& i, Shift* s)
242 {
243 return shifts.insert(new ShiftSelection(i, s));
244 }
245
246 void
247 Task::errorMessage(const QString& msg) const
248 {
249 TJMH.errorMessage(msg, this);
250 // TJMH.errorMessage(msg, definitionFile, definitionLine);
251 }
252
253 void
254 Task::warningMessage(const QString& msg) const
255 {
256 TJMH.warningMessage(msg, this);
257 // TJMH.warningMessage(msg, definitionFile, definitionLine);
258 }
259
260 bool
261 Task::isWorkingTime(const Interval& slot) const
262 {
263 if (shifts.isEmpty()) {
264 return project->isWorkingTime(slot);
265 }
266 for (ShiftSelectionList::Iterator ssli(shifts); ssli.hasNext();) {
267 ShiftSelection *s = ssli.next();
268 if (s->getPeriod().contains(slot))
269 return s->getShift()->isOnShift(slot);
270 }
271 return false;
272 }
273
274 bool
275 Task::schedule(int sc, time_t& date, time_t slotDuration)
276 {
277 // Has the task been scheduled already or is it a container?
278 if (schedulingDone || !sub->isEmpty())
279 return false;
280
281 if (DEBUGTS(15))
282 qDebug()<<QString("Trying to schedule %1 at %2").arg(name).arg(time2tjp(date));
283
284 if (scheduling == Task::ASAP)
285 {
286 if (start == 0 ||
287 (effort == 0.0 && length == 0.0 && duration == 0.0 && end == 0)) {
288 if (start == 0) {
289 warningMessage(xi18nc("@info/plain", "Cannot schedule: Valid start time is not set"));
290 } else {
291 warningMessage(xi18nc("@info/plain", "Cannot schedule: Estimate is 0"));
292 }
293 return false;
294 }
295
296 if (lastSlot == 0)
297 {
298 lastSlot = start - 1;
299 tentativeEnd = date + slotDuration - 1;
300 if (DEBUGTS(5))
301 qDebug()<<"Scheduling of ASAP task"<<name<<"starts at"<<time2tjp(start)<<"("<<time2tjp(date)<<")";
302 }
303 /* Do not schedule anything if the time slot is not directly
304 * following the time slot that was previously scheduled.
305 * The project should get back to us later */
306 if (!((date - slotDuration <= lastSlot) && (lastSlot < date))) {
307 if (DEBUGTS(20)) {
308 qDebug()<<"Scheduling of ASAP task"<<name<<"not continuous slots:"<<time2tjp(date)<<"last:"<<time2tjp(lastSlot);
309 }
310 //warningMessage(xi18nc("info/plain", "ASAP: Not continuous slots: %1 last: %2", time2ISO(date), time2ISO(lastSlot)));
311 return false;
312 }
313
314 lastSlot = date + slotDuration - 1;
315 }
316 else
317 {
318 if (end == 0 ||
319 (effort == 0.0 && length == 0.0 && duration == 0.0 && start == 0)) {
320 if (end == 0) {
321 warningMessage(xi18nc("@info/plain", "Cannot schedule: Valid end time is not set"));
322 } else {
323 warningMessage(xi18nc("@info/plain", "Cannot schedule: Estimate is 0"));
324 }
325 return false;
326 }
327 if (lastSlot == 0)
328 {
329 lastSlot = end + 1;
330 tentativeStart = date;
331 if (DEBUGTS(5))
332 qDebug()<<"Scheduling of ALAP task"<<name<<"starts at"<<time2tjp(lastSlot)<<"("<<time2tjp(date)<<")";
333 }
334 /* Do not schedule anything if the current time slot is not
335 * directly preceding the previously scheduled time slot. */
336 if (!((date + slotDuration <= lastSlot) &&
337 (lastSlot < date + 2 * slotDuration)))
338 return false;
339 lastSlot = date;
340 }
341
342 if (DEBUGTS(10))
343 qDebug()<<"Scheduling"<<name<<"at"<<time2tjp(date);
344
345 if ((duration > 0.0) || (length > 0.0))
346 {
347 // TJMH.debugMessage(QString("Scheduling duration/length at: %1").arg(time2tjp(date)), this);
348 /* Length specifies the number of working days (as daily load)
349 * and duration specifies the number of calendar days. */
350 if (!allocations.isEmpty())
351 bookResources(sc, date, slotDuration);
352
353 doneDuration += ((double) slotDuration) / ONEDAY;
354 if (isWorkingTime(Interval(date, date + slotDuration - 1))) {
355 doneLength += project->convertToDailyLoad(slotDuration);
356 }
357
358 if (DEBUGTS(10))
359 qDebug("Length: %f/%f Duration: %f/%f",
360 doneLength, length,
361 doneDuration, duration);
362 // Check whether we are done with this task.
363 /* The accumulated done* values contain rounding errors. This prevents
364 * exact float comparisons. To avoid rounding problems we compare the
365 * rounded values of the done* values multiplied by 2048. This should
366 * result in worst case errors of smaller than a minute. The value
367 * 2048 was chosen in the hope that a compiler is clever enough to
368 * avoid a costly multiplication if possible. */
369 if ((length > 0.0 &&
370 qRound(doneLength * 2048) >= qRound(length * 2048)) ||
371 (duration > 0.0 &&
372 qRound(doneDuration * 2048) >= qRound(duration * 2048)))
373 {
374 if (scheduling == ASAP)
375 propagateEnd(sc, date + slotDuration - 1);
376 else
377 propagateStart(sc, date);
378 schedulingDone = true;
379 if (DEBUGTS(4)) {
380 qDebug()<<"Scheduling of task"<<name<<"completed";
381 if (length > 0.0) qDebug()<<"Length estimate:"<<length<<"done:"<<doneLength;
382 if (duration > 0.0) qDebug()<<"Duration estimate:"<<duration<<"done:"<<doneDuration;
383 }
384 if (length > 0.0) {
385 TJMH.debugMessage(QString("Task scheduled: %1 - %2, estimated length: %3").arg(time2ISO(start)).arg(time2ISO(end)).arg(length), this);
386 } else if (duration > 0.0) {
387 TJMH.debugMessage(QString("Task scheduled: %1 - %2, estimated duration: %3").arg(time2ISO(start)).arg(time2ISO(end)).arg(duration), this);
388 }
389 return true;
390 }
391 }
392 else if (effort > 0.0)
393 {
394 // TJMH.debugMessage(QString("Scheduling effort %2 at: %1").arg(time2tjp(date)).arg(effort), this);
395 /* The effort of the task has been specified. We have to look
396 * how much the resources can contribute over the following
397 * workings days until we have reached the specified
398 * effort. */
399 bookResources(sc, date, slotDuration);
400 // Check whether we are done with this task.
401 if (qRound(doneEffort * 2048) >= qRound(effort * 2048))
402 {
403 if (scheduling == ASAP)
404 propagateEnd(sc, tentativeEnd);
405 else
406 propagateStart(sc, tentativeStart);
407 schedulingDone = true;
408 if (DEBUGTS(4)) {
409 qDebug()<<"Scheduling of task"<<this<<"completed:"<<time2ISO(start)<<"-"<<time2ISO(end);
410 qDebug()<<"Effort estimate:"<<effort<<"done:"<<doneEffort;
411 }
412 TJMH.debugMessage(QString("Task scheduled: %3 - %4, estimated effort=%1d, booked=%2d").arg(effort).arg(doneEffort).arg(time2ISO(start)).arg(time2ISO(end)), this);
413 return true;
414 }
415 }
416 else if (milestone)
417 {
418 // Task is a milestone.
419 if (scheduling == ASAP)
420 propagateEnd(sc, start - 1);
421 else
422 propagateStart(sc, end + 1);
423
424 if (DEBUGTS(4)) {
425 qDebug()<<"Scheduling of task"<<this<<"completed:"<<time2ISO(start)<<"-"<<time2ISO(end);
426 }
427 TJMH.debugMessage(QString("Milestone scheduled: %1").arg(time2ISO(start)), this);
428 return true;
429 }
430 else if (start != 0 && end != 0)
431 {
432 // Task with start and end date but no duration criteria.
433 if (!allocations.isEmpty() && !project->isVacation(date))
434 bookResources(sc, date, slotDuration);
435
436 if ((scheduling == ASAP && (date + slotDuration) >= end) ||
437 (scheduling == ALAP && date <= start))
438 {
439 schedulingDone = true;
440 if (DEBUGTS(4))
441 qDebug()<<"Scheduling of task"<<name<<"completed";
442 TJMH.debugMessage(QString("Task scheduled: %1 - %2").arg(time2ISO(start)).arg(time2ISO(end)), this);
443 return true;
444 }
445 }
446
447 return false;
448 }
449
450 bool
451 Task::scheduleContainer(int sc)
452 {
453 if (schedulingDone || !isContainer())
454 return true;
455
456 time_t nStart = 0;
457 time_t nEnd = 0;
458
459 for (TaskListIterator tli(*sub); tli.hasNext();)
460 {
461 Task *t = static_cast<Task*>(tli.next());
462 /* Make sure that all sub tasks have been scheduled. If not we
463 * can't yet schedule this task. */
464 if (t->start == 0 || t->end == 0)
465 return true;
466
467 if (nStart == 0 || t->start < nStart)
468 nStart = t->start;
469 if (t->end > nEnd)
470 nEnd = t->end;
471 }
472
473 if (start == 0 || start > nStart)
474 propagateStart(sc, nStart);
475
476 if (end == 0 || end < nEnd)
477 propagateEnd(sc, nEnd);
478
479 if (DEBUGTS(4))
480 qDebug()<<QString("Scheduling of task %1 completed").arg(name);
481 schedulingDone = true;
482
483 return false;
484 }
485
486 bool
487 Task::hasAlapPredecessor() const
488 {
489 for (const CoreAttributes *t : std::as_const(predecessors)) {
490 if (static_cast<const Task*>(t)->getScheduling() == TJ::Task::ALAP || static_cast<const Task*>(t)->hasAlapPredecessor()) {
491 return true;
492 }
493 }
494 return false;
495 }
496
497 void
498 Task::propagateStart(int sc, time_t date)
499 {
500 start = date;
501
502 if (DEBUGTS(11))
503 qDebug()<<"PS1: Setting start of"<<this<<"to"<<time2tjp(start);
504
505 // TJMH.debugMessage(QString("Set start: %2 ").arg(time2ISO(start)), this);
506
507 /* If one end of a milestone is fixed, then the other end can be set as
508 * well. */
509 if (milestone && date > 0)
510 {
511 if (!schedulingDone) {
512 schedulingDone = true;
513 propagateEnd(sc, start - 1);
514 if (DEBUGTS(4)) {
515 qDebug()<<"Scheduling:"<<this<<"completed:"<<time2ISO(start)<<"-"<<time2ISO(end);
516 }
517
518 }
519 // schedule successor ASAP milestones
520 for (TaskListIterator tli(followers); tli.hasNext();) {
521 Task *t = static_cast<Task*>(tli.next());
522 if (t->milestone && !t->schedulingDone && t->scheduling == ASAP &&
523 t->start == 0 && t->latestEnd(sc) != 0)
524 {
525 /* Recursively propagate the start date */
526 t->propagateEnd(sc, t->latestEnd(sc));
527 }
528 }
529 }
530 /* Set start date to all previous that have no start date yet, but are
531 * ALAP task or have no duration. */
532 for (TaskListIterator tli(previous); *tli != nullptr; ++tli) {
533 if ((*tli)->end == 0 && (*tli)->latestEnd(sc) != 0 &&
534 !(*tli)->schedulingDone &&
535 ((*tli)->scheduling == ALAP ||
536 ((*tli)->effort == 0.0 && (*tli)->length == 0.0 &&
537 (*tli)->duration == 0.0 && !(*tli)->milestone)))
538 {
539 /* Recursively propagate the end date */
540 (*tli)->propagateEnd(sc, (*tli)->latestEnd(sc));
541 }
542 }
543 /* Propagate start time to sub tasks which have only an implicit
544 * dependency on the parent task. Do not touch container tasks. */
545 for (TaskListIterator tli(*sub); tli.hasNext();)
546 {
547 Task *t = static_cast<Task*>(tli.next());
548 if (!t->hasStartDependency() && !t->schedulingDone)
549 {
550 /* Recursively propagate the start date */
551 t->propagateStart(sc, start);
552 }
553 }
554
555 if (parent)
556 {
557 if (DEBUGTS(11))
558 qDebug()<<"Scheduling parent of"<<name;
559 getParent()->scheduleContainer(sc);
560 }
561 }
562
563 void
564 Task::propagateEnd(int sc, time_t date)
565 {
566 end = date;
567
568 if (DEBUGTS(11))
569 qDebug()<<"PE1: Setting end of"<<name<<"to"<<time2tjp(end);
570
571 // TJMH.debugMessage(QString("Set end: %2 ").arg(time2ISO(end)), this);
572 /* If one end of a milestone is fixed, then the other end can be set as
573 * well. */
574 if (milestone && date > 0)
575 {
576 if (!schedulingDone) {
577 schedulingDone = true;
578 propagateStart(sc, end + 1);
579 if (DEBUGTS(4)) {
580 qDebug()<<"Scheduling:"<<this<<"completed:"<<time2ISO(start)<<"-"<<time2ISO(end);
581 }
582 }
583 // schedule predecessor ALAP milestones
584 for (TaskListIterator tli(previous); tli.hasNext();) {
585 Task *t = static_cast<Task*>(tli.next());
586 if (t->milestone && !t->schedulingDone && t->scheduling == ALAP &&
587 t->start == 0 && t->earliestStart(sc) != 0)
588 {
589 /* Recursively propagate the start date */
590 t->propagateEnd(sc, t->latestEnd(sc));
591 }
592 }
593 }
594
595 /* Set start date to all followers that have no start date yet, but are
596 * ASAP task or have no duration. */
597 for (TaskListIterator tli(followers); tli.hasNext();) {
598 Task *t = static_cast<Task*>(tli.next());
599 if (t->start == 0 && t->earliestStart(sc) != 0 &&
600 !t->schedulingDone &&
601 (t->scheduling == ASAP ||
602 (t->effort == 0.0 && t->length == 0.0 &&
603 t->duration == 0.0 && !t->milestone)))
604 {
605 /* Recursively propagate the start date */
606 t->propagateStart(sc, t->earliestStart(sc));
607 }
608 }
609 /* Propagate end time to sub tasks which have only an implicit
610 * dependency on the parent task. Do not touch container tasks. */
611 for (TaskListIterator tli(*sub); tli.hasNext();) {
612 Task *t = static_cast<Task*>(tli.next());
613 if (!t->hasEndDependency() && !t->schedulingDone)
614 {
615 /* Recursively propagate the end date */
616 t->propagateEnd(sc, end);
617 }
618 }
619 if (parent)
620 {
621 if (DEBUGTS(11))
622 qDebug()<<"Scheduling parent of"<<name;
623 getParent()->scheduleContainer(sc);
624 }
625 }
626
627 void
628 Task::propagateInitialValues(int sc)
629 {
630 if (start != 0)
631 propagateStart(sc, start);
632 if (end != 0)
633 propagateEnd(sc, end);
634
635 // Check if the some data of sub tasks can already be propagated.
636 if (!sub->isEmpty())
637 scheduleContainer(sc);
638 }
639
640 void
641 Task::setRunaway()
642 {
643 schedulingDone = true;
644 runAway = true;
645 }
646
647 bool
648 Task::isRunaway() const
649 {
650 /* If a container task has runaway sub tasts, it is very likely that they
651 * are the culprits. So we don't report such a container task as runaway.
652 */
653 for (TaskListIterator tli(*sub); tli.hasNext();) {
654 Task *t = static_cast<Task*>(tli.next());
655 if (t->isRunaway())
656 return false;
657 }
658 return runAway;
659 }
660
661 int
662 Task::isAvailable(Allocation *allocation, Resource *resource, time_t slot) const
663 {
664 int max = resource->isAvailable(slot);
665 if (allocation->hasRequiredResources(resource)) {
666 const auto lst = allocation->getRequiredResources(resource);
667 for (Resource *r : lst) {
668 int a = r->isAvailable(slot);
669 if (a > max) {
670 // TJMH.debugMessage(QString("Required resource '%1' is not available at %2").arg(r->getName()).arg(time2ISO(slot)), this);
671 max = a;
672 }
673 }
674 }
675 return max;
676 }
677
678 void
679 Task::bookResources(int sc, time_t date, time_t slotDuration)
680 {
681 /* If the time slot overlaps with a specified shift interval, the
682 * time slot must also be within the specified working hours of that
683 * shift interval. */
684 if (!shifts.isOnShift(Interval(date, date + slotDuration - 1)))
685 {
686 if (DEBUGRS(15))
687 qDebug()<<"Task"<<name<<"is not active at"<<time2tjp(date);
688
689 // TJMH.debugMessage(QString("Task is not active at %1").arg(time2tjp(date)), this);
690 return;
691 }
692
693 /* In projection mode we do not allow bookings prior to the current date
694 * for any task (in strict mode) or tasks which have user specified
695 * bookings (sloppy mode). */
696 if (project->getScenario(sc)->getProjectionMode() &&
697 date < project->getNow() &&
698 (project->getScenario(sc)->getStrictBookings() ||
699 !scenarios[sc].specifiedBookedResources.isEmpty()))
700 {
701 if (DEBUGRS(15))
702 qDebug()<<"No allocations prior to current date for task"<<id;
703
704 TJMH.debugMessage(QString("Allocations prior to 'now' %1 is not allowed").arg(time2tjp(project->getNow())), this);
705 return;
706 }
707
708 /* If any of the resources is marked as being mandatory, we have to check
709 * if this resource is available. In case it's not available we do not
710 * allocate any of the other resources for the time slot. */
711 bool allMandatoriesAvailables = true;
712 QList<Resource*> mandatoryResources;
713 for (QListIterator<Allocation*> ali(allocations); ali.hasNext();) {
714 Allocation *a = static_cast<Allocation*>(ali.next());
715 if (a->isMandatory())
716 {
717 if (!a->isOnShift(Interval(date, date + slotDuration - 1)))
718 {
719 // TJMH.debugMessage(QString("Mandatory allocation not on shift at: %1").arg(time2tjp(date)), this);
720 allMandatoriesAvailables = false;
721 break;
722 }
723 if (a->isPersistent() && a->getLockedResource())
724 {
725 int availability = isAvailable(a, a->getLockedResource(), date);
726 if (availability > 0)
727 {
728 allMandatoriesAvailables = false;
729 if (availability >= 4 && !a->getConflictStart())
730 a->setConflictStart(date);
731 break;
732 }
733 }
734 else
735 {
736 /* For a mandatory allocation with alternatives at least one
737 * of the resources or resource groups must be available. */
738 bool found = false;
739 int maxAvailability = 0;
740 QList<Resource*> candidates = a->getCandidates();
741 for (Resource *r : std::as_const(candidates))
742 {
743 /* If a resource group is marked mandatory, all members
744 * of the group must be available. */
745 int availability = 0;
746 bool allAvailable = true;
747 for (ResourceTreeIterator rti(r); *rti != nullptr; ++rti) {
748 if ((availability = isAvailable(a, (*rti), date)) > 0 ||
749 mandatoryResources.contains(*rti))
750 {
751 // TJMH.debugMessage(QString("Mandatory resource '%2' not available at: %1").arg(time2tjp(date)).arg((*rti)->getName()), this);
752 allAvailable = false;
753 if (availability >= maxAvailability)
754 maxAvailability = availability;
755 }
756 else {
757 mandatoryResources.append(*rti);
758 // TJMH.debugMessage(QString("Mandatory resource '%2' available at: %1").arg(time2tjp(date)).arg((*rti)->getName()));
759 }
760 }
761 if (allAvailable)
762 found = true;
763 }
764 if (!found)
765 {
766 if (maxAvailability >= 4 && !a->getConflictStart())
767 a->setConflictStart(date);
768 allMandatoriesAvailables = false;
769 break;
770 }
771 }
772 }
773 }
774 if (! allMandatoriesAvailables) {
775 // TJMH.debugMessage(QString("All mandatory resourcea are not available"), this);
776 }
777 for (QListIterator<Allocation*> ali(allocations);
778 ali.hasNext() && allMandatoriesAvailables &&
779 (effort == 0.0 || doneEffort < effort);)
780 {
781 /* If a shift has been defined for a resource for this task, there
782 * must be a shift interval defined for this day and the time must
783 * be within the working hours of that shift. */
784 Allocation *a = static_cast<Allocation*>(ali.next());
785 if (!a->isOnShift(Interval(date, date + slotDuration - 1)))
786 {
787 if (DEBUGRS(15))
788 qDebug()<<"Allocation not on shift at"<<time2tjp(date);
789
790 // TJMH.debugMessage(QString("Allocation not on shift at: %1").arg(time2tjp(date)), this);
791 continue;
792 }
793
794 /* Now check the limits set for this allocation. */
795 const UsageLimits* limits = a->getLimits();
796 /* This variable holds the number of slots that are still available to
797 * hit the nearest limit. -1 means unlimited slots. */
798 int slotsToLimit = -1;
799 if (limits)
800 {
801 QList<Resource*> resources = a->getCandidates();
802 QString resStr;
803 for (Resource *r : std::as_const(resources)) {
804 resStr += r->getId() + QLatin1Char(' ');
805 }
806 if (limits->getDailyUnits() > 0) {
807 uint bookedSlots = 0;
808 int workSlots = 0;
809 for (Resource *r : std::as_const(resources)) {
810 workSlots += r->getWorkSlots(date); // returns 0 if no bookings yet
811 bookedSlots += r->getCurrentDaySlots(date, this); // booked to this task
812 }
813 if (workSlots > 0) {
814 workSlots = (workSlots * limits->getDailyUnits()) / 100;
815 if (workSlots == 0) {
816 workSlots = 1;
817 }
818 }
819 int freeSlots = bookedSlots > 0 ? workSlots - bookedSlots : 1; // always allow one booking
820 if (freeSlots <= 0) {
821 if (DEBUGRS(6)) {
822 qDebug()<<" Resource(s)"<<resStr<<"overloaded";
823 }
824 continue;
825 } else if (slotsToLimit < 0 || slotsToLimit > freeSlots) {
826 slotsToLimit = freeSlots;
827 }
828 }
829 else if (limits->getDailyMax() > 0)
830 {
831 uint slotCount = 0;
832 for (Resource *r : std::as_const(resources))
833 slotCount += r->getCurrentDaySlots(date, this);
834 int freeSlots = limits->getDailyMax() - slotCount;
835 if (freeSlots <= 0)
836 {
837 if (DEBUGRS(6))
838 qDebug()<<" Resource(s)"<<resStr<<"overloaded";
839 continue;
840 }
841 else if (slotsToLimit < 0 || slotsToLimit > freeSlots)
842 slotsToLimit = freeSlots;
843 }
844 if (limits->getWeeklyMax() > 0)
845 {
846 uint slotCount = 0;
847 for (Resource *r : std::as_const(resources))
848 slotCount += r->getCurrentWeekSlots(date, this);
849 int freeSlots = limits->getWeeklyMax() - slotCount;
850 if (freeSlots <= 0)
851 {
852 if (DEBUGRS(6))
853 qDebug()<<" Resource(s)"<<resStr<<"overloaded";
854 continue;
855 }
856 else if (slotsToLimit < 0 || slotsToLimit > freeSlots)
857 slotsToLimit = freeSlots;
858 }
859 if (limits->getMonthlyMax() > 0)
860 {
861 uint slotCount = 0;
862 for (Resource *r : std::as_const(resources))
863 slotCount += r->getCurrentMonthSlots(date, this);
864 int freeSlots = limits->getMonthlyMax() - slotCount;
865 if (freeSlots <= 0)
866 {
867 if (DEBUGRS(6))
868 qDebug()<<" Resource(s)"<<resStr<<"overloaded";
869 continue;
870 }
871 else if (slotsToLimit < 0 || slotsToLimit > freeSlots)
872 slotsToLimit = freeSlots;
873 }
874 }
875
876 /* If the allocation has be marked persistent and a resource
877 * has already been picked, try to book this resource again. If the
878 * resource is not available there will be no booking for this
879 * time slot. */
880 int maxAvailability = 0;
881 if (a->isPersistent() && a->getLockedResource())
882 {
883 if (!bookResource(a, a->getLockedResource(), date, slotDuration,
884 slotsToLimit, maxAvailability))
885 {
886 if (maxAvailability >= 4 && !a->getConflictStart())
887 a->setConflictStart(date);
888 }
889 else if (a->getConflictStart())
890 {
891 if (DEBUGRS(2))
892 qDebug()<<"Resource"<<a->getLockedResource()->getId()<<"is not available for task '"<<id<<"'"
893 <<"from"<<time2ISO(a->getConflictStart())<<"to"<<time2ISO(date);
894
895 // TJMH.debugMessage(QString("Resource %1 is not available from %2 to %3").arg(a->getLockedResource()->getName()).arg(time2ISO(a->getConflictStart())).arg(time2ISO(date)), this);
896 a->setConflictStart(0);
897 }
898 }
899 else
900 {
901 QList<Resource*> cl = createCandidateList(sc, date, a);
902
903 bool found = false;
904 for (Resource *r : std::as_const(cl))
905 if (bookResource(a, r, date, slotDuration, slotsToLimit,
906 maxAvailability))
907 {
908 a->setLockedResource(r);
909 found = true;
910 break;
911 }
912 if (!found && maxAvailability >= 4 && !a->getConflictStart())
913 a->setConflictStart(date);
914 else if (found && a->getConflictStart())
915 {
916 if (DEBUGRS(2))
917 {
918 QString candidates;
919 bool first = true;
920 for (Resource *r : std::as_const(cl))
921 {
922 if (first)
923 first = false;
924 else
925 candidates += ", ";
926 candidates += r->getId();
927 }
928 qDebug()<<"No resource of the allocation ("<<candidates<<") is available for task '"<<name<<"' from"<<time2ISO(a->getConflictStart())<<"to"<<time2ISO(date);
929 }
930 // TJMH.debugMessage(QString("No resource is available for task from %2 to %3").arg(time2ISO(a->getConflictStart())).arg(time2ISO(date)), this);
931
932 a->setConflictStart(0);
933 }
934 }
935 }
936 }
937
938 bool
939 Task::bookResource(Allocation *allocation, Resource* r, time_t date, time_t slotDuration,
940 int& slotsToLimit, int& maxAvailability)
941 {
942 bool booked = false;
943 double intervalLoad = project->convertToDailyLoad(slotDuration);
944
945 for (ResourceTreeIterator rti(r); *rti != nullptr; ++rti)
946 {
947 int availability = isAvailable(allocation, (*rti), date);
948 if (availability == 0)
949 {
950 if (!(*rti)->book(new Booking(Interval(date, date + slotDuration - 1), this))) {
951 warningMessage(xi18nc("@info/plain 1=resource name 2=datetime", "Failed to book resource: '%1' at %2", (*rti)->getName(), formatTime(date)));
952 if (DEBUGTS(2)) {
953 qWarning()<<" Failed to book resource"<<(*rti)->getName()<<"at"<<time2ISO(date);
954 }
955 continue;
956 }
957 addBookedResource(*rti);
958 TJMH.debugMessage(QString("Booked resource: '%1' at %2").arg((*rti)->getName()).arg(time2ISO(date)), this);
959 if (DEBUGTS(20)) {
960 qDebug()<<" Booked resource"<<(*rti)->getName()<<"at"<<time2ISO(date);
961 }
962 if (allocation->hasRequiredResources(*rti)) {
963 const auto lst = allocation->getRequiredResources(*rti);
964 for(Resource *r : lst) {
965 if (r->book(new Booking(Interval(date, date + slotDuration - 1), this))) {
966 addBookedResource(r);
967 // TJMH.debugMessage(QString("Booked required resource: '%1' at %2").arg(r->getName()).arg(time2ISO(date)), this);
968 if (DEBUGTS(20)) {
969 qDebug()<<" Booked required resource"<<r->getName()<<"at"<<time2ISO(date);
970 }
971 } else {
972 warningMessage(xi18nc("@info/plain 1=resource name 2=datetime", "Failed to book required resource: '%1' at %2", r->getName(), formatTime(date)));
973 if (DEBUGTS(2)) {
974 qWarning()<<" Failed to book required resource"<<r->getName()<<"at"<<time2ISO(date);
975 }
976 // NOTE: just go on as booking the main resource worked ok
977 }
978 }
979 }
980
981 /* Move the start date to make sure that there is
982 * some work going on at the start date. */
983 if (!workStarted)
984 {
985 if (scheduling == ASAP)
986 start = date;
987 else if (scheduling == ALAP)
988 end = date + slotDuration - 1;
989 else
990 qFatal("Unknown scheduling mode");
991 workStarted = true;
992 }
993
994 tentativeStart = date;
995 tentativeEnd = date + slotDuration - 1;
996 doneEffort += intervalLoad * (*rti)->getEfficiency();
997
998 booked = true;
999
1000 if (slotsToLimit > 0 && --slotsToLimit <= 0)
1001 return true;
1002 }
1003 else if (availability > maxAvailability)
1004 maxAvailability = availability;
1005 }
1006 return booked;
1007 }
1008
1009 QList<Resource*>
1010 Task::createCandidateList(int sc, time_t date, Allocation* a)
1011 {
1012 /* This function generates a list of resources that could be allocated to
1013 * the task. The order of the list is determined by the specified
1014 * selection function of the alternatives list. From this list, the
1015 * first available resource is picked later on. */
1016 QList<Resource*> candidates = a->getCandidates();
1017 QList<Resource*> cl;
1018
1019 /* We try to minimize resource changes for consecutives time slots. So
1020 * the resource used for the previous time slot is put to the 1st position
1021 * of the list. */
1022 if (a->getLockedResource())
1023 {
1024 cl.append(a->getLockedResource());
1025 candidates.removeAll(a->getLockedResource());
1026 /* When an allocation is booked the resource is saved as locked
1027 * resource. */
1028 a->setLockedResource(nullptr);
1029 }
1030 switch (a->getSelectionMode())
1031 {
1032 case Allocation::order:
1033 if (DEBUGTS(25))
1034 qDebug("order");
1035 while (!candidates.isEmpty())
1036 {
1037 cl.append(candidates.takeFirst());
1038 }
1039 break;
1040 case Allocation::minAllocationProbability:
1041 {
1042 if (DEBUGTS(25))
1043 qDebug("minAllocationProbability");
1044 /* This is another heuristic to optimize scheduling results. The
1045 * idea is to pick the resource that is most likely to be used
1046 * least during this project (because of the specified
1047 * allocations) and try to use it first. Unfortunately this
1048 * algorithm can make things worse in certain plan setups. */
1049 while (!candidates.isEmpty())
1050 {
1051 /* Find candidate with smallest allocationProbability and
1052 * append it to the candidate list. */
1053 double minProbability = 0;
1054 Resource* minProbResource = nullptr;
1055 for (Resource *r : std::as_const(candidates))
1056 {
1057 double probability = r->getAllocationProbability(sc);
1058 if (minProbability == 0 || probability < minProbability)
1059 {
1060 minProbability = probability;
1061 minProbResource = r;
1062 }
1063 }
1064 cl.append(minProbResource);
1065 candidates.removeAt(candidates.indexOf(minProbResource));
1066 }
1067 break;
1068 }
1069 case Allocation::minLoaded:
1070 {
1071 if (DEBUGTS(25))
1072 qDebug("minLoad");
1073 while (!candidates.isEmpty())
1074 {
1075 double minLoad = 0;
1076 Resource* minLoaded = nullptr;
1077 for (Resource *r : std::as_const(candidates))
1078 {
1079 /* We calculate the load as a relative value to the daily
1080 * max load. This way part time people will reach their
1081 * max as slowly as the full timers. */
1082 double load =
1083 r->getCurrentLoad(Interval(project->getStart(),
1084 date), nullptr) /
1085 ((r->getLimits() &&
1086 r->getLimits()->getDailyMax() > 0) ?
1087 project->convertToDailyLoad
1088 (r->getLimits()->getDailyMax() *
1089 project->getScheduleGranularity()) : 1.0);
1090
1091 if (minLoaded == nullptr || load < minLoad)
1092 {
1093 minLoad = load;
1094 minLoaded = r;
1095 }
1096 }
1097 cl.append(minLoaded);
1098 candidates.removeAt(candidates.indexOf(minLoaded));
1099 }
1100 break;
1101 }
1102 case Allocation::maxLoaded:
1103 {
1104 if (DEBUGTS(25))
1105 qDebug("maxLoad");
1106 while (!candidates.isEmpty())
1107 {
1108 double maxLoad = 0;
1109 Resource* maxLoaded = nullptr;
1110 for (Resource *r : std::as_const(candidates))
1111 {
1112 /* We calculate the load as a relative value to the daily
1113 * max load. This way part time people will reach their
1114 * max as fast as the full timers. */
1115 double load =
1116 r->getCurrentLoad(Interval(project->getStart(),
1117 date), nullptr) /
1118 ((r->getLimits() &&
1119 r->getLimits()->getDailyMax() > 0) ?
1120 project->convertToDailyLoad
1121 (r->getLimits()->getDailyMax() *
1122 project->getScheduleGranularity()) : 1.0);
1123
1124 if (maxLoaded == nullptr || load > maxLoad)
1125 {
1126 maxLoad = load;
1127 maxLoaded = r;
1128 }
1129 }
1130 cl.append(maxLoaded);
1131 candidates.removeAt(candidates.indexOf(maxLoaded));
1132 }
1133 break;
1134 }
1135 case Allocation::random:
1136 {
1137 if (DEBUGTS(25))
1138 qDebug("random");
1139 while (!candidates.isEmpty())
1140 {
1141 cl.append(candidates.at(rand() % candidates.count()));
1142 candidates.takeFirst(); //### do not understand this
1143 }
1144 break;
1145 }
1146 default:
1147 qFatal("Illegal selection mode %d", a->getSelectionMode());
1148 }
1149
1150 return cl;
1151 }
1152
1153 QString
1154 Task::getSchedulingText() const
1155 {
1156 if (isLeaf())
1157 {
1158 return scheduling == ASAP ? "ASAP |-->|" : "ALAP |<--|";
1159 }
1160 else
1161 {
1162 QString text;
1163
1164 for (TaskListIterator tli(*sub); tli.hasNext();)
1165 {
1166 Task *t = static_cast<Task*>(tli.next());
1167 if (text.isEmpty())
1168 text = t->getSchedulingText();
1169 else if (text != t->getSchedulingText())
1170 {
1171 text = "Mixed";
1172 break;
1173 }
1174 }
1175 return text;
1176 }
1177 return QString();
1178 }
1179
1180 QString
1181 Task::getStatusText(int sc) const
1182 {
1183 QString text;
1184 switch (getStatus(sc))
1185 {
1186 case NotStarted:
1187 text = QString("Not yet started");
1188 break;
1189 case InProgressLate:
1190 text = QString("Behind schedule");
1191 break;
1192 case InProgress:
1193 text = QString("Work in progress");
1194 break;
1195 case OnTime:
1196 text = QString("On schedule");
1197 break;
1198 case InProgressEarly:
1199 text = QString("Ahead of schedule");
1200 break;
1201 case Finished:
1202 text = QString("Finished");
1203 break;
1204 case Late:
1205 text = QString("Late");
1206 break;
1207 default:
1208 text = QString("Unknown status");
1209 break;
1210 }
1211 return text;
1212 }
1213
1214 bool
1215 Task::isCompleted(int sc, time_t date) const
1216 {
1217 if (scenarios[sc].reportedCompletion >= 0.0)
1218 {
1219 if (scenarios[sc].reportedCompletion >= 100.0)
1220 return true;
1221
1222 // some completion degree has been specified.
1223 if (scenarios[sc].effort > 0.0)
1224 {
1225 return qRound((scenarios[sc].effort *
1226 (scenarios[sc].reportedCompletion / 100.0)) * 1000)
1227 >= qRound(getLoad(sc, Interval(scenarios[sc].start, date), nullptr)
1228 * 1000);
1229 }
1230 else
1231 {
1232 return (date <=
1233 scenarios[sc].start +
1234 static_cast<int>((scenarios[sc].reportedCompletion /
1235 100.0) * (scenarios[sc].end -
1236 scenarios[sc].start)));
1237 }
1238 }
1239
1240 if (isContainer())
1241 {
1242 return (date <=
1243 scenarios[sc].start +
1244 static_cast<int>((scenarios[sc].containerCompletion /
1245 100.0) * (scenarios[sc].end -
1246 scenarios[sc].start)));
1247 }
1248
1249 return (project->getNow() > date);
1250 }
1251
1252 bool
1253 Task::isBuffer(int sc, const Interval& iv) const
1254 {
1255 return iv.overlaps(Interval(scenarios[sc].start,
1256 scenarios[sc].startBufferEnd)) ||
1257 iv.overlaps(Interval(scenarios[sc].endBufferStart,
1258 scenarios[sc].end));
1259 }
1260
1261 time_t
1262 Task::earliestStart(int sc) const
1263 {
1264 time_t date = 0;
1265 // All tasks this task depends on must have an end date set.
1266 for (TaskListIterator tli(previous); tli.hasNext();) {
1267 Task *t = static_cast<Task*>(tli.next());
1268 if (t->end == 0)
1269 {
1270 if (t->scheduling == ASAP) {
1271 if (DEBUGTS(1)) {
1272 qDebug()<<"Earliest start:"<<this<<":"<<t<<"end == 0";
1273 }
1274 return 0;
1275 }
1276 }
1277 else if (t->end + 1 > date)
1278 date = t->end + 1;
1279 }
1280 for (QListIterator<TaskDependency*> tdi(depends); tdi.hasNext();)
1281 {
1282 /* Add the gapDuration and/or gapLength to the end of the dependent
1283 * task. */
1284 TaskDependency *td = static_cast<TaskDependency*>(tdi.next());
1285 time_t potentialDate = td->getTaskRef()->end + 1;
1286 time_t dateAfterLengthGap;
1287 long gapLength = td->getGapLength(sc);
1288 for (dateAfterLengthGap = potentialDate;
1289 gapLength > 0 && dateAfterLengthGap < project->getEnd();
1290 dateAfterLengthGap += project->getScheduleGranularity())
1291 if (isWorkingTime(dateAfterLengthGap))
1292 gapLength -= project->getScheduleGranularity();
1293 if (dateAfterLengthGap > potentialDate + td->getGapDuration(sc))
1294 potentialDate = dateAfterLengthGap;
1295 else
1296 potentialDate += td->getGapDuration(sc);
1297 // Set 'date' to the latest end date plus gaps of all preceding tasks.
1298 if (potentialDate > date)
1299 date = potentialDate;
1300 }
1301 /* If any of the parent tasks has an explicit start date, the task must
1302 * start at or after this date. */
1303 for (Task* t = getParent(); t; t = t->getParent())
1304 if (t->start > date)
1305 return t->start;
1306
1307 if (DEBUGTS(15)) {
1308 qDebug()<<"Earliest start:"<<this<<time2ISO(date);
1309 }
1310
1311 return date;
1312 }
1313
1314 time_t
1315 Task::latestEnd(int sc) const
1316 {
1317 time_t date = 0;
1318 // All tasks this task precedes must have a start date set.
1319 for (TaskListIterator tli(followers); tli.hasNext();) {
1320 Task *t = static_cast<Task*>(tli.next());
1321 if (t->start == 0)
1322 {
1323 if (t->scheduling == ALAP) {
1324 if (DEBUGTS(1)) {
1325 qDebug()<<"Latest end:"<<this<<":"<<t<<"start == 0";
1326 }
1327 return 0;
1328 }
1329 }
1330 else if (date == 0 || t->start - 1 < date) {
1331 date = t->start - 1;
1332 if (DEBUGTS(15)) {
1333 qDebug()<<"Latest end:"<<this<<time2ISO(date)<<"from follower:"<<t<<time2ISO(t->start-1);
1334 }
1335 }
1336 }
1337 for (QListIterator<TaskDependency*> tdi(precedes); tdi.hasNext();)
1338 {
1339 /* Subtract the gapDuration and/or gapLength from the start of the
1340 * following task. */
1341 TaskDependency *td = static_cast<TaskDependency*>(tdi.next());
1342 time_t potentialDate = td->getTaskRef()->start - 1;
1343 time_t dateBeforeLengthGap;
1344 long gapLength = td->getGapLength(sc);
1345 for (dateBeforeLengthGap = potentialDate;
1346 gapLength > 0 && dateBeforeLengthGap >= project->getStart();
1347 dateBeforeLengthGap -= project->getScheduleGranularity())
1348 if (isWorkingTime(dateBeforeLengthGap))
1349 gapLength -= project->getScheduleGranularity();
1350 if (dateBeforeLengthGap < potentialDate - td->getGapDuration(sc))
1351 potentialDate = dateBeforeLengthGap;
1352 else
1353 potentialDate -= td->getGapDuration(sc);
1354
1355 /* Set 'date' to the earliest end date minus gaps of all following
1356 * tasks. */
1357 if (date == 0 || potentialDate < date)
1358 date = potentialDate;
1359 if (DEBUGTS(15)) {
1360 qDebug()<<"Latest end:"<<this<<time2ISO(date)<<"from successor:"<<td->getTaskRef()<<time2ISO(td->getTaskRef()->start);
1361 }
1362 }
1363 /* If any of the parent tasks has an explicit end date, the task must
1364 * end at or before this date. */
1365 for (Task* t = getParent(); t; t = t->getParent())
1366 if (t->end != 0 && t->end < date)
1367 return t->end;
1368
1369 if (DEBUGTS(15)) {
1370 qDebug()<<"Latest end:"<<this<<time2ISO(date);
1371 }
1372 return date;
1373 }
1374
1375 double
1376 Task::getCalcEffort(int sc) const
1377 {
1378 if (milestone)
1379 return 0.0;
1380
1381 return getLoad(sc, Interval(scenarios[sc].start, scenarios[sc].end));
1382 }
1383
1384 double
1385 Task::getCalcDuration(int sc) const
1386 {
1387 if (milestone)
1388 return 0.0;
1389
1390 return static_cast<double>(scenarios[sc].end + 1 - scenarios[sc].start) / ONEDAY;
1391 }
1392
1393 double
1394 Task::getLoad(int sc, const Interval& period, const Resource* resource) const
1395 {
1396 if (milestone)
1397 return 0.0;
1398
1399 double load = 0.0;
1400
1401 if (isContainer())
1402 {
1403 for (TaskListIterator tli(*sub); tli.hasNext();) {
1404 Task *t = static_cast<Task*>(tli.next());
1405 load += t->getLoad(sc, period, resource);
1406 }
1407 }
1408 else
1409 {
1410 if (resource)
1411 load += resource->getEffectiveLoad(sc, period, AllAccounts, this);
1412 else
1413 for (ResourceListIterator rli(scenarios[sc].bookedResources);
1414 rli.hasNext();)
1415 load += static_cast<Resource*>(rli.next())->getEffectiveLoad(sc, period, AllAccounts, this);
1416 }
1417
1418 return load;
1419 }
1420
1421 double
1422 Task::getAllocatedTimeLoad(int sc, const Interval& period,
1423 const Resource* resource) const
1424 {
1425 return project->convertToDailyLoad
1426 (getAllocatedTime(sc, period, resource));
1427 }
1428
1429 long
1430 Task::getAllocatedTime(int sc, const Interval& period,
1431 const Resource* resource) const
1432 {
1433 if (milestone)
1434 return 0;
1435
1436 long allocatedTime = 0;
1437
1438 if (isContainer())
1439 {
1440 for (TaskListIterator tli(*sub); tli.hasNext();) {
1441 Task *t = static_cast<Task*>(tli.next());
1442 allocatedTime += t->getAllocatedTime(sc, period, resource);
1443 }
1444 }
1445 else
1446 {
1447 if (resource)
1448 allocatedTime += resource->getAllocatedTime(sc, period, AllAccounts,
1449 this);
1450 else
1451 for (ResourceListIterator rli(scenarios[sc].bookedResources);
1452 *rli;)
1453 allocatedTime += static_cast<Resource*>(rli.next())->getAllocatedTime(sc, period,
1454 AllAccounts, this);
1455 }
1456
1457 return allocatedTime;
1458 }
1459
1460 // double
1461 // Task::getCredits(int sc, const Interval& period, AccountType acctType,
1462 // const Resource* resource, bool recursive) const
1463 // {
1464 // double credits = 0.0;
1465 //
1466 // if (recursive && !sub->isEmpty())
1467 // {
1468 // for (TaskListIterator tli(*sub); tli.hasNext();) {
1469 // Task *t = static_cast<Task*>(tli.next());
1470 // credits += t->getCredits(sc, period, acctType, resource,
1471 // recursive);
1472 // }
1473 // }
1474 //
1475 // if (acctType != AllAccounts &&
1476 // (account == 0 || acctType != account->getAcctType()))
1477 // return credits;
1478 //
1479 // if (resource)
1480 // credits += resource->getCredits(sc, period, acctType, this);
1481 // else
1482 // for (ResourceListIterator rli(scenarios[sc].bookedResources);
1483 // *rli != 0; ++rli)
1484 // credits += r->getCredits(sc, period, acctType, this);
1485 //
1486 // if (period.contains(scenarios[sc].start))
1487 // credits += scenarios[sc].startCredit;
1488 // if (period.contains(scenarios[sc].end + (milestone ? 1 : 0)))
1489 // credits += scenarios[sc].endCredit;
1490 //
1491 // return credits;
1492 // }
1493
1494
1495 bool
1496 Task::xRef(QMap<QString, Task*>& hash)
1497 {
1498 if (DEBUGPF(5))
1499 qDebug()<<QString("Creating cross references for task %1 ...").arg(name);
1500 int errors = 0;
1501
1502 QList<TaskDependency*> brokenDeps;
1503 for (QListIterator<TaskDependency*> tdi(depends); tdi.hasNext();)
1504 {
1505 TaskDependency *td = static_cast<TaskDependency*>(tdi.next());
1506 QString absId = resolveId(td->getTaskRefId());
1507 Task* t;
1508 if ((t = hash.value(absId)) == nullptr)
1509 {
1510 errorMessage(QString("Unknown dependency '%1'").arg(absId));
1511 brokenDeps.append(td);
1512 errors++;
1513 }
1514 else
1515 {
1516 for (QListIterator<TaskDependency*> tdi2(depends); tdi2.hasNext();) {
1517 TaskDependency *td2 = static_cast<TaskDependency*>(tdi2.next());
1518 if (td2->getTaskRef() == t)
1519 {
1520 warningMessage(QString("No need to specify dependency %1 "
1521 "multiple times.").arg(absId));
1522 break;
1523 }
1524 }
1525 if (errors == 0)
1526 {
1527 td->setTaskRef(t);
1528 if (t == this)
1529 {
1530 errorMessage(QString("Task '%1' cannot depend on self.")
1531 .arg(name));
1532 break;
1533 }
1534 if (t->isDescendantOf(this))
1535 {
1536 errorMessage(QString("Task '%1' cannot depend on child.")
1537 .arg(name));
1538 break;
1539 }
1540 if (isDescendantOf(t))
1541 {
1542 errorMessage(QString/**/("Task '%1' cannot depend on parent.")
1543 .arg(t->id));
1544 break;
1545 }
1546 if (! predecessors.contains(t)) {
1547 // Unidirectional link
1548 predecessors.append(t);
1549 }
1550 // Bidirectional link
1551 if (! previous.contains(t)) {
1552 previous.append(t);
1553 }
1554 if (! t->followers.contains(this)) {
1555 t->followers.append(this);
1556 }
1557 if (DEBUGPF(11))
1558 qDebug()<<"Registering dependency:"<<this<<"precedes"<<t;
1559 }
1560 }
1561 }
1562 // Remove broken dependencies as they can cause trouble later on.
1563 for (QListIterator<TaskDependency*> tdi(brokenDeps); tdi.hasNext();) {
1564 depends.removeAt(depends.indexOf(tdi.next()));
1565 }
1566 brokenDeps.clear();
1567
1568 for (QListIterator<TaskDependency*> tdi(precedes); tdi.hasNext();)
1569 {
1570 TaskDependency *td = static_cast<TaskDependency*>(tdi.next());
1571 QString absId = resolveId(td->getTaskRefId());
1572 Task* t;
1573 if ((t = hash.value(absId)) == nullptr)
1574 {
1575 errorMessage(QString("Unknown dependency '%1'").arg(absId));
1576 brokenDeps.append(td);
1577 }
1578 else
1579 {
1580 for (QListIterator<TaskDependency*> tdi2(precedes); tdi2.hasNext();) {
1581 TaskDependency *td = static_cast<TaskDependency*>(tdi2.next());
1582 if (td->getTaskRef() == t)
1583 {
1584 warningMessage(QString("No need to specify dependency '%1'"
1585 "multiple times").arg(absId));
1586 break;
1587 }
1588 }
1589 if (errors == 0)
1590 {
1591 td->setTaskRef(t);
1592 if (t == this)
1593 {
1594 errorMessage(QString("Task '%1' cannot precede self.")
1595 .arg(name));
1596 break;
1597 }
1598 if (t->isDescendantOf(this))
1599 {
1600 errorMessage(QString("Task '%1' cannot precede a child.")
1601 .arg(name));
1602 break;
1603 }
1604 if (isDescendantOf(t))
1605 {
1606 errorMessage(QString("Task '%1' cannot precede parent.")
1607 .arg(t->id));
1608 break;
1609 }
1610 if (! successors.contains(t)) {
1611 // Unidirectional link
1612 successors.append(t);
1613 }
1614 // Bidirectional link
1615 if (! followers.contains(t)) {
1616 followers.append(t);
1617 }
1618 if (! t->previous.contains(this)) {
1619 t->previous.append(this);
1620 }
1621 if (DEBUGPF(11))
1622 qDebug()<<"Registering predecessor"<<this<<"with task"<<t;
1623 }
1624 }
1625 }
1626 // Remove broken dependencies as they can cause trouble later on.
1627 for (QListIterator<TaskDependency*> tdi(brokenDeps); tdi.hasNext();) {
1628 TaskDependency *td = static_cast<TaskDependency*>(tdi.next());
1629 precedes.removeAt(precedes.indexOf(td));
1630 }
1631 brokenDeps.clear();
1632
1633 return errors > 0;
1634 }
1635
1636 void
1637 Task::implicitXRef()
1638 {
1639 /* Every time the scheduling related information of a single task has been
1640 * changed, we have to reset the cache flags for the start and end
1641 * determinability. */
1642 for (int sc = 0; sc < project->getMaxScenarios(); ++sc)
1643 {
1644 scenarios[sc].startCanBeDetermined = false;
1645 scenarios[sc].endCanBeDetermined = false;
1646 }
1647
1648 if (!sub->isEmpty())
1649 return;
1650
1651 for (int sc = 0; sc < project->getMaxScenarios(); ++sc)
1652 {
1653 /* Propagate implicit dependencies. If a task has no specified start or
1654 * end date and no start or end dependencies, we check if a parent task
1655 * has an explicit start or end date which can be used. */
1656
1657 if (milestone)
1658 {
1659 if (scenarios[sc].specifiedStart != 0 &&
1660 scenarios[sc].specifiedEnd == 0)
1661 scenarios[sc].specifiedEnd = scenarios[sc].specifiedStart - 1;
1662 if (scenarios[sc].specifiedEnd != 0 &&
1663 scenarios[sc].specifiedStart == 0)
1664 scenarios[sc].specifiedStart = scenarios[sc].specifiedEnd + 1;
1665 }
1666 bool hasDurationSpec = scenarios[sc].duration != 0 ||
1667 scenarios[sc].length != 0 ||
1668 scenarios[sc].effort != 0;
1669
1670 if (scenarios[sc].specifiedStart == 0 && depends.isEmpty() &&
1671 !(hasDurationSpec && scheduling == ALAP))
1672 for (Task* tp = getParent(); tp; tp = tp->getParent())
1673 {
1674 if (tp->scenarios[sc].specifiedStart != 0)
1675 {
1676 if (DEBUGPF(11))
1677 qDebug()<<"Setting start of task '"<<id<<"' in scenario"<<project->getScenarioId(sc)<<"to"<<time2ISO(tp->scenarios[sc].specifiedStart);
1678
1679 scenarios[sc].specifiedStart = tp->scenarios[sc].specifiedStart;
1680 break;
1681 }
1682 }
1683 /* And the same for end values */
1684 if (scenarios[sc].specifiedEnd == 0 && precedes.isEmpty() &&
1685 !(hasDurationSpec && scheduling == ASAP))
1686 for (Task* tp = getParent(); tp; tp = tp->getParent())
1687 {
1688 if (tp->scenarios[sc].specifiedEnd != 0)
1689 {
1690 if (DEBUGPF(11))
1691 qDebug()<<"Setting end of task '"<<id<<"' in scenario"<<project->getScenarioId(sc)<<"to"<<time2ISO(tp->scenarios[sc].specifiedEnd),
1692
1693 scenarios[sc].specifiedEnd = tp->scenarios[sc].specifiedEnd;
1694 break;
1695 }
1696 }
1697 }
1698
1699 if (!isMilestone() && isLeaf())
1700 {
1701 /* Automatic milestone marker. As a convenience we convert tasks that
1702 * only have a start or end criteria as a milestone. This is handy
1703 * when in the early stage of a project draft, when you just want to
1704 * specify the project outline and fill in subtasks and details
1705 * later. */
1706 bool hasStartSpec = false;
1707 bool hasEndSpec = false;
1708 bool hasDurationSpec = false;
1709 for (int sc = 0; sc < project->getMaxScenarios(); ++sc)
1710 {
1711 if (scenarios[sc].specifiedStart != 0 || !depends.isEmpty())
1712 hasStartSpec = true;
1713 if (scenarios[sc].specifiedEnd != 0 || !precedes.isEmpty())
1714 hasEndSpec = true;
1715 if (scenarios[sc].duration != 0 || scenarios[sc].length != 0 ||
1716 scenarios[sc].effort != 0)
1717 hasDurationSpec = true;
1718 // qDebug()<<"Task::implicitXRef:"<<id<<"effort="<<getEffort(sc)<<"sc="<<sc<<":"<<hasDurationSpec<<(hasStartSpec ^ hasEndSpec);
1719 }
1720 if (!hasDurationSpec && (hasStartSpec ^ hasEndSpec)) {
1721 milestone = true;
1722 // qDebug()<<"Task::implicitXRef:"<<"set"<<id<<"to milestone ("<<hasDurationSpec<<(hasStartSpec ^ hasEndSpec)<<")";
1723 }
1724 }
1725 }
1726
1727 void
1728 Task::sortAllocations()
1729 {
1730 if (allocations.isEmpty())
1731 return;
1732
1733 // allocations.setAutoDelete(false);
1734 for (QListIterator<Allocation*> ali(allocations); ali.hasNext();)
1735 {
1736 Allocation *a = static_cast<Allocation*>(ali.next());
1737 if (!a->isWorker())
1738 {
1739 /* If the resource does not do any work we move it to the front of
1740 * the list. That way the 0 effective resources are always
1741 * allocated no matter if the effort limit has been reached or not.
1742 * At least in the same booking call. */
1743 allocations.removeAt(allocations.indexOf(a));
1744 allocations.prepend(a);
1745 }
1746
1747 }
1748 // allocations.setAutoDelete(true);
1749 }
1750
1751 void
1752 Task::saveSpecifiedBookedResources()
1753 {
1754 /* The project file readers use the same resource booking mechanism as the
1755 * scheduler. So we need to save the up to now booked resources as
1756 * specified resources. */
1757 for (int sc = 0; sc < project->getMaxScenarios(); ++sc)
1758 scenarios[sc].specifiedBookedResources =
1759 scenarios[sc].bookedResources;
1760 }
1761
1762 bool
1763 Task::loopDetector(LDIList& chkedTaskList) const
1764 {
1765 /* Only check top-level tasks. All other tasks will be checked then as
1766 * well. */
1767 if (parent)
1768 return false;
1769 if (DEBUGPF(2))
1770 qDebug()<<"Running loop detector for task "<<id;
1771 // Check ASAP tasks
1772 LDIList list;
1773 if (loopDetection(list, chkedTaskList, false, true))
1774 return true;
1775 // Check ALAP tasks
1776 if (loopDetection(list, chkedTaskList, true, true))
1777 return true;
1778 return false;
1779 }
1780
1781 bool
1782 Task::loopDetection(LDIList& list, LDIList& chkedTaskList, bool atEnd,
1783 bool fromOutside) const
1784 {
1785 if (DEBUGPF(10))
1786 qDebug()<<QString().fill(' ', list.count() + 1)<<"loopDetection at"<<id<<"("<<(atEnd ? "End" : "Start")<<")";
1787
1788 // First, check whether the task has already been checked for loops.
1789 {
1790 LoopDetectorInfo thisTask(this, atEnd);
1791 if (chkedTaskList.find(&thisTask))
1792 {
1793 // Already checked
1794 return false;
1795 }
1796 }
1797
1798 if (checkPathForLoops(list, atEnd))
1799 return true;
1800
1801 /* Now we have to traverse the graph in the direction of the specified
1802 * dependencies. 'precedes' and 'depends' specify dependencies in the
1803 * opposite direction of the flow of the tasks. So we have to make sure
1804 * that we do not follow the arcs in the direction that precedes and
1805 * depends points us. Parent/Child relationships also specify a
1806 * dependency. The scheduling mode of the child determines the direction
1807 * of the flow. With help of the 'caller' parameter we make sure that we
1808 * only visit children if we were referred to the task by a non-parent-child
1809 * relationship. */
1810 if (!atEnd)
1811 {
1812 if (fromOutside)
1813 {
1814 /*
1815 |
1816 v
1817 +--------
1818 -->| o--+
1819 +--- | --
1820 |
1821 V
1822 */
1823 /* If we were not called from a sub task we check all sub tasks.*/
1824 for (TaskListIterator tli(*sub); tli.hasNext();)
1825 {
1826 Task *t = static_cast<Task*>(tli.next());
1827 if (DEBUGPF(15))
1828 qDebug()<<QString().fill(' ', list.count())<<"Checking sub task"<<t->getId()<<"of"<<id;
1829 if (t->loopDetection(list, chkedTaskList, false, true))
1830 return true;
1831 }
1832
1833 /*
1834 |
1835 v
1836 +--------
1837 -->| o---->
1838 +--------
1839 */
1840 if (DEBUGPF(15))
1841 qDebug()<<QString().fill(' ', list.count())<<"Checking end of task"<<id;
1842 if (loopDetection(list, chkedTaskList, true, false))
1843 return true;
1844 }
1845 else
1846 {
1847 /*
1848 ^
1849 |
1850 + | -----
1851 | o <--
1852 +--------
1853 ^
1854 |
1855 */
1856 if (parent)
1857 {
1858 if (DEBUGPF(15))
1859 qDebug()<<QString().fill(' ', list.count())<<"Checking parent task of"<<id;
1860 if (getParent()->loopDetection(list, chkedTaskList, false,
1861 false))
1862 return true;
1863 }
1864
1865 /*
1866 +--------
1867 <--|- o <--
1868 +--------
1869 ^
1870 |
1871 */
1872 // Now check all previous tasks.
1873 for (TaskListIterator tli(previous); tli.hasNext();)
1874 {
1875 Task *t = static_cast<Task*>(tli.next());
1876 if (DEBUGPF(15))
1877 qDebug()<<QString().fill(' ', list.count())<<"Checking previous"<<t->getId()<<"of task"<<id;
1878 if(t->loopDetection(list, chkedTaskList, true, true))
1879 return true;
1880 }
1881 }
1882 }
1883 else
1884 {
1885 if (fromOutside)
1886 {
1887 /*
1888 |
1889 v
1890 --------+
1891 +--o |<--
1892 -- | ---+
1893 |
1894 v
1895 */
1896 /* If we were not called from a sub task we check all sub tasks.*/
1897 for (TaskListIterator tli(*sub); tli.hasNext();)
1898 {
1899 Task *t = static_cast<Task*>(tli.next());
1900 if (DEBUGPF(15))
1901 qDebug()<<QString().fill(' ', list.count())<<"Checking sub task"<<t->getId()<<"of"<<id;
1902 if (t->loopDetection(list, chkedTaskList, true, true))
1903 return true;
1904 }
1905
1906 /*
1907 |
1908 v
1909 --------+
1910 <----o |<--
1911 --------+
1912 */
1913 if (DEBUGPF(15))
1914 qDebug()<<QString().fill(' ', list.count())<<"Checking start of task"<<id;
1915 if (loopDetection(list, chkedTaskList, false, false))
1916 return true;
1917 }
1918 else
1919 {
1920 /*
1921 ^
1922 |
1923 ----- | +
1924 --> o |
1925 --------+
1926 ^
1927 |
1928 */
1929 if (parent)
1930 {
1931 if (DEBUGPF(15))
1932 qDebug()<<QString().fill(' ', list.count())<<"Checking parent task of"<<id;
1933 if (getParent()->loopDetection(list, chkedTaskList, true,
1934 false))
1935 return true;
1936 }
1937
1938 /*
1939 --------+
1940 --> o-|-->
1941 --------+
1942 ^
1943 |
1944 */
1945 // Now check all following tasks.
1946 for (TaskListIterator tli(followers); tli.hasNext();)
1947 {
1948 Task *t = static_cast<Task*>(tli.next());
1949 if (DEBUGPF(15))
1950 qDebug()<<QString().fill(' ', list.count())<<"Checking follower"<<t->getId()<<"of task"<<id;
1951 if (t->loopDetection(list, chkedTaskList, false, true))
1952 return true;
1953 }
1954 }
1955 }
1956 chkedTaskList.append(list.popLast());
1957
1958 if (DEBUGPF(5))
1959 qDebug()<<QString().fill(' ', list.count())<<"No loops found in"<<id<<"("<<(atEnd ? "End" : "Start")<<")";
1960 return false;
1961 }
1962
1963 bool
1964 Task::checkPathForLoops(LDIList& list, bool atEnd) const
1965 {
1966 /* If we find the current task (with same position) in the list, we have
1967 * detected a loop. In case there is no loop detected we add this tasks at
1968 * the end of the list. */
1969 LoopDetectorInfo* thisTask = new LoopDetectorInfo(this, atEnd);
1970 if (list.find(thisTask))
1971 {
1972 QString loopChain;
1973 LoopDetectorInfo* it;
1974 /* Find the first occurrence of this task in the list. This is the
1975 * start of the loop. */
1976 for (it = list.first(); *it != *thisTask; it = it->next())
1977 ;
1978 /* Then copy all loop elements to the loopChain string. */
1979 for (; it != nullptr; it = it->next())
1980 {
1981 loopChain += QString("%1 (%2) -> ")
1982 .arg(it->getTask()->getId())
1983 .arg(it->getAtEnd() ? "End" : "Start");
1984 }
1985 loopChain += QString("%1 (%2)").arg(name)
1986 .arg(atEnd ? "End" : "Start");
1987 delete thisTask;
1988 errorMessage(QString("Dependency loop detected: %1").arg(loopChain));
1989 return true;
1990 }
1991 list.append(thisTask);
1992
1993 return false;
1994 }
1995
1996 bool
1997 Task::checkDetermination(int sc) const
1998 {
1999 /* Check if the task and it's dependencies have enough information to
2000 * produce a fixed determined schedule. */
2001 if (DEBUGPF(10))
2002 qDebug()<<"Checking determination of task"<<id;
2003 LDIList list;
2004
2005 if (!startCanBeDetermined(list, sc))
2006 {
2007 /* The error message must only be shown if the task has prececessors.
2008 * If not, is has been reported before already. */
2009 if (!previous.isEmpty())
2010 errorMessage
2011 (QString("The start of task '%1' is "
2012 "underspecified. This is caused by underspecified "
2013 "dependent tasks. You must use more fixed dates to "
2014 "solve this problem.")
2015 .arg(name));
2016 return false;
2017 }
2018
2019 if (!endCanBeDetermined(list, sc))
2020 {
2021 /* The error message must only be shown if the task has followers.
2022 * If not, is has been reported before already. */
2023 if (!followers.isEmpty())
2024 errorMessage
2025 (QString("The end of task '%1' is underspecified. "
2026 "This is caused by underspecified dependent tasks. You "
2027 "must use more fixed dates to solve this problem.")
2028 .arg(name));
2029 return false;
2030 }
2031
2032 return true;
2033 }
2034
2035 bool
2036 Task::startCanBeDetermined(LDIList& list, int sc) const
2037 {
2038 if (DEBUGPF(10))
2039 qDebug()<<"Checking if start of task"<<id<<"can be determined";
2040
2041 if (scenarios[sc].startCanBeDetermined)
2042 {
2043 if (DEBUGPF(10))
2044 qDebug()<<"Start of task"<<id<<"can be determined (cached)";
2045 return true;
2046 }
2047
2048 if (checkPathForLoops(list, false))
2049 return false;
2050
2051 for (const Task* t = this; t; t = static_cast<const Task*>(t->parent))
2052 if (scenarios[sc].specifiedStart != 0) //FIXME ?? t->scenarios[sc] ??
2053 {
2054 if (DEBUGPF(10))
2055 qDebug()<<"Start of task"<<id<<"can be determined (fixed date)";
2056 goto isDetermined;
2057 }
2058
2059 if (scheduling == ALAP &&
2060 (scenarios[sc].duration != 0.0 || scenarios[sc].length != 0.0 ||
2061 scenarios[sc].effort != 0.0 || milestone) &&
2062 endCanBeDetermined(list, sc))
2063 {
2064 if (DEBUGPF(10))
2065 qDebug()<<"Start of task"<<id<<"can be determined (end + fixed length)";
2066 goto isDetermined;
2067 }
2068
2069 for (TaskListIterator tli(predecessors); tli.hasNext();) {
2070 Task *t = static_cast<Task*>(tli.next());
2071 if (t->endCanBeDetermined(list, sc))
2072 {
2073 if (DEBUGPF(10))
2074 qDebug()<<"Start of task"<<id<<"can be determined (dependency)";
2075 goto isDetermined;
2076 }
2077 }
2078 if (hasSubs())
2079 {
2080 for (TaskListIterator tli = getSubListIterator(); tli.hasNext();) {
2081 Task *t = static_cast<Task*>(tli.next());
2082 if (!t->startCanBeDetermined(list, sc))
2083 goto isNotDetermined;
2084 }
2085 if (DEBUGPF(10))
2086 qDebug()<<"Start of task"<<id<<"can be determined (children)";
2087 goto isDetermined;
2088 }
2089
2090 isNotDetermined:
2091 if (DEBUGPF(10))
2092 qDebug()<<"*** Start of task"<<id<<"cannot be determined";
2093 list.removeLast();
2094 return false;
2095
2096 isDetermined:
2097 list.removeLast();
2098 scenarios[sc].startCanBeDetermined = true;
2099 return true;
2100 }
2101
2102 bool
2103 Task::endCanBeDetermined(LDIList& list, int sc) const
2104 {
2105 if (DEBUGPF(10))
2106 qDebug()<<"Checking if end of task"<<id<<"can be determined";
2107
2108 if (scenarios[sc].endCanBeDetermined)
2109 {
2110 if (DEBUGPF(10))
2111 qDebug()<<"End of task"<<id<<"can be determined";
2112 return true;
2113 }
2114
2115 if (checkPathForLoops(list, true))
2116 return false;
2117
2118 for (const Task* t = this; t; t = static_cast<const Task*>(t->parent))
2119 if (scenarios[sc].specifiedEnd != 0) //FIXME ?? t->scenarios ??
2120 {
2121 if (DEBUGPF(10))
2122 qDebug()<<"End of task"<<id<<"can be determined (fixed date)";
2123 goto isDetermined;
2124 }
2125
2126 if (scheduling == ASAP &&
2127 (scenarios[sc].duration != 0.0 || scenarios[sc].length != 0.0 ||
2128 scenarios[sc].effort != 0.0 || milestone) &&
2129 startCanBeDetermined(list, sc))
2130 {
2131 if (DEBUGPF(10))
2132 qDebug()<<"End of task"<<id<<"can be determined (end + fixed length)";
2133 goto isDetermined;
2134 }
2135
2136 for (TaskListIterator tli(successors); tli.hasNext();) {
2137 Task *t = static_cast<Task*>(tli.next());
2138 if (t->startCanBeDetermined(list, sc))
2139 {
2140 if (DEBUGPF(10))
2141 qDebug()<<"End of task"<<id<<"can be determined (dependency)";
2142 goto isDetermined;
2143 }
2144 }
2145 if (hasSubs())
2146 {
2147 for (TaskListIterator tli = getSubListIterator(); tli.hasNext();) {
2148 Task *t = static_cast<Task*>(tli.next());
2149 if (!t->endCanBeDetermined(list, sc))
2150 {
2151 if (DEBUGPF(10))
2152 qDebug()<<"End of task"<<id<<"cannot be determined (child"<<t->id<<")";
2153 goto isNotDetermined;
2154 }
2155 }
2156
2157 if (DEBUGPF(10))
2158 qDebug()<<"End of task"<<id<<"can be determined (children)";
2159 goto isDetermined;
2160 }
2161
2162 isNotDetermined:
2163 if (DEBUGPF(10))
2164 qDebug()<<"*** End of task"<<id<<"cannot be determined";
2165 list.removeLast();
2166 return false;
2167
2168 isDetermined:
2169 list.removeLast();
2170 scenarios[sc].endCanBeDetermined = true;
2171 return true;
2172 }
2173
2174 QString
2175 Task::resolveId(QString relId)
2176 {
2177 /* Converts a relative ID to an absolute ID. Relative IDs start
2178 * with a number of bangs. A set of bangs means 'Name of the n-th
2179 * parent task' with n being the number of bangs. */
2180 if (relId[0] != '!')
2181 return relId;
2182
2183 Task* t = this;
2184 int i;
2185 for (i = 0; i < relId.length() && relId.mid(i, 1) == "!"; ++i)
2186 {
2187 if (t == nullptr)
2188 {
2189 errorMessage(QString("Illegal relative ID '%1'").arg(relId));
2190 return relId;
2191 }
2192 t = t->getParent();
2193 }
2194 if (t)
2195 return t->id + QLatin1Char('.') + relId.right(relId.length() - i);
2196 else
2197 return relId.right(relId.length() - i);
2198 }
2199
2200 bool
2201 Task::hasStartDependency(int sc) const
2202 {
2203 /* Checks whether the task has a start specification for the
2204 * scenario. This can be a fixed start time or a dependency on another
2205 * task's end or an implicit dependency on the fixed start time of a
2206 * parent task. */
2207 if (scenarios[sc].specifiedStart != 0 || !depends.isEmpty()) {
2208 // qDebug()<<"Task::hasStartDependency:"<<id<<sc<<(scenarios[sc].specifiedStart != 0)<<(!depends.isEmpty());
2209 return true;
2210 }
2211 for (Task* p = getParent(); p; p = p->getParent()) {
2212 if (p->scenarios[sc].specifiedStart != 0) {
2213 // qDebug()<<"Task::hasStartDependency:"<<id<<sc<<"parent";
2214 return true;
2215 }
2216 }
2217 // qDebug()<<"Task::hasStartDependency:"<<id<<sc<<"no dependency:"<<(scenarios[sc].specifiedStart != 0)<<(!depends.isEmpty());
2218 return false;
2219 }
2220
2221 bool
2222 Task::hasEndDependency(int sc) const
2223 {
2224 /* Checks whether the task has an end specification for the
2225 * scenario. This can be a fixed end time or a dependency on another
2226 * task's start or an implicit dependency on the fixed end time of a
2227 * parent task. */
2228 if (scenarios[sc].specifiedEnd != 0 || !precedes.isEmpty())
2229 return true;
2230 for (Task* p = getParent(); p; p = p->getParent())
2231 if (p->scenarios[sc].specifiedEnd != 0)
2232 return true;
2233 return false;
2234 }
2235
2236 bool
2237 Task::hasStartDependency() const
2238 {
2239 /* Check whether the task or any of it's sub tasks has a start
2240 * dependency. */
2241 if (start != 0 || !previous.isEmpty() || scheduling == ALAP)
2242 return true;
2243
2244 for (TaskListIterator tli(*sub); tli.hasNext();) {
2245 Task *t = static_cast<Task*>(tli.next());
2246 if (t->hasStartDependency())
2247 return true;
2248 }
2249
2250 return false;
2251 }
2252
2253 bool
2254 Task::hasEndDependency() const
2255 {
2256 /* Check whether the task or any of it's sub tasks has an end
2257 * dependency. */
2258 if (end != 0 || !followers.isEmpty() || scheduling == ASAP)
2259 return true;
2260
2261 for (TaskListIterator tli(*sub); tli.hasNext();) {
2262 Task *t = static_cast<Task*>(tli.next());
2263 if (t->hasEndDependency())
2264 return true;
2265 }
2266
2267 return false;
2268 }
2269
2270 bool
2271 Task::preScheduleOk(int sc)
2272 {
2273 // if (account && !account->isLeaf())
2274 // {
2275 // errorMessage(QString
2276 // ("Task '%1' must not have an account group ('%2') "
2277 // "assigned to it.")
2278 // .arg(name).arg(account->getId()));
2279 // return false;
2280 // }
2281
2282 if (hasSubs() && !scenarios[sc].bookedResources.isEmpty())
2283 {
2284 errorMessage(QString
2285 ("Task '%1' is a container task and must not have "
2286 "bookings assigned to it.").arg(name));
2287 return false;
2288 }
2289
2290 if (milestone && !scenarios[sc].bookedResources.isEmpty())
2291 {
2292 errorMessage(QString
2293 ("Task '%1' is a milestone task and must not have "
2294 "bookings assigned to it.").arg(name));
2295 return false;
2296 }
2297
2298 if (scenarios[sc].specifiedScheduled && !sub->isEmpty() &&
2299 (scenarios[sc].specifiedStart == 0 ||
2300 scenarios[sc].specifiedEnd == 0))
2301 {
2302 errorMessage(QString
2303 ("Task '%1' is marked as scheduled but does not have "
2304 "a fixed start and end date.").arg(name));
2305 return false;
2306 }
2307
2308 if (scenarios[sc].effort > 0.0 && allocations.count() == 0 &&
2309 !scenarios[sc].specifiedScheduled)
2310 {
2311 errorMessage(QString
2312 ("No allocations specified for effort based task '%1'")
2313 .arg(name));
2314 return false;
2315 }
2316
2317 if (scenarios[sc].startBuffer + scenarios[sc].endBuffer >= 100.0)
2318 {
2319 errorMessage(QString
2320 ("Start and end buffers may not overlap. So their sum must be smaller then 100%."));
2321 return false;
2322 }
2323
2324 int durationSpec = 0;
2325 if (scenarios[sc].effort > 0.0)
2326 durationSpec++;
2327 if (scenarios[sc].length > 0.0)
2328 durationSpec++;
2329 if (scenarios[sc].duration > 0.0)
2330 durationSpec++;
2331 if (durationSpec > 1)
2332 {
2333 errorMessage(QString("Task '%1' may only have one duration "
2334 "criteria in '%2' scenario.").arg(name)
2335 .arg(project->getScenarioId(sc)));
2336 return false;
2337 }
2338
2339 /*
2340 |: fixed start or end date
2341 -: no fixed start or end date
2342 M: Milestone
2343 D: start or end dependency
2344 x->: ASAP task with duration criteria
2345 <-x: ALAP task with duration criteria
2346 -->: ASAP task without duration criteria
2347 <--: ALAP task without duration criteria
2348 */
2349 bool hasStartDep = hasStartDependency(sc);
2350 bool hasEndDep = hasEndDependency(sc);
2351 if (!sub->isEmpty())
2352 {
2353 if (durationSpec != 0)
2354 {
2355 errorMessage(QString
2356 ("Container task '%1' may not have a duration "
2357 "criteria in '%2' scenario").arg(name)
2358 .arg(project->getScenarioId(sc)));
2359 return false;
2360 }
2361 if (milestone)
2362 {
2363 errorMessage(QString
2364 ("The container task '%1' may not be a "
2365 "milestone.").arg(name));
2366 return false;
2367 }
2368 }
2369 else if (milestone)
2370 {
2371 if (durationSpec != 0)
2372 {
2373 errorMessage(QString
2374 ("Milestone '%1' may not have a duration "
2375 "criteria in '%2' scenario").arg(name)
2376 .arg(project->getScenarioId(sc)));
2377 return false;
2378 }
2379 /*
2380 | M - ok |D M - ok - M - err1 -D M - ok
2381 | M | err2 |D M | err2 - M | ok -D M | ok
2382 | M -D ok |D M -D ok - M -D ok -D M -D ok
2383 | M |D err2 |D M |D err2 - M |D ok -D M |D ok
2384 */
2385 /* err1: no start and end
2386 - M -
2387 */
2388 if (!hasStartDep && !hasEndDep)
2389 {
2390 errorMessage(QString("Milestone '%1' must have a start or end "
2391 "specification in '%2' scenario.")
2392 .arg(name).arg(project->getScenarioId(sc)));
2393 return false;
2394 }
2395 /* err2: different start and end
2396 | M |
2397 | M |D
2398 |D M |
2399 |D M |D
2400 */
2401 if (scenarios[sc].specifiedStart != 0 &&
2402 scenarios[sc].specifiedEnd != 0 &&
2403 scenarios[sc].specifiedStart != scenarios[sc].specifiedEnd + 1)
2404 {
2405 errorMessage(QString
2406 ("Milestone '%1' may not have both a start "
2407 "and an end specification that do not "
2408 "match in the '%2' scenario.").arg(name)
2409 .arg(project->getScenarioId(sc)));
2410 return false;
2411 }
2412 }
2413 else
2414 {
2415 /*
2416 Error table for non-container, non-milestone tasks:
2417
2418 | x-> - ok |D x-> - ok - x-> - err3 -D x-> - ok
2419 | x-> | err1 |D x-> | err1 - x-> | err3 -D x-> | err1
2420 | x-> -D ok |D x-> -D ok - x-> -D err3 -D x-> -D ok
2421 | x-> |D err1 |D x-> |D err1 - x-> |D err3 -D x-> |D err1
2422 | --> - err2 |D --> - err2 - --> - err3 -D --> - err2
2423 | --> | ok |D --> | ok - --> | err3 -D --> | ok
2424 | --> -D ok |D --> -D ok - --> -D err3 -D --> -D ok
2425 | --> |D ok |D --> |D ok - --> |D err3 -D --> |D ok
2426 | <-x - err4 |D <-x - err4 - <-x - err4 -D <-x - err4
2427 | <-x | err1 |D <-x | err1 - <-x | ok -D <-x | ok
2428 | <-x -D err1 |D <-x -D err1 - <-x -D ok -D <-x -D ok
2429 | <-x |D err1 |D <-x |D err1 - <-x |D ok -D <-x |D ok
2430 | <-- - err4 |D <-- - err4 - <-- - err4 -D <-- - err4
2431 | <-- | ok |D <-- | ok - <-- | err2 -D <-- | ok
2432 | <-- -D ok |D <-- -D ok - <-- -D err2 -D <-- -D ok
2433 | <-- |D ok |D <-- |D ok - <-- |D err2 -D <-- |D ok
2434 */
2435 /*
2436 err1: Overspecified (12 cases)
2437 | x-> |
2438 | <-x |
2439 | x-> |D
2440 | <-x |D
2441 |D x-> |
2442 |D <-x |
2443 |D <-x |D
2444 |D x-> |D
2445 -D x-> |
2446 -D x-> |D
2447 |D <-x -D
2448 | <-x -D
2449 */
2450 if (((scenarios[sc].specifiedStart != 0 &&
2451 scenarios[sc].specifiedEnd != 0) ||
2452 (hasStartDep && scenarios[sc].specifiedStart == 0 &&
2453 scenarios[sc].specifiedEnd != 0 && scheduling == ASAP) ||
2454 (scenarios[sc].specifiedStart != 0 && scheduling == ALAP &&
2455 hasEndDep && scenarios[sc].specifiedEnd == 0)) &&
2456 durationSpec != 0 && !scenarios[sc].specifiedScheduled)
2457 {
2458 errorMessage(QString("Task '%1' has a start, an end and a "
2459 "duration specification for '%2' scenario.")
2460 .arg(name).arg(project->getScenarioId(sc)));
2461 return false;
2462 }
2463 /*
2464 err2: Underspecified (6 cases)
2465 | --> -
2466 |D --> -
2467 -D --> -
2468 - <-- |
2469 - <-- |D
2470 - <-- -D
2471 */
2472 if ((hasStartDep ^ hasEndDep) && durationSpec == 0)
2473 {
2474 errorMessage(QString
2475 ("Task '%1' has only a start or end specification "
2476 "but no duration for the '%2' scenario.")
2477 .arg(name).arg(project->getScenarioId(sc)));
2478 return false;
2479 }
2480 /*
2481 err3: ASAP + Duration must have fixed start (8 cases)
2482 - x-> -
2483 - x-> |
2484 - x-> -D
2485 - x-> |D
2486 - --> -
2487 - --> |
2488 - --> -D
2489 - --> |D
2490 */
2491 if (!hasStartDep && scheduling == ASAP)
2492 {
2493 errorMessage(QString
2494 ("Task '%1' needs a start specification to be "
2495 "scheduled in ASAP mode in the '%2' scenario.")
2496 .arg(name).arg(project->getScenarioId(sc)));
2497 return false;
2498 }
2499 /*
2500 err4: ALAP + Duration must have fixed end (8 cases)
2501 - <-x -
2502 | <-x -
2503 |D <-x -
2504 -D <-x -
2505 - <-- -
2506 | <-- -
2507 -D <-- -
2508 |D <-- -
2509 */
2510 if (!hasEndDep && scheduling == ALAP)
2511 {
2512 errorMessage(QString
2513 ("Task '%1' needs an end specification to be "
2514 "scheduled in ALAP mode in the '%2' scenario.")
2515 .arg(name).arg(project->getScenarioId(sc)));
2516 return false;
2517 }
2518 }
2519
2520 // if (!account &&
2521 // (scenarios[sc].startCredit > 0.0 || scenarios[sc].endCredit > 0.0))
2522 // {
2523 // errorMessage(QString
2524 // ("Task '%1' has a specified start- or endcredit "
2525 // "but no account assigned in scenario '%2'.")
2526 // .arg(name).arg(project->getScenarioId(sc)));
2527 // return false;
2528 // }
2529
2530 if (!scenarios[sc].bookedResources.isEmpty() && scheduling == ALAP &&
2531 !scenarios[sc].specifiedScheduled)
2532 {
2533 errorMessage
2534 (QString("Error in task '%1'. "
2535 "An ALAP task can only have bookings if it has been "
2536 "completely scheduled. The 'scheduled' attribute must be "
2537 "present. Keep in mind that certain attributes such as "
2538 "'precedes' or 'end' implicitly set the scheduling mode "
2539 "to ALAP. Put 'scheduling asap' at the end of the task "
2540 "definition to avoid the problem.")
2541 .arg(name));
2542 return false;
2543 }
2544
2545 return true;
2546 }
2547
2548 bool
2549 Task::scheduleOk(int sc) const
2550 {
2551 // const QString scenario = project->getScenarioId(sc);
2552
2553 /* It is of little use to report errors of container tasks, if any of
2554 * their sub tasks has errors. */
2555 int oldErrors = TJMH.getErrors();
2556 for (TaskListIterator tli(*sub); tli.hasNext();) {
2557 Task *t = static_cast<Task*>(tli.next());
2558 t->scheduleOk(sc);
2559 }
2560 if (oldErrors != TJMH.getErrors())
2561 {
2562 if (DEBUGPS(2))
2563 tjDebug(QString("Scheduling errors in sub tasks of '%1'.")
2564 .arg(name));
2565 return false;
2566 }
2567
2568 /* Runaway errors have already been reported. Since the data of this task
2569 * is very likely completely bogus, we just return false. */
2570 if (runAway)
2571 return false;
2572
2573 if (DEBUGPS(3))
2574 qDebug()<<"Checking task"<<name;
2575
2576 /* If any of the dependent tasks is a runAway, we can safely suppress all
2577 * other error messages. */
2578 for (QListIterator<TaskDependency*> tdi(depends); tdi.hasNext();) {
2579 TaskDependency *td = static_cast<TaskDependency*>(tdi.next());
2580 if (td->getTaskRef()->runAway)
2581 return false;
2582 }
2583 for (QListIterator<TaskDependency*> tdi(precedes); tdi.hasNext();) {
2584 TaskDependency *td = static_cast<TaskDependency*>(tdi.next());
2585 if (td->getTaskRef()->runAway)
2586 return false;
2587 }
2588 if (start == 0)
2589 {
2590 warningMessage(xi18nc("@info/plain", "Start time is not calculated"));
2591 return false;
2592 }
2593 if (start < project->getStart() || start > project->getEnd())
2594 {
2595 warningMessage(xi18nc("@info/plain", "Start time %1 is outside of the project target times (%2 - %3)",
2596 formatTime(start),
2597 formatTime(project->getStart()),
2598 formatTime(project->getEnd())));
2599 return false;
2600 }
2601 #if 0
2602 NOT USED ATM
2603 if (scenarios[sc].minStart != 0 && start < scenarios[sc].minStart)
2604 {
2605 warningMessage(QString("'%1' start time of task '%2' is too early\n"
2606 "Date is: %3\n"
2607 "Limit is: %4")
2608 .arg(scenario).arg(name).arg(time2tjp(start))
2609 .arg(time2tjp(scenarios[sc].minStart)));
2610 return false;
2611 }
2612 if (scenarios[sc].maxStart != 0 && start > scenarios[sc].maxStart)
2613 {
2614 warningMessage(QString("'%1' start time of task '%2' is too late\n"
2615 "Date is: %3\n"
2616 "Limit is: %4")
2617 .arg(scenario).arg(name)
2618 .arg(time2tjp(start))
2619 .arg(time2tjp(scenarios[sc].maxStart)));
2620 return false;
2621 }
2622 #endif
2623 if (end == 0)
2624 {
2625 warningMessage(xi18nc("info/plain", "End time is not calculated"));
2626 return false;
2627 }
2628 if ((end + 1) < project->getStart() || (end > project->getEnd()))
2629 {
2630 warningMessage(xi18nc("info/plain", "End time %1 is outside of the project target times (%2 - %3)",
2631 formatTime(end + 1),
2632 formatTime(project->getStart()),
2633 formatTime(project->getEnd() + 1)));
2634 return false;
2635 }
2636 #if 0
2637 NOT USED ATM
2638 if (scenarios[sc].minEnd != 0 && end < scenarios[sc].minEnd)
2639 {
2640 warningMessage(QString("'%1' end time of task '%2' is too early\n"
2641 "Date is: %3\n"
2642 "Limit is: %4")
2643 .arg(scenario).arg(name)
2644 .arg(time2tjp(end + 1))
2645 .arg(time2tjp(scenarios[sc].minEnd + 1)));
2646 return false;
2647 }
2648 if (scenarios[sc].maxEnd != 0 && end > scenarios[sc].maxEnd)
2649 {
2650 warningMessage(QString("'%1' end time of task '%2' is too late\n"
2651 "Date is: %2\n"
2652 "Limit is: %3")
2653 .arg(scenario).arg(name)
2654 .arg(time2tjp(end + 1))
2655 .arg(time2tjp(scenarios[sc].maxEnd + 1)));
2656 return false;
2657 }
2658 if (!sub->isEmpty())
2659 {
2660 // All sub task must fit into their parent task.
2661 for (TaskListIterator tli(*sub); tli.hasNext();)
2662 {
2663 Task *t = static_cast<Task*>(tli.next());
2664 if (start > t->start)
2665 {
2666 if (!t->runAway)
2667 {
2668 errorMessage(QString("Task '%1' has earlier '%2' start than "
2669 "parent\n"
2670 "%3 start date: %4\n"
2671 "%5 start date: %6")
2672 .arg(t->getId()).arg(scenario)
2673 .arg(name)
2674 .arg(time2ISO(start))
2675 .arg(t->getId())
2676 .arg(time2ISO(t->start)));
2677 }
2678 return false;
2679 }
2680 if (end < t->end)
2681 {
2682 if (!t->runAway)
2683 {
2684 errorMessage(QString("Task '%1' has later '%2' end than "
2685 "parent")
2686 .arg(name).arg(scenario));
2687 }
2688 return false;
2689 }
2690 }
2691 }
2692 #endif
2693 // Check if all previous tasks end before start of this task.
2694 for (TaskListIterator tli(predecessors); tli.hasNext();) {
2695 Task *t = static_cast<Task*>(tli.next());
2696 if (t->end > start && !t->runAway) {
2697 if (t->end == 0) {
2698 warningMessage(xi18nc("@info/plain", "Impossible dependency:<nl/>"
2699 "Predeccessor task '%1': End time not calculated", t->getName()));
2700 } else {
2701 warningMessage(xi18nc("@info/plain", "Impossible dependency:<nl/>"
2702 "Task '%1' ends at %2 but must precede<nl/>"
2703 "task '%3' which starts at %4",
2704 t->getName(), formatTime(t->end + 1),
2705 name, formatTime(start)));
2706 }
2707 return false;
2708 }
2709 }
2710 // Check if all following task start after this tasks end.
2711 for (TaskListIterator tli(successors); tli.hasNext();) {
2712 Task *t = static_cast<Task*>(tli.next());
2713 if (end > t->start && !t->runAway) {
2714 if (t->start == 0) {
2715 warningMessage(xi18nc("@info/plain", "Impossible dependency:<nl/>"
2716 "Successor task '%1': Start time not calculated", t->getName()));
2717 } else {
2718 warningMessage(xi18nc("@info/plain", "Impossible dependency:<nl/>"
2719 "Task '%1' starts at %2 but must follow<nl/>"
2720 "task %3 which ends at %4",
2721 t->getName(), formatTime(t->start),
2722 name, formatTime(end + 1)));
2723 }
2724 return false;
2725 }
2726 }
2727 if (!schedulingDone)
2728 {
2729 warningMessage(xi18nc("info/plain", "Task has not been marked completed.\n"
2730 "It is scheduled to last from %1 to %2.\n"
2731 "This might be a bug in the scheduler.",
2732 formatTime(start), formatTime(end + 1)));
2733 return false;
2734 }
2735
2736 return true;
2737 }
2738
2739 time_t
2740 Task::nextSlot(time_t slotDuration) const
2741 {
2742 if (scheduling == ASAP)
2743 {
2744 if (lastSlot == 0)
2745 return start;
2746 return lastSlot + 1;
2747 }
2748 else
2749 {
2750 if (lastSlot == 0)
2751 return end - slotDuration + 1;
2752
2753 return lastSlot - slotDuration;
2754 }
2755
2756 return 0;
2757 }
2758
2759 bool
2760 Task::isReadyForScheduling() const
2761 {
2762 /* This function returns true if the tasks has all the necessary
2763 * information to be scheduled and has not been completely scheduled yet.
2764 */
2765 if (schedulingDone)
2766 return false;
2767
2768 if (scheduling == ASAP)
2769 {
2770 if (start != 0)
2771 {
2772 if (effort == 0.0 && length == 0.0 && duration == 0.0 &&
2773 !milestone && end == 0)
2774 return false;
2775
2776 return true;
2777 }
2778 }
2779 else
2780 {
2781 if (end != 0)
2782 {
2783 if (effort == 0.0 && length == 0.0 && duration == 0.0 &&
2784 !milestone && start == 0) {
2785 return false;
2786 }
2787
2788 return true;
2789 }
2790 }
2791 // TJMH.debugMessage(QString("Not ready for scheduling: %1 start=%2, end=%3").arg(scheduling==ASAP?"ASAP":"ALAP").arg(start).arg(end), this);
2792 return false;
2793 }
2794
2795 bool
2796 Task::isActive(int sc, const Interval& period) const
2797 {
2798 return period.overlaps(Interval(scenarios[sc].start,
2799 milestone ? scenarios[sc].start :
2800 scenarios[sc].end));
2801 }
2802
2803 bool
2804 Task::isSubTask(const Task* tsk) const
2805 {
2806 for (TaskListIterator tli(*sub); tli.hasNext();) {
2807 Task *t = static_cast<Task*>(tli.next());
2808 if (*tli == tsk || t->isSubTask(tsk))
2809 return true;
2810 }
2811 return false;
2812 }
2813
2814 void
2815 Task::overlayScenario(int base, int sc)
2816 {
2817 /* Copy all values that the scenario sc does not provide, but that are
2818 * provided by the base scenario to the scenario sc. */
2819 if (scenarios[sc].specifiedStart == 0)
2820 scenarios[sc].specifiedStart = scenarios[base].specifiedStart;
2821 if (scenarios[sc].specifiedEnd == 0)
2822 scenarios[sc].specifiedEnd = scenarios[base].specifiedEnd;
2823 if (scenarios[sc].minStart == 0)
2824 scenarios[sc].minStart = scenarios[base].minStart;
2825 if (scenarios[sc].maxStart == 0)
2826 scenarios[sc].maxStart = scenarios[base].maxStart;
2827 if (scenarios[sc].minEnd == 0)
2828 scenarios[sc].minEnd = scenarios[base].minEnd;
2829 if (scenarios[sc].maxEnd == 0)
2830 scenarios[sc].maxEnd = scenarios[base].maxEnd;
2831 if (scenarios[sc].duration == 0.0)
2832 scenarios[sc].duration = scenarios[base].duration;
2833 if (scenarios[sc].length == 0.0)
2834 scenarios[sc].length = scenarios[base].length;
2835 if (scenarios[sc].effort == 0.0)
2836 scenarios[sc].effort = scenarios[base].effort;
2837 if (scenarios[sc].startBuffer < 0.0)
2838 scenarios[sc].startBuffer = scenarios[base].startBuffer;
2839 if (scenarios[sc].endBuffer < 0.0)
2840 scenarios[sc].endBuffer = scenarios[base].endBuffer;
2841 if (scenarios[sc].startCredit < 0.0)
2842 scenarios[sc].startCredit = scenarios[base].startCredit;
2843 if (scenarios[sc].endCredit < 0.0)
2844 scenarios[sc].endCredit = scenarios[base].endCredit;
2845 if (scenarios[sc].reportedCompletion < 0.0)
2846 scenarios[sc].reportedCompletion = scenarios[base].reportedCompletion;
2847 }
2848
2849 void
2850 Task::prepareScenario(int sc)
2851 {
2852 start = scenarios[sc].start = scenarios[sc].specifiedStart;
2853 end = scenarios[sc].end = scenarios[sc].specifiedEnd;
2854 schedulingDone = scenarios[sc].scheduled = scenarios[sc].specifiedScheduled;
2855 scenarios[sc].isOnCriticalPath = false;
2856 scenarios[sc].pathCriticalness = -1.0;
2857
2858 duration = scenarios[sc].duration;
2859 length = scenarios[sc].length;
2860 effort = scenarios[sc].effort;
2861 lastSlot = 0;
2862 doneEffort = 0.0;
2863 doneDuration = 0.0;
2864 doneLength = 0.0;
2865 tentativeStart = tentativeEnd = 0;
2866 workStarted = false;
2867 runAway = false;
2868 bookedResources.clear();
2869 bookedResources = scenarios[sc].specifiedBookedResources;
2870
2871 /* The user could have made manual bookings already. The effort of these
2872 * bookings needs to be calculated so that the scheduler only schedules
2873 * the still missing effort. Scheduling will begin after the last booking.
2874 * This will only work for ASAP tasks. ALAP tasks cannot be partly booked.
2875 */
2876 time_t firstSlot = 0;
2877 for (ResourceListIterator rli(bookedResources); rli.hasNext();)
2878 {
2879 Resource *r = static_cast<Resource*>(rli.next());
2880 double effort = r->getEffectiveLoad
2881 (sc, Interval(project->getStart(), project->getEnd()),
2882 AllAccounts, this);
2883 if (effort > 0.0)
2884 {
2885 doneEffort += effort;
2886 if (firstSlot == 0 ||
2887 firstSlot > r->getStartOfFirstSlot(sc, this))
2888 {
2889 firstSlot = r->getStartOfFirstSlot(sc, this);
2890 }
2891 time_t ls = r->getEndOfLastSlot(sc, this);
2892 if (ls > lastSlot)
2893 lastSlot = ls;
2894 }
2895 }
2896
2897 if (lastSlot > 0)
2898 {
2899 if (schedulingDone)
2900 {
2901 /* If the done flag is set, the user declares that the task is
2902 * done. If no end date has been specified, set the start and end
2903 * date to the begin of the first slot and end of the last slot.
2904 */
2905 if (scenarios[sc].start == 0)
2906 start = scenarios[sc].start = firstSlot;
2907 if (scenarios[sc].end == 0)
2908 end = scenarios[sc].end = lastSlot;
2909 }
2910 else
2911 {
2912 /* Some bookings have been specified for the task, but it is not
2913 * marked completed yet. */
2914 workStarted = true;
2915 // Trim start to first booked time slot.
2916 start = firstSlot;
2917
2918 /* In projection mode, we assume that the completed work has been
2919 * reported with booking attributes. Now we compute the completion
2920 * degree according to the overall effort. Then the end date of
2921 * the task is calculated. */
2922 if (project->getScenario(sc)->getProjectionMode() && effort > 0.0)
2923 {
2924 scenarios[sc].reportedCompletion = doneEffort / effort * 100.0;
2925 if (scenarios[sc].reportedCompletion > 100.0)
2926 scenarios[sc].reportedCompletion = 100.0;
2927
2928 if (doneEffort >= effort)
2929 {
2930 /* In case the required effort is reached or exceeded by
2931 * the specified bookings for this task, we set the task
2932 * end to the last booking and mark the task as completely
2933 * scheduled. */
2934 end = scenarios[sc].end = lastSlot;
2935 schedulingDone = true;
2936
2937 /* We allow up to one time slot fuzziness before we
2938 * generate a warning. */
2939 if (project->getScenario(sc)->getStrictBookings() &&
2940 doneEffort > effort +
2941 project->convertToDailyLoad
2942 (project->getScheduleGranularity() - 1))
2943 {
2944 /* In case the bookings exceed the specified effort
2945 * in strict mode, show a warning. */
2946 warningMessage(xi18nc("info/plain", "Planned effort %1 exceeds estimated effort %2",
2947 doneEffort,
2948 effort));
2949 }
2950 }
2951 else
2952 lastSlot = project->getNow() - 1;
2953 }
2954 }
2955 }
2956
2957 /*
2958 * To determine the criticalness of an effort based task, we need to
2959 * determine the allocation probability of all of the resources. The more
2960 * the resources that are allocated to a task are allocated the smaller is
2961 * the likelihood that the task will get it's allocation, the more
2962 * critical it is.
2963 *
2964 * The allocation probability of a resource for this task is basically
2965 * effort divided by number of allocated resources. Since the efficiency
2966 * of resources can vary we need to determine the overall efficiency
2967 * first.
2968 *
2969 * TODO: We need to respect limits and shifts here!
2970 */
2971 double allocationEfficiency = 0;
2972 for (QListIterator<Allocation*> ali(allocations); ali.hasNext();)
2973 {
2974 Allocation *a = static_cast<Allocation*>(ali.next());
2975 a->init();
2976 if (a->isPersistent() && !bookedResources.isEmpty())
2977 {
2978 /* If the allocation is persistent and we have already bookings,
2979 * we need to find the resource with the last booking for this
2980 * task and save it as looked resource. */
2981 time_t lastSlot = 0;
2982 Resource* lastResource = nullptr;
2983 for (QListIterator<Resource*> rli = a->getCandidatesIterator(); rli.hasNext();) {
2984 Resource *r = static_cast<Resource*>(rli.next());
2985 for (ResourceTreeIterator rti(r); *rti; ++rti) {
2986 if (bookedResources.indexOf(*rti) != -1 &&
2987 (lastResource == nullptr ||
2988 lastSlot < (*rti)->getEndOfLastSlot(sc, this)))
2989 {
2990 lastSlot = (*rti)->getEndOfLastSlot(sc, this);
2991 lastResource = r;
2992 }
2993 }
2994 }
2995 a->setLockedResource(lastResource);
2996 }
2997 if (scenarios[sc].effort > 0.0)
2998 {
2999 double maxEfficiency = 0;
3000 for (QListIterator<Resource*> rli = a->getCandidatesIterator(); rli.hasNext();)
3001 {
3002 Resource *r = static_cast<Resource*>(rli.next());
3003 for (ResourceTreeIterator rti(r); *rti; ++rti) {
3004 if ((*rti)->getEfficiency() > maxEfficiency)
3005 maxEfficiency = (*rti)->getEfficiency();
3006 }
3007 }
3008 allocationEfficiency += maxEfficiency;
3009 }
3010 }
3011 if (scenarios[sc].effort > 0.0)
3012 {
3013 /* Now we can add the allocation probability for this task to all the
3014 * individual resources. */
3015 double effortPerResource = effort / allocationEfficiency;
3016 for (QListIterator<Allocation*> ali(allocations); ali.hasNext();) {
3017 Allocation *a = static_cast<Allocation*>(ali.next());
3018 for (QListIterator<Resource*> rli = a->getCandidatesIterator(); rli.hasNext();) {
3019 Resource *r = static_cast<Resource*>(rli.next());
3020 for (ResourceTreeIterator rti(r); *rti; ++rti) {
3021 (*rti)->addAllocationProbability
3022 (sc, effortPerResource * (*rti)->getEfficiency());
3023 }
3024 }
3025 }
3026 }
3027 }
3028
3029 void
3030 Task::computeCriticalness(int sc)
3031 {
3032 if (scenarios[sc].effort > 0.0)
3033 {
3034 double overallAllocationProbability = 0;
3035 for (QListIterator<Allocation*> ali(allocations); ali.hasNext();)
3036 {
3037 /* We assume that out of the candidates for an allocation the
3038 * one with the smallest overall allocation probability will
3039 * be assigned to the task. */
3040 Allocation *a = static_cast<Allocation*>(ali.next());
3041 double smallestAllocationProbablity = 0;
3042 for (QListIterator<Resource*> rli =
3043 a->getCandidatesIterator(); rli.hasNext();)
3044 {
3045 /* If the candidate is a resource group we use the average
3046 * allocation probability of all the resources of the group.
3047 */
3048 int resources = 0;
3049 double averageProbability = 0.0;
3050 for (ResourceTreeIterator rti(rli.next()); *rti; ++rti, ++resources) {
3051 averageProbability +=
3052 (*rti)->getAllocationProbability(sc);
3053 }
3054 if (resources > 0)
3055 averageProbability /= resources;
3056
3057 if (smallestAllocationProbablity == 0 ||
3058 averageProbability < smallestAllocationProbablity)
3059 smallestAllocationProbablity = averageProbability;
3060 }
3061 overallAllocationProbability += smallestAllocationProbablity;
3062 }
3063 /* New we normalize the allocationProbability to the duration of the
3064 * project (working days). For a resource that is statistically
3065 * allocated no more and no less than the number of working days in
3066 * the expected project time the probability will be one. This
3067 * certainly neglects many things like vacations, shifts, parallel
3068 * assignments and other factors. But we don't know enough about
3069 * these factors yet, to take them into account. So we have to live
3070 * with what we got. */
3071 overallAllocationProbability /=
3072 allocations.count() *
3073 ((project->getEnd() - project->getStart()) / (60.0 * 60 * 24)) *
3074 (project->getYearlyWorkingDays() / 365.0);
3075 /* Weight the average allocation probability with the effort of the
3076 * task. The higher the effort and the higher the probability that the
3077 * resources are allocated, the more critical the task rating gets. To
3078 * ensure that the criticalness is at least as high as a comparable
3079 * 'length' tasks use the effort value as a baseline and add the
3080 * weighted effort ontop. */
3081 scenarios[sc].criticalness = (1 + overallAllocationProbability) *
3082 scenarios[sc].effort;
3083 }
3084 else if (scenarios[sc].duration > 0.0)
3085 scenarios[sc].criticalness = duration;
3086 else if (scenarios[sc].length > 0.0)
3087 scenarios[sc].criticalness = length *
3088 (365 / project->getYearlyWorkingDays());
3089 else if (isMilestone())
3090 {
3091 /* People think of milestones usually as something important. So let's
3092 * assume a milestone has the importance of a full working day. This
3093 * is only done to raise the criticalness of paths that contain
3094 * milestones. */
3095 scenarios[sc].criticalness = 1.0;
3096 }
3097 else
3098 scenarios[sc].criticalness = 0;
3099
3100 }
3101
3102 double
3103 Task::computePathCriticalness(int sc)
3104 {
3105 /*
3106 * The path criticalness is a measure for the overall criticalness of the
3107 * task taking the dependencies into account. The fact that a task is part
3108 * of a chain of effort-based task raises all the task in the chain to a
3109 * higher criticalness level than the individual tasks. In fact, the path
3110 * criticalness of this chain is equal to the sum of the individual
3111 * criticalnesses of the tasks that are trailing this task. It does not
3112 * take the user-defined priorities into account.
3113 */
3114 // If the value has been computed already, just return it.
3115 if (scenarios[sc].pathCriticalness >= 0.0)
3116 return scenarios[sc].pathCriticalness;
3117
3118 double maxCriticalness = 0.0;
3119 if (hasSubs())
3120 {
3121 double criticalness;
3122 for (TaskListIterator tli(getSubListIterator()); tli.hasNext();)
3123 {
3124 Task *t = static_cast<Task*>(tli.next());
3125 criticalness = t->computePathCriticalness(sc);
3126
3127 if (criticalness > maxCriticalness)
3128 maxCriticalness = criticalness;
3129 }
3130 }
3131 else
3132 {
3133 /* We only care about leaf tasks because that's were the resources are
3134 * actually used. Container tasks are respected during path tracking,
3135 * though.
3136 * Therefore, we generate a list of all successors to this task. These
3137 * are directly specified successors or successors of any of the
3138 * parent tasks of this task. */
3139 TaskList followerList;
3140 Task* t = this;
3141 while (t)
3142 {
3143 for (TaskListIterator tli(t->followers); tli.hasNext();) {
3144 Task *t = static_cast<Task*>(tli.next());
3145 if (followerList.indexOf(t) == -1)
3146 followerList.append(t);
3147 }
3148 t = static_cast<Task*>(t->parent);
3149 }
3150
3151
3152 double criticalness;
3153 for (TaskListIterator tli(followerList); tli.hasNext();)
3154 {
3155 Task *t = static_cast<Task*>(tli.next());
3156 criticalness = t->computePathCriticalness(sc);
3157
3158 if (criticalness > maxCriticalness)
3159 maxCriticalness = criticalness;
3160 }
3161 }
3162
3163 scenarios[sc].pathCriticalness = scenarios[sc].criticalness +
3164 maxCriticalness;
3165
3166 return scenarios[sc].pathCriticalness;
3167 }
3168
3169 void
3170 Task::checkAndMarkCriticalPath(int sc, double minSlack, time_t maxEnd)
3171 {
3172 // The algorithm has to start at a leaf task that has no predecessors.
3173 if (hasSubs() || !previous.isEmpty())
3174 return;
3175
3176 if (DEBUGPA(3))
3177 qDebug()<<"Starting critical path search at"<<id;
3178
3179 long worstMinSlackTime = static_cast<long>((maxEnd - getStart(sc)) *
3180 minSlack);
3181 long checks = 0;
3182 long found = 0;
3183 analyzePath(sc, minSlack, getStart(sc), 0, worstMinSlackTime, checks,
3184 found);
3185 }
3186
3187 bool
3188 Task::analyzePath(int sc, double minSlack, time_t pathStart, long busyTime,
3189 long worstMinSlackTime, long& checks, long& found)
3190 {
3191 /* Safeguard to limit the runtime for this NP hard algorithm. */
3192 long maxPaths = project->getScenario(sc)->getMaxPaths();
3193 if (maxPaths > 0 && checks >= maxPaths)
3194 return false;
3195
3196 if (DEBUGPA(14))
3197 qDebug()<<" * Checking task"<<id;
3198
3199 bool critical = false;
3200
3201 if (hasSubs())
3202 {
3203 if (DEBUGPA(15))
3204 qDebug()<<" > Sub check started for"<<id;
3205
3206 for (TaskListIterator tli(*sub); tli.hasNext();) {
3207 Task *t = static_cast<Task*>(tli.next());
3208 if (t->analyzePath(sc, minSlack, pathStart, busyTime,
3209 worstMinSlackTime, checks, found))
3210 critical = true;
3211 }
3212 if (DEBUGPA(15))
3213 qDebug()<<" < Sub check finished for"<<id;
3214 }
3215 else
3216 {
3217 busyTime += (getEnd(sc) + 1 - getStart(sc));
3218
3219 /* If we have enough slack already that the path cannot be critical,
3220 * we stop looking at the rest of the path. */
3221 long currentSlack = (getEnd(sc) + 1 - pathStart) - busyTime;
3222 if (currentSlack > worstMinSlackTime)
3223 {
3224 checks++;
3225 if (DEBUGPA(6))
3226 qDebug()<<"Path cannot be critical. Stopping at task"<<id;
3227 return false;
3228 }
3229
3230 /* Find out if any of the followers is a sibling of the parent of this
3231 * task. */
3232 bool hasBrotherFollower = false;
3233 for (TaskListIterator tli(followers); tli.hasNext() && !hasBrotherFollower;)
3234 for (Task* t = static_cast<Task*>(tli.next()); t; t = t->getParent())
3235 if (t == getParent())
3236 {
3237 hasBrotherFollower = true;
3238 break;
3239 }
3240
3241 /* We first have to gather a list of all followers of this task. This
3242 * list must also include the followers registered for all parent
3243 * tasks of this task as they are followers as well. */
3244 TaskList allFollowers;
3245 for (Task* task = this; task; task = task->getParent())
3246 {
3247 for (TaskListIterator tli(task->followers); tli.hasNext();) {
3248 Task *t = static_cast<Task*>(tli.next());
3249 if (allFollowers.indexOf(t) < 0)
3250 allFollowers.append(t);
3251 }
3252 /* If the task has a follower that is a sibling of the same parent
3253 * we ignore the parent followers. */
3254 if (hasBrotherFollower)
3255 break;
3256 }
3257
3258 /* Get a list of all transient followers that follow the direct and
3259 * indirect followers of this task. If the allFollowers list contain
3260 * any of the transient followers, we can ignore it later. */
3261 TaskList transientFollowers;
3262 for (TaskListIterator tli(allFollowers); tli.hasNext();) {
3263 Task *t = static_cast<Task*>(tli.next());
3264 t->collectTransientFollowers(transientFollowers);
3265 }
3266 /* For inherited dependencies we only follow the bottommost task that
3267 * is a follower. All parents in the allFollowers list are ignored. */
3268 TaskList ignoreList;
3269 for (TaskListIterator tli(allFollowers); tli.hasNext();) {
3270 Task *t = static_cast<Task*>(tli.next());
3271 for (Task* p = t->getParent(); p; p = p->getParent()) {
3272 if (allFollowers.indexOf(p) >= 0 && ignoreList.indexOf(p) < 0)
3273 ignoreList.append(p);
3274 }
3275 }
3276 /* Now we can check the paths through the remaining followers. */
3277 for (TaskListIterator tli(allFollowers); tli.hasNext();)
3278 {
3279 Task *t = static_cast<Task*>(tli.next());
3280 if (ignoreList.indexOf(t) >= 0 ||
3281 transientFollowers.indexOf(t) >= 0)
3282 continue;
3283
3284 if (DEBUGPA(16))
3285 qDebug()<<QString(" > Follower check started for %1").arg(t->id);
3286
3287 if (t->analyzePath(sc, minSlack, pathStart, busyTime,
3288 worstMinSlackTime, checks, found))
3289 {
3290 if (scenarios[sc].criticalLinks.indexOf(t) < 0)
3291 {
3292 if (DEBUGPA(5))
3293 qDebug()<<QString(" +++ Critical link %1 -> %2").arg(name).arg(t->id);
3294 scenarios[sc].criticalLinks.append(t);
3295 }
3296
3297 critical = true;
3298 }
3299
3300 if (DEBUGPA(16))
3301 qDebug()<<" < Follower check finished for"<<id;
3302 }
3303
3304 if (allFollowers.isEmpty())
3305 {
3306 // We've reached the end of a path. Now let's see if it's critical.
3307 long overallDuration = getEnd(sc) + 1 - pathStart;
3308 /* A path is considered critical if the ratio of busy time and
3309 * overall path time is above the minSlack threshold and the path
3310 * contains more than one task. */
3311 critical = overallDuration > 0 &&
3312 ((double) busyTime / overallDuration) > (1.0 - minSlack);
3313 if (critical)
3314 {
3315 found++;
3316 if (DEBUGPA(5))
3317 qDebug()<<"Critical path with"<<(100.0 - ((double) busyTime / overallDuration) * 100.0)<<"% slack ending at"<<id<<"found";
3318 }
3319 else
3320 {
3321 if (DEBUGPA(11))
3322 qDebug()<<"Path ending at"<<id<<"is not critical";
3323 }
3324 if (++checks == maxPaths)
3325 {
3326 warningMessage(QString("Maximum number of paths reached during "
3327 "critical path analysis. Set 'maxPaths' "
3328 "to 0 if you want an exhaustive search. "
3329 "Aborting critical paths detection."));
3330 return false;
3331 }
3332 if (checks % 100000 == 0 && DEBUGPA(1))
3333 qDebug()<<"Already check"<<checks<<"paths."<<found<<"critical found.";
3334 }
3335 }
3336
3337 if (critical)
3338 scenarios[sc].isOnCriticalPath = true;
3339
3340 if (DEBUGPA(14))
3341 qDebug()<<" - Check of task"<<id<<"completed ("<<checks<<")";
3342 return critical;
3343 }
3344
3345 void
3346 Task::collectTransientFollowers(TaskList& list)
3347 {
3348 if (hasSubs())
3349 {
3350 for (TaskListIterator tli(followers); tli.hasNext();) {
3351 Task *t = static_cast<Task*>(tli.next());
3352 if (list.indexOf(t) < 0)
3353 {
3354 list.append(t);
3355 t->collectTransientFollowers(list);
3356 }
3357 }
3358 }
3359 else
3360 {
3361 for (Task* task = getParent(); task; task = task->getParent()) {
3362 for (TaskListIterator tli(task->followers); tli.hasNext();) {
3363 Task *t = static_cast<Task*>(tli.next());
3364 if (list.indexOf(t) < 0)
3365 {
3366 list.append(t);
3367 t->collectTransientFollowers(list);
3368 }
3369 }
3370 }
3371 }
3372 }
3373
3374 void
3375 Task::finishScenario(int sc)
3376 {
3377 scenarios[sc].start = start;
3378 scenarios[sc].end = end;
3379 scenarios[sc].bookedResources = bookedResources;
3380 scenarios[sc].scheduled = schedulingDone;
3381 // qDebug()<<"finishScenario: '"<< name << "' finish: " << time2ISO(start) << " - " << time2ISO(end);
3382 }
3383
3384 void
3385 Task::computeBuffers()
3386 {
3387 int sg = project->getScheduleGranularity();
3388 for (int sc = 0; sc < project->getMaxScenarios(); sc++)
3389 {
3390 scenarios[sc].startBufferEnd = scenarios[sc].start - 1;
3391 scenarios[sc].endBufferStart = scenarios[sc].end + 1;
3392
3393 if (scenarios[sc].start == 0 || scenarios[sc].end == 0)
3394 {
3395 scenarios[sc].startBufferEnd = scenarios[sc].endBufferStart = 0;
3396 continue;
3397 }
3398
3399 if (duration > 0.0)
3400 {
3401 if (scenarios[sc].startBuffer > 0.0)
3402 scenarios[sc].startBufferEnd = scenarios[sc].start +
3403 static_cast<time_t>((scenarios[sc].end -
3404 scenarios[sc].start) *
3405 scenarios[sc].startBuffer / 100.0);
3406 if (scenarios[sc].endBuffer > 0.0)
3407 scenarios[sc].endBufferStart = scenarios[sc].end -
3408 static_cast<time_t>((scenarios[sc].end -
3409 scenarios[sc].start) *
3410 scenarios[sc].endBuffer / 100.0);
3411 }
3412 else if (length > 0.0)
3413 {
3414 double l;
3415 if (scenarios[sc].startBuffer > 0.0)
3416 {
3417 for (l = 0.0; scenarios[sc].startBufferEnd < scenarios[sc].end;
3418 scenarios[sc].startBufferEnd += sg)
3419 {
3420 if (project->isWorkingDay(scenarios[sc].startBufferEnd))
3421 l += (double) sg / ONEDAY;
3422 if (l >= scenarios[sc].length *
3423 scenarios[sc].startBuffer / 100.0)
3424 break;
3425 }
3426 }
3427 if (scenarios[sc].endBuffer > 0.0)
3428 {
3429 for (l = 0.0; scenarios[sc].endBufferStart >
3430 scenarios[sc].start; scenarios[sc].endBufferStart -= sg)
3431 {
3432 if (project->isWorkingDay(scenarios[sc].endBufferStart))
3433 l += (double) sg / ONEDAY;
3434 if (l >= scenarios[sc].length *
3435 scenarios[sc].endBuffer / 100.0)
3436 break;
3437 }
3438 }
3439 }
3440 else if (effort > 0.0)
3441 {
3442 double e;
3443 if (scenarios[sc].startBuffer > 0.0)
3444 {
3445 for (e = 0.0; scenarios[sc].startBufferEnd < scenarios[sc].end;
3446 scenarios[sc].startBufferEnd += sg)
3447 {
3448 e += getLoad(sc,
3449 Interval(scenarios[sc].startBufferEnd,
3450 scenarios[sc].startBufferEnd + sg));
3451 if (e >= scenarios[sc].effort *
3452 scenarios[sc].startBuffer / 100.0)
3453 break;
3454 }
3455 }
3456 if (scenarios[sc].endBuffer > 0.0)
3457 {
3458 for (e = 0.0; scenarios[sc].endBufferStart >
3459 scenarios[sc].start; scenarios[sc].endBufferStart -= sg)
3460 {
3461 e += getLoad(sc,
3462 Interval(scenarios[sc].endBufferStart - sg,
3463 scenarios[sc].endBufferStart));
3464 if (e >= scenarios[sc].effort *
3465 scenarios[sc].endBuffer / 100.0)
3466 break;
3467 }
3468 }
3469 }
3470 }
3471 }
3472
3473 void
3474 Task::calcCompletionDegree(int sc)
3475 {
3476 time_t now = project->getNow();
3477
3478 /* In-progress container task are pretty complex to deal with. The mixture
3479 * of effort, length and duration tasks makes it impossible to use one
3480 * coherent criteria to determine the progress of a task. */
3481 if (isContainer() && scenarios[sc].start < now && now <= scenarios[sc].end)
3482 calcContainerCompletionDegree(sc, now);
3483 else
3484 /* Calc completion for simple tasks and determine the task state. */
3485 scenarios[sc].calcCompletionDegree(now);
3486 }
3487
3488 double
3489 Task::getCompletionDegree(int sc) const
3490 {
3491 if(scenarios[sc].reportedCompletion >= 0.0)
3492 return(scenarios[sc].reportedCompletion);
3493
3494 return isContainer() && scenarios[sc].containerCompletion >= 0.0 ?
3495 scenarios[sc].containerCompletion : scenarios[sc].completionDegree;
3496 }
3497
3498 double
3499 Task::getCalcedCompletionDegree(int sc) const
3500 {
3501 return scenarios[sc].completionDegree;
3502 }
3503
3504 void
3505 Task::calcContainerCompletionDegree(int sc, time_t now)
3506 {
3507 assert(isContainer());
3508 assert(scenarios[sc].start < now && now <= scenarios[sc].end);
3509
3510 scenarios[sc].status = InProgress;
3511
3512 int totalMilestones = 0;
3513 int completedMilestones = 0;
3514 int reportedCompletedMilestones = 0;
3515 if (countMilestones(sc, now, totalMilestones, completedMilestones,
3516 reportedCompletedMilestones))
3517 {
3518 scenarios[sc].completionDegree = completedMilestones * 100.0 /
3519 totalMilestones;
3520 scenarios[sc].containerCompletion = reportedCompletedMilestones
3521 * 100.0 / totalMilestones;
3522 return;
3523 }
3524
3525 double totalEffort = 0.0;
3526 double completedEffort = 0.0;
3527 double reportedCompletedEffort = 0.0;
3528 if (sumUpEffort(sc, now, totalEffort, completedEffort,
3529 reportedCompletedEffort))
3530 {
3531 scenarios[sc].completionDegree = completedEffort * 100.0 /
3532 totalEffort;
3533 scenarios[sc].containerCompletion = reportedCompletedEffort * 100.0 /
3534 totalEffort;
3535 }
3536 else
3537 {
3538 /* We can't determine the completion degree for mixed work/non-work
3539 * tasks. So we use -1.0 as "in progress" value. */
3540 double comp = -1.0;
3541 if (scenarios[sc].start > now)
3542 comp = 0.0; // not yet started
3543 else if (scenarios[sc].end < now)
3544 comp = 100.0; // completed
3545 scenarios[sc].completionDegree =
3546 scenarios[sc].containerCompletion = comp;
3547 }
3548 }
3549
3550 double
3551 Task::getCompletedLoad(int sc) const
3552 {
3553 return getLoad(sc, Interval(project->getStart(), project->getEnd())) *
3554 getCompletionDegree(sc) / 100.0;
3555 }
3556
3557 double
3558 Task::getRemainingLoad(int sc) const
3559 {
3560 return getLoad(sc, Interval(project->getStart(), project->getEnd())) *
3561 (1.0 - getCompletionDegree(sc) / 100.0);
3562 }
3563
3564 bool
3565 Task::countMilestones(int sc, time_t now, int& totalMilestones,
3566 int& completedMilestones,
3567 int& reportedCompletedMilestones)
3568 {
3569 if (isContainer())
3570 {
3571 for (TaskListIterator tli(*sub); tli.hasNext();) {
3572 Task *t = static_cast<Task*>(tli.next());
3573 if (!t->countMilestones(sc, now, totalMilestones,
3574 completedMilestones,
3575 reportedCompletedMilestones))
3576 return false;
3577 }
3578 /* A reported completion for a container always overrides the computed
3579 * completion. */
3580 if (scenarios[sc].reportedCompletion >= 0.0)
3581 reportedCompletedMilestones = static_cast<int>(totalMilestones *
3582 scenarios[sc].reportedCompletion / 100.0);
3583
3584 return true;
3585 }
3586 else if (isMilestone())
3587 {
3588 totalMilestones++;
3589 if (scenarios[sc].start <= now)
3590 completedMilestones++;
3591
3592 if (scenarios[sc].reportedCompletion >= 100.0)
3593 reportedCompletedMilestones++;
3594 else
3595 if (scenarios[sc].start <= now)
3596 reportedCompletedMilestones++;
3597
3598 return true;
3599 }
3600
3601 return false;
3602 }
3603
3604 bool
3605 Task::sumUpEffort(int sc, time_t now, double& totalEffort,
3606 double& completedEffort, double& reportedCompletedEffort)
3607 {
3608 if (isContainer())
3609 {
3610 for (TaskListIterator tli(*sub); tli.hasNext();) {
3611 Task *t = static_cast<Task*>(tli.next());
3612 if (!t->sumUpEffort(sc, now, totalEffort, completedEffort,
3613 reportedCompletedEffort))
3614 return false;
3615 }
3616 /* A reported completion for a container always overrides the computed
3617 * completion. */
3618 if (scenarios[sc].reportedCompletion >= 0.0)
3619 reportedCompletedEffort = totalEffort *
3620 scenarios[sc].reportedCompletion / 100.0;
3621
3622 return true;
3623 }
3624 if (scenarios[sc].effort > 0.0)
3625 {
3626 /* Pure effort based tasks are simple to handle. The total effort is
3627 * specified and the effort up to 'now' can be computed. */
3628 totalEffort += scenarios[sc].effort;
3629 double load = getLoad(sc, Interval(scenarios[sc].start, now));
3630 if (scenarios[sc].start < now)
3631 completedEffort += load;
3632
3633 /* If the user reported a completion we use this instead of the
3634 * calculated completion. */
3635 if (scenarios[sc].reportedCompletion >= 0.0)
3636 reportedCompletedEffort +=
3637 getLoad(sc, Interval(scenarios[sc].start, scenarios[sc].end)) *
3638 scenarios[sc].reportedCompletion / 100.0;
3639 else
3640 reportedCompletedEffort += load;
3641
3642 return true;
3643 }
3644 if (!allocations.isEmpty())
3645 {
3646 /* This is for length and duration tasks that have allocations. We
3647 * handle them similar to effort tasks. Since there is no specified
3648 * total effort, we calculate the total allocated effort. */
3649 double totalLoad = getLoad(sc, Interval(scenarios[sc].start,
3650 scenarios[sc].end));
3651 totalEffort += totalLoad;
3652 double load = getLoad(sc, Interval(scenarios[sc].start, now));
3653 if (scenarios[sc].start < now)
3654 completedEffort += load;
3655
3656 /* If the user reported a completion we use this instead of the
3657 * calculated completion. */
3658 if (scenarios[sc].reportedCompletion >= 0.0)
3659 reportedCompletedEffort += totalLoad *
3660 scenarios[sc].reportedCompletion / 100.0;
3661 else
3662 reportedCompletedEffort += load;
3663
3664 return true;
3665 }
3666 if (isMilestone())
3667 {
3668 /* We assume that milestones are only dependent on sub tasks of this
3669 * tasks. So we can ignore them for the completion degree. In case
3670 * there is a non completed task that the milestone depends on, the
3671 * milestone is accounted for as well. This approximation should work
3672 * fine for most real world projects. */
3673 return true;
3674 }
3675
3676 return false;
3677 }
3678
3679 QDomElement Task::xmlElement(QDomDocument& doc, bool /* absId */)
3680 {
3681 QDomElement taskElem = doc.createElement("Task");
3682 /* QDomElement tempElem;
3683
3684 QString idStr = getId();
3685 if(!absId)
3686 idStr = idStr.section('.', -1);
3687
3688 taskElem.setAttribute("Id", idStr);
3689
3690 QDomText t;
3691 taskElem.appendChild(ReportXML::createXMLElem(doc, "Index", QString::number(getIndex())));
3692 taskElem.appendChild(ReportXML::createXMLElem(doc, "Name", getName()));
3693 taskElem.appendChild(ReportXML::createXMLElem(doc, "ProjectID", projectId));
3694 taskElem.appendChild(ReportXML::createXMLElem(doc, "Priority", QString::number(getPriority())));
3695
3696 double cmplt = getCompletionDegree(0);
3697 taskElem.appendChild(ReportXML::createXMLElem(doc, "complete", QString::number(cmplt, 'f', 1)));
3698
3699 QString tType = "Milestone";
3700 if(!isMilestone())
3701 {
3702 if(isContainer())
3703 tType = "Container";
3704 else
3705 tType = "Task";
3706
3707 }
3708 taskElem.appendChild(ReportXML::createXMLElem(doc, "Type", tType));
3709
3710 CoreAttributes *parent = getParent();
3711 if(parent)
3712 taskElem.appendChild(ReportXML::ReportXML::createXMLElem(doc, "ParentTask", parent->getId()));
3713
3714 if(!note.isEmpty())
3715 taskElem.appendChild(ReportXML::createXMLElem(doc, "Note", getNote()));
3716 if(!ref.isEmpty())
3717 taskElem.appendChild(ReportXML::createXMLElem(doc, "Reference",
3718 ref));
3719 if(!refLabel.isEmpty())
3720 taskElem.appendChild(ReportXML::createXMLElem(doc, "ReferenceLabel",
3721 refLabel));
3722
3723 if (scenarios[0].minStart != 0)
3724 {
3725 tempElem = ReportXML::createXMLElem
3726 (doc, "minStart", QString::number(scenarios[0].minStart));
3727 tempElem.setAttribute("humanReadable",
3728 time2ISO(scenarios[0].minStart));
3729 taskElem.appendChild(tempElem);
3730 }
3731
3732 if (scenarios[0].maxStart != 0)
3733 {
3734 tempElem = ReportXML::createXMLElem
3735 (doc, "maxStart", QString::number(scenarios[0].maxStart));
3736 tempElem.setAttribute("humanReadable",
3737 time2ISO(scenarios[0].maxStart));
3738 taskElem.appendChild(tempElem);
3739 }
3740
3741 if (scenarios[0].minEnd != 0)
3742 {
3743 tempElem = ReportXML::createXMLElem
3744 (doc, "minEnd", QString::number(scenarios[0].minEnd));
3745 tempElem.setAttribute("humanReadable",
3746 time2ISO(scenarios[0].minEnd));
3747 taskElem.appendChild(tempElem);
3748 }
3749
3750 if (scenarios[0].maxEnd != 0)
3751 {
3752 tempElem = ReportXML::createXMLElem
3753 (doc, "maxEnd", QString::number(scenarios[0].maxEnd));
3754 tempElem.setAttribute("humanReadable",
3755 time2ISO(scenarios[0].maxEnd));
3756 taskElem.appendChild(tempElem);
3757 }
3758 if (project->getMaxScenarios() > 1)
3759 {
3760 tempElem = ReportXML::createXMLElem(doc, "actualStart",
3761 QString::number(scenarios[1].start));
3762 tempElem.setAttribute("humanReadable",
3763 time2ISO(scenarios[1].start));
3764 taskElem.appendChild(tempElem);
3765
3766 tempElem = ReportXML::createXMLElem(doc, "actualEnd",
3767 QString::number(scenarios[1].end + 1));
3768 tempElem.setAttribute("humanReadable",
3769 time2ISO(scenarios[1].end + 1));
3770 taskElem.appendChild(tempElem);
3771 }
3772
3773 tempElem = ReportXML::createXMLElem(doc, "planStart", QString::number(scenarios[0].start));
3774 tempElem.setAttribute("humanReadable", time2ISO(scenarios[0].start));
3775 taskElem.appendChild(tempElem);
3776
3777 tempElem = ReportXML::createXMLElem(doc, "planEnd",
3778 QString::number(scenarios[0].end + 1));
3779 tempElem.setAttribute("humanReadable", time2ISO(scenarios[0].end + 1));
3780 taskElem.appendChild(tempElem);
3781
3782 // Start- and Endbuffer
3783 if(getStartBuffer(0) > 0.01)
3784 {
3785 // startbuffer exists
3786 tempElem = ReportXML::createXMLElem
3787 (doc, "startBufferSize",
3788 QString::number(getStartBuffer(0)));
3789 taskElem.appendChild(tempElem);
3790
3791 tempElem = ReportXML::createXMLElem
3792 (doc, "PlanStartBufferEnd",
3793 QString::number(getStartBufferEnd(0)));
3794 tempElem.setAttribute("humanReadable",
3795 time2ISO(getStartBufferEnd(0)));
3796 taskElem.appendChild(tempElem);
3797
3798 tempElem = ReportXML::createXMLElem
3799 (doc, "PlanStartBufferEnd",
3800 QString::number(getStartBufferEnd(0)));
3801 tempElem.setAttribute("humanReadable",
3802 time2ISO(getStartBufferEnd(0)));
3803 taskElem.appendChild(tempElem);
3804 }
3805
3806 if(getEndBuffer(0) > 0.01)
3807 {
3808 // startbuffer exists
3809 tempElem = ReportXML::createXMLElem
3810 (doc, "EndBufferSize", QString::number(getEndBuffer(0)));
3811 taskElem.appendChild(tempElem);
3812
3813 tempElem = ReportXML::createXMLElem
3814 (doc, "PlanEndBufferStart",
3815 QString::number(getEndBufferStart(0)));
3816 tempElem.setAttribute("humanReadable",
3817 time2ISO(getEndBufferStart(0)));
3818 taskElem.appendChild(tempElem);
3819
3820 tempElem = ReportXML::createXMLElem
3821 (doc, "PlanEndBufferStart",
3822 QString::number(getEndBufferStart(0)));
3823 tempElem.setAttribute("humanReadable",
3824 time2ISO(getStartBufferEnd(0)));
3825 taskElem.appendChild(tempElem);
3826 }
3827
3828 // Responsible persons
3829 if(getResponsible())
3830 taskElem.appendChild(getResponsible()->xmlIDElement(doc));
3831
3832 // Now start the subtasks
3833 int cnt = 0;
3834 QDomElement subTaskElem = doc.createElement("SubTasks");
3835 for (Task* t = subFirst(); t != 0; t = subNext())
3836 {
3837 if(t != this)
3838 {
3839 QDomElement sTask = t->xmlElement(doc, false);
3840 subTaskElem.appendChild(sTask);
3841 cnt++;
3842 }
3843 }
3844 if(cnt > 0)
3845 taskElem.appendChild(subTaskElem);
3846
3847 // list of tasks by id which are previous
3848 if(previous.count() > 0)
3849 {
3850 for (TaskListIterator tli(previous); tli.hasNext();)
3851 {
3852 Task *t = static_cast<Task*>(tli.next());
3853 if(*tli != this)
3854 {
3855 taskElem.appendChild(ReportXML::createXMLElem(doc, "Previous",
3856 t->getId()));
3857 }
3858 }
3859 }
3860
3861 // list of tasks by id which follow
3862 if(followers.count() > 0)
3863 {
3864 for (TaskListIterator tli(followers); tli.hasNext();)
3865 {
3866 Task *t = static_cast<Task*>(tli.next());
3867 if(t != this)
3868 {
3869 taskElem.appendChild(ReportXML::createXMLElem(doc, "Follower",
3870 (t)->getId()));
3871 }
3872 }
3873 }
3874
3875 ** Allocations and Booked Resources
3876 * With the following code, the task in XML contains simply a list of all Allocations
3877 * with the ResourceID for which resource the allocation is. After that, there comes
3878 * a list of all Resources, again having the Resource Id as key. That could be put
3879 * in a hierarchy like
3880 * <Resource Id="dev2" >Larry Bono
3881 * <Income>1000</Income>
3882 * <Allocation>
3883 * <Load>100</Load>
3884 * <Persistent>Yes</Persistent>
3885 * </Allocation>
3886 * </Resource>
3887 *
3888 * But we do not ;-) to have full flexibility.
3889 *
3890 *
3891 // Allocations
3892 if(allocations.count() > 0)
3893 {
3894 QPtrList<Allocation> al(allocations);
3895 for (QListIterator<Allocation*> ali(al); ali.hasNext();)
3896 {
3897 Allocation *a = static_cast<Allocation*>(ali.next());
3898 taskElem.appendChild(a->xmlElement(doc));
3899 }
3900 }
3901
3902 // booked Resources
3903 if(bookedResources.count() > 0)
3904 {
3905 for (ResourceListIterator rli(bookedResources); *rli != 0; ++rli)
3906 {
3907 taskElem.appendChild(r->xmlIDElement(doc));
3908 }
3909 }
3910 */
3911 return(taskElem);
3912 }
3913
3914 bool
3915 Task::isOrHasDescendantOnCriticalPath(int sc) const
3916 {
3917 if (isOnCriticalPath(sc, false))
3918 return true;
3919 if (isContainer())
3920 {
3921 for (TaskListIterator tli = getSubListIterator(); tli.hasNext();) {
3922 Task *t = static_cast<Task*>(tli.next());
3923 if (t->isOrHasDescendantOnCriticalPath(sc))
3924 return true;
3925 }
3926 }
3927 return false;
3928 }
3929
3930 } // namespace TJ
3931
3932 QDebug operator<<(QDebug dbg, const TJ::Task* t)
3933 {
3934 if (t == nullptr) {
3935 return dbg << (void*)t;
3936 }
3937 return operator<<(dbg, *t);
3938 }
3939
3940 QDebug operator<<(QDebug dbg, const TJ::Task& t)
3941 {
3942 dbg << (t.isMilestone() ? "Milestone[" : "Task[");
3943 dbg << t.getName() << (t.getScheduling() == TJ::Task::ASAP ? "(ASAP)" : "(ALAP)");
3944 if (t.isSchedulingDone()) {
3945 dbg << "Scheduled";
3946 } else if (t.isReadyForScheduling()) {
3947 dbg << "ReadyForScheduling";
3948 } else if (t.isRunaway()) {
3949 dbg << "Runaway";
3950 }
3951 dbg << "]";
3952 return dbg;
3953 }