PlanningBox.py 116 KB
Newer Older
Sebastien Robin's avatar
Sebastien Robin committed
1 2
##############################################################################
#
Sebastien Robin's avatar
Sebastien Robin committed
3
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
4 5
#                    Tomas Bernard <thomas@nexedi.com>
#     from an original experimental script written by :
Sebastien Robin's avatar
Sebastien Robin committed
6 7 8 9 10 11 12
#                    Jonathan Loriette <john@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
Thomas Bernard's avatar
Thomas Bernard committed
13
# Service Company
Sebastien Robin's avatar
Sebastien Robin committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################
30 31
import pdb

Sebastien Robin's avatar
Sebastien Robin committed
32
import string, types, sys
33 34 35 36 37 38

# class monitoring access security control
from Products.PythonScripts.Utility import allow_class
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass

Sebastien Robin's avatar
Sebastien Robin committed
39 40 41 42 43 44 45
from Form import BasicForm
from Products.Formulator.Field import ZMIField
from Products.Formulator.DummyField import fields
from Products.Formulator.MethodField import BoundMethod
from DateTime import DateTime
from Products.Formulator import Widget, Validator
from Products.Formulator.Errors import FormValidationError, ValidationError
Sebastien Robin's avatar
Sebastien Robin committed
46
from SelectionTool import makeTreeList,TreeListLine
47
from Selection import Selection, DomainSelection
Sebastien Robin's avatar
Sebastien Robin committed
48 49 50 51 52 53 54
import OFS
from AccessControl import ClassSecurityInfo
from zLOG import LOG
from copy import copy
from Acquisition import aq_base, aq_inner, aq_parent, aq_self
from Products.Formulator.Form import BasicForm
from Products.CMFCore.utils import getToolByName
55
from Products.ERP5Type.Utils import getPath
Thomas Bernard's avatar
Thomas Bernard committed
56 57
from Products.ERP5Type.Message import Message

Sebastien Robin's avatar
Sebastien Robin committed
58
class PlanningBoxValidator(Validator.StringBaseValidator):
59 60
  """
  Class holding all methods used to validate a modified PlanningBox
Thomas Bernard's avatar
Thomas Bernard committed
61
  can be called only from an HTML rendering using wz_dragdrop script
62 63 64 65 66 67 68 69 70 71 72
  """
  def validate(self,field,key,REQUEST):
    """
    main method to solve validation
    first rebuild the whole structure but do not display it
    then recover the list of block moved and check the modifications to
    apply
    """

    # init params
    value = None
Sebastien Robin's avatar
Sebastien Robin committed
73 74
    form = field.aq_parent
    here = getattr(form, 'aq_parent', REQUEST)
75 76

    # recover usefull properties
Thomas Bernard's avatar
Thomas Bernard committed
77 78
    block_moved_string = REQUEST.get('block_moved','')
    block_previous_string = REQUEST.get('previous_block_moved','')
79

80
    #pdb.set_trace()
81 82 83 84 85

    ##################################################
    ############## REBUILD STRUCTURE #################
    ##################################################
    # build structure
Thomas Bernard's avatar
Thomas Bernard committed
86 87
    structure = PlanningBoxWidgetInstance.render_structure(field=field,
                         key=key, value=value, REQUEST=REQUEST, here=here)
88 89 90 91 92 93 94

    # getting coordinates script generator
    planning_coordinates_method = getattr(here,'planning_coordinates')
    # calling script to generate coordinates
    planning_coordinates = planning_coordinates_method(structure=structure)

    ##################################################
Thomas Bernard's avatar
Thomas Bernard committed
95
    ########## RECOVERING BLOCK MOVED DICTS ##########
96 97
    ##################################################
    #  converting string to a structure
Thomas Bernard's avatar
Thomas Bernard committed
98 99 100
    block_moved_list = self.getBlockPositionFromString(block_moved_string)
    # block_moved_list now holds a list of structure recovered from the REQUEST
    # and correspondig to the movements done before validating
Thomas Bernard's avatar
Thomas Bernard committed
101 102
    block_previous_list =\
                       self.getBlockPositionFromString(block_previous_string)
Thomas Bernard's avatar
Thomas Bernard committed
103 104 105 106
    # list of previous blocks moved if an error occured during previous
    # validation


Thomas Bernard's avatar
Thomas Bernard committed
107 108 109
    # updating block_moved_list using block_previous_list.
    # This is very important not to escape processing blocks that have been
    # moved during a previous validation attempt.
Thomas Bernard's avatar
Thomas Bernard committed
110 111
    if block_previous_list != [] and block_moved_list != []:
      for block_previous in block_previous_list:
Thomas Bernard's avatar
Thomas Bernard committed
112
        # checking if the block has been moved again in this validation attempt
Thomas Bernard's avatar
Thomas Bernard committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
        # if it is the case, the block must be also present in the current
        # block_moved_list
        block_found = {}
        for block_moved in block_moved_list:
          if block_moved['name'] == block_previous['name']:
            block_found = block_moved
            break
        if block_found != {}:
          # block has been moved again, updating its properties in the current
          # list to take into account its previous position. current block is
          # known as 'block_found', and the value to update is the original
          # absolute position used to get relative coordinates
          block_found['old_X'] = block_previous['old_X']
          block_found['old_Y'] = block_previous['old_Y']
        else:
Thomas Bernard's avatar
Thomas Bernard committed
128 129
          # block has not been moved again, adding old block informations to
          # the current list of block_moved
Thomas Bernard's avatar
Thomas Bernard committed
130 131 132 133 134 135 136 137 138
          block_moved_list.append(block_previous)
    elif block_previous_list != []:
      # block_moved_list is empty but not block_previous_list. This means the
      # user is trying to validate again without any change
      block_moved_list = block_previous_list
    elif block_moved_list != []:
      # block_previous_list is empty, this means this is the first validation
      # attempt. Using the block_moved_list as it is
      pass
139
    else:
Thomas Bernard's avatar
Thomas Bernard committed
140 141 142
      # the two lists are empty : nothing to validate
      return None
    # block_moved_list is updated
143 144 145 146


    # dict aimed to hold all informations about block
    final_block_dict = {}
Thomas Bernard's avatar
Thomas Bernard committed
147 148
    # dict holding all the activities that will need an update because at least
    # one of the blocks concerned is moved
149
    activity_dict = {}
Thomas Bernard's avatar
Thomas Bernard committed
150 151 152 153
    # list holding all the activities having one of their block not validated
    # in such a case the update process of the activity is canceled
    warning_activity_list = []
    error_block_list = []
154
    error_info_dict = {}
Thomas Bernard's avatar
Thomas Bernard committed
155 156


157 158 159 160 161 162 163 164 165
    ##################################################
    ########## GETTING BLOCK INFORMATIONS ############
    ##################################################
    # iterating each block_moved element and recovering all usefull properties
    # BEWARE : no update is done here as an activity can be composed of several
    # blocks and so we need first to check all the blocks moved
    for block_moved in block_moved_list:
      final_block = {}
      # recovering the block object from block_moved informations
Thomas Bernard's avatar
Thomas Bernard committed
166 167
      final_block['block_object'] = self.getBlockObject(block_moved['name'], \
                                                   structure.planning.content)
168
      # recovering original activity object
Thomas Bernard's avatar
Thomas Bernard committed
169 170
      final_block['activity_origin'] = \
           final_block['block_object'].parent_activity
171
      # recovering original axis_group object
Thomas Bernard's avatar
Thomas Bernard committed
172 173
      final_block['group_origin'] = \
           final_block['activity_origin'].parent_axis_element.parent_axis_group
174
      # recovering relative block information in planning_coordinates
Thomas Bernard's avatar
Thomas Bernard committed
175 176
      final_block['block_info'] = \
           planning_coordinates['content'][block_moved['name']]
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

      # calculating delta
      # block_moved holds coordinates recovered from drag&drop script, while
      # block_info has the relative coordinates.
      # In fact the Drag&Drop java script used to get destination coordinates
      # gives them in absolute. so using original block position to get the
      # relative position
      deltaX = block_moved['old_X'] - final_block['block_info']['margin-left']
      deltaY = block_moved['old_Y'] - final_block['block_info']['margin-top']

      # calculating new block position:
      # width and height are already in the good format
      block_moved['left'] = block_moved['new_X'] - deltaX
      block_moved['top']  = block_moved['new_Y'] - deltaY

      # abstracting axis representation (for generic processing)
      if structure.planning.render_format == 'YX':
        block_moved['main_axis_position']      = block_moved['top']
        block_moved['main_axis_length']        = block_moved['height']
        block_moved['secondary_axis_position'] = block_moved['left']
        block_moved['secondary_axis_length']   = block_moved['width']
        # used afterwards to get destination group
        group_position = 'margin-top'
        group_length = 'height'
        # used afterwards to get secondary axis displacements and modifications
        axis_length = 'width'
      else:
        block_moved['main_axis_position']      = block_moved['left']
        block_moved['main_axis_length']        = block_moved['width']
        block_moved['secondary_axis_position'] = block_moved['top']
        block_moved['secondary_axis_length']   = block_moved['height']
        group_position = 'margin-left'
        group_length = 'width'
        axis_length = 'height'

      # calculating center of block over main axis to check block position
Thomas Bernard's avatar
Thomas Bernard committed
213 214
      block_moved['center'] = (block_moved['main_axis_length'] / 2) + \
                               block_moved['main_axis_position']
215

Thomas Bernard's avatar
Thomas Bernard committed
216 217 218 219 220 221
      # now that block coordinates are recovered as well as planning
      # coordinates, recovering destination group over the main axis to know
      # if the block has been moved from a group to another
      group_destination = self.getDestinationGroup(structure,
               block_moved,planning_coordinates['main_axis'],
               group_position, group_length)
222 223

      if group_destination == None:
Thomas Bernard's avatar
Thomas Bernard committed
224 225 226 227 228
        # !! Generate an Error !!
        # block has been moved outside the content area (not in line with any
        # group of the current area).
        # adding current block to error_list
        error_block_list.append(block_moved['name'])
229
        error_info_dict[block_moved['name']] = 'out of bounds on main axis'
Thomas Bernard's avatar
Thomas Bernard committed
230 231 232 233
        # adding if necessary current activity to warning_list
        if final_block['activity_origin'].name not in warning_activity_list:
          warning_activity_list.append(final_block['activity_origin'].name)

234 235 236

      # now that all informations about the main axis changes are
      # known, checking modifications over the secondary axis.
Thomas Bernard's avatar
Thomas Bernard committed
237 238 239
      secondary_axis_positions = self.getDestinationBounds(structure,
              block_moved, final_block['block_object'],
              planning_coordinates, axis_length)
Thomas Bernard's avatar
Thomas Bernard committed
240 241 242 243 244 245
      if secondary_axis_positions[2] == 1 :
        # !! Generate an Error !!
        # block has been moved outside the content area (bounds do not match
        # current area limits)
        if block_moved['name'] not in error_block_list:
          error_block_list.append(block_moved['name'])
246
          error_info_dict[block_moved['name']] = 'out of bounds on sec axis'
Thomas Bernard's avatar
Thomas Bernard committed
247 248 249 250
          if final_block['activity_origin'].name not in warning_activity_list:
            warning_activity_list.append(final_block['activity_origin'].name)


251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
      block_moved['secondary_axis_start'] = secondary_axis_positions[0]
      block_moved['secondary_axis_stop'] = secondary_axis_positions[1]

      final_block['block_moved'] = block_moved
      final_block['group_destination'] = group_destination

      #final_block_dict[block_moved['name']] = final_block
      try:
        activity_dict[final_block['activity_origin'].name].append(final_block)
      except KeyError:
        activity_dict[final_block['activity_origin'].name] = [final_block]


    ##################################################
    ############# UPDATING ACTIVITIES ################
    ##################################################
    update_dict = {}
Thomas Bernard's avatar
Thomas Bernard committed
268 269 270 271 272 273
    errors_list = []
    # getting start & stop property names
    start_property = structure.basic.field.get_value('x_start_bloc')
    stop_property = structure.basic.field.get_value('x_stop_bloc')
    # getting round_script if exists
    round_script=getattr(here,field.get_value('round_script'),None)
274 275 276 277 278 279 280 281
    # now processing activity updates
    for activity_name in activity_dict.keys():
      # recovering list of moved blocks in the current activity
      activity_block_moved_list = activity_dict[activity_name]
      # recovering activity object from first moved block
      activity_object = activity_block_moved_list[0]['activity_origin']
      # now getting list of blocks related to the activity (moved or not)
      activity_block_list = activity_object.block_list
Thomas Bernard's avatar
Thomas Bernard committed
282 283 284 285 286 287 288 289 290
      if activity_object.name in warning_activity_list:
        # activity contains a block that has not be validated
        # The validation update process is canceled, and the error is reported
        err = ValidationError(StandardError,activity_object)
        errors_list.append(err)
        pass
      else:
        # no error : continue
        # recovering new activity bounds
Thomas Bernard's avatar
Thomas Bernard committed
291 292 293 294
        (start_value, stop_value) = \
             self.getActivityBounds(activity_object, activity_block_moved_list,
                                    activity_block_list)
        # call specific external method to round value
Thomas Bernard's avatar
Thomas Bernard committed
295 296 297
        if round_script != None:
          start_value = round_script(start_value)
          stop_value = round_script(stop_value)
Thomas Bernard's avatar
Thomas Bernard committed
298 299 300
        # saving updated informations in the final dict
        update_dict[activity_object.object.getUrl()] =  \
        {start_property:start_value, stop_property:stop_value}
Thomas Bernard's avatar
Thomas Bernard committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314


    # testing if need to raise errors
    if len(errors_list) > 0:
      # need to raise an error
      # rebuilt position string including new values
      block_moved_string = self.setBlockPositionToString(block_moved_list)
      # save the current block_list for repositionning the blocks
      # to their final position
      REQUEST.set('previous_block_moved',block_moved_string)
      # saving blocks not validated as such as the activity they belong to to
      # apply a special treatment.
      REQUEST.set('warning_activity_list',warning_activity_list)
      REQUEST.set('error_block_list',error_block_list)
315 316 317 318 319
      REQUEST.set('error_info_dict',error_info_dict)
      # now raise error => automatically called
      # parameters are :
      # -list of errors
      # - dict with error results
Thomas Bernard's avatar
Thomas Bernard committed
320 321 322
      raise FormValidationError(errors_list, {} )

    # the whole process is now finished, just need to return final dict
Thomas Bernard's avatar
Thomas Bernard committed
323
    # for updating data
Thomas Bernard's avatar
Thomas Bernard committed
324
    return update_dict
325 326 327



