/usr/share/pyshared/trytond/modules/project_plan/work.py is in tryton-modules-project-plan 3.0.0-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 | #This file is part of Tryton. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import datetime
from collections import deque, defaultdict
from heapq import heappop, heappush
from trytond.model import ModelSQL, fields
from trytond.wizard import Wizard, StateTransition
from trytond.pyson import Eval
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Work', 'PredecessorSuccessor', 'Leveling']
__metaclass__ = PoolMeta
def intfloor(x):
return int(round(x, 4))
class Work:
__name__ = 'project.work'
predecessors = fields.Many2Many('project.predecessor_successor',
'successor', 'predecessor', 'Predecessors',
domain=[
('parent', '=', Eval('parent')),
('id', '!=', Eval('id')),
],
depends=['parent', 'id'])
successors = fields.Many2Many('project.predecessor_successor',
'predecessor', 'successor', 'Successors',
domain=[
('parent', '=', Eval('parent')),
('id', '!=', Eval('id')),
],
depends=['parent', 'id'])
leveling_delay = fields.Float("Leveling Delay", required=True)
back_leveling_delay = fields.Float("Back Leveling Delay", required=True)
allocations = fields.One2Many('project.allocation', 'work', 'Allocations',
states={
'invisible': Eval('type') != 'task',
}, depends=['type'])
duration = fields.Function(fields.Float('Duration'), 'get_function_fields')
early_start_time = fields.DateTime("Early Start Time", readonly=True)
late_start_time = fields.DateTime("Late Start Time", readonly=True)
early_finish_time = fields.DateTime("Early Finish Time", readonly=True)
late_finish_time = fields.DateTime("Late Finish Time", readonly=True)
actual_start_time = fields.DateTime("Actual Start Time")
actual_finish_time = fields.DateTime("Actual Finish Time")
constraint_start_time = fields.DateTime("Constraint Start Time")
constraint_finish_time = fields.DateTime("Constraint Finish Time")
early_start_date = fields.Function(fields.Date('Early Start'),
'get_function_fields')
late_start_date = fields.Function(fields.Date('Late Start'),
'get_function_fields')
early_finish_date = fields.Function(fields.Date('Early Finish'),
'get_function_fields')
late_finish_date = fields.Function(fields.Date('Late Finish'),
'get_function_fields')
actual_start_date = fields.Function(fields.Date('Actual Start'),
'get_function_fields', setter='set_function_fields')
actual_finish_date = fields.Function(fields.Date('Actual Finish'),
'get_function_fields', setter='set_function_fields')
constraint_start_date = fields.Function(fields.Date('Constraint Start',
depends=['type']), 'get_function_fields',
setter='set_function_fields')
constraint_finish_date = fields.Function(fields.Date('Constraint Finish',
depends=['type']), 'get_function_fields',
setter='set_function_fields')
@classmethod
def __setup__(cls):
super(Work, cls).__setup__()
@classmethod
def validate(cls, works):
super(Work, cls).validate(works)
cls.check_recursion(works, parent='successors')
@staticmethod
def default_leveling_delay():
return 0.0
@staticmethod
def default_back_leveling_delay():
return 0.0
@classmethod
def get_function_fields(cls, works, names):
'''
Function to compute function fields
'''
res = {}
ids = [w.id for w in works]
if 'duration' in names:
all_works = cls.search([
('parent', 'child_of', ids),
('active', '=', True)]) + works
all_works = set(all_works)
durations = {}
id2work = {}
leafs = set()
for work in all_works:
id2work[work.id] = work
if not work.children:
leafs.add(work.id)
total_allocation = 0
if not work.allocations:
durations[work.id] = work.effort
continue
for allocation in work.allocations:
total_allocation += allocation.percentage
durations[work.id] = work.effort / (total_allocation / 100.0)
while leafs:
for work_id in leafs:
work = id2work[work_id]
all_works.remove(work)
if not work.active:
continue
if work.parent and work.parent.id in durations:
durations[work.parent.id] += durations[work_id]
next_leafs = set(w.id for w in all_works)
for work in all_works:
if not work.parent:
continue
if work.parent.id in next_leafs and work.parent in works:
next_leafs.remove(work.parent.id)
leafs = next_leafs
res['duration'] = durations
fun_fields = ('early_start_date', 'early_finish_date',
'late_start_date', 'late_finish_date',
'actual_start_date', 'actual_finish_date',
'constraint_start_date', 'constraint_finish_date')
db_fields = ('early_start_time', 'early_finish_time',
'late_start_time', 'late_finish_time',
'actual_start_time', 'actual_finish_time',
'constraint_start_time', 'constraint_finish_time')
for fun_field, db_field in zip(fun_fields, db_fields):
if fun_field in names:
values = {}
for work in works:
values[work.id] = getattr(work, db_field) \
and getattr(work, db_field).date() or None
res[fun_field] = values
return res
@classmethod
def set_function_fields(cls, works, name, value):
fun_fields = ('actual_start_date', 'actual_finish_date',
'constraint_start_date', 'constraint_finish_date')
db_fields = ('actual_start_time', 'actual_finish_time',
'constraint_start_time', 'constraint_finish_time')
for fun_field, db_field in zip(fun_fields, db_fields):
if fun_field == name:
cls.write(works, {
db_field: (value
and datetime.datetime.combine(value,
datetime.time())
or None),
})
break
@classmethod
def add_minutes(cls, company, date, minutes):
minutes = int(round(minutes))
minutes = date.minute + minutes
hours = minutes // 60
if hours:
date = cls.add_hours(company, date, hours)
minutes = minutes % 60
date = datetime.datetime(
date.year,
date.month,
date.day,
date.hour,
minutes,
date.second)
return date
@classmethod
def add_hours(cls, company, date, hours):
while hours:
if hours != intfloor(hours):
minutes = (hours - intfloor(hours)) * 60
date = cls.add_minutes(company, date, minutes)
hours = intfloor(hours)
hours = date.hour + hours
days = hours // company.hours_per_work_day
if days:
date = cls.add_days(company, date, days)
hours = hours % company.hours_per_work_day
date = datetime.datetime(
date.year,
date.month,
date.day,
intfloor(hours),
date.minute,
date.second)
hours = hours - intfloor(hours)
return date
@classmethod
def add_days(cls, company, date, days):
day_per_week = company.hours_per_work_week / company.hours_per_work_day
while days:
if days != intfloor(days):
hours = (days - intfloor(days)) * company.hours_per_work_day
date = cls.add_hours(company, date, hours)
days = intfloor(days)
days = date.weekday() + days
weeks = days // day_per_week
days = days % day_per_week
if weeks:
date = cls.add_weeks(company, date, weeks)
date += datetime.timedelta(days=-date.weekday() + intfloor(days))
days = days - intfloor(days)
return date
@classmethod
def add_weeks(cls, company, date, weeks):
day_per_week = company.hours_per_work_week / company.hours_per_work_day
if weeks != intfloor(weeks):
days = (weeks - intfloor(weeks)) * day_per_week
if days:
date = cls.add_days(company, date, days)
date += datetime.timedelta(days=7 * intfloor(weeks))
return date
def compute_dates(self):
values = {}
get_early_finish = lambda work: values.get(work, {}).get(
'early_finish_time', work.early_finish_time)
get_late_start = lambda work: values.get(work, {}).get(
'late_start_time', work.late_start_time)
maxdate = lambda x, y: x and y and max(x, y) or x or y
mindate = lambda x, y: x and y and min(x, y) or x or y
# propagate constraint_start_time
constraint_start = reduce(maxdate, (pred.early_finish_time
for pred in self.predecessors), None)
if constraint_start is None and self.parent:
constraint_start = self.parent.early_start_time
constraint_start = maxdate(constraint_start,
self.constraint_start_time)
works = deque([(self, constraint_start)])
work2children = {}
parent = None
while works or parent:
if parent:
work = parent
parent = None
# Compute early_finish
if work.children:
early_finish_time = reduce(
maxdate, map(get_early_finish, work.children), None)
else:
early_finish_time = None
if values[work]['early_start_time']:
early_finish_time = self.add_hours(work.company,
values[work]['early_start_time'],
work.duration)
values[work]['early_finish_time'] = early_finish_time
# Propagate constraint_start on successors
for w in work.successors:
works.append((w, early_finish_time))
if not work.parent:
continue
# housecleaning work2children
if work.parent not in work2children:
work2children[work.parent] = set()
work2children[work.parent].update(work.successors)
if work in work2children[work.parent]:
work2children[work.parent].remove(work)
# if no sibling continue to walk up the tree
if not work2children.get(work.parent):
if not work.parent in values:
values[work.parent] = {}
parent = work.parent
continue
work, constraint_start = works.popleft()
# take constraint define on the work into account
constraint_start = maxdate(constraint_start,
work.constraint_start_time)
if constraint_start:
early_start = self.add_hours(work.company, constraint_start,
work.leveling_delay)
else:
early_start = None
# update values
if not work in values:
values[work] = {}
values[work]['early_start_time'] = early_start
# Loop on children if they exist
if work.children and work not in work2children:
work2children[work] = set(work.children)
# Propagate constraint_start on children
for w in work.children:
if w.predecessors:
continue
works.append((w, early_start))
else:
parent = work
# propagate constraint_finish_time
constraint_finish = reduce(mindate, (succ.late_start_time
for succ in self.successors), None)
if constraint_finish is None and self.parent:
constraint_finish = self.parent.late_finish_time
constraint_finish = mindate(constraint_finish,
self.constraint_finish_time)
works = deque([(self, constraint_finish)])
work2children = {}
parent = None
while works or parent:
if parent:
work = parent
parent = None
# Compute late_start
if work.children:
reduce(mindate, map(get_late_start, work.children), None)
else:
late_start_time = None
if values[work]['late_finish_time']:
late_start_time = self.add_hours(work.company,
values[work]['late_finish_time'],
-work.duration)
values[work]['late_start_time'] = late_start_time
# Propagate constraint_finish on predecessors
for w in work.predecessors:
works.append((w, late_start_time))
if not work.parent:
continue
# housecleaning work2children
if work.parent not in work2children:
work2children[work.parent] = set()
work2children[work.parent].update(work.predecessors)
if work in work2children[work.parent]:
work2children[work.parent].remove(work)
# if no sibling continue to walk up the tree
if not work2children.get(work.parent):
if not work.parent in values:
values[work.parent] = {}
parent = work.parent
continue
work, constraint_finish = works.popleft()
# take constraint define on the work into account
constraint_finish = mindate(constraint_finish,
work.constraint_finish_time)
if constraint_finish:
late_finish = self.add_hours(work.company, constraint_finish,
-work.back_leveling_delay)
else:
late_finish = None
# update values
if not work in values:
values[work] = {}
values[work]['late_finish_time'] = late_finish
# Loop on children if they exist
if work.children and work not in work2children:
work2children[work] = set(work.children)
# Propagate constraint_start on children
for w in work.children:
if w.successors:
continue
works.append((w, late_finish))
else:
parent = work
# write values
write_fields = ('early_start_time', 'early_finish_time',
'late_start_time', 'late_finish_time')
for work, val in values.iteritems():
write_cond = False
for field in write_fields:
if field in val and getattr(work, field) != val[field]:
write_cond = True
break
if write_cond:
self.write([work], val)
def reset_leveling(self):
get_key = lambda w: (set(p.id for p in w.predecessors),
set(s.id for s in w.successors))
parent_id = self.parent and self.parent.id or None
siblings = self.search([
('parent', '=', parent_id)
])
to_clean = []
ref_key = get_key(self)
for sibling in siblings:
if sibling.leveling_delay == sibling.back_leveling_delay == 0:
continue
if get_key(sibling) == ref_key:
to_clean.append(sibling)
if to_clean:
self.write(to_clean, {
'leveling_delay': 0,
'back_leveling_delay': 0,
})
def create_leveling(self):
# define some helper functions
get_key = lambda w: (set(p.id for p in w.predecessors),
set(s.id for s in w.successors))
over_alloc = lambda current_alloc, work: (
reduce(lambda res, alloc: (res
or (current_alloc[alloc.employee.id]
+ alloc.percentage) > 100),
work.allocations,
False))
def sum_allocs(current_alloc, work):
res = defaultdict(float)
for alloc in work.allocations:
empl = alloc.employee.id
res[empl] = current_alloc[empl] + alloc.percentage
return res
def compute_delays(siblings):
# time_line is a list [[end_delay, allocations], ...], this
# mean that allocations is valid between the preceding end_delay
# (or 0 if it doesn't exist) and the current end_delay.
timeline = []
for sibling in siblings:
delay = 0
ignored = []
overloaded = []
item = None
while timeline:
# item is [end_delay, allocations]
item = heappop(timeline)
if over_alloc(item[1], sibling):
ignored.extend(overloaded)
ignored.append(item)
delay = item[0]
continue
elif item[1] >= delay + sibling.duration:
overloaded.append(item)
else:
#Succes!
break
heappush(timeline,
[delay + sibling.duration,
sum_allocs(defaultdict(float), sibling),
sibling.id])
for i in ignored:
heappush(timeline, i)
for i in overloaded:
i[1] = sum_allocs(i[1], sibling)
heappush(timeline, i)
yield sibling, delay
siblings = self.search([
('parent', '=', self.parent.id if self.parent else None)
])
refkey = get_key(self)
siblings = [s for s in siblings if get_key(s) == refkey]
for sibling, delay in compute_delays(siblings):
self.write([sibling], {
'leveling_delay': delay,
})
siblings.reverse()
for sibling, delay in compute_delays(siblings):
self.write([sibling], {
'back_leveling_delay': delay,
})
if self.parent:
self.parent.compute_dates()
@classmethod
def write(cls, works, values):
super(Work, cls).write(works, values)
if 'effort' in values:
for work in works:
work.reset_leveling()
fields = ('constraint_start_time', 'constraint_finish_time',
'effort')
if reduce(lambda x, y: x or y in values, fields, False):
for work in works:
work.compute_dates()
@classmethod
def create(cls, vlist):
works = super(Work, cls).create(vlist)
for work in works:
work.reset_leveling()
work.compute_dates()
return works
@classmethod
def delete(cls, works):
to_update = set()
for work in works:
if work.parent and work.parent not in works:
to_update.add(work.parent)
to_update.update(c for c in work.parent.children
if c not in works)
super(Work, cls).delete(works)
for work in to_update:
work.reset_leveling()
work.compute_dates()
class PredecessorSuccessor(ModelSQL):
'Predecessor - Successor'
__name__ = 'project.predecessor_successor'
predecessor = fields.Many2One('project.work', 'Predecessor',
ondelete='CASCADE', required=True, select=True)
successor = fields.Many2One('project.work', 'Successor',
ondelete='CASCADE', required=True, select=True)
@classmethod
def write(cls, pred_succs, values):
Work = Pool().get('project.work')
super(PredecessorSuccessor, cls).write(pred_succs, values)
works = Work.browse(values.itervalues())
for work in works:
work.reset_leveling()
for work in works:
work.compute_dates()
@classmethod
def delete(cls, pred_succs):
works = set()
parents = set()
for pred_succ in pred_succs:
works.update((pred_succ.predecessor,
pred_succ.successor))
if pred_succ.predecessor.parent:
parents.add(pred_succ.predecessor.parent)
super(PredecessorSuccessor, cls).delete(pred_succs)
for work in works:
work.reset_leveling()
for parent in parents:
parent.compute_dates()
@classmethod
def create(cls, vlist):
pred_succs = super(PredecessorSuccessor, cls).create(vlist)
for pred_succ in pred_succs:
pred_succ.predecessor.reset_leveling()
pred_succ.successor.reset_leveling()
if pred_succ.predecessor.parent:
pred_succ.predecessor.parent.compute_dates()
return pred_succs
class Leveling(Wizard):
'Tasks Leveling'
__name__ = 'project_plan.work.leveling'
start_state = 'leveling'
leveling = StateTransition()
def transition_leveling(self):
Work = Pool().get('project.work')
Work(Transaction().context['active_id']).create_leveling()
return 'end'
|