Thomas Bernard's avatar
Thomas Bernard committed
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
  def getBlockPositionFromString(self, block_string):
    """
    takes a string with block data and convert it to a list of dicts
    """
    block_list = []
    if block_string != '':
      block_object_list = block_string.split('*')
      for block_object_string in block_object_list:
        block_dict = None
        block_dict = {}
        block_sub_list = block_object_string.split(',')
        block_dict['name'] = block_sub_list[0]
        block_dict['old_X'] = float(block_sub_list[1])
        block_dict['old_Y'] = float(block_sub_list[2])
        block_dict['new_X'] = float(block_sub_list[3])
        block_dict['new_Y'] = float(block_sub_list[4])
        block_dict['width'] = float(block_sub_list[5])
        block_dict['height'] = float(block_sub_list[6])
        block_list.append(block_dict)
      return block_list
    else:
      return block_list

  def setBlockPositionToString(self,block_list):
    """
    takes a list of dicts updated and convert it to a string in order to save
    it in the request
    """
    block_string = ''
    if block_list != []:
      block_object_list = []
      for block_dict in block_list:
        # property position is important that's why ','.join() is not used in
        # this case
        block_sub_string  = '%s,%s,%s,%s,%s,%s,%s' % (
                         str(block_dict['name']),
                         str(block_dict['old_X']),
                         str(block_dict['old_Y']),
                         str(block_dict['new_X']),
                         str(block_dict['new_Y']),
                         str(block_dict['width']),
                         str(block_dict['height'])
                         )
        block_object_list.append(block_sub_string)
      block_string = '*'.join(block_object_list)
      return block_string
    else:
      return block_string
376 377 378 379 380 381 382 383 384 385 386


  def getBlockObject(self, block_name, content_list):
    """
    recover the block related to the block_name inside the content_list
    """
    for block in content_list:
      if block.name == block_name:
        return block


Thomas Bernard's avatar
Thomas Bernard committed
387 388
  def getDestinationGroup(self, structure, block_moved, axis_groups,
                                group_position, group_length):
389 390 391 392 393 394 395 396
    """
    recover destination group from block coordinates and main axis coordinates
    block_moved is a dict of properties.
    returns the group object itself, none if the block has no good coordinates
    """
    good_group_name = ''
    # recovering group name
    for axis_name in axis_groups.keys():
Thomas Bernard's avatar
Thomas Bernard committed
397 398 399
      if  axis_groups[axis_name][group_position] < block_moved['center'] and \
          axis_groups[axis_name][group_position] + \
          axis_groups[axis_name][group_length] > block_moved['center']:
400 401 402 403
        # the center of the block is between group min and max bounds
        # the group we are searching for is known
        good_group_name = axis_name
        break
Thomas Bernard's avatar
Thomas Bernard committed
404
    # if no group is found, this means the block is outside the bounds
405 406 407 408 409 410 411 412 413 414
    if good_group_name == '':
      return None
    # group name is known, searching corresponding group object
    for group in structure.planning.main_axis.axis_group:
      if group.name == good_group_name:
        return group
    return None



Thomas Bernard's avatar
Thomas Bernard committed
415 416
  def getDestinationBounds(self, structure, block_moved, block_object,
                                 planning_coordinates, axis_length):
417 418 419 420
    """
    check the new bounds of the block over the secondary axis according to its
    new position
    """
Thomas Bernard's avatar
Thomas Bernard committed
421
    error = 0
422 423 424 425 426
    # XXX CALENDAR
    # has to be improved : for now the axis bounds are recovered globally, it
    # implies that all groups have the same bounds, which is not the case in
    # calendar mode. for that will need to add special informations about the
    # group itself to know its own bounds.
Thomas Bernard's avatar
Thomas Bernard committed
427 428 429 430 431
    delta_start = block_moved['secondary_axis_position'] / \
                  planning_coordinates['frame']['content'][axis_length]
    delta_stop  = (block_moved['secondary_axis_position'] + \
                  block_moved['secondary_axis_length']) / \
                  planning_coordinates['frame']['content'][axis_length]
432 433 434 435

    # testing different cases of invalidation
    if delta_stop < 0 or delta_start > 1 :
      # block if fully out of the bounds
Thomas Bernard's avatar
Thomas Bernard committed
436 437
      # can not validate it : returning None
      error = 1
438 439 440 441 442
    else:
      if delta_start < 0 or delta_stop > 1:
        # part of the block is inside
        pass

Thomas Bernard's avatar
Thomas Bernard committed
443 444
    axis_range = structure.basic.secondary_axis_info['bound_stop'] - \
                 structure.basic.secondary_axis_info['bound_start']
445 446

    # defining new final block bounds
Thomas Bernard's avatar
Thomas Bernard committed
447 448 449 450
    new_start = structure.basic.secondary_axis_info['bound_start'] + \
                delta_start * axis_range
    new_stop  = structure.basic.secondary_axis_info['bound_start'] + \
                delta_stop * axis_range 
451

Thomas Bernard's avatar
Thomas Bernard committed
452 453 454 455 456 457

    # update block bounds (round to the closest round day)
    #new_start = DateTime(new_start.Date())
    #new_stop = DateTime(new_stop.Date())

    return [new_start,new_stop, error]
458 459 460



Thomas Bernard's avatar
Thomas Bernard committed
461 462
  def getActivityBounds(self, activity, activity_block_moved_list,
                              activity_block_list):
463 464 465 466 467 468 469
    """
    takes a list with modified blocks and another one with original blocks,
    returning new startactivity_block_moved_list & stop for the activity
    BEWARE : in case an activity bound was cut off to fit planning size, the
    value will not be updated (as the block was not on the real activity bound)
    """
    # getting list moved block names
Thomas Bernard's avatar
Thomas Bernard committed
470 471
    block_moved_name_list = map(lambda x: x['block_moved']['name'],
                                activity_block_moved_list)
472 473 474 475 476 477 478 479 480 481


    for activity_block in activity_block_list:
      if activity_block.name in block_moved_name_list:
        # the block composing the activity has been moved, not taking care of
        # the original one, but only the final position (block_moved)
        for temp_block_moved in activity_block_moved_list:
          # recovering corresponding moved block
          if temp_block_moved['block_moved']['name'] == activity_block.name:
            # moved block has been found
Thomas Bernard's avatar
Thomas Bernard committed
482 483
            temp_start =temp_block_moved['block_moved']['secondary_axis_start']
            temp_stop = temp_block_moved['block_moved']['secondary_axis_stop']
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
            break
      else:
        # the block has not been moved
        temp_start = activity_block.position_secondary.absolute_begin
        temp_stop  = activity_block.position_secondary.absolute_end
      # once the start & stop values are recovered, need to test them to check
      # if it is needed to update
      try:
        if temp_start < new_start:
          new_start = temp_start
        if temp_stop > new_stop:
          new_stop = temp_stop
      except NameError:
        # new_start is not defined because it is the first block found
        new_start = temp_start
        new_stop = temp_stop

    # new start & stop values are known
    # checking weither activity has been cut-off to fit the planning bounds 
    if activity.secondary_axis_begin != activity.secondary_axis_start:
      new_start = activity.secondary_axis_begin
    if activity.secondary_axis_end != activity.secondary_axis_stop:
      new_stop  = activity.secondary_axis_end

    return [new_start,new_stop]


class PlanningBoxWidget(Widget.Widget):
  """
  PlanningBox main class used to run all the process in order to generate
  the structure of the Planning including all internal properties.
  Contains BasicStructure and PlanningStructure instances
  """



  property_names = Widget.Widget.property_names +\
521 522 523 524 525
  [# kind of display : YX or XY
   'representation_type',
   # number of groups over the main axis
   'main_axis_groups',
   # width properties
Thomas Bernard's avatar
Thomas Bernard committed
526 527
   'size_border_width_left','size_planning_width','size_y_axis_space',
   'size_y_axis_width',
528
   # height properties
Thomas Bernard's avatar
Thomas Bernard committed
529 530
   'size_header_height','size_planning_height','size_x_axis_space',
   'size_x_axis_height',
531 532
   # axis position
   'y_axis_position', 'x_axis_position',
533 534 535
   'report_root_list','selection_name',
   'portal_types','sort',
   'list_method',
536 537 538 539 540
   # method used to get title of each line
   'title_line',
   # specific block properties
   'x_start_bloc','x_stop_bloc', 'y_size_block',
   # name of scripts 
Thomas Bernard's avatar
Thomas Bernard committed
541 542
   'stat_method','split_method','color_script',
   'round_script','sec_axis_script',
543 544 545
   # number of delimitations over the secondary axis
   'delimiter',
   # specific methods for inserting info block
Thomas Bernard's avatar
Thomas Bernard committed
546 547
   'info_center','info_topleft','info_topright',
   'info_backleft','info_backright'
548
   ]
549

550 551 552 553 554
  """
  'security_index'
  # constraint method between block
  'constraint_method',
  """
555 556 557 558 559
  # Planning properties (accessed through Zope Management Interface)


  # kind of representation to render :
  # Planning or Calendar
Thomas Bernard's avatar
Thomas Bernard committed
560
  representation_type = fields.StringField('representation_type',
561 562 563
      title='representtion Type (YX or XY)',
      description='YX for horizontal or XY for vertical',
      default='YX',
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
      required=1)

  # added especially for new Planning Structure generation
  # is used to split result in pages in a ListBox like rendering
  # (delimitation over the main axis)
  main_axis_groups = fields.IntegerField('main_axis_groups',
      title='groups per page on main axis:',
      description=('number of groups displayed per page on main axis'),
      default=10,
      required=1)

  # setting header height
  size_header_height = fields.IntegerField('size_header_height',
      title='header height:',
      desciption=(
      'height of the planning header'),
      default=100,
      required=1)

  # setting left border size
  size_border_width_left = fields.IntegerField('size_border_width_left',
      title='Size border width left',
      desciption=(
      'setting left border size'),
      default=10,
      required=1)

  # setting the width of the Planning (excl. Y axis : only the block area)
  size_planning_width = fields.IntegerField('size_planning_width',
      title='Planning width:',
      desciption=(
      'size of the planning area, excluding axis size'),
      default=1000,
      required=1)

  # setting the with of the Y axis
  size_y_axis_width = fields.IntegerField('size_y_axis_width',
      title='Y axis width:',
      description=(
      'width of the Y axis'),
      default=200,
      required=1)

  # setting the with of the space (between Planning and Y axis)
  size_y_axis_space = fields.IntegerField('size_y_axis_space',
      title='Y axis space:',
      description=(
      'space between Y axis and PLanning content'),
      default=10,
      required=1)

  # setting the height of the Planning (excl. X axis)
  size_planning_height = fields.IntegerField('size_planning_height',
      title='Planning height:',
      description=(
      'size of the planning area, excluding axis_size'),
      default=800,
      required=1)

  # setting the height of the X axis
  size_x_axis_height = fields.IntegerField('size_x_axis_height',
      title='X axis height:',
      description=(
      'height of the X axis'),
      default=200,
      required=1)

  # setting the height of the space (between Planning and X axis)
  size_x_axis_space = fields.IntegerField('size_x_axis_space',
      title='X axis space:',
      description=(
635
      'space between X axis and Planning content '),
636 637 638 639
      default=10,
      required=1)


640 641 642 643 644 645 646 647 648 649 650 651 652
  y_axis_position = fields.StringField('y_axis_position',
      title='Y axis position, (left or right) :',
      description=('position of Y axis over the planning content'),
      default = 'left',
      required = 1)

  x_axis_position = fields.StringField('x_axis_position',
      title='X axis position, (top or bottom) :',
      description=('position or X axis over the planning content'),
      default = 'bottom',
      required = 1)


653 654 655 656 657 658 659 660 661
  default = fields.TextAreaField('default',
      title='Default',
      description=(
      "Default value of the text in the widget."),
      default="",
      width=20, height=3,
      required=0)


662
  delimiter = fields.IntegerField('delimiter',
663 664
      title='min number of delimiters over the secondary axis:',
      description=("min number of delimitations over the sec axis, required"),
665 666
      default = 5,
      required=1)
667

668

669 670 671 672 673 674
  report_root_list = fields.ListTextAreaField('report_root_list',
      title="Report Root",
      description=("A list of domains which define the possible root."),
      default=[],
      required=0)

675

676 677 678 679 680 681
  selection_name = fields.StringField('selection_name',
      title='Selection Name',
      description=("The name of the selection to store selections params"),
      default='',
      required=0)

682

683 684 685 686 687 688
  portal_types = fields.ListTextAreaField('portal_types',
      title="Portal Types",
      description=("Portal Types of objects to list. Required."),
      default=[],
      required=0)

689

690 691 692 693 694 695
  sort = fields.ListTextAreaField('sort',
      title='Default Sort',
      description=("The default sort keys and order"),
      default=[],
      required=0)

696

697 698 699 700 701 702
  list_method = fields.MethodField('list_method',
      title='List Method',
      description=("Method to use to list objects"),
      default='',
      required=0)

703

704 705 706 707 708 709 710 711 712 713
  title_line = fields.StringField('title_line',
      title="specific method which fetches the title of each line: ",
      description=("specific method for inserting title in line"),
      default='',
      required=0)




  x_start_bloc = fields.StringField('x_start_bloc',
714
      title='specific property to get start of blocks (ex. start_date)',
Thomas Bernard's avatar
Thomas Bernard committed
715
      description=('Property for building X-Axis such as start_date\
716
      objects'),
Thomas Bernard's avatar
Thomas Bernard committed
717
      default='start_date',
718 719 720
      required=0)

  x_stop_bloc = fields.StringField('x_stop_bloc',
721
      title='specific property to get stop of blocks (ex. stop_date)',
Thomas Bernard's avatar
Thomas Bernard committed
722
      description=('Property for building X-Axis such as stop_date\
723
      objects'),
Thomas Bernard's avatar
Thomas Bernard committed
724
      default='stop_date',
725
      required=0)
726

727 728
  y_size_block = fields.StringField('y_size_block',
      title='specific property to get height of blocks (ex.quantity)',
729
      description=('Method for building height of blocks objects'),
730
      default='quantity',
731
      required=0)
732 733 734 735 736 737 738 739


  constraint_method = fields.StringField('constraint_method',
      title='name of constraint method between blocks',
      description=('Constraint method between blocks objects'),
      default='SET_DHTML',
      required=1)

740 741 742 743 744 745
  stat_method = fields.StringField('stat_method',
      title="name of script generating statistics:",
      description=("script for statistics"),
      default='',
      required=0)

746
  split_method = fields.StringField('split_method',
747 748
      title='name of script splitting activities into blocks',
      description=("script for splitting activities into multiple blocks"),
749 750 751
      default='',
      required=0)

752
  color_script = fields.StringField('color_script',
753
      title='name of script colorizing blocks',
754 755 756 757
      description=('script for block colors object'),
      default='',
      required=0)

Thomas Bernard's avatar
Thomas Bernard committed
758
  round_script = fields.StringField('round_script',
Thomas Bernard's avatar
Thomas Bernard committed
759 760
      title='name of script rounding blocks during validation (ex.\
            Planning_roundBoundToDay)',
Thomas Bernard's avatar
Thomas Bernard committed
761
      description=('script for block bounds rounding when validating'),
762
      default='',
Thomas Bernard's avatar
Thomas Bernard committed
763 764
      required=0)

765

Thomas Bernard's avatar
Thomas Bernard committed
766
  sec_axis_script = fields.StringField('sec_axis_script',
Thomas Bernard's avatar
Thomas Bernard committed
767 768
      title='name of script building secondary axis (ex.\
            Planning_generateAxis)',
Thomas Bernard's avatar
Thomas Bernard committed
769
      description=('script for building secondary axis'),
770
      default='Planning_generateAxis',
771
      required=1)
Thomas Bernard's avatar
Thomas Bernard committed
772

773

774 775 776 777 778 779
  info_center = fields.StringField('info_center',
      title='specific method of data called for inserting info in\
      block center',
      description=('Method for displaying info in the center of a\
      block object'),
      default='',
780
      required=0)
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831

  info_topright = fields.StringField('info_topright',
      title='specific method of data called for inserting info in\
      block topright',
      description=('Method for displaying info in the topright of a block\
      object'),
      default='',
      required=0)

  info_topleft = fields.StringField('info_topleft',
      title='specific method of data called for inserting info in\
      block topleft',
      description=('Method for displaying info in the topleft corner\
      of a block object'),
      default='',
      required=0)

  info_backleft = fields.StringField('info_backleft',
      title='specific method of data called for inserting info in\
      block backleft',
      description=('Method for displaying info in the backleft of a\
      block object'),
      default='',
      required=0)

  info_backright = fields.StringField('info_backright',
      title='specific method of data called for inserting info in\
      block backright',
      description=('Method for displaying info in the backright of a\
      block object'),
      default='',
      required=0)

  security_index = fields.IntegerField('security_index',
      title='variable depending on the type of web browser :',
      description=("This variable is used because the rounds of each\
      web browser seem to work differently"),
      default=2,
      required=0)



  def render_css(self,field, key, value, REQUEST):
    """
    first method called for rendering by PageTemplate form_view
    create the whole object based structure, and then call a special
    external PageTemplate (or DTML depending) to render the CSS code
    relative to the structure that need to be rendered
    """

    here = REQUEST['here']
832

833
    #pdb.set_trace()
Thomas Bernard's avatar
Thomas Bernard committed
834 835 836 837 838 839
    # build structure
    # render_structure will call all method necessary to build the entire
    # structure relative to the planning
    # creates and fill up self.basic, self.planning and self.build_error_list
    self.render_structure(field=field, key=key, value=value,
                                    REQUEST=REQUEST, here=here)
840

Thomas Bernard's avatar
Thomas Bernard committed
841

Thomas Bernard's avatar
Thomas Bernard committed
842 843 844 845 846 847 848
    
    # getting CSS script generator
    planning_css_method = getattr(REQUEST['here'],'planning_css')
    # recover CSS data buy calling DTML document
    CSS_data = planning_css_method(structure=self)
    # saving structure inside the request for HTML render
    REQUEST.set('structure',self)
849

Thomas Bernard's avatar
Thomas Bernard committed
850
    return CSS_data
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866



  def render(self,field,key,value,REQUEST):
    """
    method called to render the HTML code relative to the planning.
    for that recover the structure previouly saved in the REQUEST, and then
    call a special Page Template aimed to render
    """
    # need to test if render is HTML (to be implemented in a page template)
    # or list (to generated a PDF output or anything else).

    # recover structure
    structure = REQUEST.get('structure')


867
    #pdb.set_trace()
868

Thomas Bernard's avatar
Thomas Bernard committed
869 870 871 872 873 874
    # getting HTML rendering Page Template
    planning_html_method = getattr(REQUEST['here'],'planning_content')
    # recovering HTML data by calling Page Template document
    HTML_data = planning_html_method(struct=structure)
    # return HTML data
    return HTML_data
875 876 877 878 879 880 881 882 883 884


  def render_structure(self, field, key, value, REQUEST, here):
    """ this method is the begining of the rendering procedure. it calls all
        methods needed to generate BasicStructure with ERP5 objects, and then
        creates the PlanningStructure before applying zoom.
        No code is generated (for example HTML code) contrary to the previous
        implementation of PlanningBox. The final rendering must be done through
        a PageTemplate parsing the PlanningStructure object.
        """
Thomas Bernard's avatar
Thomas Bernard committed
885 886
    # XXX testing : uncoment to put selection to null => used for debugging
    #here.portal_selections.setSelectionFor(selection_name, None)
887

Thomas Bernard's avatar
Thomas Bernard committed
888 889
    ####### DATA DEFINITION #######
    self.build_error_list = None
890 891 892 893
    # recovering usefull planning properties
    form = field.aq_parent # getting form
    list_method = field.get_value('list_method') # method used to list objects
    report_root_list = field.get_value('report_root_list') # list of domains
Thomas Bernard's avatar
Thomas Bernard committed
894
    portal_types = field.get_value('portal_types') # Portal Types of objects
895
    # selection name used to store selection params
Sebastien Robin's avatar
Sebastien Robin committed
896
    selection_name = field.get_value('selection_name')
897
    # getting sorting keys and order (list)
Sebastien Robin's avatar
Sebastien Robin committed
898
    sort = field.get_value('sort')
899 900
    # contains the list of blocks that are not validated
    # for them a special rendering is done (special colors for example)
Sebastien Robin's avatar
Sebastien Robin committed
901
    list_error=REQUEST.get('list_block_error')
902 903 904 905 906 907 908 909 910 911
    if list_error==None : list_error = []
    selection = here.portal_selections.getSelectionFor(
                      selection_name, REQUEST)
    # params contained in the selection object is a dictionnary.
    # must exist as an empty dictionnary if selection is empty.
    try:
      params = selection.getParams()
    except (AttributeError,KeyError):
      params = {}

Thomas Bernard's avatar
Thomas Bernard committed
912 913

    ###### CALL CLASS METHODS TO BUILD BASIC STRUCTURE ######
914
    # creating BasicStructure instance (and initializing its internal values)
Thomas Bernard's avatar
Thomas Bernard committed
915 916 917 918 919 920 921
    self.basic = BasicStructure(here=here,form=form, field=field,
                                REQUEST=REQUEST, list_method=list_method,
                                selection=selection, params = params,
                                selection_name=selection_name,
                                report_root_list=report_root_list,
                                portal_types=portal_types, sort=sort,
                                list_error=list_error)
922
    # call build method to generate BasicStructure
Thomas Bernard's avatar
Thomas Bernard committed
923 924 925 926
    status = self.basic.build()
    if status != 1:
      self.build_error_list = status
      return self
927

Thomas Bernard's avatar
Thomas Bernard committed
928
    ###### CALL CLASS METHODS TO BUILD PLANNING STRUCTURE ######
929 930 931
    # creating PlanningStructure instance and initializing its internal values
    self.planning = PlanningStructure()
    # call build method to generate final Planning Structure
Thomas Bernard's avatar
Thomas Bernard committed
932 933 934 935 936 937
    status = self.planning.build(basic_structure = self.basic,field=field,
                                 REQUEST=REQUEST)
    if status != 1:
      # in case error during planning structure generation
      self.build_error_list = status
      return self
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964

    return self

# instanciating class
PlanningBoxWidgetInstance = PlanningBoxWidget()

class BasicStructure:
  """
  First Structure recovered from ERP5 objects. Does not represent in any
  way the final structure used for rendering the Planning (for that see
  PlanningStructure class). for each returned object from ERP5's request,
  create a BasicGroup and stores all object properties.
  No zoom is applied on this structure
  """

  def __init__ (self, here='', form='', field='', REQUEST='', list_method='',
    selection=None, params = '', selection_name='', report_root_list='',
    portal_types='', sort=None, list_error=None):
    """ init main internal parameters """
    self.here = here
    self.form = form
    self.field = field
    self.REQUEST = REQUEST
    self.sort = sort
    self.selection = selection
    self.params = params
    self.list_method = list_method
Thomas Bernard's avatar
Thomas Bernard committed
965
    self.selection_name = selection_name
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
    self.report_root_list = report_root_list
    self.portal_types = portal_types
    self.basic_group_list = None
    self.report_groups= '' # needed to generate groups
    self.list_error = list_error

    self.secondary_axis_occurence = []
    self.render_format = '' # 'list' in case output is a list containing the
                            # full planning structure without any selection
    self.main_axis_info = {}
    self.secondary_axis_info = {}


  def build(self):
    """
    build BasicStructure from given parameters, and for that do the
    specified processes :
    1 - define variables
    2 - building query
    3 - generate report_tree, a special structure containing all the
        objects with their values
    4 - create report_sections
    """

    default_params ={}
    current_section = None
    #params = self.selection.getParams()


    #recovering selection if necessary
    if self.selection is None:
Thomas Bernard's avatar
Thomas Bernard committed
997 998
      self.selection = Selection(params=default_params,
                                 default_sort_on=self.sort)
Sebastien Robin's avatar
Sebastien Robin committed
999
    else:
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
      # immediately updating the default sort value
      self.selection.edit(default_sort_on=self.sort)
      self.selection.edit(sort_on=self.sort)

    self.here.portal_selections.setSelectionFor(self.selection_name,
                                        self.selection,REQUEST=self.REQUEST)

    # building list of portal_types
    self.filtered_portal_types = map(lambda x: x[0], self.portal_types)
    if len(self.filtered_portal_types) == 0:
      self.filtered_portal_types = None

    report_depth = self.REQUEST.get('report_depth',None)
    # In report tree mode, need to remember if the items have to be displayed
    is_report_opened = self.REQUEST.get('is_report_opened',\
                                    self.selection.isReportOpened())
1016
    self.selection.edit(report_opened=is_report_opened)
1017 1018 1019
    portal_categories = getattr(self.form,'portal_categories',None)
    portal_domains = getattr(self.form,'portal_domains',None)

Thomas Bernard's avatar
Thomas Bernard committed
1020 1021


1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    ##################################################
    ############### BUILDING QUERY ###################
    ##################################################
    kw = self.params
    # remove selection_expression if present
    # This is necessary for now, because the actual selection expression in
    # search catalog does not take the requested columns into account. If
    # select_expression is passed, this can raise an exception, because stat
    # method sets select_expression, and this might cause duplicated column
    # names.
    if 'select_expression' in kw:
      del kw['select_expression']
    if hasattr(self.list_method, 'method_name'):
      if self.list_method.method_name == 'ObjectValues':
        # list_method is available
        self.list_method = self.here.objectValues
1038
        kw = copy(self.params)
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
      else:
        # building a complex query so we should not pass too many variables
        kw={}
        if self.REQUEST.form.has_key('portal_type'):
          kw['portal_type'] = self.REQUEST.form['portal_type']
        elif self.REQUEST.has_key('portal_type'):
          kw['portal_type'] = self.REQUEST['portal_type']
        elif self.filtered_portal_types is not None:
          kw['portal_type'] = self.filtered_portal_types
        elif kw.has_key('portal_type'):
          if kw['portal_type'] == '':
            del kw['portal_type']
        # remove useless matter
        for cname in self.params.keys():
          if self.params[cname] != '' and self.params[cname] != None:
            kw[cname] = self.params[cname]
        # try to get the method through acquisition
        try:
          self.list_method = getattr(self.here, self.list_method.method_name)
        except (AttributeError, KeyError):
          pass
    elif self.list_method in (None,''):
      # use current selection
      self.list_method = None

1064 1065 1066 1067
    ##################################################
    ############## DEFINING STAT METHOD ##############
    ##################################################
    stat_method = self.field.get_value('stat_method')
1068 1069
    stat_method = getattr(self.here,stat_method, None)
    if stat_method == None:
1070
      show_stat = 0
1071 1072
    else:
      show_stat = 1
1073 1074


1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
    ##################################################
    ############ BUILDING REPORT_TREE ################
    ##################################################
    # assuming result is report tree, building it
    # When building the body, need to go through all report lines
    # each report line is a tuple of the form :
    #(selection_id, is_summary, depth, object_list, object_list_size, is_open)
    default_selection_report_path = self.report_root_list[0][0].split('/')[0]
    if (default_selection_report_path in portal_categories.objectIds()) or \
      (portal_domains is not None and default_selection_report_path in \
       portal_domaind.objectIds()):
      pass
    else:
      default_selection_root_path = self.report_root_list[0][0]
    selection_report_path = self.selection.getReportPath(default = \
     (default_selection_report_path,))

    # testing report_depth value
    if report_depth is not None:
1094
      selection_report_current = ()
1095 1096 1097 1098
    else:
      selection_report_current = self.selection.getReportList()

    # building report_tree_list
Thomas Bernard's avatar
Thomas Bernard committed
1099 1100 1101 1102 1103 1104
    report_tree_list = makeTreeList(here=self.here, form=self.form,
                                    root_dict=None,
                                    report_path=selection_report_path,
                                    base_category=None, depth=0,
                                    unfolded_list=selection_report_current,
                                    selection_name=self.selection_name,
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
     report_depth=report_depth,is_report_opened=is_report_opened,
     sort_on=self.selection.sort_on,form_id=self.form.id)

    ##################################################
    ########### BUILDING REPORT_GROUPS ###############
    ##################################################
    # report_groups is another structure based on report_tree but
    # taking care of the object activities.
    # build two structures :
    # - report_groups : list of object_tree_lines composing the planning,
    #   whatever the current group depth, just listing all of them
    # - blocks_object : dict (object_tree_line.getObject()) of objects
    # (assuming objects is a list of activities).

    # first init parameters
    self.report_groups = []
    list_object = []
    self.nbr_groups=0
    object_list=[]
    self.report_activity_dict = {}
    indic_line=0
    index_line=0
    blocks_object={}
    select_expression = ''


1131 1132


1133
    # now iterating through report_tree_list
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    for object_tree_line in report_tree_list:
      # prepare query by defining selection report object
      self.selection.edit(report = object_tree_line.getSelectDomainDict())

      # defining info_dict, holding all information about the current object.
      info_dict = None
      info_dict = {}

      if object_tree_line.getIsPureSummary() and show_stat:

        info_dict['stat'] = 1

        # push new select_expression
        original_select_expression = kw.get('select_expression')
        kw['select_expression'] = select_expression
        self.selection.edit(params = kw)
1150 1151
        # recovering statistics if needed
        # getting list of statistic blocks
Thomas Bernard's avatar
Thomas Bernard committed
1152 1153 1154 1155 1156 1157
        stat_list = stat_method(selection=self.selection,
                                list_method=self.list_method,
                                selection_context=self.here,
                                report_tree_list=report_tree_list,
                                object_tree_line=object_tree_line,
                                REQUEST=self.REQUEST, field=self.field)
1158

1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
        if original_select_expression is None:
          del kw['select_expression']
        else:
          kw['select_expression'] = original_select_expression

        # adding current line to report_section where
        # line is pure Summary
        self.report_groups += [(object_tree_line,stat_list,info_dict)]
        self.nbr_groups += 1

      else:
        info_dict['stat'] = 0

        # processing all cases
        self.selection.edit(params = kw)

        # recovering object list
        if self.list_method not in (None,''):
          # valid list_method has been found
          self.selection.edit(exception_uid_list= \
             object_tree_line.getExceptionUidList())
          object_list = self.selection(method = self.list_method,
             context=self.here, REQUEST=self.REQUEST)
        else:
          # no list_method found
          object_list = self.here.portal_selections.getSelectionValueList(
            self.selection_name, context=self.here, REQUEST=self.REQUEST)

        # recovering exeption_uid_list
        exception_uid_list = object_tree_line.getExceptionUidList()
        if exception_uid_list not in (None,()):
          # Filter folders if parent tree :
          # build new object_list for current line
          # (list of relative elements)
          new_object_list = []
          for selected_object in object_list:
            if selected_object.getUid() not in exception_uid_list:
              new_object_list.append(selected_object)
          object_list = new_object_list

        if not object_tree_line.getIsPureSummary():
          # Object is not pure summary
          if show_stat:
            # this represents the second duplicated object
            # display object content in report tree with stat
            # stats are displayed in the first object present
            #
            self.report_groups += [(object_tree_line,object_list, info_dict)]
            self.nbr_groups += 1
          else:
            # do nothing
            # case of parent tree unfolded (second object and no stats)
            pass
        else:
          # object is pure summary !
          if len(object_list) and object_tree_line.is_open:
            # pure summary, open, and has object_list
            # case = ?!?
            self.report_groups += [(object_tree_line, object_list, info_dict)]
            self.nbr_groups += 1
          else:
            if exception_uid_list is not None:
              # case of parent tree mode (first/unique object).
              # beware object_list is not null in case folded sons exists so
Thomas Bernard's avatar
Thomas Bernard committed
1223 1224
              # do not export voluntary object_list to prevent bad
              # interpretation
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
              self.report_groups += [(object_tree_line, [], info_dict)]
              self.nbr_groups += 1
            else:
              # case of report_tree mode
              # saving information in report_groups
              self.report_groups += [(object_tree_line,object_list,info_dict)]
              self.nbr_groups += 1



    # reset to original value
    self.selection.edit(report = None)
1237
    self.selection.edit(report_list=None)
1238

1239 1240 1241
    # update report list if report_depth was specified
    if report_depth is not None:
      unfolded_list = []
1242 1243
      for (report_line, object_list, info_dict) in self.report_groups:
        if report_line.depth < report_depth and not info_dict['stat'] :
Thomas Bernard's avatar
Thomas Bernard committed
1244 1245 1246
          # depth of current report_line is inferior to the current
          # report_depth and current report_line is not stat line.
          # saving information
1247 1248 1249
          unfolded_list.append(report_line.getObject().getRelativeUrl())
      self.selection.edit(report_list=unfolded_list)

Thomas Bernard's avatar
Thomas Bernard committed
1250

1251 1252 1253 1254 1255
    ##################################################
    ########### GETTING MAIN AXIS BOUNDS #############
    ##################################################
    # before building group_object structure, need to recover axis begin & end
    # for main to be able to generate a 'smart' structure taking into account
Thomas Bernard's avatar
Thomas Bernard committed
1256 1257
    # only the area that need to be rendered. This prevents from useless
    # processing
1258 1259 1260
    # calculating main axis bounds
    self.getMainAxisInfo(self.main_axis_info)
    # applying main axis selection
1261
    if self.report_groups != []:
Thomas Bernard's avatar
Thomas Bernard committed
1262 1263
      self.report_groups=self.report_groups[self.main_axis_info['bound_start']:
                                            self.main_axis_info['bound_stop']]
1264
    else:
Thomas Bernard's avatar
Thomas Bernard committed
1265
      # ERROR : self.report_groups = []
1266
      # no group is available so the Y and X axis will be empty...
Thomas Bernard's avatar
Thomas Bernard committed
1267 1268 1269
      message = 'selection method returned empty list of objects : please check\
                your list_method and report_root'
      return [(Message(domain=None, message=message,mapping=None))]
1270 1271 1272 1273 1274


    ##################################################
    ############ GETTING SEC AXIS BOUNDS #############
    ##################################################
Thomas Bernard's avatar
Thomas Bernard committed
1275 1276
    # now that our report_group structure has been cut need to get secondary
    # axis bounds to add only the blocs needed afterwards
1277 1278 1279 1280 1281
    # getting secondary_axis_occurence to define begin and end secondary_axis
    # bounds (getting absolute size)
    self.secondary_axis_occurence = self.getSecondaryAxisOccurence()
    # now getting start & stop bounds (getting relative size to the current
    # rendering)
Thomas Bernard's avatar
Thomas Bernard committed
1282 1283 1284 1285 1286
    status = self.getSecondaryAxisInfo(self.secondary_axis_info)
    if status != 1:
      # ERROR
      # Found error while setting secondary axis bounds
      return status
1287 1288 1289 1290 1291 1292 1293


    ##################################################
    ####### SAVING NEW PROPERTIES INTO REQUEST #######
    ##################################################
    if self.list_method is not None and self.render_format != 'list':
     self.selection.edit(params = self.params)
Thomas Bernard's avatar
Thomas Bernard committed
1294 1295 1296
     self.here.portal_selections.setSelectionFor(self.selection_name,
                                                 self.selection,
                                                 REQUEST = self.REQUEST)
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306


    ##################################################
    ######### BUILDING GROUP_OBJECT STRUCTURE ########
    ##################################################
    # building group_object structure using sub lines depth (in case of a
    # report tree) by doing this.
    # taking into account page bounds to generate only the structure needed
    # instanciate BasicGroup class in BasicStructure so that the structure can
    # be built
Thomas Bernard's avatar
Thomas Bernard committed
1307 1308 1309 1310 1311
    status = self.buildGroupStructure()
    if status != 1:
      # ERROR
      # Found errors while setting group structure
      return status
1312 1313 1314
    # everything is fine
    return 1

1315

1316

1317 1318
  def getSecondaryAxisOccurence(self):
    """
Thomas Bernard's avatar
Thomas Bernard committed
1319 1320 1321
    get secondary_axis occurences in order to define begin and end bounds.
    Just make a listing of all the start and stop values for all the
    report_group objects
1322 1323 1324 1325
    """
    secondary_axis_occurence = []

    # specific start & stop methods name for secondary axis
Thomas Bernard's avatar
Thomas Bernard committed
1326 1327
    start_property_id = self.field.get_value('x_start_bloc')
    stop_property_id= self.field.get_value('x_stop_bloc')
1328
    for (object_tree_group, object_list, info_dict) in self.report_groups:
1329
      # recover method to get begin and end limits
1330

1331
      if object_list not in (None, [], {}) :
1332 1333
        for object_request in object_list:
          if start_property_id != None:
Thomas Bernard's avatar
Thomas Bernard committed
1334 1335
            block_begin = \
            object_request.getObject().getProperty(start_property_id,None)
1336 1337 1338
          else:
            block_begin = None
          if stop_property_id != None:
Thomas Bernard's avatar
Thomas Bernard committed
1339 1340
            block_stop = \
            object_request.getObject().getProperty(stop_property_id,None)
1341 1342 1343
          else:
            block_stop = None
          secondary_axis_occurence.append([block_begin,block_stop])
1344
      else:
Thomas Bernard's avatar
Thomas Bernard committed
1345
        if start_property_id != None:
Thomas Bernard's avatar
Thomas Bernard committed
1346 1347 1348
          block_begin = \
          object_tree_group.object.getObject().getProperty(start_property_id,
                                                           None)
1349 1350
        else:
          block_begin = None
Thomas Bernard's avatar
Thomas Bernard committed
1351
        if stop_property_id != None:
Thomas Bernard's avatar
Thomas Bernard committed
1352 1353 1354
          block_stop = \
          object_tree_group.object.getObject().getProperty(stop_property_id,
                                                           None)
1355 1356 1357 1358 1359 1360 1361
        else:
          block_stop = None
        secondary_axis_occurence.append([block_begin,block_stop])

    return secondary_axis_occurence


1362

1363 1364 1365 1366 1367 1368 1369
  def getSecondaryAxisInfo(self, axis_dict):
    """
    secondary_axis_ocurence holds couples of data (begin,end) related to
    basicActivity blocks, and axis if the instance representing the sec axis.
    it is now possible to recover begin and end value of the planning and then
    apply selection informations to get start and stop.
    """
Thomas Bernard's avatar
Thomas Bernard committed
1370 1371

    # recovering zoom properties
1372 1373 1374 1375 1376 1377 1378
    axis_dict['zoom_start'] = int(self.params.get('zoom_start',0))
    axis_dict['zoom_level'] = float(self.params.get('zoom_level',1))

    # recovering min and max bounds to get absolute bounds
    axis_dict['bound_begin'] = self.secondary_axis_occurence[0][0]
    axis_dict['bound_end'] = axis_dict['bound_begin']
    for occurence in self.secondary_axis_occurence:
Thomas Bernard's avatar
Thomas Bernard committed
1379 1380
      if (occurence[0] < axis_dict['bound_begin'] or \
          axis_dict['bound_begin'] == None) and occurence[0] != None:
1381
        axis_dict['bound_begin'] = occurence[0]
Thomas Bernard's avatar
Thomas Bernard committed
1382 1383
      if (occurence[1] > axis_dict['bound_end'] or  \
          axis_dict['bound_end'] == None) and occurence[1] != None:
1384
        axis_dict['bound_end'] = occurence[1]
1385 1386

    if axis_dict['bound_end']==None or axis_dict['bound_begin']==None:
Thomas Bernard's avatar
Thomas Bernard committed
1387
      # ERROR
1388
      # no bounds over the secondary axis have been defined
Thomas Bernard's avatar
Thomas Bernard committed
1389 1390 1391 1392 1393
      # can append if bad property has been selected 
      message = 'can not find secondary axis bounds for planning view :\
      No object has good start & stop properties, please check your objects \
      and their corresponding properties'
      return [(Message(domain=None, message=message,mapping=None))]
1394

Thomas Bernard's avatar
Thomas Bernard committed
1395 1396

    axis_dict['bound_range'] = axis_dict['bound_end']-axis_dict['bound_begin']
1397
    # now start and stop have the extreme values of the second axis bound.
Thomas Bernard's avatar
Thomas Bernard committed
1398
    # this represents in fact the size of the Planning's secondary axis
1399

Thomas Bernard's avatar
Thomas Bernard committed
1400
    # can now get selection informations ( float range 0..1)
1401 1402 1403
    axis_dict['bound_start'] = 0
    axis_dict['bound_stop'] = 1
    if self.selection != None:
Thomas Bernard's avatar
Thomas Bernard committed
1404 1405
      # selection is not None, trying to recover previously saved values about
      # secondary axis (axis start and stop bounds)
1406 1407 1408
      try:
        axis_dict['bound_start'] = self.selection.getSecondaryAxisStart()
        axis_dict['bound_stop'] = self.selection.getSecondaryAxisStop()
Thomas Bernard's avatar
Thomas Bernard committed
1409 1410
      except AttributeError:
        # bounds were not defined, escaping test
1411 1412 1413 1414 1415 1416
        pass

    # getting secondary axis page step
    axis_zoom_step = axis_dict['bound_range'] / axis_dict['zoom_level']

    # now setting bound_start
Thomas Bernard's avatar
Thomas Bernard committed
1417 1418
    axis_dict['bound_start'] = axis_dict['zoom_start'] * axis_zoom_step + \
                               axis_dict['bound_begin']
1419 1420 1421 1422 1423 1424 1425
    # for bound_stop just add page step
    axis_dict['bound_stop'] = axis_dict['bound_start'] + axis_zoom_step

    # saving current zoom values
    self.params['zoom_level'] = axis_dict['zoom_level']
    self.params['zoom_start'] = axis_dict['zoom_start']

Thomas Bernard's avatar
Thomas Bernard committed
1426 1427
    # everything is OK, returning 'true' flag
    return 1
1428

1429

1430 1431 1432 1433 1434 1435 1436 1437 1438
  def getMainAxisInfo(self, axis_dict):
    """
    getting main axis properties (total pages, current page, groups per page)
    and setting selection bounds (start & stop).
    beware this justs calculate the position of the first group present on the
    page (same for the last one), applying the selection is another thing in
    case of report tree (if the first element is a sub group of a report for
    example).
    """
1439
    axis_dict['bound_axis_groups'] = self.field.get_value('main_axis_groups')
1440
    if axis_dict['bound_axis_groups'] == None:
1441
      #XXX raise exception : no group nb/page defined
1442 1443
      pass

1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472

    # setting begin & end bounds
    axis_dict['bound_begin'] = 0
    axis_dict['bound_end'] = len(self.report_groups)
    if self.render_format == 'list':
      axis_dict['bound_start'] = 0
      axis_dict['bound_stop'] = axis_dict['bound_end']
      axis_dict['bound_page_total'] = 1
      axis_dict['bound_page_current'] = 1
      axis_dict['bound_page_groups'] = 1
    else:
      # recovering first group displayed on actual page
      try:
        # trying to recover from REQUEST
        axis_dict['bound_start'] = self.REQUEST.get('list_start')
        axis_dict['bound_start'] = int(axis_dict['bound_start'])
      except (AttributeError, TypeError):
        # recovering from params is case failed with REQUEST
        axis_dict['bound_start'] = self.params.get('list_start',0)
        if type(axis_dict['bound_start']) is type([]):
          axis_dict['bound_start'] = axis_dict['bound_start'][0]
        axis_dict['bound_start'] = int(axis_dict['bound_start'])
      axis_dict['bound_start'] = max(axis_dict['bound_start'],0)

      if axis_dict['bound_start'] > axis_dict['bound_end']:
        # new report_group is so small that previous if after the last element
        axis_dict['bound_start'] = axis_dict['bound_end']

      # updating start position to fit page size.
Thomas Bernard's avatar
Thomas Bernard committed
1473 1474
      axis_dict['bound_start'] -= \
               (axis_dict['bound_start'] % axis_dict['bound_axis_groups'])
1475 1476

      # setting last group displayed on page
Thomas Bernard's avatar
Thomas Bernard committed
1477 1478
      axis_dict['bound_stop'] = min (axis_dict['bound_end'],
               axis_dict['bound_start'] + axis_dict['bound_axis_groups'])
1479
      # calculating total number of pages
Thomas Bernard's avatar
Thomas Bernard committed
1480 1481
      axis_dict['bound_page_total'] = int(max(axis_dict['bound_end'] - 1,0) / \
               axis_dict['bound_axis_groups']) + 1
1482
      # calculating current page number
Thomas Bernard's avatar
Thomas Bernard committed
1483 1484
      axis_dict['bound_page_current'] = int(axis_dict['bound_start'] / \
               axis_dict['bound_axis_groups']) + 1
1485
      # adjusting first group displayed on current page
Thomas Bernard's avatar
Thomas Bernard committed
1486 1487
      axis_dict['bound_start'] = min(axis_dict['bound_start'], max(0,
           (axis_dict['bound_page_total']-1) * axis_dict['bound_axis_groups']))
1488

1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
      self.params['list_lines'] = axis_dict['bound_axis_groups']
      self.params['list_start'] = axis_dict['bound_start']


  def buildGroupStructure(self):
      """
      this procedure builds BasicGroup instances corresponding to the
      report_group_objects returned from the ERP5 request.
      """
      position = 0

      # iterating each element
Thomas Bernard's avatar
Thomas Bernard committed
1501 1502
      for (report_group_object, object_list, property_dict) in \
           self.report_groups:
1503 1504 1505

        stat_result = {}
        stat_context = report_group_object.getObject().asContext(**stat_result)
Thomas Bernard's avatar
Thomas Bernard committed
1506 1507 1508 1509
        stat_context.domain_url = \
                     report_group_object.getObject().getRelativeUrl()
        stat_context.absolute_url = \
                     lambda x: report_group_object.getObject().absolute_url()
1510 1511 1512 1513 1514 1515 1516
        url=getattr(stat_context,'domain_url','')
        # updating position_informations
        position +=1
        # recovering usefull informations
        title = report_group_object.getObject().getTitle()
        name = report_group_object.getObject().getTitle()
        depth = report_group_object.getDepth()
1517 1518
        is_open = report_group_object.getIsOpen()
        is_pure_summary = report_group_object.getIsPureSummary()
1519 1520

        # creating new group_object with all the informations collected
Thomas Bernard's avatar
Thomas Bernard committed
1521 1522 1523 1524 1525 1526 1527 1528
        child_group = BasicGroup(title=title, name=name, url=url,
                                 constraints=None, depth=depth,
                                 position=position, field =self.field,
                                 object=report_group_object, is_open=is_open,
                                 is_pure_summary=is_pure_summary,
                                 property_dict = property_dict)


1529
        if object_list != None:
Thomas Bernard's avatar
Thomas Bernard committed
1530 1531
          child_group.setBasicActivities(object_list,self.list_error,
                                         self.secondary_axis_info)
1532 1533 1534 1535 1536 1537 1538

        try:
          self.basic_group_list.append(child_group)
        except (AttributeError):
          self.basic_group_list = []
          self.basic_group_list.append(child_group)

Thomas Bernard's avatar
Thomas Bernard committed
1539 1540
      return 1

1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553

class BasicGroup:
  """
  A BasicGroup holds informations about an ERP5Object and is stored
  exclusively in BasicStructure. for each activity that will need to be
  represented in the PlanningBox, a BasicActivity is created and added to
  the current structure (for example BasicGroup represents an employee,
  and each BasicActivity represents a task the employee has).
  *Only one BasicGroup present while in Calendar mode.
  *BasicGroup instance itself can hold other BasicGroups in case of
  ReportTree mode to handle child groups.
  """

Thomas Bernard's avatar
Thomas Bernard committed
1554 1555 1556
  def __init__ (self, title='', name='',url='', constraints='', depth=0,
                position=0, field = None, object = None, is_open=0,
                is_pure_summary=1, property_dict = {}):
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
    self.title = title
    self.name = name
    self.url = url
    self.basic_group_list = None # used with ReportTree
    self.basic_activity_list = None # bloc activities
    self.constraints = constraints# global contraints applying to all group
    self.depth = depth # depth of the actual group (report_tree mode)
    self.position = position # position of current group in the selection
    self.field = field # field object itself. used for several purposes
    self.object = object # ERP5 object returned & related to the group
Thomas Bernard's avatar
Thomas Bernard committed
1567 1568 1569 1570
    self.is_open = is_open
    self.is_pure_summary = is_pure_summary
    # specific start and stop bound values specifiec to the current group and
    # used in case of calendar mode
1571 1572
    self.start = None
    self.stop = None
1573 1574 1575 1576
    # property_dict holds all information about the current axis_group
    # type of group, stat, etc.
    self.property_dict = property_dict

1577 1578 1579 1580

  def setBasicActivities(self,activity_list, list_error,secondary_axis_info):
    """
    link a list of activities to the current object.
Thomas Bernard's avatar
Thomas Bernard committed
1581 1582 1583 1584 1585 1586
    *Recover group properties. Used in case activity is built from Group
     itself
    *create a BasicActivity for each activity referenced in the list if
     necessary
    *add the activity to the current group.
    *update secondary_axis_occurence
1587
    """
Thomas Bernard's avatar
Thomas Bernard committed
1588
    info = {}
Thomas Bernard's avatar
Thomas Bernard committed
1589 1590 1591
    # specific begin & stop property names for secondary axis
    object_property_begin = self.field.get_value('x_start_bloc')
    object_property_end = self.field.get_value('x_stop_bloc')
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
    # specific block text_information methods
    info_center = self.field.get_value('info_center')
    info_topleft = self.field.get_value('info_topleft')
    info_topright = self.field.get_value('info_topright')
    info_backleft = self.field.get_value('info_backleft')
    info_backright = self.field.get_value('info_backright')
    # getting info method from activity itself if exists
    info_center_method = getattr(self.object.getObject(),info_center,None)
    info_topright_method = getattr(self.object.getObject(),info_topright,None)
    info_topleft_method = getattr(self.object.getObject(),info_topleft,None)
    info_backleft_method = getattr(self.object.getObject(),info_backleft,None)
Thomas Bernard's avatar
Thomas Bernard committed
1603 1604
    info_backright_method = \
                  getattr(self.object.getObject(),info_backright,None)
1605
    # if method recovered is not null, then updating
Thomas Bernard's avatar
Thomas Bernard committed
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
    if info_center_method!=None: \
                  info['info_center'] = str(info_center_method())
    if info_topright_method!=None: \
                  info['info_topright'] = str(info_topright_method())
    if info_topleft_method!=None: \
                  info['info_topleft'] = str(info_topleft_method())
    if info_backleft_method!=None: \
                  info['info_backleft'] = str(info_backleft_method())
    if info_backright_method!=None: \
                  info['info_backright'] = str(info_backright_method())
1616

1617
    if activity_list not in ([],None):
1618 1619 1620 1621 1622
      indic=0
      # iterating each activity linked to the current group
      for activity_content in activity_list:
        # interpreting results and getting begin and end values from 
        # previously recovered method
1623 1624
        block_begin = None
        block_end = None
Thomas Bernard's avatar
Thomas Bernard committed
1625
        if object_property_begin !=None:
Thomas Bernard's avatar
Thomas Bernard committed
1626 1627
          block_begin = \
                 getattr(activity_content.getObject(),object_property_begin)
1628 1629
        else:
          block_begin = None
1630

Thomas Bernard's avatar
Thomas Bernard committed
1631
        if object_property_end != None:
1632
          block_end = getattr(activity_content.getObject(),object_property_end)
1633 1634 1635
        else:
          block_end = None

1636
        # handling case where activity bound is not defined
1637 1638 1639 1640 1641 1642
        if block_begin == None:
          block_begin = secondary_axis_info['bound_start']
          current_color='#E4CCE1'
        if block_end == None:
          block_end = secondary_axis_info['bound_stop']
          current_color='#E4CCE1'
Thomas Bernard's avatar
Thomas Bernard committed
1643 1644 1645 1646
        # testing if activity is visible according to the current zoom
        # selection over the secondary_axis
        if  block_begin > secondary_axis_info['bound_stop'] or \
            block_end < secondary_axis_info['bound_start']:
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
          # activity will not be displayed, stopping process
          pass
        else:
          # activity is somehow displayed. checking if need to cut its bounds
          if block_begin < secondary_axis_info['bound_start']:
            # need to cut begin bound
            block_start = secondary_axis_info['bound_start']
          else: block_start = block_begin

          if block_end > secondary_axis_info['bound_stop']:
            block_stop = secondary_axis_info['bound_stop']
          else:
            block_stop = block_end

          # defining name
1662
          name = "Activity_%s" % (str(indic))
1663 1664

          error = 'false'
1665
          current_color=''
1666

1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
          if self.property_dict['stat'] == 1:
            info = None
            info = {}
            info['info_center'] = ''
            info['info_topright'] = ''
            info['info_topleft'] = ''
            info['info_backleft'] = ''
            info['info_backright'] = ''
            title = ''
            object = activity_content
            url=''
            object_property_height = self.field.get_value('y_size_block')
Thomas Bernard's avatar
Thomas Bernard committed
1679 1680
            height = \
                 getattr(activity_content.getObject(),object_property_height)
1681 1682 1683 1684 1685 1686 1687 1688
          else:
            info = None
            info = {}
            # getting info text from activity itself if exists
            info_center_method = getattr(activity_content,info_center,None)
            info_topright_method = getattr(activity_content,info_topright,None)
            info_topleft_method = getattr(activity_content,info_topleft,None)
            info_backleft_method = getattr(activity_content,info_backleft,None)
Thomas Bernard's avatar
Thomas Bernard committed
1689 1690
            info_backright_method = \
                 getattr(activity_content,info_backright,None)
1691 1692

            # if value recovered is not null, then updating 
Thomas Bernard's avatar
Thomas Bernard committed
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
            if info_center_method!=None:
               info['info_center']=str(info_center_method())
            if info_topright_method!=None:
               info['info_topright']=str(info_topright_method())
            if info_topleft_method!=None:
               info['info_topleft']=str(info_topleft_method())
            if info_backleft_method!=None:
               info['info_backleft'] =str(info_backleft_method())
            if info_backright_method!=None:
               info['info_backright']=str(info_backright_method())
1703 1704 1705

            title = info['info_center']

Thomas Bernard's avatar
Thomas Bernard committed
1706 1707
            color_script = getattr(activity_content.getObject(),
                                   self.field.get_value('color_script'),None)
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
            # calling color script if exists to set up activity_color
            if color_script !=None:
              current_color = color_script(activity_content.getObject())

            # testing if some activities have errors
            if list_error not in (None, []):
              for activity_error in list_error:
                if activity_error[0][0] == name:
                  error = 'true'
                  break

            stat_result = {}
Thomas Bernard's avatar
Thomas Bernard committed
1720 1721 1722 1723 1724 1725
            stat_context = \
                         activity_content.getObject().asContext(**stat_result)
            stat_context.domain_url = \
                         activity_content.getObject().getRelativeUrl()
            stat_context.absolute_url = \
                         lambda x: activity_content.getObject().absolute_url()
1726 1727 1728 1729 1730
            object = stat_context.getObject()
            url = stat_context.getUrl()

            # XXX should define height of block here
            height = None
1731 1732

          # creating new activity instance
Thomas Bernard's avatar
Thomas Bernard committed
1733 1734 1735 1736 1737 1738 1739 1740
          activity = BasicActivity(title=title, name=name, object=object,
                                   url=url, absolute_begin=block_begin,
                                   absolute_end=block_end,
                                   absolute_start=block_start,
                                   absolute_stop=block_stop, height = height,
                                   color=current_color, info_dict=info,
                                   error=error,
                                   property_dict=self.property_dict)
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752


          # adding new activity to personal group activity list
          try:
            self.basic_activity_list.append(activity)
          except (AttributeError):
            self.basic_activity_list = []
            self.basic_activity_list.append(activity)
          # incrementing indic used for differenciating activities in the same 
          # group (used for Activity naming)
          indic += 1

1753

1754

Sebastien Robin's avatar
Sebastien Robin committed
1755
    else:
Thomas Bernard's avatar
Thomas Bernard committed
1756 1757 1758
      # specific color script
      color_script = getattr(self.object.getObject(),
                             self.field.get_value('color_script'),None)
1759 1760 1761 1762 1763
      # calling color script if exists to set up activity_color
      current_color=''
      if color_script !=None:
        current_color = color_script(self.object.getObject())

1764
      # getting begin and end values from previously recovered method
Thomas Bernard's avatar
Thomas Bernard committed
1765
      if object_property_begin !=None:
Thomas Bernard's avatar
Thomas Bernard committed
1766 1767
        block_begin = \
                    self.object.getObject().getProperty(object_property_begin)
Sebastien Robin's avatar
Sebastien Robin committed
1768 1769
      else:
        block_begin = None
1770

Thomas Bernard's avatar
Thomas Bernard committed
1771 1772
      if object_property_end != None:
        block_end = self.object.getObject().getProperty(object_property_end)
Sebastien Robin's avatar
Sebastien Robin committed
1773
      else:
1774 1775
        block_end = None

Thomas Bernard's avatar
Thomas Bernard committed
1776 1777
      # testing if activity is visible according to the current zoom selection
      # over the secondary_axis
1778 1779 1780 1781 1782 1783
      if block_begin == None:
        block_begin = secondary_axis_info['bound_start']
        current_color='#E4CCE1'
      if block_end == None:
        block_end = secondary_axis_info['bound_stop']
        current_color='#E4CCE1'
Thomas Bernard's avatar
Thomas Bernard committed
1784 1785 1786
      if  (block_begin > secondary_axis_info['bound_stop'] or \
        block_end < secondary_axis_info['bound_start']):
        # activity will not be displayed, stopping process
1787
        pass
Sebastien Robin's avatar
Sebastien Robin committed
1788
      else:
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
        # activity is somehow displayed. checking if need to cut its bounds
        if block_begin < secondary_axis_info['bound_start']:
          # need to cut begin bound
          block_start = secondary_axis_info['bound_start']
        else: block_start = block_begin

        if block_end > secondary_axis_info['bound_stop']:
          block_stop = secondary_axis_info['bound_stop']
        else:
          block_stop = block_end

        # testing if some activities have errors
        error = 'false'
1802
        if list_error not in (None,[]):
1803 1804 1805
          for activity_error in list_error:
            if activity_error[0][0] == name:
              error = 'true'
Sebastien Robin's avatar
Sebastien Robin committed
1806
              break
1807 1808 1809 1810

        # defining name
        name = "Activity_%s" % (self.object.getObject().getTitle())

1811 1812 1813
        # height should be implemented here
        height = None

1814
        # creating new activity instance
Thomas Bernard's avatar
Thomas Bernard committed
1815 1816 1817 1818 1819 1820 1821 1822
        activity=BasicActivity(title=info['info_center'], name=name,
                               object=self.object.object, url=self.url,
                               absolute_begin=block_begin,
                               absolute_end=block_end,
                               absolute_start=block_start,
                               absolute_stop=block_stop, height=height,
                               color=current_color, info_dict=info,
                               error=error, property_dict=self.property_dict)
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838

        # adding new activity to personal group activity list
        try:
          self.basic_activity_list.append(activity)
        except (AttributeError):
          self.basic_activity_list = []
          self.basic_activity_list.append(activity)





class BasicActivity:
  """ Represents an activity, a task, in the group it belongs to. Beware
      nothing about multitask rendering. """

Thomas Bernard's avatar
Thomas Bernard committed
1839 1840 1841 1842
  def __init__ (self, title='', name='',object = None, url='',
                absolute_begin=None, absolute_end=None, absolute_start=None,
                absolute_stop=None, height=None, constraints='', color=None,
                error='false', info_dict= None, property_dict = {}):
1843 1844
    self.title = title
    self.name = name
1845
    self.object = object
1846 1847 1848 1849 1850 1851
    self.url = url
    self.absolute_begin = absolute_begin # absolute values independant of any
                                         # hypothetic zoom
    self.absolute_end = absolute_end
    self.absolute_start = absolute_start
    self.absolute_stop = absolute_stop
1852
    self.height = height
Thomas Bernard's avatar
Thomas Bernard committed
1853
    self.constraints = constraints
1854 1855 1856
    self.color = color
    self.info_dict = info_dict
    self.error = error
1857
    self.property_dict = property_dict # dict containing specific properties
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869




class PlanningStructure:
  """ class aimed to generate the Planning final structure, including :
      - activities with their blocs (so contains Activity structure)
      - Axis informations (contains Axis Structure).
      The zoom properties on secondary axis are applied to this structure.
      """


1870
  def __init__ (self):
1871 1872 1873 1874 1875 1876 1877 1878 1879
    self.main_axis = ''
    self.secondary_axis = ''
    self.content = []
    self.content_delimiters = None


  def build(self,basic_structure=None, field=None, REQUEST=None):
    """
    main procedure for building Planning Structure
Thomas Bernard's avatar
Thomas Bernard committed
1880 1881 1882 1883 1884
    do all the necessary process to construct a full Structure compliant with
    all expectations (axis, zoom, colors, report_tree, multi_lines, etc.).
    From this final structure just need to run a PageTemplate to get an HTML
    output, or any other script to get the Planning result in the format you
    like...
1885
    """
Thomas Bernard's avatar
Thomas Bernard committed
1886
    # recovering render format ('YX' or 'XY')
1887 1888
    self.render_format = field.get_value('representation_type')

1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
    # declaring main axis
    self.main_axis = Axis(title='main axis', name='axis',
                     unit='', axis_order=1,axis_group=[])

    # declaring secondary axis
    self.secondary_axis = Axis(title='sec axis', name='axis',
                     unit='', axis_order=2, axis_group=[])

    # linking axis objects to their corresponding accessor, i.e X or Y
    # this allows the planning to be generic.
    if self.render_format == 'YX':
      self.Y = self.main_axis
      self.X = self.secondary_axis
Sebastien Robin's avatar
Sebastien Robin committed
1902
    else:
1903 1904 1905 1906 1907 1908 1909 1910 1911
      self.Y = self.secondary_axis
      self.X = self.main_axis

    # initializing axis properties
    self.X.name = 'axis_x'
    self.Y.name = 'axis_y'


    # recovering secondary_axis_ bounds
Thomas Bernard's avatar
Thomas Bernard committed
1912 1913 1914 1915
    self.secondary_axis.start = \
                      basic_structure.secondary_axis_info['bound_start']
    self.secondary_axis.stop = \
                      basic_structure.secondary_axis_info['bound_stop']
1916 1917 1918 1919


    self.main_axis.size =  self.buildGroups(basic_structure=basic_structure)

Thomas Bernard's avatar
Thomas Bernard committed
1920

1921 1922
    # call method to build secondary axis structure
    # need start_bound, stop_bound and number of groups to build
Thomas Bernard's avatar
Thomas Bernard committed
1923 1924 1925 1926
    status = self.buildSecondaryAxis(basic_structure,field)
    if status != 1:
      # ERROR while building secondary axis
      return status
1927
    # completing axisgroup informations according to their bounds
Thomas Bernard's avatar
Thomas Bernard committed
1928 1929 1930 1931
    status = self.completeAxis()
    if status != 1:
      # ERROR while completing axis
      return status
1932
    # the whole structure is almost completed : axis_groups are defined, as
Thomas Bernard's avatar
Thomas Bernard committed
1933 1934
    # axis_elements with their activities. Just need to create blocks related
    # to the activities (special process only for Calendar mode) with their
1935
    # BlockPosition
Thomas Bernard's avatar
Thomas Bernard committed
1936 1937 1938 1939 1940 1941
    status = self.buildBlocs(REQUEST = REQUEST)
    if status != 1:
      # ERROR while building blocks
      return status
    # everything is fine, returning 'true' flag.
    return 1
1942 1943


1944
  def buildSecondaryAxis(self,basic_structure, field):
1945 1946 1947
    """
    build secondary axis structure
    """
1948

Thomas Bernard's avatar
Thomas Bernard committed
1949 1950 1951 1952
    # defining min and max delimiter number
    delimiter_min_number = basic_structure.field.get_value('delimiter')
    axis_stop = (self.secondary_axis.stop)
    axis_start = (self.secondary_axis.start)
1953 1954


Thomas Bernard's avatar
Thomas Bernard committed
1955 1956 1957 1958 1959 1960 1961 1962
    axis_script=getattr(basic_structure.here,
                       basic_structure.field.get_value('sec_axis_script'),None)
    if axis_script == None:
      # ERROR
      message = 'unable to find secondary axis generation script : "%s" does \
             not exist' % basic_structure.field.get_value('sec_axis_script')
      return [(Message(domain=None, message=message, mapping=None))]

Thomas Bernard's avatar
Thomas Bernard committed
1963
    # calling script to get list of delimiters to implement
Thomas Bernard's avatar
Thomas Bernard committed
1964 1965 1966 1967 1968 1969 1970 1971 1972
    # just need to pass start, stop, and the minimum number of delimiter
    # wanted. a structure is returned : list of delimiters, each delimiter
    # defined by a list [ relative position, title, tooltip , delimiter_type]
    try:
      delimiter_list = axis_script(axis_start,axis_stop,delimiter_min_number)
    except (ArithmeticError, LookupError, AttributeError, TypeError):
      message =  'error raised in secondary axis generation script : please \
             check "%s"'% basic_structure.field.get_value('sec_axis_script')
      return [(Message(domain=None, message=message,mapping=None))]
1973

Thomas Bernard's avatar
Thomas Bernard committed
1974 1975 1976
    axis_stop = int(axis_stop)
    axis_start = int(axis_start)
    axis_range = axis_stop - axis_start
1977

Thomas Bernard's avatar
Thomas Bernard committed
1978 1979 1980
    # axis_element_number is used to fix the group size
    self.secondary_axis.axis_size = axis_range
    # axis_group_number is used to differenciate groups
1981
    axis_group_number = 0
Thomas Bernard's avatar
Thomas Bernard committed
1982 1983 1984 1985
    # now iterating list of delimiters and building group list
    # group position and size informations are saved in position_secondary
    # using relative coordinates
    for delimiter in delimiter_list:
Thomas Bernard's avatar
Thomas Bernard committed
1986 1987
      axis_group = AxisGroup(name='Group_sec_' + str(axis_group_number),
                             title=delimiter[1], delimiter_type=delimiter[3])
Thomas Bernard's avatar
Thomas Bernard committed
1988
      axis_group.tooltip = delimiter[2]
Thomas Bernard's avatar
Thomas Bernard committed
1989 1990
      axis_group.position_secondary.relative_begin = \
                             int(delimiter[0]) - int(axis_start)
Thomas Bernard's avatar
Thomas Bernard committed
1991 1992
      # set defaut stop bound and size
      axis_group.position_secondary.relative_end  = int(axis_stop)
Thomas Bernard's avatar
Thomas Bernard committed
1993 1994
      axis_group.position_secondary.relative_range = \
                             int(axis_stop) - int(delimiter[0])
Thomas Bernard's avatar
Thomas Bernard committed
1995 1996 1997 1998 1999 2000 2001
      if delimiter == delimiter_list[0]:
        # actual delimiter is the first delimiter entered
        # do not need to update previous delimiter informations
        pass
      else:
        # actual delimiter info has a previous delimiter
        # update its informations
Thomas Bernard's avatar
Thomas Bernard committed
2002 2003 2004 2005 2006
        self.secondary_axis.axis_group[-1].position_secondary.relative_end = \
          axis_group.position_secondary.relative_begin
        self.secondary_axis.axis_group[-1].position_secondary.relative_range =\
          axis_group.position_secondary.relative_begin - \
          self.secondary_axis.axis_group[-1].position_secondary.relative_begin
Thomas Bernard's avatar
Thomas Bernard committed
2007
      # add current axis_group to axis_group list
2008 2009 2010 2011
      self.secondary_axis.axis_group.append(axis_group)
      axis_group_number += 1


Thomas Bernard's avatar
Thomas Bernard committed
2012 2013 2014
    return 1


Thomas Bernard's avatar
Thomas Bernard committed
2015
  def completeAxis (self):
2016 2017 2018 2019 2020 2021 2022
    """
    complete axis infomations (and more precisely axis position objects) thanks
    to the actual planning structure
    """

    # processing main axis
    for axis_group_element in self.main_axis.axis_group:
Thomas Bernard's avatar
Thomas Bernard committed
2023 2024 2025 2026 2027 2028 2029 2030 2031
      axis_group_element.position_main.absolute_begin = (
              float(axis_group_element.axis_element_start - 1) /
              float(self.main_axis.size))
      axis_group_element.position_main.absolute_end = (
              float(axis_group_element.axis_element_stop) /
              float(self.main_axis.size))
      axis_group_element.position_main.absolute_range = (
              float(axis_group_element.axis_element_number) /
              float(self.main_axis.size))
2032 2033 2034 2035
      axis_group_element.position_secondary.absolute_begin = 0
      axis_group_element.position_secondary.absolute_end = 1
      axis_group_element.position_secondary.absolute_range= 1

Thomas Bernard's avatar
Thomas Bernard committed
2036

2037
    for axis_group_element in self.secondary_axis.axis_group:
Thomas Bernard's avatar
Thomas Bernard committed
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
      position = axis_group_element.position_secondary
      axis_group_element.position_secondary.absolute_begin = (
           float(axis_group_element.position_secondary.relative_begin) /
           self.secondary_axis.axis_size)
      axis_group_element.position_secondary.absolute_end = (
           float(axis_group_element.position_secondary.relative_end) /
           self.secondary_axis.axis_size)
      axis_group_element.position_secondary.absolute_range = (
           float(axis_group_element.position_secondary.relative_range) /
           self.secondary_axis.axis_size)
2048
      axis_group_element.position_main.absolute_begin = 0
Thomas Bernard's avatar
Thomas Bernard committed
2049 2050 2051
      axis_group_element.position_main.absolute_end   = 1
      axis_group_element.position_main.absolute_range = 1

Thomas Bernard's avatar
Thomas Bernard committed
2052 2053 2054
    # returning 'true' flag at the end of the process
    return 1

2055 2056 2057 2058 2059 2060 2061


  def buildGroups (self, basic_structure=None):
    """
    build groups from activities saved in the structure groups.
    """
    axis_group_number = 0
2062
    #pdb.set_trace()
2063 2064 2065
    axis_element_already_present=0
    for basic_group_object in basic_structure.basic_group_list:
      axis_group_number += 1
Thomas Bernard's avatar
Thomas Bernard committed
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
      axis_group= AxisGroup(name='Group_' + str(axis_group_number),
                            title=basic_group_object.title,
                            object=basic_group_object.object,
                            axis_group_number = axis_group_number,
                            is_open=basic_group_object.is_open,
                            is_pure_summary=basic_group_object.is_pure_summary,
                            url = basic_group_object.url,
                            depth=basic_group_object.depth,
                            secondary_axis_start= self.secondary_axis.start,
                            secondary_axis_stop= self.secondary_axis.stop,
                            property_dict = basic_group_object.property_dict)
2077 2078 2079
      if self.render_format == 'YX':
        axis_group.position_y = axis_group.position_main
        axis_group.position_x = axis_group.position_secondary
Sebastien Robin's avatar
Sebastien Robin committed
2080
      else:
2081 2082 2083 2084 2085 2086 2087
        axis_group.position_y = axis_group.position_secondary
        axis_group.position_x = axis_group.position_main
      # init absolute position over the axis
      axis_group.position_secondary.absolute_begin = 0
      axis_group.position_secondary.absolute_end= 1
      axis_group.position_secondary.absolute_range = 1
      # updating axis_group properties
Thomas Bernard's avatar
Thomas Bernard committed
2088 2089
      axis_group.fixProperties(form_id = basic_structure.form.id,
                               selection_name = basic_structure.selection_name)
2090 2091 2092 2093 2094 2095
      # updating start value
      axis_group.axis_element_start = axis_element_already_present + 1
      activity_number = 0
      if basic_group_object.basic_activity_list != None:
        # need to check if activity list is not empty : possible in case zoom
        # selection is used over the secondary axis
2096 2097 2098 2099 2100 2101
        if axis_group.property_dict['stat'] == 0:
          # case group is task group. Using default method that
          # generates automatically the necessary axis elements
          for basic_activity_object in basic_group_object.basic_activity_list:
            activity_number += 1
            # create new activity in the PlanningStructure
Thomas Bernard's avatar
Thomas Bernard committed
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
            activity=Activity(name='Group_%s_Activity_%s' %(
                                            str(axis_group_number),
                                            str(activity_number)),
                              title=basic_activity_object.title,
                              object=basic_activity_object.object,
                              color=basic_activity_object.color,
                              link=basic_activity_object.url,
                              secondary_axis_begin= \
                                          basic_activity_object.absolute_begin,
                              secondary_axis_end= \
                                          basic_activity_object.absolute_end,
                              secondary_axis_start= \
                                          basic_activity_object.absolute_start,
                              secondary_axis_stop= \
                                          basic_activity_object.absolute_stop,
                              primary_axis_block=self,
                              info=basic_activity_object.info_dict,
                              render_format=self.render_format,
                              property_dict=basic_group_object.property_dict)
2121 2122 2123 2124 2125 2126
            # adding activity to the current group
            axis_group.addActivity(activity,axis_element_already_present)
        else:
          # case group is stat group. Using special method that prevent
          # from generating more than 1 axis element and divide tasks size if
          # necessary
Thomas Bernard's avatar
Thomas Bernard committed
2127 2128
          axis_group.addStatActivities(
               basic_activity_list=basic_group_object.basic_activity_list,
2129
               axis_group_number=axis_group_number,
Thomas Bernard's avatar
Thomas Bernard committed
2130 2131 2132
               axis_element_already_present=axis_element_already_present,
               render_format=self.render_format, primary_axis_block=self,
               property_dict=basic_group_object.property_dict)
Sebastien Robin's avatar
Sebastien Robin committed
2133
      else:
2134 2135 2136
        # basic_activity_list is empty : need to add a empty axis_element to
        # prevent bug or crash
        axis_group.axis_element_number = 1
Thomas Bernard's avatar
Thomas Bernard committed
2137 2138 2139 2140 2141
        new_axis_element=AxisElement(name='Group_%s_AxisElement_1' %
                                           str(axis_group_number),
                                 relative_number= 1,
                                 absolute_number=axis_group.axis_element_start,
                                 parent_axis_group=axis_group)
2142 2143 2144 2145
        # add new activity to this brand new axis_element
        new_axis_element.activity_list = []
        axis_group.axis_element_list = []
        axis_group.axis_element_list.append(new_axis_element)
2146

Thomas Bernard's avatar
Thomas Bernard committed
2147 2148
      axis_group.axis_element_stop = (axis_element_already_present +
                                     axis_group.axis_element_number)
2149 2150 2151 2152 2153 2154 2155
      axis_element_already_present = axis_group.axis_element_stop
      try:
        self.main_axis.axis_group.append(axis_group)
      except AttributeError:
        self.main_axis.axis_group = []
        self.main_axis.axis_group.append(axis_group)
    return axis_element_already_present
Sebastien Robin's avatar
Sebastien Robin committed
2156

2157

Thomas Bernard's avatar
Thomas Bernard committed
2158
  def buildBlocs(self,REQUEST):
2159 2160 2161 2162
    """
    iterate the whole planning structure to get various activities and build
    their related blocs.
    """
Thomas Bernard's avatar
Thomas Bernard committed
2163 2164 2165
    # recover activity and block error lists
    warning_activity_list = REQUEST.get('warning_activity_list',[])
    error_block_list = REQUEST.get('error_block_list',[])
2166
    error_info_dict = REQUEST.get('error_info_dict',{})
Thomas Bernard's avatar
Thomas Bernard committed
2167

2168 2169 2170 2171 2172 2173 2174 2175
    for axis_group_object in self.main_axis.axis_group:
      for axis_element_object in axis_group_object.axis_element_list:
        for activity in axis_element_object.activity_list:
          if activity.name in warning_activity_list:
            warning = 1
          else:
            warning = 0
          # generate activity_info
Thomas Bernard's avatar
Thomas Bernard committed
2176 2177 2178 2179 2180 2181 2182 2183
          status = activity.addBlocs(main_axis_start=0,
                                main_axis_stop=self.main_axis.size,
                                secondary_axis_start=self.secondary_axis.start,
                                secondary_axis_stop=self.secondary_axis.stop,
                                planning=self, warning=warning,
                                error_block_list=error_block_list,
                                error_info_dict=error_info_dict)
          if status !=1: return status
2184 2185 2186
        if axis_group_object.property_dict['stat'] == 1:
          # case stat group_object, need to update block size to display
          # stats informations
Thomas Bernard's avatar
Thomas Bernard committed
2187 2188 2189 2190
          status = axis_group_object.updateStatBlocks()
          if status !=1: return status
    # no problem during process, returning 'true' flag
    return 1 
2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201


class Activity:
  """
  Class representing a task in the Planning, for example an appointment or
  a duration. Can be divided in several blocs for being rendered correctly
  (contains Bloc Structure).
  Activity instance are not rendered but only their blocs. This Activity
  structure is used for rebuilding tasks from bloc positions when
  validating the Planning.
  """
Thomas Bernard's avatar
Thomas Bernard committed
2202 2203 2204 2205 2206
  def __init__ (self,name=None, title=None, object=None, types=None,
                color=None, link=None, height=None, secondary_axis_begin=None,
                secondary_axis_end=None, secondary_axis_start=None,
                secondary_axis_stop=None, primary_axis_block=None, info=None,
                render_format='YX', property_dict={} ):
2207
    self.name = name # internal activity_name
Thomas Bernard's avatar
Thomas Bernard committed
2208
    self.id = self.name
2209
    self.title = title # displayed activity_name
2210
    self.object = object
2211 2212 2213
    self.types = types # activity, activity_error, info
    self.color = color # color used to render all Blocs
    self.link = link # link to the ERP5 object
2214
    self.height = height
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
    # self.constraints = constraints
    self.block_list = None # contains all the blocs used to render the activity
    self.secondary_axis_begin =secondary_axis_begin
    self.secondary_axis_end=secondary_axis_end
    self.secondary_axis_start=secondary_axis_start
    self.secondary_axis_stop=secondary_axis_stop
    self.primary_axis_block = primary_axis_block
    self.block_bounds = None
    self.info = info
    self.parent_axis_element = None
    self.render_format= render_format
2226
    self.property_dict = property_dict
2227

Thomas Bernard's avatar
Thomas Bernard committed
2228 2229 2230

  def get_error_message (self, Error):
    # need to update the error message
2231
    return 'task %s (%s)not validated' % (self.name, self.title)
Thomas Bernard's avatar
Thomas Bernard committed
2232 2233


2234 2235 2236 2237 2238 2239 2240
  def isValidPosition(self, bound_begin, bound_end):
    """
    can check if actual activity can fit within the bounds, returns :
    - 0 if not
    - 1 if partially ( need to cut the activity bounds to make it fit)
    - 2 definitely
    """
Thomas Bernard's avatar
Thomas Bernard committed
2241 2242
    if (self.secondary_axis_begin > bound_end) or \
       (self.secondary_axis_end < bound_begin):
2243
      return 0
Thomas Bernard's avatar
Thomas Bernard committed
2244 2245
    elif (self.secondary_axis_begin > bound_begin) and \
         (self.secondary_axis_end < bound_end):
2246
      return 1
2247
    else:
2248 2249
      return 2

Thomas Bernard's avatar
Thomas Bernard committed
2250 2251 2252 2253 2254

  def addBlocs(self, main_axis_start=None, main_axis_stop=None,
               secondary_axis_start=None,
               secondary_axis_stop=None,planning=None, warning=0,
               error_block_list=[], error_info_dict={}):
2255 2256 2257 2258 2259
    """
    define list of (begin & stop) values for blocs representing the actual
    activity (can have several blocs if necessary).
    """
    # recover list of bounds
2260
    if self.secondary_axis_start != None or self.secondary_axis_stop != None:
Thomas Bernard's avatar
Thomas Bernard committed
2261 2262 2263 2264
      #split_method_name = field.get_value('split_method',None)
      #split_method = getattr(self.object,split_method_name, None)
      #if split_method != None:

2265
      secondary_block_bounds = self.splitActivity()
Thomas Bernard's avatar
Thomas Bernard committed
2266 2267 2268
      #secondary_block_bounds = split_method(self.secondary_axis_start,
                                           # self.secondary_axis_stop)

2269
    else:
Thomas Bernard's avatar
Thomas Bernard committed
2270 2271
      secondary_block_bounds = \
               [[self.secondary_axis_start,self.secondary_axis_stop,1]]
2272 2273 2274

    block_number = 0
    # iterating resulting list
2275
    for (start,stop,zone) in secondary_block_bounds:
2276 2277

      block_number += 1
2278

Thomas Bernard's avatar
Thomas Bernard committed
2279
      block_name = self.name + '_Block_' + str(block_number)
2280
      # create new block instance
2281

Thomas Bernard's avatar
Thomas Bernard committed
2282 2283
      if block_name in error_block_list:
        error = 1
2284
        error_text= error_info_dict[block_name]
Thomas Bernard's avatar
Thomas Bernard committed
2285 2286
      else:
        error = 0
2287 2288
        error_text=''

Thomas Bernard's avatar
Thomas Bernard committed
2289 2290
      # zone property is used to check if block is an active (main activity
      # block) block or a passive one (just a display block)
2291 2292 2293 2294 2295 2296 2297 2298
      if zone == 1:
        # active
        block_color = self.color
        block_link = self.link
      else:
        # passive
        block_color = '#D1E8FF'
        block_link = ''
2299

Thomas Bernard's avatar
Thomas Bernard committed
2300 2301 2302 2303 2304 2305
      new_block = Bloc(name= block_name,color=block_color,link=block_link,
                       number = block_number,
                       render_format=self.render_format, parent_activity=self,
                       warning=warning, error=error,
                       error_text=error_text,zone=zone,
                       property_dict=self.property_dict)
2306 2307 2308 2309

      new_block.buildInfoDict(info_dict = self.info)

      # updating secondary_axis block position
2310 2311 2312 2313 2314 2315 2316 2317
      if self.secondary_axis_start != None:
        new_block.position_secondary.absolute_begin = start
      else:
        new_block.position_secondary.absolute_begin = secondary_axis_start
      if self.secondary_axis_stop != None:
        new_block.position_secondary.absolute_end = stop
      else:
        new_block.position_secondary.absolute_end = secondary_axis_stop
2318 2319
      new_block.position_secondary.absolute_range = stop - start
      # updating main_axis block position
Thomas Bernard's avatar
Thomas Bernard committed
2320 2321 2322 2323 2324 2325 2326
      new_block.position_main.absolute_begin = \
                      self.parent_axis_element.absolute_number - 1
      new_block.position_main.absolute_end = \
                      self.parent_axis_element.absolute_number
      new_block.position_main.absolute_range = (
                      new_block.position_main.absolute_end -
                      new_block.position_main.absolute_begin)
2327 2328 2329

      # now absolute positions are updated, and the axis values are known
      # (as parameters), processing relative values
Thomas Bernard's avatar
Thomas Bernard committed
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
      new_block.position_secondary.relative_begin = (
          float(new_block.position_secondary.absolute_begin -
          secondary_axis_start) / float(secondary_axis_stop -
          secondary_axis_start))
      new_block.position_secondary.relative_end = (
          float(new_block.position_secondary.absolute_end -
          secondary_axis_start) / float(secondary_axis_stop -
          secondary_axis_start))
      new_block.position_secondary.relative_range = (
          new_block.position_secondary.relative_end -
          new_block.position_secondary.relative_begin)
      new_block.position_main.relative_begin = (
          float(new_block.position_main.absolute_begin - main_axis_start) /
          float(main_axis_stop - main_axis_start))
      new_block.position_main.relative_end = (
          float(new_block.position_main.absolute_end - main_axis_start) /
          float(main_axis_stop - main_axis_start))
      new_block.position_main.relative_range = (
          new_block.position_main.relative_end -
          new_block.position_main.relative_begin)
2350

2351
      try:
2352
        self.block_list.append(new_block)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
2353
      except AttributeError:
2354 2355 2356 2357
        # in case this is the first add 
        # need to initialize the list
        self.block_list = []
        self.block_list.append(new_block)
Thomas Bernard's avatar
Thomas Bernard committed
2358

2359 2360 2361 2362 2363 2364
      try:
        planning.content.append(new_block)
      except AttributeError:
        planning.content = []
        planning.content.append(new_block)

Thomas Bernard's avatar
Thomas Bernard committed
2365 2366
    return 1

2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
  def splitActivity(self):
    """
    Used for splitting an activity in multiple bloc.
    [EDIT] will not be used to split Calendar axis (by date time depending on
           the axis size), but will certainly be used afterwards in all cases
           to split activity in multiple blocs according to some external
           constraints (do not work sat & sun, or for a dayly planning do not
           work from 18P.M to 9A.M).
           will use an external script to do so.
    """
    # XXX not implemented yet
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
    return [(self.secondary_axis_start,self.secondary_axis_stop,1)]

    returned_list = []


    start_date = self.secondary_axis_start
    stop_date = self.secondary_axis_stop

    temp_start = start_date
    temp_stop  = temp_start

    # defining usefull list of data
    break_list = ['Saturday','Sunday']
    worked_list = ['Monday','Tuesday','Wednesday','Thursday','Friday']

    if temp_start.Day() in break_list:
      # temp_start is in weekend,
      # getting first worked day
      while temp_start.Day() in break_list and temp_start < stop_date:
        temp_start += 1
      returned_list.append([temp_stop,temp_start,0])
    else:
      # temp_stop is in week, getting first weekend
      while temp_stop.Day() in worked_list and temp_stop < stop_date:
        temp_stop += 1
      if temp_stop > stop_date:
        temp_stop = stop_date

    # testing if current activity is not too small to create blocks
    while temp_start < stop_date:
      returned_list.append([temp_start,temp_stop,1])

      temp_start = temp_stop
      # going to next start_date
      while temp_start.Day() in break_list and temp_start < stop_date:
        temp_start += 1

      # adding new start date to list
      if temp_start >= stop_date:
        returned_list.append([temp_stop,stop_date,0])
      elif temp_start != temp_stop:
        returned_list.append([temp_stop,temp_start,0])
      # next temp_start has been found
      # now processing new temp_stop
      temp_stop = temp_start
      while temp_stop.Day() in worked_list and temp_stop < stop_date:
        temp_stop += 1
      if temp_stop > stop_date:
        temp_stop = stop_date

    # return new list
    return returned_list


2432 2433 2434 2435

class Bloc:
  """
  structure that will be rendered as a bloc, a task element.
Thomas Bernard's avatar
Thomas Bernard committed
2436 2437 2438 2439
  Blocs are referenced in the Activity they belong to (logical structure), but
  are also referenced in their relative AxisElement (to be able to calculate
  the number of lines required for rendering when having multi-tasking in
  parallel).
2440 2441 2442 2443 2444
  Contains Bloc Structure for position informations.
  """

  def __init__ (self, name=None, types=None,
                color=None, info=None, link=None, number=0,
2445 2446
                constraints=None, secondary_start=None, secondary_stop=None,
                render_format='YX', parent_activity = None, warning=0, error=0,
2447
                error_text='', zone=1, property_dict ={} ):
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
    """
    creates a Bloc object
    """
    self.name = name # internal name
    self.types = types # activity, activity_error, info
    self.color = color
    self.info = info # dict containing text with their position
    self.link = link # on clic link
    self.number = number
    self.title=''
Thomas Bernard's avatar
Thomas Bernard committed
2458
    self.zone = zone # 1 = usefull area : 0 = useless one
2459 2460
    self.parent_activity = parent_activity
    self.constraints = constraints
Thomas Bernard's avatar
Thomas Bernard committed
2461 2462 2463 2464
    # setting warning and error flags in case parent_activity or block itself
    # have not been validated
    self.warning = warning
    self.error = error
2465
    self.error_text = error_text
2466 2467 2468 2469 2470
    # list of all the groups the bloc belongs to (reportTree)
    #self.container_axis_group = container_AxisGroup
    # integer pointing to the AxisElement containing the bloc (multitasking)
    #self.container_axis_element = container_AxisElement
    self.position_main = Position()
Thomas Bernard's avatar
Thomas Bernard committed
2471 2472
    self.position_secondary = \
          Position(absolute_begin=secondary_start,absolute_end=secondary_stop)
2473 2474 2475 2476 2477 2478 2479
    if render_format == 'YX':
      self.position_y = self.position_main
      self.position_x = self.position_secondary
    else:
      self.position_y = self.position_secondary
      self.position_x = self.position_main
    self.render_dict = None
2480
    self.property_dict = property_dict # dict containing internal properties
2481

2482 2483
  def buildInfoDict (self, info_dict=[]):
    """
Thomas Bernard's avatar
Thomas Bernard committed
2484 2485
    create Info objects to display text & images, then link them to the
    current object
2486
    """
2487

2488
    # updating title
2489 2490 2491 2492 2493 2494
    if self.property_dict['stat'] == 1:
      self.title = str(self.parent_activity.height)
      self.info = None
    else:
      self.info = {}
      title_list = []
Thomas Bernard's avatar
Thomas Bernard committed
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
      title_list.append(
                 self.buildInfo(info_dict=info_dict, area='info_topleft'))
      title_list.append(
                 self.buildInfo(info_dict=info_dict, area='info_topright'))
      title_list.append(
                 self.buildInfo(info_dict=info_dict, area='info_center'))
      title_list.append(
                 self.buildInfo(info_dict=info_dict, area='info_botleft'))
      title_list.append(
                 self.buildInfo(info_dict=info_dict, area='info_botright'))
2505 2506 2507
      self.title = " | ".join(title_list)


2508 2509 2510 2511
    if self.error != 0:
      # field has error
      # adding text_error
      self.info['info_error'] = Info(info=self.error_text, link='')
2512 2513 2514 2515 2516 2517 2518 2519 2520

  def buildInfo(self,info_dict=[],area=None):
    if area in info_dict:
      # creating new object
      info = Info(info = info_dict[area], link = self.link)
      # saving new object to block dict
      self.info[area] = info
      # recovering text information
      return info_dict[area]
Sebastien Robin's avatar
Sebastien Robin committed
2521
    else:
2522
      return ''
Sebastien Robin's avatar
Sebastien Robin committed
2523

2524 2525 2526 2527 2528 2529 2530
class Position:
  """
  gives a bloc [/or an area] informations about it's position on the X or Y
  axis. can specify position in every kind of axis : continuous or listed
  with lower and upper bound.
  """

Thomas Bernard's avatar
Thomas Bernard committed
2531 2532 2533
  def __init__ (self, absolute_begin=None, absolute_end=None,
                absolute_range=None, relative_begin=None, relative_end=None,
                relative_range=None):
2534 2535 2536
    # absolute size takes the bloc size in the original unit for the axis
    self.absolute_begin = absolute_begin
    self.absolute_end = absolute_end
Thomas Bernard's avatar
Thomas Bernard committed
2537
    self.absolute_range = absolute_range
2538 2539 2540
    # selative size in % of the current axis size
    self.relative_begin = relative_begin
    self.relative_end = relative_end
Thomas Bernard's avatar
Thomas Bernard committed
2541
    self.relative_range = relative_range
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552


class Axis:
  """
  Structure holding informations about a specified axis.Can be X or Y axis.
  Is aimed to handle axis with any kind of unit : continuous or listed (
  including possibly a listed ReportTree).
  Two of them are needed in a PlanningStructure to have X and Y axis.
  In case of listed axis, holds AxisGroup Structure.
  """

Thomas Bernard's avatar
Thomas Bernard committed
2553 2554
  def __init__(self, title=None, unit=None, types=None, axis_order=None,
               name=None, axis_group=None):
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
    self.title = title # axis title
    self.unit = unit # unit kind (time, nb... person, task, etc.)
    self.types = types # continuous / listed (incl. ReportTree)
    self.name = name
    self.size = 0 # value
    # axis group is a single group that contain the axis structure.
    # defined to be able to use a generic and recursive method to 
    self.axis_group = axis_group
    # specify if axis is primary or secondary.
    # - if primary axis in Planning, zoom selection is applied thanks to 
    # a cut over the basic structure objects (based on their position and
    # their length).
    # - if secondary axis in Planning, then need to apply the second zoom
    # bounds (application will be based on two bounds : start & stop)
    self.axis_order = axis_order
    # dict containing all class properties with their values
    self.render_dict=None


class AxisGroup:
  """
  Class representing an item, that can have the following properties :
  - one or several rendered lines (multiTasking) : contains AxisElement
  structure to hold this.
  - one or several sub groups (ReportTree) : contains AxisGroup structure
  to hold sub groups elements.
  """

2583 2584
  def __init__ (self, name='', title='', object = None,
                axis_group_list=None, axis_group_number=0,
Thomas Bernard's avatar
Thomas Bernard committed
2585 2586 2587 2588 2589
                axis_element_list=None, axis_element_number=0,
                delimiter_type=0, is_open=0, is_pure_summary=1,depth=0,
                url=None, axis_element_already_insered= 0,
                secondary_axis_start=None, secondary_axis_stop=None,
                property_dict={}):
2590 2591
    self.name = name
    self.title = title
Thomas Bernard's avatar
Thomas Bernard committed
2592
    self.link = None # link to fold or unfold report in report-tree mode
2593
    self.info_title = Info(info=self.title, link=self.link, title=self.title)
Thomas Bernard's avatar
Thomas Bernard committed
2594
    self.tooltip = '' # tooltip used when cursor pass over the group
Thomas Bernard's avatar
Thomas Bernard committed
2595
    self.object = object # ZODB object used to validate modifications
2596 2597 2598 2599
    self.axis_group_list = axis_group_list # ReportTree
    self.axis_group_number = axis_group_number
    self.axis_element_list = axis_element_list # Multitasking
    self.axis_element_number = axis_element_number
2600 2601
    self.axis_element_start = None
    self.axis_element_stop = None
Thomas Bernard's avatar
Thomas Bernard committed
2602 2603 2604
    self.delimiter_type = delimiter_type
       # define the kind of separator used in graphic rendering
       # 0 for standard, 1 for bold, 2 for 2x bold
2605 2606 2607 2608 2609
    # dict containing all class properties with their values
    self.render_dict=None
    self.is_open = is_open
    self.is_pure_summary = is_pure_summary
    self.depth = depth
Thomas Bernard's avatar
Thomas Bernard committed
2610
    self.url = url # url to the object
2611

2612 2613 2614 2615 2616 2617 2618 2619
    self.position_main = Position()
    self.position_secondary = Position()
    self.position_x = None
    self.position_y = None
    # UPDATE secondary axis_bounds are now linked to each axis_group to support
    # calendar output( were each axis_group has its own start and stop)
    self.secondary_axis_start = secondary_axis_start
    self.secondary_axis_stop = secondary_axis_stop
2620
    self.property_dict = property_dict
2621 2622


2623 2624 2625 2626 2627
  security = ClassSecurityInfo()
  security.declarePublic('setTitle')
  def setTitle(self,new_title = None):
    self.title = new_title

2628 2629 2630 2631 2632
  def fixProperties(self, form_id=None, selection_name=None):
    """
    using actual AxisGroup properties to define some special comportement that
    the axisGroup should have, especially in case of report-tree
    """
2633

2634 2635
    if self.is_open:
      # current report is unfold, action 'fold'
Thomas Bernard's avatar
Thomas Bernard committed
2636 2637 2638
      self.info_title.link = 'portal_selections/foldReport?report_url=' + \
                              '%s&form_id=%s&list_selection_name=%s' %(
                              self.url, form_id, selection_name)
2639
      self.info_title.info = '[-] ' + self.info_title.info
Sebastien Robin's avatar
Sebastien Robin committed
2640
    else:
2641
      # current report is fold, action 'unfold'
Thomas Bernard's avatar
Thomas Bernard committed
2642 2643 2644
      self.info_title.link = 'portal_selections/unfoldReport?report_url=' + \
                             '%s&form_id=%s&list_selection_name=%s' %(
                              self.url, form_id, selection_name)
2645 2646 2647 2648 2649
      self.info_title.info = '[+] ' + self.info_title.info

    #for i in range(self.depth):
    #  self.title = '| ' + self.title
    self.info_title.title = self.info_title.info
2650

2651
    self.tooltip = self.info_title.info
2652

Sebastien Robin's avatar
Sebastien Robin committed
2653

2654 2655
  def addActivity(self, activity=None, axis_element_already_insered= 0):
    """
2656 2657 2658
    procedure that permits to add activity to the corresponding AxisElement in
    an AxisGroup. can create new Axis Element in the actual Axisgroup if
    necessary. Permits representation of MULTITASKING
2659 2660 2661 2662 2663 2664 2665
    """

    # declaring variable used to check if activity has already been added
    added = 0
    try:
      # iterating each axis_element of the axis_group
      for axis_element in self.axis_element_list:
2666

2667 2668 2669 2670
        can_add = 1
        # recovering all activity properties of the actual axis_element and
        # iterating through them to check if one of them crosses the new one
        for activity_statement in axis_element.activity_list:
2671

Thomas Bernard's avatar
Thomas Bernard committed
2672 2673
          if activity_statement.isValidPosition(activity.secondary_axis_begin,
                                             activity.secondary_axis_end) != 0:
2674 2675
            # isValidPosition returned 1 or 2, this means the activity already
            # present does prevent from adding the new activity as there is
2676
            # coverage on the current axis_element.
2677 2678 2679
            # stop iterating actual axis_element and try with the next one
            can_add = 0
            break
2680

2681 2682 2683 2684 2685 2686
        if can_add:
          # the whole activity_statements in actual axis have been succesfully
          # tested without problem.
          # can add new activity to the actual axis_element
          added = 1
          axis_element.activity_list.append(activity)
2687

2688 2689
          # updating activity properties
          activity.parent_axis_element = axis_element
2690

Thomas Bernard's avatar
Thomas Bernard committed
2691 2692
          # no need to check the next axis_elements to know if they can hold
          # the new activity as it is already added to an axis_element
2693
          break
2694

2695
      if not added:
Thomas Bernard's avatar
Thomas Bernard committed
2696 2697
        # all axis_elements of the current group have been tested and no one
        # can contain the new activity.
2698 2699
        self.axis_element_number += 1
        # Need to create a new axis_element to hold the new activity
Thomas Bernard's avatar
Thomas Bernard committed
2700 2701 2702 2703 2704 2705
        new_axis_element=AxisElement(name='Group_%s_AxisElement_%s'%
                                          (str(self.axis_group_number),
                                           str(self.axis_element_number)),
                                     relative_number=self.axis_element_number,
                                     absolute_number=self.axis_element_number+
                                              axis_element_already_insered)
2706

2707 2708 2709
        # add new activity to this brand new axis_element
        new_axis_element.activity_list = []
        new_axis_element.activity_list.append(activity)
2710

2711 2712
        # updating activity properties
        activity.parent_axis_element = new_axis_element
2713

2714 2715 2716
        # register the axis_element to the actual group.
        self.axis_element_list.append(new_axis_element)
    except TypeError:
2717
      # in case axis_element_list is Empty (first activity to the group)
2718 2719
      # Need to create a new axis_element to hold the new activity
      self.axis_element_number += 1
Thomas Bernard's avatar
Thomas Bernard committed
2720 2721 2722 2723 2724 2725 2726 2727
      new_axis_element = AxisElement(name='Group_%s_AxisElement_1' %
                                           str(self.axis_group_number),
                                     relative_number=\
                                           self.axis_element_number,
                                     absolute_number =\
                                           axis_element_already_insered +
                                           self.axis_element_number,
                                     parent_axis_group=self)
Sebastien Robin's avatar
Sebastien Robin committed
2728

2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740
      # add new activity to this brand new axis_element
      new_axis_element.activity_list = []
      new_axis_element.activity_list.append(activity)

      # updating activity properties
      activity.parent_axis_element = new_axis_element

      # register the axis_element to the actual group.
      self.axis_element_list = []
      self.axis_element_list.append(new_axis_element)


Thomas Bernard's avatar
Thomas Bernard committed
2741 2742 2743
  def addStatActivities(self, basic_activity_list=None, axis_group_number=0,
                        axis_element_already_present= 0, render_format=None,
                        primary_axis_block=None, property_dict={}):
2744 2745 2746 2747 2748 2749
    """
    Permits to add stat block to the current AxisGroup. In this way use the
    single AxisElement present to fit the blocks
    """
    # first adding axis_element to the current group
    self.axis_element_number += 1
Thomas Bernard's avatar
Thomas Bernard committed
2750 2751 2752 2753 2754 2755
    new_axis_element=AxisElement(name='Group_%s_AxisElement_1' %
                                       str(self.axis_group_number),
                                 relative_number=self.axis_element_number,
                                 absolute_number=axis_element_already_present+
                                                 self.axis_element_number,
                                 parent_axis_group=self)
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
    new_axis_element.activity_list = []

    self.axis_element_list = []
    self.axis_element_list.append(new_axis_element)

    activity_number = 0
    # add all activities to the same axis_element
    for basic_activity_object in basic_activity_list:

      # defining Activity from basic_activity_object
Thomas Bernard's avatar
Thomas Bernard committed
2766 2767 2768
      activity = Activity(name= 'Group_%s_Activity_%s' 
                               %(str(axis_group_number),
                                 str(activity_number)),
2769 2770 2771 2772
                          title=basic_activity_object.title,
                          object=basic_activity_object.object,
                          color=basic_activity_object.color,
                          link=basic_activity_object.url,
Thomas Bernard's avatar
Thomas Bernard committed
2773 2774 2775 2776 2777 2778 2779 2780
                          secondary_axis_begin=\
                                 basic_activity_object.absolute_begin,
                          secondary_axis_end=\
                                 basic_activity_object.absolute_end,
                          secondary_axis_start=\
                                 basic_activity_object.absolute_start,
                          secondary_axis_stop=\
                                 basic_activity_object.absolute_stop,
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
                          height=basic_activity_object.height,
                          primary_axis_block=primary_axis_block,
                          info=basic_activity_object.info_dict,
                          render_format=render_format,
                          property_dict = property_dict)
      activity.parent_axis_element = new_axis_element

      # append activity to current axis_element
      new_axis_element.activity_list.append(activity)

      activity_number +=1


  def updateStatBlocks(self):
    """
    called once the blocks have been defined on all activities
    if the current group is  stat group, then this method is called
    process :
      - find the largest element to display
      - update size of all other elements
    """
    # usually should get only 1 axis_element : all stats are displayed on the
    # same line.
    max_activity_height = 0
    for activity in self.axis_element_list[0].activity_list:
      if activity.height > max_activity_height:
        max_activity_height = activity.height

    # now max height is known, just need to adapt size of all the blocks
    # composing the activities
    for activity in self.axis_element_list[0].activity_list:
      if activity.height in (0,None):
        relative_size = 1
      else:
        relative_size = float(activity.height) / max_activity_height
      for block in activity.block_list:
        # recovering original values
        block_range = block.position_main.relative_range
        block_begin = block.position_main.relative_begin
        block_end   = block.position_main.relative_end
        # calculating values
        final_range = relative_size * block_range
        final_loss = block_range - final_range
        final_begin = block_begin + final_loss
        # saving new values
        block.position_main.relative_begin = final_begin
        block.position_main.relative_range = final_range
Thomas Bernard's avatar
Thomas Bernard committed
2828
    return 1
2829 2830


2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
class AxisElement:
  """
  Represents a line in an item. In most cases, an AxisGroup element will
  hold ony one AxisElement (simple listed axis), but sometimes more
  AxisElements are required (multi, simultaneous tasking).
  AxisElement is linked with the blocs displayed in it : this is only
  usefull when doing multitasking to check if a new bloc can be added to an
  existing AxisElement or if it is needed to create a new AxisElement in
  the AxisGroup to hold it.
  """
Thomas Bernard's avatar
Thomas Bernard committed
2841 2842
  def __init__ (self,name='', relative_number=0, absolute_number=0,
                activity_list=None, parent_axis_group = None):
2843
    self.name = name
Thomas Bernard's avatar
Thomas Bernard committed
2844
    self.relative_number = relative_number # relative number / AxisGroup
2845 2846 2847 2848 2849 2850 2851 2852 2853
    self.absolute_number = absolute_number # id in the current rendering
    self.activity_list = activity_list
    # dict containing all class properties with their values
    self.render_dict=None
    self.parent_axis_group = parent_axis_group


class Info:
  """
Thomas Bernard's avatar
Thomas Bernard committed
2854 2855
  Class holding all informations to display an info text div inside of a block
  or AxisGroup or whatever
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871
  """
  security = ClassSecurityInfo()
  def __init__(self, info=None, link=None, title=None):
    self.info = info
    self.link = link
    self.title = title

  security.declarePublic('edit')
  def edit(self, info=None):
     """
     special method allowing to update Info content from an external script
     """
     self.info = info

# declaring validator instance
PlanningBoxValidatorInstance = PlanningBoxValidator()
Sebastien Robin's avatar
Sebastien Robin committed
2872

Sebastien Robin's avatar
Sebastien Robin committed
2873 2874 2875 2876 2877 2878 2879 2880
class PlanningBox(ZMIField):
    meta_type = "PlanningBox"
    widget = PlanningBoxWidgetInstance
    validator = PlanningBoxValidatorInstance
    security = ClassSecurityInfo()
    security.declareProtected('Access contents information', 'get_value')
    def get_value(self, id, **kw):
      if id == 'default' and kw.get('render_format') in ('list', ):
Sebastien Robin's avatar
Sebastien Robin committed
2881
        return self.widget.render(self, self.generate_field_key() , None , 
2882 2883
                                  kw.get('REQUEST'),
                                  render_format=kw.get('render_format'))
Sebastien Robin's avatar
Sebastien Robin committed
2884 2885 2886
      else:
        return ZMIField.get_value(self, id, **kw)

2887
    def render_css(self, value=None, REQUEST=None):
Sebastien Robin's avatar
Sebastien Robin committed
2888
      return self.widget.render_css(self,'',value,REQUEST)
2889 2890


Thomas Bernard's avatar
Thomas Bernard committed
2891 2892
InitializeClass(PlanningBoxWidget)
allow_class(PlanningBoxWidget)
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914
InitializeClass(BasicStructure)
allow_class(BasicStructure)
InitializeClass(BasicGroup)
allow_class(BasicGroup)
InitializeClass(BasicActivity)
allow_class(BasicActivity)
InitializeClass(PlanningStructure)
allow_class(PlanningStructure)
InitializeClass(Activity)
allow_class(Activity)
InitializeClass(Bloc)
allow_class(Bloc)
InitializeClass(Position)
allow_class(Position)
InitializeClass(Axis)
allow_class(Axis)
InitializeClass(AxisGroup)
allow_class(AxisGroup)
InitializeClass(AxisElement)
allow_class(AxisElement)
InitializeClass(Info)
allow_class(Info)