PlanningBox.py 133 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 32 33 34 35 36 37 38 39

    # XXX need to decide how Constraints between task should be defined on
    # planning.
    # ideally, an external method should be called for validating all
    # constraints within the planning. (such a method sould be called from
    # anywhere in the Project module : listbox, editing form).
    # this method should return a list of all the objects' urls that does not
    # fit the constraints.


Sebastien Robin's avatar
Sebastien Robin committed
40
import string, types, sys
41

42
# Class monitoring access security control
43 44 45 46
from Products.PythonScripts.Utility import allow_class
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass

Sebastien Robin's avatar
Sebastien Robin committed
47 48 49 50 51 52 53
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
54
from SelectionTool import makeTreeList,TreeListLine
55
from Selection import Selection
Sebastien Robin's avatar
Sebastien Robin committed
56 57 58 59 60 61 62
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
63
from Products.ERP5Type.Utils import getPath
Thomas Bernard's avatar
Thomas Bernard committed
64 65
from Products.ERP5Type.Message import Message

66 67 68
class PlanningBoxError(Exception):
  pass

Sebastien Robin's avatar
Sebastien Robin committed
69
class PlanningBoxValidator(Validator.StringBaseValidator):
70 71
  """
  Class holding all methods used to validate a modified PlanningBox
Thomas Bernard's avatar
Thomas Bernard committed
72
  can be called only from an HTML rendering using wz_dragdrop script
73
  """
Romain Courteaud's avatar
Romain Courteaud committed
74
  def validate(self, field, key, REQUEST):
75 76
    """
    main method to solve validation
77 78 79 80 81 82 83 84 85 86 87 88
    - rebuild the whole planning structure but do not display it.
      this is needed to be able to get the block positions
    - apply block movements recovered from the java script
    - for each block moved, check the modification (over he primary axis in
      case task association has changed, and also over the secondary axis to
      check block movement / resizement).
      Beware : This checking part does not include constraint checking.
    - build a list with the validated blocks and also with the error blocks
      (if any).
    - return a dict of values to update objects in case no errors have been
      found. Otherwise save in the REQUEST the list of error blocks so that
      they can be displayed in a special way.
89
    """
90 91
    # init params
    value = None
92
    context = getContext(field, REQUEST)
93 94

    # recover usefull properties
Romain Courteaud's avatar
Romain Courteaud committed
95
    # XXX Incompatible with multiple planning box in the same form
Thomas Bernard's avatar
Thomas Bernard committed
96 97
    block_moved_string = REQUEST.get('block_moved','')
    block_previous_string = REQUEST.get('previous_block_moved','')
98 99 100 101 102

    ##################################################
    ############## REBUILD STRUCTURE #################
    ##################################################
    # build structure
103
    basic, planning = PlanningBoxWidgetInstance.render_structure(field=field,
104
                          REQUEST= REQUEST,
105
                          context=context)
106 107

    # getting coordinates script generator
108
    planning_coordinates_method = getattr(context, 'planning_coordinates')
109
    # calling script to generate coordinates
110 111
    planning_coordinates = planning_coordinates_method(basic=basic,
                                                       planning=planning)
112 113

    ##################################################
Thomas Bernard's avatar
Thomas Bernard committed
114
    ########## RECOVERING BLOCK MOVED DICTS ##########
115 116
    ##################################################
    #  converting string to a structure
Thomas Bernard's avatar
Thomas Bernard committed
117 118 119
    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
120 121
    block_previous_list =\
                       self.getBlockPositionFromString(block_previous_string)
Thomas Bernard's avatar
Thomas Bernard committed
122 123 124
    # list of previous blocks moved if an error occured during previous
    # validation

Thomas Bernard's avatar
Thomas Bernard committed
125 126 127
    # 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
128 129
    if block_previous_list != [] and block_moved_list != []:
      for block_previous in block_previous_list:
Thomas Bernard's avatar
Thomas Bernard committed
130
        # checking if the block has been moved again in this validation attempt
Thomas Bernard's avatar
Thomas Bernard committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
        # 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
146 147
          # block has not been moved again, adding old block informations to
          # the current list of block_moved
Thomas Bernard's avatar
Thomas Bernard committed
148 149 150 151 152 153 154 155 156
          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
157
    else:
Thomas Bernard's avatar
Thomas Bernard committed
158 159 160
      # the two lists are empty : nothing to validate
      return None
    # block_moved_list is updated
161 162 163

    # dict aimed to hold all informations about block
    final_block_dict = {}
Thomas Bernard's avatar
Thomas Bernard committed
164 165
    # dict holding all the activities that will need an update because at least
    # one of the blocks concerned is moved
166
    activity_dict = {}
Thomas Bernard's avatar
Thomas Bernard committed
167 168 169 170
    # 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 = []
171
    error_info_dict = {}
Thomas Bernard's avatar
Thomas Bernard committed
172

173 174 175 176 177 178 179 180 181
    ##################################################
    ########## 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
182
      final_block['block_object'] = self.getBlockObject(block_moved['name'], \
183
                                                        planning.content)
184
      # recovering original activity object
Thomas Bernard's avatar
Thomas Bernard committed
185 186
      final_block['activity_origin'] = \
           final_block['block_object'].parent_activity
187
      # recovering original axis_group object
Thomas Bernard's avatar
Thomas Bernard committed
188 189
      final_block['group_origin'] = \
           final_block['activity_origin'].parent_axis_element.parent_axis_group
190
      # recovering relative block information in planning_coordinates
Thomas Bernard's avatar
Thomas Bernard committed
191 192
      final_block['block_info'] = \
           planning_coordinates['content'][block_moved['name']]
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

      # 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)
209
      if planning.calendar_view == 0:
Romain Courteaud's avatar
Romain Courteaud committed
210 211
        block_moved['main_axis_position'] = block_moved['top']
        block_moved['main_axis_length'] = block_moved['height']
212
        block_moved['secondary_axis_position'] = block_moved['left']
Romain Courteaud's avatar
Romain Courteaud committed
213
        block_moved['secondary_axis_length'] = block_moved['width']
214 215 216 217 218 219
        # 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:
Romain Courteaud's avatar
Romain Courteaud committed
220 221
        block_moved['main_axis_position'] = block_moved['left']
        block_moved['main_axis_length'] = block_moved['width']
222
        block_moved['secondary_axis_position'] = block_moved['top']
Romain Courteaud's avatar
Romain Courteaud committed
223
        block_moved['secondary_axis_length'] = block_moved['height']
224 225 226 227 228
        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
229 230
      block_moved['center'] = (block_moved['main_axis_length'] / 2) + \
                               block_moved['main_axis_position']
231

Thomas Bernard's avatar
Thomas Bernard committed
232 233 234
      # 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
235
      group_destination = self.getDestinationGroup(basic, planning,
Thomas Bernard's avatar
Thomas Bernard committed
236 237
               block_moved,planning_coordinates['main_axis'],
               group_position, group_length)
238

Romain Courteaud's avatar
Romain Courteaud committed
239
      if group_destination is None:
Thomas Bernard's avatar
Thomas Bernard committed
240 241 242 243 244
        # !! 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'])
245
        error_info_dict[block_moved['name']] = 'out of bounds on main axis'
Thomas Bernard's avatar
Thomas Bernard committed
246 247 248 249
        # 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)

250 251 252
      else:
        # now that all informations about the main axis changes are
        # known, checking modifications over the secondary axis.
253
        secondary_axis_positions = self.getDestinationBounds(basic, planning,
254 255 256 257 258 259 260 261 262 263 264 265
                block_moved, final_block['block_object'],
                planning_coordinates, axis_length,
                destination_group = group_destination)
        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'])
            error_info_dict[block_moved['name']] = 'out of bounds on sec axis'
            if final_block['activity_origin'].name not in warning_activity_list:
              warning_activity_list.append(final_block['activity_origin'].name)
Thomas Bernard's avatar
Thomas Bernard committed
266 267


268 269 270 271 272 273 274 275 276 277 278 279
      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]

280 281 282

    ##################################################
    # getting object_dict to update object properties once activities are up to
283
    # date. Activities values will be updated directly on the
284
    object_dict = self.getObjectDict(basic=basic, planning=planning)
285

286 287 288
    ##################################################
    ############# UPDATING ACTIVITIES ################
    ##################################################
289 290 291 292 293 294
    # if activity is composed of several blocks, then check if it is needed to
    # update activity itself depending on blocks moved. Beware this part only
    # deals with activities (i.e task object) : an object can be represented by
    # several activities (in case of calendar mode for example).
    # build a dict
    update_list = []
Thomas Bernard's avatar
Thomas Bernard committed
295 296
    errors_list = []
    # getting start & stop property names
297 298
    start_property = field.get_value('x_start_bloc')
    stop_property = field.get_value('x_stop_bloc')
Thomas Bernard's avatar
Thomas Bernard committed
299
    # getting round_script if exists
300
    round_script=getattr(context, field.get_value('round_script'), None)
301 302 303 304 305 306 307 308
    # 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
309
      if activity_object.name in warning_activity_list:
310
        # activity contains a block that has not been validated
Thomas Bernard's avatar
Thomas Bernard committed
311 312 313 314 315 316 317
        # 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
318 319 320 321
        (start_value, stop_value) = \
             self.getActivityBounds(activity_object, activity_block_moved_list,
                                    activity_block_list)
        # call specific external method to round value
Romain Courteaud's avatar
Romain Courteaud committed
322
        if round_script is not None:
Thomas Bernard's avatar
Thomas Bernard committed
323 324
          start_value = round_script(start_value)
          stop_value = round_script(stop_value)
325
        # adding object name to list of objects to update
Romain Courteaud's avatar
Romain Courteaud committed
326
        if activity_object.object.getUrl() not in update_list:
327
          update_list.append(activity_object.object.getUrl())
Thomas Bernard's avatar
Thomas Bernard committed
328
        # saving updated informations in the final dict
Romain Courteaud's avatar
Romain Courteaud committed
329
        for activity_desc in object_dict[activity_object.object.getUrl()]:
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
          if activity_desc['activity_name'] == activity_object.name:
            activity_desc['axis_start'] = start_value
            activity_desc['axis_stop'] = stop_value

    ##################################################
    ############### UPDATING OBJECTS #################
    ##################################################
    # using result from updated activities to process update on objects.
    update_dict = {}
    # first building a dict with all informations for each object.
    # now processing activity updates
    for object_name in update_list:
      object_info = object_dict[object_name]
      axis_start = None
      axis_stop  = None
      for activity in object_info:
Romain Courteaud's avatar
Romain Courteaud committed
346 347
        activity_start_date = activity['axis_start']
        activity_stop_date = activity['axis_stop']
348 349 350 351
        if activity['activity_name'] == 'update':
          # case current activity is in fact 'fake' activity, just data telling
          # if can update min & max bounds according to global decision toward
          # objects.
Romain Courteaud's avatar
Romain Courteaud committed
352 353
          can_update_start = activity_start_date
          can_update_stop  = activity_stop_date
354
        else:
Romain Courteaud's avatar
Romain Courteaud committed
355 356 357 358 359
          if axis_start > activity_start_date or axis_start is None:
            axis_start = activity_start_date
          if axis_stop  < activity_stop_date  or axis_stop  is None:
            axis_stop = activity_stop_date

360
      update_dict[object_name] = {}
Romain Courteaud's avatar
Romain Courteaud committed
361
      if can_update_start and axis_start is not None:
362
        update_dict[object_name][start_property] = axis_start
Romain Courteaud's avatar
Romain Courteaud committed
363
      if can_update_stop  and axis_stop  is not None:
364
        update_dict[object_name][stop_property]  = axis_stop
Thomas Bernard's avatar
Thomas Bernard committed
365 366 367 368 369 370 371 372 373 374 375 376 377

    # 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)
378 379 380
      REQUEST.set('error_info_dict',error_info_dict)
      # now raise error => automatically called
      # parameters are :
381
      # - list of errors
382
      # - dict with error results
Romain Courteaud's avatar
Romain Courteaud committed
383
      raise FormValidationError(errors_list, {})
Thomas Bernard's avatar
Thomas Bernard committed
384

Romain Courteaud's avatar
Romain Courteaud committed
385 386 387
    # the whole process is now finished, 
    # just need to return editor for updating data
    return PlanningBoxEditor(field.id, update_dict)
388

Thomas Bernard's avatar
Thomas Bernard committed
389 390
  def getBlockPositionFromString(self, block_string):
    """
391
    Takes a string with block data and convert it to a list of dicts
Thomas Bernard's avatar
Thomas Bernard committed
392 393 394 395 396 397
    """
    block_list = []
    if block_string != '':
      block_object_list = block_string.split('*')
      for block_object_string in block_object_list:
        block_sub_list = block_object_string.split(',')
Romain Courteaud's avatar
Romain Courteaud committed
398 399 400 401 402 403 404 405 406
        block_dict = {
          'name': block_sub_list[0],
          'old_X': float(block_sub_list[1]),
          'old_Y': float(block_sub_list[2]),
          'new_X': float(block_sub_list[3]),
          'new_Y': float(block_sub_list[4]),
          'width': float(block_sub_list[5]),
          'height': float(block_sub_list[6]),
        }
Thomas Bernard's avatar
Thomas Bernard committed
407
        block_list.append(block_dict)
Romain Courteaud's avatar
Romain Courteaud committed
408
    return block_list
Thomas Bernard's avatar
Thomas Bernard committed
409

Romain Courteaud's avatar
Romain Courteaud committed
410
  def setBlockPositionToString(self, block_list):
Thomas Bernard's avatar
Thomas Bernard committed
411
    """
Romain Courteaud's avatar
Romain Courteaud committed
412
    Takes a list of dicts updated and convert it to a string in order to save
Thomas Bernard's avatar
Thomas Bernard committed
413 414 415 416 417 418 419 420
    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
Romain Courteaud's avatar
Romain Courteaud committed
421 422
        block_sub_string = '%(name)s,%(old_X)s,%(old_Y)s,%(new_X)s,' \
                           '%(new_Y)s,%(width)s,%(height)s' % block_dict
Thomas Bernard's avatar
Thomas Bernard committed
423 424
        block_object_list.append(block_sub_string)
      block_string = '*'.join(block_object_list)
Romain Courteaud's avatar
Romain Courteaud committed
425
    return block_string
426 427 428 429 430 431 432

  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:
433
        return block 
434 435


436
  def getDestinationGroup(self, basic, planning, block_moved, axis_groups,
Thomas Bernard's avatar
Thomas Bernard committed
437
                                group_position, group_length):
438 439 440 441 442 443 444 445
    """
    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
446 447 448
      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']:
449 450 451 452
        # 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
453
    # if no group is found, this means the block is outside the bounds
454 455 456
    if good_group_name == '':
      return None
    # group name is known, searching corresponding group object
457
    for group in planning.main_axis.axis_group:
458 459 460 461 462
      if group.name == good_group_name:
        return group
    return None


463
  def getDestinationBounds(self, basic, planning, block_moved, block_object,
464 465
                                 planning_coordinates, axis_length,
                                 destination_group=None):
466 467 468 469
    """
    check the new bounds of the block over the secondary axis according to its
    new position
    """
Thomas Bernard's avatar
Thomas Bernard committed
470
    error = 0
471 472 473 474 475
    # 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.
476 477 478
    # => In case of calendar mode, axis_bounds are recovered from the
    #    destination group instead of the planning itself

Thomas Bernard's avatar
Thomas Bernard committed
479
    delta_start = block_moved['secondary_axis_position'] / \
480
                  planning_coordinates['frame']['planning_content'][axis_length]
Thomas Bernard's avatar
Thomas Bernard committed
481 482
    delta_stop  = (block_moved['secondary_axis_position'] + \
                  block_moved['secondary_axis_length']) / \
483
                  planning_coordinates['frame']['planning_content'][axis_length]
484 485 486 487

    # 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
488 489
      # can not validate it : returning None
      error = 1
490 491 492
    else:
      if delta_start < 0 or delta_stop > 1:
        # part of the block is inside
493 494
        # should handle support for correcting bounds : user should not be able
        # to define any data out of its group bounds.
495 496
        pass

497
    if basic.calendar_mode:
498 499 500 501 502 503
      axis_range = destination_group.secondary_axis_range
      new_start = destination_group.secondary_axis_start + \
                  delta_start * axis_range
      new_stop = destination_group.secondary_axis_start + \
                  delta_stop * axis_range
    else:
504 505
      axis_range = basic.secondary_axis_info['bound_stop'] - \
                   basic.secondary_axis_info['bound_start']
Thomas Bernard's avatar
Thomas Bernard committed
506

507
      # defining new final block bounds
508
      new_start = basic.secondary_axis_info['bound_start'] + \
509
                  delta_start * axis_range
510
      new_stop  = basic.secondary_axis_info['bound_start'] + \
511
                  delta_stop * axis_range
Thomas Bernard's avatar
Thomas Bernard committed
512 513

    return [new_start,new_stop, error]
514

Thomas Bernard's avatar
Thomas Bernard committed
515 516
  def getActivityBounds(self, activity, activity_block_moved_list,
                              activity_block_list):
517
    """
518 519 520 521
    Recompose Activity from moved blocks.
    Warning : in case of calendar view, object bounds are not recomposed : only
              bounds of each activity are calculated, not object bounds !

522 523 524 525 526 527
    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
528 529
    block_moved_name_list = [x['block_moved']['name'] for x in activity_block_moved_list]
    
530 531 532 533 534 535 536 537
    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
538 539
            temp_start = temp_block_moved['block_moved']['secondary_axis_start']
            temp_stop  = temp_block_moved['block_moved']['secondary_axis_stop']
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
            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
558
    # checking weither activity has been cut-off to fit the planning bounds
559 560 561 562
    #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
563 564 565

    return [new_start,new_stop]

566
  def getObjectDict(self, basic, planning):
567 568 569 570 571 572
    """
    Takes all activities related to a specified object and return
    """
    # init dict
    object_dict = {}
    # get property_names
573 574
    start_property = basic.field.get_value('x_start_bloc')
    stop_property = basic.field.get_value('x_stop_bloc')
575
    # get full axis length
576 577 578
    axis_start = basic.secondary_axis_info['bound_start']
    axis_stop  = basic.secondary_axis_info['bound_stop']
    for axis_group in planning.main_axis.axis_group:
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
      for axis_element in axis_group.axis_element_list:
        for activity in axis_element.activity_list:
          # for each activity, saving its properties into a dict
          if activity.link in object_dict.keys():
            object_dict[activity.link].append(
                       { 'activity_name' : activity.name,
                         'axis_start': activity.secondary_axis_start,
                         'axis_stop' : activity.secondary_axis_stop
                       })
          else:
            # need to add object start & stop properties
            object_start = activity.object.getProperty(start_property)
            object_stop = activity.object.getProperty(stop_property)
            # check if need to update start and stop.
            # according to general specifications, this can be done only if the
            # original object is not cut to fit view bounds :min and max bounds
            if object_start < axis_start:
              bound_start = 'no'
            else:
              bound_start = 'yes'
            if object_stop > axis_stop:
              bound_stop = 'no'
            else:
              bound_stop = 'yes'
            object_dict[activity.link] = \
                       [{ 'activity_name' : 'update',
                          'axis_start' : bound_start,
                          'axis_stop'  : bound_stop
                         }]
            # adding activity properties
            object_dict[activity.link].append(
                       { 'activity_name' : activity.name,
                         'axis_start': activity.secondary_axis_start,
                         'axis_stop' : activity.secondary_axis_stop
                       })
    return object_dict

Romain Courteaud's avatar
Romain Courteaud committed
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
class PlanningBoxEditor:
  """
  A class holding all values required to update objects
  """
  def __init__(self, field_id, update_dict):
    self.field_id = field_id
    self.update_dict = update_dict

  def view(self):
    return self.__dict__

  def __call__(self, REQUEST):
    # XXX Planning Box does not handle FormValidationError
    pass

  def edit(self, context):
    for url, kw in self.update_dict.items():
      context.restrictedTraverse(url).edit(**kw)

allow_class(PlanningBoxEditor)

637 638 639 640 641 642
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
  """
Romain Courteaud's avatar
Romain Courteaud committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
  property_names = Widget.Widget.property_names + \
    ['js_enabled',
     # kind of display : horizontal or vertical
     'calendar_view',
     # number of groups over the main axis
     'main_axis_groups',
     # width properties
     'size_border_width_left', 'size_planning_width', 'size_y_axis_space',
     'size_y_axis_width',
     # height properties
     'size_header_height', 'size_planning_height', 'size_x_axis_space',
     'size_x_axis_height',
     # axis position
     'y_axis_position', 'x_axis_position',
     'report_root_list', 'selection_name',
658
     # Main List Method
Romain Courteaud's avatar
Romain Courteaud committed
659 660
     'portal_types', 'sort',
     'list_method',
661 662
     # Second Layer Properties
     'second_layer_list_method',
Romain Courteaud's avatar
Romain Courteaud committed
663 664 665 666 667 668 669 670 671 672 673 674 675
     # 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
     'stat_method', 'split_method', 'color_script',
     'round_script', 'sec_axis_script',
     # number of delimitations over the secondary axis
     'delimiter',
     # specific methods for inserting info block
     'info_center', 'info_topleft', 'info_topright',
     'info_backleft', 'info_backright'
     ]
676 677 678

  # Planning properties (accessed through Zope Management Interface)

679 680 681
  # kind of representation to render :
  # Planning or Calendar
  js_enabled = fields.CheckBoxField('js_enabled',
682
      title='enable on the fly edition (based on java script)',
683 684 685
      description='define if javascript is enabled or not on the current Planning',
      default=1,
      required=1)
686 687 688

  # kind of representation to render :
  # Planning or Calendar
689 690 691
  calendar_view = fields.CheckBoxField('calendar_view',
      title='calendar view (vertical view)',
      description='define if need to changes axis order. By default Y axis is'
Romain Courteaud's avatar
Romain Courteaud committed
692
                  'main axis, but to display calendar main axis must be X one.',
693
      default=0,
694 695 696 697 698 699
      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',
700
      title='groups per page on main axis',
Romain Courteaud's avatar
Romain Courteaud committed
701
      description='number of groups displayed per page on main axis',
702 703 704 705 706
      default=10,
      required=1)

  # setting header height
  size_header_height = fields.IntegerField('size_header_height',
707
      title='header height',
Romain Courteaud's avatar
Romain Courteaud committed
708
      description='height of the planning header',
709 710 711 712 713 714
      default=100,
      required=1)

  # setting left border size
  size_border_width_left = fields.IntegerField('size_border_width_left',
      title='Size border width left',
Romain Courteaud's avatar
Romain Courteaud committed
715
      description='setting left border size',
716 717 718 719 720
      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',
721
      title='Planning width',
Romain Courteaud's avatar
Romain Courteaud committed
722
      description='size of the planning area, excluding axis size',
723 724 725 726 727
      default=1000,
      required=1)

  # setting the with of the Y axis
  size_y_axis_width = fields.IntegerField('size_y_axis_width',
728
      title='Y axis width',
Romain Courteaud's avatar
Romain Courteaud committed
729
      description='width of the Y axis',
730 731 732 733 734
      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',
735
      title='Y axis space',
Romain Courteaud's avatar
Romain Courteaud committed
736
      description='space between Y axis and PLanning content',
737 738 739 740 741
      default=10,
      required=1)

  # setting the height of the Planning (excl. X axis)
  size_planning_height = fields.IntegerField('size_planning_height',
742
      title='Planning height',
Romain Courteaud's avatar
Romain Courteaud committed
743
      description='size of the planning area, excluding axis_size',
744 745 746 747 748
      default=800,
      required=1)

  # setting the height of the X axis
  size_x_axis_height = fields.IntegerField('size_x_axis_height',
749
      title='X axis height',
Romain Courteaud's avatar
Romain Courteaud committed
750
      description='height of the X axis',
751 752 753 754 755
      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',
756
      title='X axis space',
Romain Courteaud's avatar
Romain Courteaud committed
757
      description='space between X axis and Planning content',
758 759 760 761
      default=10,
      required=1)


762 763
  y_axis_position = fields.CheckBoxField('y_axis_position',
      title='Force Y axis to the right intead of left',
Romain Courteaud's avatar
Romain Courteaud committed
764 765 766 767 768
      description='position of Y axis over the planning content.' \
                  'If checked, the Y axis will match the right border' \
                  'of the planning, otherwise default is applied : left',
      default=0,
      required=1)
769

770 771
  x_axis_position = fields.CheckBoxField('x_axis_position',
      title='Force X axis to the bottom instead of top',
Romain Courteaud's avatar
Romain Courteaud committed
772 773 774 775
      description='position of X axis over the planning content.' \
                  'default is top, if checked then right apply',
      default=0,
      required=1)
776 777


778 779
  default = fields.TextAreaField('default',
      title='Default',
Romain Courteaud's avatar
Romain Courteaud committed
780
      description="Default value of the text in the widget.",
781 782 783 784 785
      default="",
      width=20, height=3,
      required=0)


786
  delimiter = fields.IntegerField('delimiter',
787
      title='min number of delimiters over the secondary axis',
Romain Courteaud's avatar
Romain Courteaud committed
788 789
      description="min number of delimitations over the sec axis, required",
      default=5,
790
      required=1)
791 792 793

  report_root_list = fields.ListTextAreaField('report_root_list',
      title="Report Root",
Romain Courteaud's avatar
Romain Courteaud committed
794
      description="A list of domains which define the possible root.",
795 796 797 798 799 800
      default=[],
      required=0)

  selection_name = fields.StringField('selection_name',
      title='Selection Name',
      description=("The name of the selection to store selections params"),
801 802
      default='planning_0',
      required=1)
803 804 805

  portal_types = fields.ListTextAreaField('portal_types',
      title="Portal Types",
Romain Courteaud's avatar
Romain Courteaud committed
806
      description="Portal Types of objects to list. Required.",
807 808 809 810 811
      default=[],
      required=0)

  sort = fields.ListTextAreaField('sort',
      title='Default Sort',
Romain Courteaud's avatar
Romain Courteaud committed
812
      description="The default sort keys and order",
813 814 815 816 817
      default=[],
      required=0)

  list_method = fields.MethodField('list_method',
      title='List Method',
Romain Courteaud's avatar
Romain Courteaud committed
818
      description="Method to use to list objects",
Rafael Monnerat's avatar
Rafael Monnerat committed
819
      default='',
820 821
      required=0)

822 823 824 825 826 827 828
  second_layer_list_method = fields.MethodField('second_layer_list_method',
     title='Secondary Layer List Method',
     description="Method to use to list background objects",
     default='',
     required=0)


829
  title_line = fields.StringField('title_line',
Rafael Monnerat's avatar
Rafael Monnerat committed
830
      title="Specific method which fetches the title of each line",
Romain Courteaud's avatar
Romain Courteaud committed
831
      description="Method for inserting title in line",
832 833 834 835
      default='',
      required=0)

  x_start_bloc = fields.StringField('x_start_bloc',
Rafael Monnerat's avatar
Rafael Monnerat committed
836
      title='Specific property to get start of blocks (ex. start_date)',
Romain Courteaud's avatar
Romain Courteaud committed
837 838
      description='Property for building X-Axis such as start_date ' \
                  'objects',
Thomas Bernard's avatar
Thomas Bernard committed
839
      default='start_date',
840 841 842
      required=0)

  x_stop_bloc = fields.StringField('x_stop_bloc',
Rafael Monnerat's avatar
Rafael Monnerat committed
843
      title='Specific property to get stop of blocks (ex. stop_date)',
Romain Courteaud's avatar
Romain Courteaud committed
844 845
      description='Property for building X-Axis such as stop_date ' \
                  'objects',
Thomas Bernard's avatar
Thomas Bernard committed
846
      default='stop_date',
847
      required=0)
848

849
  y_size_block = fields.StringField('y_size_block',
Rafael Monnerat's avatar
Rafael Monnerat committed
850
      title='Specific property to get height of blocks (ex.quantity)',
Romain Courteaud's avatar
Romain Courteaud committed
851
      description='Method for building height of blocks objects',
852
      default='quantity',
853
      required=0)
854 855 856

  constraint_method = fields.StringField('constraint_method',
      title='name of constraint method between blocks',
Romain Courteaud's avatar
Romain Courteaud committed
857
      description='Constraint method between blocks objects',
858 859 860
      default='SET_DHTML',
      required=1)

861
  stat_method = fields.StringField('stat_method',
Rafael Monnerat's avatar
Rafael Monnerat committed
862
      title="Name of script generating statistics",
Romain Courteaud's avatar
Romain Courteaud committed
863
      description="script for statistics",
864 865 866
      default='',
      required=0)

867
  split_method = fields.StringField('split_method',
Rafael Monnerat's avatar
Rafael Monnerat committed
868
      title='Name of script splitting activities into blocks',
Romain Courteaud's avatar
Romain Courteaud committed
869
      description="script for splitting activities into multiple blocks",
870 871 872
      default='',
      required=0)

873
  color_script = fields.StringField('color_script',
Rafael Monnerat's avatar
Rafael Monnerat committed
874
      title='Name of script colorizing blocks',
Romain Courteaud's avatar
Romain Courteaud committed
875
      description='script for block colors object',
876 877 878
      default='',
      required=0)

Thomas Bernard's avatar
Thomas Bernard committed
879
  round_script = fields.StringField('round_script',
Romain Courteaud's avatar
Romain Courteaud committed
880 881 882
      title='Name of script rounding blocks during validation (ex. ' \
            'Planning_roundBoundToDay)',
      description='script for block bounds rounding when validating',
883
      default='',
Thomas Bernard's avatar
Thomas Bernard committed
884 885
      required=0)

886

Thomas Bernard's avatar
Thomas Bernard committed
887
  sec_axis_script = fields.StringField('sec_axis_script',
Romain Courteaud's avatar
Romain Courteaud committed
888 889 890
      title='Name of script building secondary axis (ex. ' \
            'Planning_generateAxis)',
      description='Script for building secondary axis',
891
      default='Planning_generateAxis',
892
      required=1)
Thomas Bernard's avatar
Thomas Bernard committed
893

894
  info_center = fields.StringField('info_center',
Romain Courteaud's avatar
Romain Courteaud committed
895 896 897 898
      title='Specific method of data called for inserting info in ' \
            'block center',
      description='Method for displaying info in the center of a ' \
                  'block object',
899
      default='',
900
      required=0)
901 902

  info_topright = fields.StringField('info_topright',
Romain Courteaud's avatar
Romain Courteaud committed
903 904 905 906
      title='Specific method of data called for inserting info in '\
            'block topright',
      description='Method for displaying info in the topright of a block ' \
                  'object',
907 908 909 910
      default='',
      required=0)

  info_topleft = fields.StringField('info_topleft',
Romain Courteaud's avatar
Romain Courteaud committed
911 912 913 914
      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',
915 916 917 918
      default='',
      required=0)

  info_backleft = fields.StringField('info_backleft',
Romain Courteaud's avatar
Romain Courteaud committed
919 920 921 922
      title='Specific method of data called for inserting info in '\
            'block backleft',
      description='Method for displaying info in the backleft of a ' \
                  'block object',
923 924 925 926
      default='',
      required=0)

  info_backright = fields.StringField('info_backright',
Romain Courteaud's avatar
Romain Courteaud committed
927 928 929 930
      title='Specific method of data called for inserting info in '
            'block backright',
      description='Method for displaying info in the backright of a ' \
                  'block object',
931 932 933 934
      default='',
      required=0)

  security_index = fields.IntegerField('security_index',
Rafael Monnerat's avatar
Rafael Monnerat committed
935
      title='Variable depending on the type of web browser :',
Romain Courteaud's avatar
Romain Courteaud committed
936 937
      description='This variable is used because the rounds of each ' \
                  'web browser seem to work differently',
938 939 940
      default=2,
      required=0)

941 942 943 944 945 946 947 948 949 950 951 952 953
  def get_javascript_list(self, field, REQUEST=None):
    """
    Returns list of javascript needed by the widget
    """
    if field.get_value('js_enabled'):
      context = getContext(field, REQUEST)
      # XXX Instead of harcoding library name
      # it should be better to call a python script, as
      # it is done on type base method.
      return ['%s/wz_dragdrop.js' % context.portal_url.getPortalPath()]
    else:
      return []

954
  def render_css(self, field, REQUEST):
955 956 957 958 959 960
    """
    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
    """
961
    context = getContext(field, REQUEST)
Thomas Bernard's avatar
Thomas Bernard committed
962 963 964 965
    # 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
966 967
    basic, planning = self.render_structure(field=field, REQUEST=REQUEST, 
                                            context=context)
Thomas Bernard's avatar
Thomas Bernard committed
968
    # getting CSS script generator
969
    planning_css_method = getattr(context, 'planning_css')
Thomas Bernard's avatar
Thomas Bernard committed
970
    # recover CSS data buy calling DTML document
971
    CSS_data = planning_css_method(basic=basic, planning=planning)
Thomas Bernard's avatar
Thomas Bernard committed
972
    # saving structure inside the request for HTML render
Romain Courteaud's avatar
Romain Courteaud committed
973
    # XXX This prevent multiple planning box on the same form
974 975
    REQUEST.set('basic', basic)
    REQUEST.set('planning', planning)
976

Thomas Bernard's avatar
Thomas Bernard committed
977
    return CSS_data
978

Romain Courteaud's avatar
Romain Courteaud committed
979
  def render(self, field, key, value, REQUEST):
980
    """
981
    Method called to render the HTML code relative to the planning.
982 983 984 985 986 987 988
    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
989 990
    basic = REQUEST.get('basic')
    planning = REQUEST.get('planning')
991

Thomas Bernard's avatar
Thomas Bernard committed
992
    # getting HTML rendering Page Template
993 994
    planning_html_method = getattr(getContext(field, REQUEST), 
                                   'planning_content')
Thomas Bernard's avatar
Thomas Bernard committed
995
    # recovering HTML data by calling Page Template document
996
    HTML_data = planning_html_method(basic=basic, planning=planning)
Thomas Bernard's avatar
Thomas Bernard committed
997 998
    # return HTML data
    return HTML_data
999

1000
  def render_structure(self, field, REQUEST, context):
Romain Courteaud's avatar
Romain Courteaud committed
1001 1002 1003 1004 1005 1006 1007 1008
    """
    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
1009 1010 1011
    # XXX testing : uncoment to put selection to null => used for debugging
    #here.portal_selections.setSelectionFor(selection_name, None)
    ####### DATA DEFINITION #######
1012
    # recovering usefull planning properties
1013 1014 1015
    # getting form
    form = field.aq_parent
    list_method = field.get_value('list_method')
1016
    sec_layer_list_method = field.get_value('second_layer_list_method')
1017 1018 1019 1020
    title_line = field.get_value('title_line')
    # list of domain
    report_root_list = field.get_value('report_root_list')
    portal_types = field.get_value('portal_types')
1021
    # selection name used to store selection params
Sebastien Robin's avatar
Sebastien Robin committed
1022
    selection_name = field.get_value('selection_name')
1023
    # getting sorting keys and order (list)
Sebastien Robin's avatar
Sebastien Robin committed
1024
    sort = field.get_value('sort')
1025 1026
    # contains the list of blocks that are not validated
    # for them a special rendering is done (special colors for example)
Romain Courteaud's avatar
Romain Courteaud committed
1027 1028 1029
    list_error = REQUEST.get('list_block_error')
    if list_error is None:
      list_error = []
1030
    selection = context.portal_selections.getSelectionFor(
1031 1032 1033 1034 1035
                      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()
Romain Courteaud's avatar
Romain Courteaud committed
1036
    except (AttributeError, KeyError):
1037
      params = {}
Romain Courteaud's avatar
Romain Courteaud committed
1038

Thomas Bernard's avatar
Thomas Bernard committed
1039
    ###### CALL CLASS METHODS TO BUILD BASIC STRUCTURE ######
1040
    # creating BasicStructure instance (and initializing its internal values)
1041 1042
    basic = BasicStructure(context=context,
                           form=form, field=field,
1043 1044 1045
                           REQUEST=REQUEST, 
                           list_method=list_method,
                           sec_layer_list_method=sec_layer_list_method,
1046 1047 1048 1049
                           selection=selection, params=params,
                           selection_name=selection_name,
                           title_line=title_line,
                           report_root_list=report_root_list,
1050
                           portal_types=portal_types, 
1051 1052
                           sort=sort,
                           list_error=list_error)
1053
    # call build method to generate BasicStructure
1054
    status = basic.build()
Thomas Bernard's avatar
Thomas Bernard committed
1055
    if status != 1:
1056
      raise PlanningBoxError, status
1057

Thomas Bernard's avatar
Thomas Bernard committed
1058
    ###### CALL CLASS METHODS TO BUILD PLANNING STRUCTURE ######
1059
    # creating PlanningStructure instance and initializing its internal values
1060
    planning = PlanningStructure()
1061
    # call build method to generate final Planning Structure
1062 1063 1064
    status = planning.build(basic_structure=basic,
                            field=field,
                            REQUEST=REQUEST)
Thomas Bernard's avatar
Thomas Bernard committed
1065 1066
    if status != 1:
      # in case error during planning structure generation
1067
      raise PlanningBoxError, status
1068

1069
    return basic, planning
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082

# 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
  """

1083
  def __init__ (self, context='', form='', field='', REQUEST='', list_method='',
Romain Courteaud's avatar
Romain Courteaud committed
1084 1085
                selection=None, params = '', selection_name='',
                report_root_list='', title_line='', portal_types='',
1086
                sec_layer_list_method=None, sort=None, list_error=None):
1087 1088
    """
    Init main internal parameters
Rafael Monnerat's avatar
Rafael Monnerat committed
1089
    """
1090
    self.context = context
1091 1092 1093 1094 1095 1096 1097
    self.form = form
    self.field = field
    self.REQUEST = REQUEST
    self.sort = sort
    self.selection = selection
    self.params = params
    self.list_method = list_method
1098
    self.sec_layer_list_method = sec_layer_list_method
1099
    self.title_line = title_line
Thomas Bernard's avatar
Thomas Bernard committed
1100
    self.selection_name = selection_name
1101 1102 1103
    self.report_root_list = report_root_list
    self.portal_types = portal_types
    self.basic_group_list = None
Romain Courteaud's avatar
Romain Courteaud committed
1104 1105
    # needed to generate groups
    self.report_groups= ''
1106 1107
    self.list_error = list_error
    self.secondary_axis_occurence = []
Romain Courteaud's avatar
Romain Courteaud committed
1108 1109 1110
    # 'list' in case output is a list containing the
    # full planning structure without any selection
    self.render_format = ''
1111 1112 1113 1114 1115
    self.main_axis_info = {}
    self.secondary_axis_info = {}

  def build(self):
    """
Rafael Monnerat's avatar
Rafael Monnerat committed
1116
    Build BasicStructure from given parameters, and for that do the
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    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
Romain Courteaud's avatar
Romain Courteaud committed
1129
    # XXX Use seclection tool API
1130
    if self.selection is None:
Thomas Bernard's avatar
Thomas Bernard committed
1131 1132
      self.selection = Selection(params=default_params,
                                 default_sort_on=self.sort)
Sebastien Robin's avatar
Sebastien Robin committed
1133
    else:
1134 1135 1136 1137
      # immediately updating the default sort value
      self.selection.edit(default_sort_on=self.sort)
      self.selection.edit(sort_on=self.sort)

1138
    self.context.portal_selections.setSelectionFor(
Romain Courteaud's avatar
Romain Courteaud committed
1139 1140 1141
                                        self.selection_name,
                                        self.selection,
                                        REQUEST=self.REQUEST)
1142
    # building list of portal_types
Romain Courteaud's avatar
Romain Courteaud committed
1143
    self.filtered_portal_types = [x[0] for x in self.portal_types]
1144 1145 1146 1147 1148 1149 1150
    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())
1151
    self.selection.edit(report_opened=is_report_opened)
1152 1153 1154
    portal_categories = getattr(self.form,'portal_categories',None)
    portal_domains = getattr(self.form,'portal_domains',None)

1155 1156 1157 1158 1159
    if getattr(self.sec_layer_list_method, 'method_name', None) is not None:
       self.sec_layer_list_method = getattr(
                                      self.context,
                                      self.sec_layer_list_method.method_name)

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
    ##################################################
    ############### 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']
1172
    if getattr(self.list_method, 'method_name', None) is not None:
1173 1174
      if self.list_method.method_name == 'ObjectValues':
        # list_method is available
1175
        self.list_method = self.context.objectValues
1176
        kw = copy(self.params)
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
      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():
Romain Courteaud's avatar
Romain Courteaud committed
1191
          if self.params[cname] != '' and self.params[cname] is not None:
1192 1193 1194
            kw[cname] = self.params[cname]
        # try to get the method through acquisition
        try:
1195
          self.list_method = getattr(self.context, self.list_method.method_name)
1196 1197 1198 1199 1200 1201
        except (AttributeError, KeyError):
          pass
    elif self.list_method in (None,''):
      # use current selection
      self.list_method = None

1202 1203 1204 1205
    ##################################################
    ############## DEFINING STAT METHOD ##############
    ##################################################
    stat_method = self.field.get_value('stat_method')
1206
    stat_method = getattr(self.context, stat_method, None)
Romain Courteaud's avatar
Romain Courteaud committed
1207
    if stat_method is None:
1208
      show_stat = 0
1209 1210
    else:
      show_stat = 1
1211

1212 1213 1214 1215 1216 1217 1218
    ##################################################
    ############ 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)
1219

1220 1221 1222 1223 1224 1225
    default_selection_report_path = self.report_root_list[0][0].split('/', 1)[0]
    if (portal_categories is None or \
        portal_categories._getOb(default_selection_report_path, None) is None) \
       and (portal_domains is None or \
          portal_domains._getOb(default_selection_report_path, None) is None):
      default_selection_report_path = self.report_root_list[0][0]
1226

1227 1228 1229 1230 1231 1232
    self.selection_report_path = self.selection.getReportPath(
                                  default=default_selection_report_path)

    if self.selection_report_path in (None, ()):
      raise PlanningBoxError, 'report path is empty or not valid on %s' % \
        self.field.absolute_url()
1233 1234 1235

    # testing report_depth value
    if report_depth is not None:
1236
      selection_report_current = ()
1237 1238
    else:
      selection_report_current = self.selection.getReportList()
1239

1240
    # building report_tree_list
1241
    report_tree_list = makeTreeList(here=self.context, form=self.form,
Thomas Bernard's avatar
Thomas Bernard committed
1242
                                    root_dict=None,
1243
                                    report_path=self.selection_report_path,
Thomas Bernard's avatar
Thomas Bernard committed
1244 1245 1246
                                    base_category=None, depth=0,
                                    unfolded_list=selection_report_current,
                                    selection_name=self.selection_name,
1247
                                    report_depth=report_depth,
1248
                                    list_method=self.list_method,
Rafael Monnerat's avatar
Rafael Monnerat committed
1249
                                    filtered_portal_types= \
1250
                                                self.filtered_portal_types,
1251 1252 1253
                                    is_report_opened=is_report_opened,
                                    sort_on=self.selection.sort_on,
                                    form_id=self.form.id)
1254

1255 1256 1257 1258
    if report_tree_list == []:
      raise PlanningBoxError, "Report tree list is empty on %s" % \
        self.field.absolute_url()

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278

    ##################################################
    ########### 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
1279
    blocks_object={}
1280 1281
    select_expression = ''

1282
    # now iterating through report_tree_list
1283
#     LOG('PlanningBox, build', 0, 'report_tree_list %s' % len(report_tree_list))
1284
    for object_tree_line in report_tree_list:
1285
#       LOG('PlanningBox, build', 0, 'object_tree_line %s' % str(object_tree_line))
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
      # prepare query by defining selection report object
      # 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)
1299 1300
        # recovering statistics if needed
        # getting list of statistic blocks
Thomas Bernard's avatar
Thomas Bernard committed
1301 1302
        stat_list = stat_method(selection=self.selection,
                                list_method=self.list_method,
1303
                                selection_context=self.context,
Thomas Bernard's avatar
Thomas Bernard committed
1304 1305 1306
                                report_tree_list=report_tree_list,
                                object_tree_line=object_tree_line,
                                REQUEST=self.REQUEST, field=self.field)
1307

1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
        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)
1323

1324 1325 1326 1327 1328 1329
        # 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,
1330
                        context=self.context, REQUEST=self.REQUEST)
1331 1332
        else:
          # no list_method found
1333 1334
          raise PlanningBoxError, "No list method found on %s" % \
              self.field.absolute_url()
1335 1336 1337 1338 1339 1340 1341 1342 1343

        # Defining the Secondary Layer Object List
        if self.sec_layer_list_method not in (None,''):
          sec_layer_object_list = self.selection(
                          method=self.sec_layer_list_method,
                          context=self.context, 
                          REQUEST=self.REQUEST)          
        else:
          sec_layer_object_list = []
1344 1345
        # recovering exeption_uid_list
        exception_uid_list = object_tree_line.getExceptionUidList()
1346

1347
        domain_obj = object_tree_line.getObject()
1348
        new_object_list = []
1349
        sec_new_object_list = []
1350 1351
        if domain_obj.getPortalType() == 'Domain':
          category_obj = domain_obj.getMembershipCriterionCategory()
1352
          for bc in domain_obj.getMembershipCriterionBaseCategoryList():
1353 1354
            if (category_obj is not None) and (bc is not None):
              category_value = category_obj.getRelativeUrl()
1355 1356 1357 1358 1359 1360
              new_object_list.extend([ s_obj for s_obj in object_list \
                   if s_obj._getDefaultAcquiredCategoryMembership(bc) == category_value])
 
              sec_new_object_list.extend([ s_obj for s_obj in sec_layer_object_list \
                   if s_obj._getDefaultAcquiredCategoryMembership(bc) == category_value])

1361
          object_list = new_object_list
1362
          sec_layer_object_list = sec_new_object_list
1363 1364

        if exception_uid_list not in ([],None) :
1365 1366 1367
          # Filter folders if parent tree :
          # build new object_list for current line
          # (list of relative elements)
1368 1369 1370 1371 1372 1373
          new_object_list = [s_obj for s_obj in object_list \
                             if s_obj.getUid() not in exception_uid_list]
          sec_new_object_list = [s_obj for s_obj in object_list \
                                 if s_obj.getUid() not in exception_uid_list]

          sec_layer_object_list = sec_new_object_list
1374 1375
          object_list = new_object_list

1376 1377 1378 1379 1380
        self.sec_layer_uid_list = [obj.getUid() for obj in sec_layer_object_list]
        # The order is important 
        sec_layer_object_list.extend(object_list)
        object_list = sec_layer_object_list

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
        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
1405 1406
              # do not export voluntary object_list to prevent bad
              # interpretation
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
              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)
1418
    #self.selection.edit(report_list=None) # comment to save report_list status
1419

1420 1421 1422
    # update report list if report_depth was specified
    if report_depth is not None:
      unfolded_list = []
1423 1424
      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
1425 1426 1427
          # depth of current report_line is inferior to the current
          # report_depth and current report_line is not stat line.
          # saving information
1428 1429 1430
          unfolded_list.append(report_line.getObject().getRelativeUrl())
      self.selection.edit(report_list=unfolded_list)

Thomas Bernard's avatar
Thomas Bernard committed
1431

1432 1433 1434 1435 1436 1437 1438
    ##################################################
    ############## CHECKING CONSTRAINTS ##############
    ##################################################
    # XXX Constraints checking chould be called here
    # and results saved in a list (list of url corresponding to objects not
    # validated)

1439 1440 1441 1442 1443
    ##################################################
    ########### 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
1444 1445
    # only the area that need to be rendered. This prevents from useless
    # processing
1446 1447 1448
    # calculating main axis bounds
    self.getMainAxisInfo(self.main_axis_info)
    # applying main axis selection
1449
    if self.report_groups != []:
Thomas Bernard's avatar
Thomas Bernard committed
1450 1451
      self.report_groups=self.report_groups[self.main_axis_info['bound_start']:
                                            self.main_axis_info['bound_stop']]
1452 1453
    else:
      # no group is available so the Y and X axis will be empty...
1454 1455 1456 1457
      raise PlanningBoxError, \
          'selection method returned empty list of objects : please check' \
          'list_method and report_root of %s' % \
          self.field.absolute_url()
1458 1459 1460 1461

    ##################################################
    ############ GETTING SEC AXIS BOUNDS #############
    ##################################################
Thomas Bernard's avatar
Thomas Bernard committed
1462 1463
    # now that our report_group structure has been cut need to get secondary
    # axis bounds to add only the blocs needed afterwards
1464 1465
    # getting secondary_axis_occurence to define begin and end secondary_axis
    # bounds (getting absolute size)
1466 1467 1468 1469 1470
    self.getSecondaryAxisOccurence()
    # XXX changing point of view to handle axis occurences : their are now
    # handled by group, so that it is easy to recover group bounds in case the
    # current rendering is calendar mode.

1471 1472
    # now getting start & stop bounds (getting relative size to the current
    # rendering)
Thomas Bernard's avatar
Thomas Bernard committed
1473 1474 1475 1476 1477
    status = self.getSecondaryAxisInfo(self.secondary_axis_info)
    if status != 1:
      # ERROR
      # Found error while setting secondary axis bounds
      return status
1478 1479 1480 1481 1482 1483

    ##################################################
    ####### SAVING NEW PROPERTIES INTO REQUEST #######
    ##################################################
    if self.list_method is not None and self.render_format != 'list':
     self.selection.edit(params = self.params)
1484
     self.context.portal_selections.setSelectionFor(self.selection_name,
Thomas Bernard's avatar
Thomas Bernard committed
1485 1486
                                                 self.selection,
                                                 REQUEST = self.REQUEST)
1487 1488 1489 1490 1491 1492 1493 1494 1495

    ##################################################
    ######### 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
1496 1497 1498 1499 1500
    status = self.buildGroupStructure()
    if status != 1:
      # ERROR
      # Found errors while setting group structure
      return status
1501 1502 1503
    # everything is fine
    return 1

1504 1505
  def getSecondaryAxisOccurence(self):
    """
Thomas Bernard's avatar
Thomas Bernard committed
1506 1507 1508
    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
1509 1510
    """
    secondary_axis_occurence = []
1511 1512

    # defining the objects requested for calendar mode testing
1513
    if 'parent' in self.selection_report_path :
1514 1515 1516 1517 1518 1519 1520
      calendar_mode = 0
    else:
      calendar_mode = 1 # assuming calendar_mode = 1 by default.
    calendar_range = 0  # range max on the current calendar mode. used for
                        # example while dealing with months : 31 is saved as
                        # the largest range, even if some month have only 28
                        # to 30 days
1521 1522

    # specific start & stop methods name for secondary axis
Thomas Bernard's avatar
Thomas Bernard committed
1523 1524
    start_property_id = self.field.get_value('x_start_bloc')
    stop_property_id= self.field.get_value('x_stop_bloc')
1525
    for (object_tree_group, object_list, info_dict) in self.report_groups:
1526

1527 1528 1529 1530 1531 1532 1533
      # defining empty list for each kind of occurence.
      group_list = None
      group_list = []
      item_list = None
      item_list = []

      # recovering group_properties
Romain Courteaud's avatar
Romain Courteaud committed
1534
      if start_property_id is not None:
1535 1536 1537 1538 1539 1540 1541 1542
        group_start = \
        object_tree_group.object.getObject().getProperty(start_property_id,
                                                         None)
        if object_tree_group.object.getObject().hasProperty('start_date'):
          group_start = \
          object_tree_group.object.getObject().start_date
      else:
        group_start= None
Romain Courteaud's avatar
Romain Courteaud committed
1543
      if stop_property_id is not None:
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
        group_stop = \
        object_tree_group.object.getObject().getProperty(stop_property_id,None)
        if object_tree_group.object.getObject().hasProperty('stop_date'):
          group_stop = \
          object_tree_group.object.getObject().stop_date
      else:
        group_stop = None

      group_list = [[group_start, group_stop]]

      # no calendar mode available if group has no valid bounds.
      if None in [group_start,group_stop]:
        calendar_mode = 0
      else:
        # seems to be a valid calendar mode, checking if need to update
        # calendar_range
        if calendar_range < (group_stop - group_start):
          calendar_range = (group_stop - group_start)


      # recovering item properties
1565
      if object_list not in (None, [], {}) :
1566
        for object_request in object_list:
Romain Courteaud's avatar
Romain Courteaud committed
1567
          if start_property_id is not None:
Thomas Bernard's avatar
Thomas Bernard committed
1568 1569
            block_begin = \
            object_request.getObject().getProperty(start_property_id,None)
1570 1571
          else:
            block_begin = None
Romain Courteaud's avatar
Romain Courteaud committed
1572
          if stop_property_id is not None:
Thomas Bernard's avatar
Thomas Bernard committed
1573 1574
            block_stop = \
            object_request.getObject().getProperty(stop_property_id,None)
1575 1576
          else:
            block_stop = None
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
          item_list.append([block_begin,block_stop])

          # testing if current item is compliant with calendar mode
          # i.e item car be represented within the current group
          if calendar_mode and (block_stop <= group_start) and \
                               (block_begin >= group_stop):
            # invalid conditions : item outside group, so no calendar mode
            calendar_mode = 0

        # adding list of items to group_list
        group_list.extend(item_list)
1588

1589 1590 1591 1592 1593 1594 1595
      # adding current group list to list of occurences
      secondary_axis_occurence.extend(group_list)

    # saving resulting values.
    self.calendar_mode  = calendar_mode
    self.calendar_range = calendar_range
    self.secondary_axis_occurence =  secondary_axis_occurence
1596 1597 1598 1599 1600 1601 1602 1603

  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
1604
    # recovering zoom properties
1605 1606 1607 1608 1609 1610 1611
    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
1612
      if (occurence[0] < axis_dict['bound_begin'] or \
Romain Courteaud's avatar
Romain Courteaud committed
1613
          axis_dict['bound_begin'] is None) and occurence[0] is not None:
1614
        axis_dict['bound_begin'] = occurence[0]
Thomas Bernard's avatar
Thomas Bernard committed
1615
      if (occurence[1] > axis_dict['bound_end'] or  \
Romain Courteaud's avatar
Romain Courteaud committed
1616
          axis_dict['bound_end'] is None) and occurence[1] is not None:
1617
        axis_dict['bound_end'] = occurence[1]
1618

Romain Courteaud's avatar
Romain Courteaud committed
1619
    if axis_dict['bound_end']is None or axis_dict['bound_begin'] is None:
Thomas Bernard's avatar
Thomas Bernard committed
1620
      # ERROR
1621
      # no bounds over the secondary axis have been defined
1622
      # can append if bad property has been selected
Thomas Bernard's avatar
Thomas Bernard committed
1623 1624 1625
      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'
1626 1627
      #axis_dict['bound_begin'] = 0
      #axis_dict['bound_end'] = 1
1628
      return [(Message(domain='erp5_ui', message=message,mapping=None))]
1629

Rafael Monnerat's avatar
Rafael Monnerat committed
1630
    axis_dict['bound_range'] = axis_dict['bound_end'] - axis_dict['bound_begin']
1631
    # now start and stop have the extreme values of the second axis bound.
Thomas Bernard's avatar
Thomas Bernard committed
1632
    # this represents in fact the size of the Planning's secondary axis
1633

Thomas Bernard's avatar
Thomas Bernard committed
1634
    # can now get selection informations ( float range 0..1)
1635 1636
    axis_dict['bound_start'] = 0
    axis_dict['bound_stop'] = 1
Romain Courteaud's avatar
Romain Courteaud committed
1637
    if self.selection is not None:
Thomas Bernard's avatar
Thomas Bernard committed
1638 1639
      # selection is not None, trying to recover previously saved values about
      # secondary axis (axis start and stop bounds)
1640 1641 1642
      try:
        axis_dict['bound_start'] = self.selection.getSecondaryAxisStart()
        axis_dict['bound_stop'] = self.selection.getSecondaryAxisStop()
Thomas Bernard's avatar
Thomas Bernard committed
1643 1644
      except AttributeError:
        # bounds were not defined, escaping test
1645 1646 1647 1648 1649 1650
        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
1651 1652
    axis_dict['bound_start'] = axis_dict['zoom_start'] * axis_zoom_step + \
                               axis_dict['bound_begin']
1653 1654 1655 1656 1657 1658 1659
    # 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
1660 1661
    # everything is OK, returning 'true' flag
    return 1
1662 1663 1664

  def getMainAxisInfo(self, axis_dict):
    """
1665
    Getting main axis properties (total pages, current page, groups per page)
1666 1667 1668 1669 1670 1671
    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).
    """
1672
    axis_dict['bound_axis_groups'] = self.field.get_value('main_axis_groups')
Romain Courteaud's avatar
Romain Courteaud committed
1673
    if axis_dict['bound_axis_groups'] is None:
1674
      #XXX raise exception : no group nb/page defined
1675 1676
      pass

1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
    # 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
1705 1706
      axis_dict['bound_start'] -= \
               (axis_dict['bound_start'] % axis_dict['bound_axis_groups'])
1707 1708

      # setting last group displayed on page
Thomas Bernard's avatar
Thomas Bernard committed
1709 1710
      axis_dict['bound_stop'] = min (axis_dict['bound_end'],
               axis_dict['bound_start'] + axis_dict['bound_axis_groups'])
1711
      # calculating total number of pages
Thomas Bernard's avatar
Thomas Bernard committed
1712 1713
      axis_dict['bound_page_total'] = int(max(axis_dict['bound_end'] - 1,0) / \
               axis_dict['bound_axis_groups']) + 1
1714
      # calculating current page number
Thomas Bernard's avatar
Thomas Bernard committed
1715 1716
      axis_dict['bound_page_current'] = int(axis_dict['bound_start'] / \
               axis_dict['bound_axis_groups']) + 1
1717
      # adjusting first group displayed on current page
Thomas Bernard's avatar
Thomas Bernard committed
1718 1719
      axis_dict['bound_start'] = min(axis_dict['bound_start'], max(0,
           (axis_dict['bound_page_total']-1) * axis_dict['bound_axis_groups']))
1720

1721 1722 1723 1724 1725
      self.params['list_lines'] = axis_dict['bound_axis_groups']
      self.params['list_start'] = axis_dict['bound_start']

  def buildGroupStructure(self):
      """
1726
      This procedure builds BasicGroup instances corresponding to the
1727 1728 1729 1730
      report_group_objects returned from the ERP5 request.
      """
      position = 0
      # iterating each element
Thomas Bernard's avatar
Thomas Bernard committed
1731 1732
      for (report_group_object, object_list, property_dict) in \
           self.report_groups:
1733 1734 1735

        stat_result = {}
        stat_context = report_group_object.getObject().asContext(**stat_result)
Thomas Bernard's avatar
Thomas Bernard committed
1736 1737 1738 1739
        stat_context.domain_url = \
                     report_group_object.getObject().getRelativeUrl()
        stat_context.absolute_url = \
                     lambda x: report_group_object.getObject().absolute_url()
1740 1741 1742
        url=getattr(stat_context,'domain_url','')
        # updating position_informations
        position +=1
1743
        # recovering usefull informations, basic_structure
Rafael Monnerat's avatar
Rafael Monnerat committed
1744
        if self.title_line not in (None,''):
Romain Courteaud's avatar
Romain Courteaud committed
1745 1746
	        title_line_method = getattr(report_group_object.getObject(),
			                                self.title_line, None)
1747
        else:
Romain Courteaud's avatar
Romain Courteaud committed
1748 1749
          title_line_method = getattr(report_group_object.getObject(),
                                      'getTitle', None)
1750
        if title_line_method is not None:
Romain Courteaud's avatar
Romain Courteaud committed
1751
          title = name = title_line_method()
1752
        depth = report_group_object.getDepth()
1753 1754
        is_open = report_group_object.getIsOpen()
        is_pure_summary = report_group_object.getIsPureSummary()
1755 1756

        # creating new group_object with all the informations collected
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
        group_start = group_stop = None
        if self.calendar_mode == 1:
          # recover start and stop of current object to generate good BasicGroup
          group_start = report_group_object.getObject().start_date
          group_stop  = report_group_object.getObject().stop_date -1
          # build dict to fix BasicActivity bounds
          secondary_axis_bounds = {}
          secondary_axis_bounds['bound_start'] = group_start
          secondary_axis_bounds['bound_stop']  = group_stop
        else:
          secondary_axis_bounds = self.secondary_axis_info
Rafael Monnerat's avatar
Rafael Monnerat committed
1768

Thomas Bernard's avatar
Thomas Bernard committed
1769
        child_group = BasicGroup(title=title, name=name, url=url,
Rafael Monnerat's avatar
Rafael Monnerat committed
1770 1771 1772 1773 1774 1775
                                constraints=None, depth=depth,
                                position=position, field =self.field,
                                object=report_group_object, is_open=is_open,
                                is_pure_summary=is_pure_summary,
                                secondary_axis_start = group_start,
                                secondary_axis_stop  = group_stop,
1776 1777
                                property_dict = property_dict,
                                sec_layer_uid_list=self.sec_layer_uid_list)
Thomas Bernard's avatar
Thomas Bernard committed
1778

1779
        if object_list not in [None, []]:
Thomas Bernard's avatar
Thomas Bernard committed
1780
          child_group.setBasicActivities(object_list,self.list_error,
1781
                                         secondary_axis_bounds)
1782 1783 1784 1785 1786 1787

        try:
          self.basic_group_list.append(child_group)
        except (AttributeError):
          self.basic_group_list = []
          self.basic_group_list.append(child_group)
1788
	
Thomas Bernard's avatar
Thomas Bernard committed
1789 1790
      return 1

1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802

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.
  """
1803

1804
  def __init__ (self, title='', name='',url='', constraints='', depth=0,
Thomas Bernard's avatar
Thomas Bernard committed
1805
                position=0, field = None, object = None, is_open=0,
1806
                is_pure_summary=1, secondary_axis_start=None,
1807 1808
                secondary_axis_stop=None, sec_layer_uid_list=[],
                property_dict = {}):
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
    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
1819 1820 1821 1822
    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
1823 1824
    self.secondary_axis_start = secondary_axis_start
    self.secondary_axis_stop = secondary_axis_stop
1825 1826 1827
    # property_dict holds all information about the current axis_group
    # type of group, stat, etc.
    self.property_dict = property_dict
1828
    self.sec_layer_uid_list = sec_layer_uid_list
1829 1830 1831

  def setBasicActivities(self,activity_list, list_error,secondary_axis_info):
    """
Rafael Monnerat's avatar
Rafael Monnerat committed
1832
    Link a list of activities to the current object.
Thomas Bernard's avatar
Thomas Bernard committed
1833 1834 1835 1836 1837 1838
    *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
1839
    """
Thomas Bernard's avatar
Thomas Bernard committed
1840
    info = {}
Thomas Bernard's avatar
Thomas Bernard committed
1841 1842 1843
    # 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')
1844 1845 1846 1847
    # 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')
1848 1849
    info_botleft = self.field.get_value('info_backleft')
    info_botright = self.field.get_value('info_backright')
1850 1851 1852 1853
    # 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)
1854 1855 1856
    info_botleft_method = getattr(self.object.getObject(),info_botleft,None)
    info_botright_method = \
                  getattr(self.object.getObject(),info_botright,None)
1857
    # if method recovered is not null, then updating
Romain Courteaud's avatar
Romain Courteaud committed
1858 1859
    # XXX Does script have to manage multiple context object ?
    if info_center_method is not None:
1860
      info['info_center'] = str(info_center_method())
Romain Courteaud's avatar
Romain Courteaud committed
1861
    if info_topright_method is not None:
1862
      info['info_topright'] = str(info_topright_method())
Romain Courteaud's avatar
Romain Courteaud committed
1863
    if info_topleft_method is not None:
1864
      info['info_topleft'] = str(info_topleft_method())
Romain Courteaud's avatar
Romain Courteaud committed
1865
    if info_botleft_method is not None:
1866
      info['info_botleft'] = str(info_botleft_method())
Romain Courteaud's avatar
Romain Courteaud committed
1867
    if info_botright_method is not None:
1868
      info['info_botright'] = str(info_botright_method())
1869

1870
    if activity_list not in ([],None):
1871 1872 1873
      indic=0
      # iterating each activity linked to the current group
      for activity_content in activity_list:
1874
        # interpreting results and getting begin and end values from
1875
        # previously recovered method
1876 1877
        block_begin = None
        block_end = None
1878

1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
        obj = activity_content.getObject()
        _marker = []

        try:
          block_begin = obj.getProperty(object_property_begin, _marker)
          if block_begin is _marker:
            raise AttributeError, object_property_begin
        except AttributeError:
          block_begin = getattr(obj, object_property_begin, None)

        try:
          block_end = obj.getProperty(object_property_end, _marker)
          if block_end is _marker:
            raise AttributeError, object_property_end
        except AttributeError:
          block_end = getattr(obj, object_property_end, None)
1895

1896
        # handling case where activity bound is not defined
Romain Courteaud's avatar
Romain Courteaud committed
1897
        if block_begin is None:
1898 1899
          block_begin = secondary_axis_info['bound_start']
          current_color='#E4CCE1'
Romain Courteaud's avatar
Romain Courteaud committed
1900
        if block_end is None:
1901 1902
          block_end = secondary_axis_info['bound_stop']
          current_color='#E4CCE1'
Thomas Bernard's avatar
Thomas Bernard committed
1903 1904 1905 1906
        # 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']:
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
          # 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
1922
          name = "Activity_%s" % (str(indic))
1923 1924

          error = 'false'
1925
          current_color=''
1926

1927 1928 1929 1930 1931 1932
          if self.property_dict['stat'] == 1:
            info = None
            info = {}
            info['info_center'] = ''
            info['info_topright'] = ''
            info['info_topleft'] = ''
1933 1934
            info['info_botleft'] = ''
            info['info_botright'] = ''
1935 1936 1937 1938
            title = ''
            object = activity_content
            url=''
            object_property_height = self.field.get_value('y_size_block')
Thomas Bernard's avatar
Thomas Bernard committed
1939 1940
            height = \
                 getattr(activity_content.getObject(),object_property_height)
1941 1942 1943 1944 1945 1946 1947
          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)
1948 1949 1950
            info_botleft_method = getattr(activity_content,info_botleft,None)
            info_botright_method = \
                 getattr(activity_content,info_botright,None)
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
            if obj.getUid() not in self.sec_layer_uid_list:
              # if value recovered is not null, then updating
              if info_center_method is not None:
                 info['info_center']=str(info_center_method())
              if info_topright_method is not None:
                 info['info_topright']=str(info_topright_method())
              if info_topleft_method is not None:
                 info['info_topleft']=str(info_topleft_method())
              if info_botleft_method is not None:
                 info['info_botleft'] =str(info_botleft_method())
              if info_botright_method is not None:
                 info['info_botright']=str(info_botright_method())
            else:
              info['info_center'] = ''
              info['info_topright'] = ''
              info['info_topleft'] = ''
              info['info_botleft'] = ''
              info['info_botright'] = ''
1969 1970

            title = info['info_center']
Thomas Bernard's avatar
Thomas Bernard committed
1971 1972
            color_script = getattr(activity_content.getObject(),
                                   self.field.get_value('color_script'),None)
1973
            # calling color script if exists to set up activity_color
Romain Courteaud's avatar
Romain Courteaud committed
1974
            if color_script  is not None:
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
              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
1985 1986 1987 1988 1989 1990
            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()
1991
            object = stat_context.getObject()
1992 1993 1994 1995 1996
            
            # check if the activity_content has some special method for URL
            # This approach is also used by ListBox, but in Planning Box
            # the parameters are not important for now. In future, can be define
            # special sublinks using this implementation.
1997 1998 1999 2000 2001 2002 2003
            #if getattr(activity_content, 'getListItemUrl', None):
            #  url = activity_content.getListItemUrl(cname_id='', 
            #      selection_index='',
            #      selection_name=self.field.get_value('selection_name'))
            #else:
            #  url = object.getUrl()
            url = object.getUrl()
2004 2005 2006

            # XXX should define height of block here
            height = None
2007 2008

          # creating new activity instance
Thomas Bernard's avatar
Thomas Bernard committed
2009 2010 2011 2012 2013 2014 2015 2016
          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)
2017 2018


2019 2020 2021 2022 2023 2024
          # 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)
2025
          # incrementing indic used for differenciating activities in the same
2026 2027 2028
          # group (used for Activity naming)
          indic += 1

Sebastien Robin's avatar
Sebastien Robin committed
2029
    else:
Thomas Bernard's avatar
Thomas Bernard committed
2030 2031 2032
      # specific color script
      color_script = getattr(self.object.getObject(),
                             self.field.get_value('color_script'),None)
2033 2034
      # calling color script if exists to set up activity_color
      current_color=''
Romain Courteaud's avatar
Romain Courteaud committed
2035
      if color_script  is not None:
2036 2037
        current_color = color_script(self.object.getObject())

2038
      # getting begin and end values from previously recovered method
Romain Courteaud's avatar
Romain Courteaud committed
2039
      if object_property_begin  is not None:
Thomas Bernard's avatar
Thomas Bernard committed
2040 2041
        block_begin = \
                    self.object.getObject().getProperty(object_property_begin)
Sebastien Robin's avatar
Sebastien Robin committed
2042 2043
      else:
        block_begin = None
2044

Romain Courteaud's avatar
Romain Courteaud committed
2045
      if object_property_end is not None:
Thomas Bernard's avatar
Thomas Bernard committed
2046
        block_end = self.object.getObject().getProperty(object_property_end)
Sebastien Robin's avatar
Sebastien Robin committed
2047
      else:
2048 2049
        block_end = None

2050 2051 2052 2053
      if secondary_axis_info.has_key('bound_start') and \
               secondary_axis_info.has_key('bound_stop'):
        # testing if activity is visible according to the current zoom selection
        # over the secondary_axis
Romain Courteaud's avatar
Romain Courteaud committed
2054
        if (block_begin is None):
2055 2056
          block_begin = secondary_axis_info['bound_start']
          current_color='#E4CCE1'
Romain Courteaud's avatar
Romain Courteaud committed
2057
        if block_end is None:
2058 2059
          block_end = secondary_axis_info['bound_stop']
          current_color='#E4CCE1'
2060

2061 2062 2063 2064
        if  (block_begin > secondary_axis_info['bound_stop'] or \
          block_end < secondary_axis_info['bound_start']):
          # activity will not be displayed, stopping process
          pass
2065
        else:
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
          # 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'
          if list_error not in (None,[]):
            for activity_error in list_error:
              if activity_error[0][0] == name:
                error = 'true'
                break

          # XXX testing constraint result here.
          # if current object url in list of error constranint urls, then
          # colorizing the block.

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

          # height should be implemented here
          height = None

          # get object url, not group url
2096
          url = self.object.getObject().getUrl()
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113

          # creating new activity instance
          activity=BasicActivity(title=info['info_center'], name=name,
                                 object=self.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)

          # 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)
2114 2115

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

Thomas Bernard's avatar
Thomas Bernard committed
2119 2120 2121 2122
  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 = {}):
2123 2124
    self.title = title
    self.name = name
2125
    self.object = object
2126 2127 2128 2129 2130 2131
    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
2132
    self.height = height
Thomas Bernard's avatar
Thomas Bernard committed
2133
    self.constraints = constraints
2134 2135 2136
    self.color = color
    self.info_dict = info_dict
    self.error = error
2137
    self.property_dict = property_dict # dict containing specific properties
2138 2139 2140


class PlanningStructure:
Romain Courteaud's avatar
Romain Courteaud committed
2141 2142 2143 2144 2145 2146
  """
  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.
  """
2147

2148
  def __init__ (self):
2149 2150 2151 2152 2153 2154
    self.main_axis = ''
    self.secondary_axis = ''
    self.content = []
    self.content_delimiters = None


Romain Courteaud's avatar
Romain Courteaud committed
2155
  def build(self, basic_structure=None, field=None, REQUEST=None):
2156 2157
    """
    main procedure for building Planning Structure
Thomas Bernard's avatar
Thomas Bernard committed
2158 2159 2160 2161 2162
    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...
2163
    """
2164
    # recovering render format ('YX' or 'XY')
2165
    self.calendar_view = field.get_value('calendar_view')
2166

2167 2168
    # declaring main axis
    self.main_axis = Axis(title='main axis', name='axis',
Romain Courteaud's avatar
Romain Courteaud committed
2169
                          unit='', axis_order=1, axis_group=[])
2170 2171 2172

    # declaring secondary axis
    self.secondary_axis = Axis(title='sec axis', name='axis',
Romain Courteaud's avatar
Romain Courteaud committed
2173
                               unit='', axis_order=2, axis_group=[])
2174 2175 2176

    # linking axis objects to their corresponding accessor, i.e X or Y
    # this allows the planning to be generic.
2177
    if self.calendar_view == 0:
2178 2179
      self.Y = self.main_axis
      self.X = self.secondary_axis
Sebastien Robin's avatar
Sebastien Robin committed
2180
    else:
2181 2182 2183 2184 2185 2186 2187 2188
      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
2189
    # Used in case of non calendar mode
Thomas Bernard's avatar
Thomas Bernard committed
2190 2191 2192 2193
    self.secondary_axis.start = \
                      basic_structure.secondary_axis_info['bound_start']
    self.secondary_axis.stop = \
                      basic_structure.secondary_axis_info['bound_stop']
2194 2195 2196 2197

    self.main_axis.size =  self.buildGroups(basic_structure=basic_structure)
    # call method to build secondary axis structure
    # need start_bound, stop_bound and number of groups to build
2198
    # used in non calendar mode
Romain Courteaud's avatar
Romain Courteaud committed
2199
    status = self.buildSecondaryAxis(basic_structure, field)
Thomas Bernard's avatar
Thomas Bernard committed
2200
    if status != 1:
Romain Courteaud's avatar
Romain Courteaud committed
2201
      # XXX Hidding error is not a good solution generally
Thomas Bernard's avatar
Thomas Bernard committed
2202 2203
      # ERROR while building secondary axis
      return status
2204
    # completing axisgroup informations according to their bounds
Thomas Bernard's avatar
Thomas Bernard committed
2205 2206 2207 2208
    status = self.completeAxis()
    if status != 1:
      # ERROR while completing axis
      return status
2209
    # the whole structure is almost completed : axis_groups are defined, as
Thomas Bernard's avatar
Thomas Bernard committed
2210 2211
    # axis_elements with their activities. Just need to create blocks related
    # to the activities (special process only for Calendar mode) with their
2212
    # BlockPosition
Romain Courteaud's avatar
Romain Courteaud committed
2213
    status = self.buildBlocs(basic_structure=basic_structure, REQUEST=REQUEST)
Thomas Bernard's avatar
Thomas Bernard committed
2214 2215 2216 2217 2218
    if status != 1:
      # ERROR while building blocks
      return status
    # everything is fine, returning 'true' flag.
    return 1
2219

Romain Courteaud's avatar
Romain Courteaud committed
2220
  def buildSecondaryAxis(self, basic_structure, field):
2221 2222 2223
    """
    build secondary axis structure
    """
Thomas Bernard's avatar
Thomas Bernard committed
2224
    # defining min and max delimiter number
2225
    delimiter_min_number = field.get_value('delimiter')
2226 2227 2228 2229
    if basic_structure.calendar_mode:
      axis_start = 1
      axis_stop = basic_structure.calendar_range + 1
    else:
Romain Courteaud's avatar
Romain Courteaud committed
2230 2231
      axis_stop = self.secondary_axis.stop
      axis_start = self.secondary_axis.start
2232

2233
    axis_script=getattr(basic_structure.context,
2234
                        field.get_value('sec_axis_script'),None)
Romain Courteaud's avatar
Romain Courteaud committed
2235
    if axis_script is None:
Thomas Bernard's avatar
Thomas Bernard committed
2236
      # ERROR
Romain Courteaud's avatar
Romain Courteaud committed
2237
      # XXX Shouldn't planning box failed in this case, because of bad config ?
Thomas Bernard's avatar
Thomas Bernard committed
2238
      message = 'unable to find secondary axis generation script : "%s" does \
2239
             not exist' % field.get_value('sec_axis_script')
2240
      return [(Message(domain='erp5_ui', message=message, mapping=None))]
Thomas Bernard's avatar
Thomas Bernard committed
2241

Thomas Bernard's avatar
Thomas Bernard committed
2242
    # calling script to get list of delimiters to implement
Thomas Bernard's avatar
Thomas Bernard committed
2243 2244
    # just need to pass start, stop, and the minimum number of delimiter
    # wanted. a structure is returned : list of delimiters, each delimiter
2245
    # defined by a dictionary
Thomas Bernard's avatar
Thomas Bernard committed
2246
    try:
2247 2248 2249 2250 2251
      delimiter_list = axis_script(axis_start=axis_start,
                                 axis_stop=axis_stop,
                                 delimiter_min_number=delimiter_min_number,
                                 form_id = basic_structure.form.id,
                                 selection_name = basic_structure.selection_name)
Thomas Bernard's avatar
Thomas Bernard committed
2252
    except (ArithmeticError, LookupError, AttributeError, TypeError):
Romain Courteaud's avatar
Romain Courteaud committed
2253 2254
      # XXX Seems that too many error are catched
      # XXX Shouldn't planning box failed in this case, because of bad config ?
Thomas Bernard's avatar
Thomas Bernard committed
2255
      message =  'error raised in secondary axis generation script : please \
2256
            check "%s"'% field.get_value('sec_axis_script')
2257
      return [(Message(domain='erp5_ui', message=message,mapping=None))]
2258

Thomas Bernard's avatar
Thomas Bernard committed
2259 2260 2261
    axis_stop = int(axis_stop)
    axis_start = int(axis_start)
    axis_range = axis_stop - axis_start
2262

Thomas Bernard's avatar
Thomas Bernard committed
2263 2264 2265
    # 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
2266
    axis_group_number = 0
Thomas Bernard's avatar
Thomas Bernard committed
2267 2268 2269 2270
    # 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:
2271 2272
      link = None
      if delimiter.has_key('link'): link = delimiter['link'] 
Thomas Bernard's avatar
Thomas Bernard committed
2273
      axis_group = AxisGroup(name='Group_sec_' + str(axis_group_number),
2274
                             title=delimiter['title'], 
2275 2276
			     delimiter_type=delimiter['delimiter_type'],
			     link=link)
2277
      axis_group.tooltip = delimiter['tooltip']
Thomas Bernard's avatar
Thomas Bernard committed
2278
      axis_group.position_secondary.relative_begin = \
2279
                             int(delimiter['relative_position']) - int(axis_start)
Thomas Bernard's avatar
Thomas Bernard committed
2280 2281
      # set defaut stop bound and size
      axis_group.position_secondary.relative_end  = int(axis_stop)
Thomas Bernard's avatar
Thomas Bernard committed
2282
      axis_group.position_secondary.relative_range = \
2283
                             int(axis_stop) - int(delimiter['relative_position'])
Romain Courteaud's avatar
Romain Courteaud committed
2284 2285 2286
      # do not need to update previous delimiter informations for first
      # delimiter
      if delimiter != delimiter_list[0]:
Thomas Bernard's avatar
Thomas Bernard committed
2287 2288
        # actual delimiter info has a previous delimiter
        # update its informations
Thomas Bernard's avatar
Thomas Bernard committed
2289 2290 2291 2292 2293
        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
2294
      # add current axis_group to axis_group list
2295 2296 2297
      self.secondary_axis.axis_group.append(axis_group)
      axis_group_number += 1

Thomas Bernard's avatar
Thomas Bernard committed
2298 2299
    return 1

Rafael Monnerat's avatar
Rafael Monnerat committed
2300
  def completeAxis(self):
2301
    """
Romain Courteaud's avatar
Romain Courteaud committed
2302
    complete axis informations (and more precisely axis position objects) thanks
2303 2304 2305 2306
    to the actual planning structure
    """
    # processing main axis
    for axis_group_element in self.main_axis.axis_group:
Romain Courteaud's avatar
Romain Courteaud committed
2307 2308
      position_main = axis_group_element.position_main
      position_main.absolute_begin = (
Thomas Bernard's avatar
Thomas Bernard committed
2309 2310
              float(axis_group_element.axis_element_start - 1) /
              float(self.main_axis.size))
Romain Courteaud's avatar
Romain Courteaud committed
2311
      position_main.absolute_end = (
Thomas Bernard's avatar
Thomas Bernard committed
2312 2313
              float(axis_group_element.axis_element_stop) /
              float(self.main_axis.size))
Romain Courteaud's avatar
Romain Courteaud committed
2314
      position_main.absolute_range = (
Thomas Bernard's avatar
Thomas Bernard committed
2315 2316
              float(axis_group_element.axis_element_number) /
              float(self.main_axis.size))
Romain Courteaud's avatar
Romain Courteaud committed
2317 2318 2319 2320
      position_secondary = axis_group_element.position_secondary
      position_secondary.absolute_begin = 0
      position_secondary.absolute_end = 1
      position_secondary.absolute_range= 1
2321

Thomas Bernard's avatar
Thomas Bernard committed
2322

2323
    for axis_group_element in self.secondary_axis.axis_group:
Romain Courteaud's avatar
Romain Courteaud committed
2324 2325 2326
      position_secondary = axis_group_element.position_secondary
      position_secondary.absolute_begin = (
           float(position_secondary.relative_begin) /
Thomas Bernard's avatar
Thomas Bernard committed
2327
           self.secondary_axis.axis_size)
Romain Courteaud's avatar
Romain Courteaud committed
2328 2329
      position_secondary.absolute_end = (
           float(position_secondary.relative_end) /
Thomas Bernard's avatar
Thomas Bernard committed
2330
           self.secondary_axis.axis_size)
Romain Courteaud's avatar
Romain Courteaud committed
2331 2332
      position_secondary.absolute_range = (
           float(position_secondary.relative_range) /
Thomas Bernard's avatar
Thomas Bernard committed
2333
           self.secondary_axis.axis_size)
Romain Courteaud's avatar
Romain Courteaud committed
2334 2335 2336 2337
      position_main = axis_group_element.position_main
      position_main.absolute_begin = 0
      position_main.absolute_end = 1
      position_main.absolute_range = 1
Thomas Bernard's avatar
Thomas Bernard committed
2338

Thomas Bernard's avatar
Thomas Bernard committed
2339 2340 2341
    # returning 'true' flag at the end of the process
    return 1

Rafael Monnerat's avatar
Rafael Monnerat committed
2342
  def buildGroups(self, basic_structure=None):
2343
    """
Rafael Monnerat's avatar
Rafael Monnerat committed
2344
    Build groups from activities saved in the structure groups.
2345 2346 2347 2348
    """
    axis_group_number = 0
    axis_element_already_present=0
    for basic_group_object in basic_structure.basic_group_list:
2349 2350 2351 2352
      if basic_structure.calendar_mode == 1:
        secondary_axis_range = basic_structure.calendar_range
      else:
        secondary_axis_range = None
Rafael Monnerat's avatar
Rafael Monnerat committed
2353
      axis_group_number += 1
Romain Courteaud's avatar
Romain Courteaud committed
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
      axis_group = AxisGroup(
                name='Group_%s' % 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=basic_group_object.secondary_axis_start,
                secondary_axis_stop=basic_group_object.secondary_axis_stop,
                secondary_axis_range=secondary_axis_range,
                property_dict=basic_group_object.property_dict)
Rafael Monnerat's avatar
Rafael Monnerat committed
2367

2368
      if self.calendar_view == 0:
2369 2370
        axis_group.position_y = axis_group.position_main
        axis_group.position_x = axis_group.position_secondary
Sebastien Robin's avatar
Sebastien Robin committed
2371
      else:
2372 2373 2374 2375 2376 2377 2378
        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
2379 2380
      axis_group.fixProperties(form_id = basic_structure.form.id,
                               selection_name = basic_structure.selection_name)
2381 2382
      # updating start value
      activity_number = 0
Rafael Monnerat's avatar
Rafael Monnerat committed
2383
      axis_group.axis_element_start = axis_element_already_present + 1
Romain Courteaud's avatar
Romain Courteaud committed
2384
      if basic_group_object.basic_activity_list is not None:
2385 2386
        # need to check if activity list is not empty : possible in case zoom
        # selection is used over the secondary axis
2387 2388 2389 2390 2391 2392
        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
Rafael Monnerat's avatar
Rafael Monnerat committed
2393
            activity=Activity(name='Group_%s_Activity_%s' % (
Romain Courteaud's avatar
Romain Courteaud committed
2394 2395
                                   axis_group_number,
                                   activity_number),
Thomas Bernard's avatar
Thomas Bernard committed
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
                              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,
2410
                              calendar_view=self.calendar_view,
Thomas Bernard's avatar
Thomas Bernard committed
2411
                              property_dict=basic_group_object.property_dict)
2412
            # adding activity to the current group
2413 2414
            axis_group.addActivity(activity, axis_element_already_present,
                                   basic_structure)
2415 2416 2417 2418
        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
2419 2420
          axis_group.addStatActivities(
               basic_activity_list=basic_group_object.basic_activity_list,
2421
               axis_group_number=axis_group_number,
Thomas Bernard's avatar
Thomas Bernard committed
2422
               axis_element_already_present=axis_element_already_present,
2423
               calendar_view=self.calendar_view, primary_axis_block=self,
Thomas Bernard's avatar
Thomas Bernard committed
2424
               property_dict=basic_group_object.property_dict)
Sebastien Robin's avatar
Sebastien Robin committed
2425
      else:
2426 2427 2428
        # 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
2429
        new_axis_element=AxisElement(name='Group_%s_AxisElement_1' %
Romain Courteaud's avatar
Romain Courteaud committed
2430 2431
                                           axis_group_number,
                                 relative_number=1,
Thomas Bernard's avatar
Thomas Bernard committed
2432 2433
                                 absolute_number=axis_group.axis_element_start,
                                 parent_axis_group=axis_group)
2434 2435 2436 2437
        # 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)
2438

Romain Courteaud's avatar
Romain Courteaud committed
2439 2440
      axis_group.axis_element_stop = \
          axis_element_already_present + axis_group.axis_element_number
2441 2442 2443 2444 2445 2446 2447
      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
2448

2449

Romain Courteaud's avatar
Romain Courteaud committed
2450
  def buildBlocs(self, basic_structure=None, REQUEST=None):
2451 2452 2453 2454
    """
    iterate the whole planning structure to get various activities and build
    their related blocs.
    """
Thomas Bernard's avatar
Thomas Bernard committed
2455
    # recover activity and block error lists
Romain Courteaud's avatar
Romain Courteaud committed
2456 2457 2458
    warning_activity_list = REQUEST.get('warning_activity_list', [])
    error_block_list = REQUEST.get('error_block_list', [])
    error_info_dict = REQUEST.get('error_info_dict', {})
2459 2460 2461
    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:
2462
          # test if activity in warning_activity_list
2463 2464 2465 2466
          if activity.name in warning_activity_list:
            warning = 1
          else:
            warning = 0
2467 2468 2469 2470 2471 2472 2473 2474
          if basic_structure.calendar_mode == 1:
            axis_range = axis_group_object.secondary_axis_range
            axis_start = axis_group_object.secondary_axis_start
            axis_stop  = axis_group_object.secondary_axis_stop
          else:
            axis_start = basic_structure.secondary_axis_info['bound_start']
            axis_stop  = basic_structure.secondary_axis_info['bound_stop']
            axis_range = axis_stop - axis_start
Thomas Bernard's avatar
Thomas Bernard committed
2475 2476
          status = activity.addBlocs(main_axis_start=0,
                                main_axis_stop=self.main_axis.size,
2477 2478 2479
                                secondary_axis_start = axis_start,
                                secondary_axis_stop  = axis_stop,
                                secondary_axis_range = axis_range,
Thomas Bernard's avatar
Thomas Bernard committed
2480 2481 2482
                                planning=self, warning=warning,
                                error_block_list=error_block_list,
                                error_info_dict=error_info_dict)
Romain Courteaud's avatar
Romain Courteaud committed
2483 2484
          if status != 1: 
            return status
2485 2486 2487
        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
2488
          status = axis_group_object.updateStatBlocks()
Romain Courteaud's avatar
Romain Courteaud committed
2489 2490
          if status != 1: 
            return status
Thomas Bernard's avatar
Thomas Bernard committed
2491
    # no problem during process, returning 'true' flag
2492
    return 1
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503


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
2504 2505 2506 2507
  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,
Romain Courteaud's avatar
Romain Courteaud committed
2508 2509 2510
                calendar_view=0, property_dict={}):
    # internal activity_name
    self.name = name
Thomas Bernard's avatar
Thomas Bernard committed
2511
    self.id = self.name
Romain Courteaud's avatar
Romain Courteaud committed
2512 2513
    # displayed activity_name
    self.title = title
2514
    self.object = object
Romain Courteaud's avatar
Romain Courteaud committed
2515 2516 2517 2518 2519 2520
    # activity, activity_error, info
    self.types = types
    # color used to render all Blocs
    self.color = color
    # link to the ERP5 object
    self.link = link
2521
    self.height = height
2522
    # self.constraints = constraints
Romain Courteaud's avatar
Romain Courteaud committed
2523 2524 2525 2526 2527 2528
    # contains all the blocs used to render the activity
    self.block_list = None
    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
2529 2530 2531 2532
    self.primary_axis_block = primary_axis_block
    self.block_bounds = None
    self.info = info
    self.parent_axis_element = None
Romain Courteaud's avatar
Romain Courteaud committed
2533
    self.calendar_view = calendar_view
2534
    self.property_dict = property_dict
2535

Thomas Bernard's avatar
Thomas Bernard committed
2536

Romain Courteaud's avatar
Romain Courteaud committed
2537 2538
  # XXX Still used ?
  def get_error_message(self, Error):
Thomas Bernard's avatar
Thomas Bernard committed
2539
    # need to update the error message
2540
    return 'task %s (%s)not validated' % (self.name, self.title)
Thomas Bernard's avatar
Thomas Bernard committed
2541 2542


2543 2544 2545 2546 2547 2548 2549
  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
2550 2551
    if (self.secondary_axis_begin > bound_end) or \
       (self.secondary_axis_end < bound_begin):
2552
      return 0
Thomas Bernard's avatar
Thomas Bernard committed
2553 2554
    elif (self.secondary_axis_begin > bound_begin) and \
         (self.secondary_axis_end < bound_end):
2555
      return 1
2556
    else:
2557 2558
      return 2

Thomas Bernard's avatar
Thomas Bernard committed
2559
  def addBlocs(self, main_axis_start=None, main_axis_stop=None,
2560 2561
               secondary_axis_start=None, secondary_axis_stop=None,
               secondary_axis_range=None, planning=None, warning=0,
Thomas Bernard's avatar
Thomas Bernard committed
2562
               error_block_list=[], error_info_dict={}):
2563 2564 2565 2566 2567
    """
    define list of (begin & stop) values for blocs representing the actual
    activity (can have several blocs if necessary).
    """
    # recover list of bounds
Romain Courteaud's avatar
Romain Courteaud committed
2568 2569
    if self.secondary_axis_start is not None or \
        self.secondary_axis_stop is not None:
2570
      secondary_block_bounds = self.splitActivity()
Thomas Bernard's avatar
Thomas Bernard committed
2571

2572
    else:
2573
       secondary_block_bounds = \
Romain Courteaud's avatar
Romain Courteaud committed
2574
          [[secondary_axis_start, secondary_axis_stop, 1]]
2575 2576 2577

    block_number = 0
    # iterating resulting list
Romain Courteaud's avatar
Romain Courteaud committed
2578
    for (start, stop, zone) in secondary_block_bounds:
2579 2580

      block_number += 1
2581

Thomas Bernard's avatar
Thomas Bernard committed
2582
      block_name = self.name + '_Block_' + str(block_number)
2583
      # create new block instance
2584

Thomas Bernard's avatar
Thomas Bernard committed
2585 2586
      if block_name in error_block_list:
        error = 1
Romain Courteaud's avatar
Romain Courteaud committed
2587
        error_text = error_info_dict[block_name]
Thomas Bernard's avatar
Thomas Bernard committed
2588 2589
      else:
        error = 0
Romain Courteaud's avatar
Romain Courteaud committed
2590
        error_text = ''
2591

Thomas Bernard's avatar
Thomas Bernard committed
2592 2593
      # zone property is used to check if block is an active (main activity
      # block) block or a passive one (just a display block)
2594 2595 2596 2597 2598 2599 2600 2601
      if zone == 1:
        # active
        block_color = self.color
        block_link = self.link
      else:
        # passive
        block_color = '#D1E8FF'
        block_link = ''
Thomas Bernard's avatar
Thomas Bernard committed
2602 2603
      new_block = Bloc(name= block_name,color=block_color,link=block_link,
                       number = block_number,
2604
                       calendar_view=self.calendar_view, parent_activity=self,
Thomas Bernard's avatar
Thomas Bernard committed
2605 2606 2607
                       warning=warning, error=error,
                       error_text=error_text,zone=zone,
                       property_dict=self.property_dict)
2608 2609 2610 2611

      new_block.buildInfoDict(info_dict = self.info)

      # updating secondary_axis block position
Romain Courteaud's avatar
Romain Courteaud committed
2612 2613 2614
      position_secondary = new_block.position_secondary
      if self.secondary_axis_start is not None:
        position_secondary.absolute_begin = start
2615
      else:
Romain Courteaud's avatar
Romain Courteaud committed
2616 2617 2618
        position_secondary.absolute_begin = secondary_axis_start
      if self.secondary_axis_stop is not None:
        position_secondary.absolute_end = stop
2619
      else:
Romain Courteaud's avatar
Romain Courteaud committed
2620 2621 2622
        position_secondary.absolute_end = secondary_axis_stop
      position_secondary.absolute_range = stop - start

2623
      # updating main_axis block position
Romain Courteaud's avatar
Romain Courteaud committed
2624 2625
      position_main = new_block.position_main
      position_main.absolute_begin = \
Thomas Bernard's avatar
Thomas Bernard committed
2626
                      self.parent_axis_element.absolute_number - 1
Romain Courteaud's avatar
Romain Courteaud committed
2627
      position_main.absolute_end = \
Thomas Bernard's avatar
Thomas Bernard committed
2628
                      self.parent_axis_element.absolute_number
Romain Courteaud's avatar
Romain Courteaud committed
2629
      position_main.absolute_range = (
Thomas Bernard's avatar
Thomas Bernard committed
2630 2631
                      new_block.position_main.absolute_end -
                      new_block.position_main.absolute_begin)
2632 2633 2634

      # now absolute positions are updated, and the axis values are known
      # (as parameters), processing relative values
2635
      # => but before updating secondary_axis bounds
Romain Courteaud's avatar
Romain Courteaud committed
2636 2637
      position_secondary.relative_begin = (
          float(position_secondary.absolute_begin -
2638
          secondary_axis_start) / float(secondary_axis_range))
Romain Courteaud's avatar
Romain Courteaud committed
2639 2640
      position_secondary.relative_end = (
          float(position_secondary.absolute_end -
2641
          secondary_axis_start) / float(secondary_axis_range))
Romain Courteaud's avatar
Romain Courteaud committed
2642 2643 2644
      position_secondary.relative_range = (
          position_secondary.relative_end -
          position_secondary.relative_begin)
2645

2646
      # new coordinates are processed from the axis properties instead of the
Romain Courteaud's avatar
Romain Courteaud committed
2647 2648
      position_main.relative_begin = (
          float(position_main.absolute_begin - main_axis_start) /
Thomas Bernard's avatar
Thomas Bernard committed
2649
          float(main_axis_stop - main_axis_start))
Romain Courteaud's avatar
Romain Courteaud committed
2650 2651
      position_main.relative_end = (
          float(position_main.absolute_end - main_axis_start) /
Thomas Bernard's avatar
Thomas Bernard committed
2652
          float(main_axis_stop - main_axis_start))
Romain Courteaud's avatar
Romain Courteaud committed
2653 2654 2655
      position_main.relative_range = (
          position_main.relative_end -
          position_main.relative_begin)
2656

2657
      try:
2658
        self.block_list.append(new_block)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
2659
      except AttributeError:
2660
        # in case this is the first add
2661 2662 2663
        # need to initialize the list
        self.block_list = []
        self.block_list.append(new_block)
Thomas Bernard's avatar
Thomas Bernard committed
2664

2665 2666 2667 2668 2669 2670
      try:
        planning.content.append(new_block)
      except AttributeError:
        planning.content = []
        planning.content.append(new_block)

Thomas Bernard's avatar
Thomas Bernard committed
2671 2672
    return 1

2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
  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.
    """
Romain Courteaud's avatar
Romain Courteaud committed
2683 2684
    # XXX Not implemented yet
    return [(self.secondary_axis_start, self.secondary_axis_stop,1)]
2685

Romain Courteaud's avatar
Romain Courteaud committed
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
    # Draft implementation
#     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
2736 2737


2738 2739 2740 2741

class Bloc:
  """
  structure that will be rendered as a bloc, a task element.
Thomas Bernard's avatar
Thomas Bernard committed
2742 2743 2744 2745
  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).
2746 2747 2748 2749 2750
  Contains Bloc Structure for position informations.
  """

  def __init__ (self, name=None, types=None,
                color=None, info=None, link=None, number=0,
2751
                constraints=None, secondary_start=None, secondary_stop=None,
2752
                calendar_view=0, parent_activity = None, warning=0, error=0,
2753
                error_text='', zone=1, property_dict ={} ):
2754 2755 2756
    """
    creates a Bloc object
    """
Romain Courteaud's avatar
Romain Courteaud committed
2757 2758 2759 2760
    # internal name
    self.name = name
    # activity, activity_error, info
    self.types = types
2761
    self.color = color
Romain Courteaud's avatar
Romain Courteaud committed
2762 2763 2764 2765
    # dict containing text with their position
    self.info = info
    # on clic link
    self.link = link
2766 2767
    self.number = number
    self.title=''
Romain Courteaud's avatar
Romain Courteaud committed
2768 2769 2770
    # 1 = usefull area : 0 = useless one
    # XXX Bad naming, as it's not easy to understand
    self.zone = zone
2771 2772
    self.parent_activity = parent_activity
    self.constraints = constraints
Thomas Bernard's avatar
Thomas Bernard committed
2773 2774 2775 2776
    # setting warning and error flags in case parent_activity or block itself
    # have not been validated
    self.warning = warning
    self.error = error
2777
    self.error_text = error_text
2778 2779 2780 2781 2782
    # 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
2783 2784
    self.position_secondary = \
          Position(absolute_begin=secondary_start,absolute_end=secondary_stop)
2785
    if calendar_view == 0:
2786 2787 2788 2789 2790 2791
      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
2792
    self.property_dict = property_dict # dict containing internal properties
2793

Romain Courteaud's avatar
Romain Courteaud committed
2794
  def buildInfoDict(self, info_dict=[]):
2795
    """
Thomas Bernard's avatar
Thomas Bernard committed
2796 2797
    create Info objects to display text & images, then link them to the
    current object
2798 2799
    """
    # updating title
2800 2801 2802 2803 2804
    if self.property_dict['stat'] == 1:
      self.title = str(self.parent_activity.height)
      self.info = None
    else:
      self.info = {}
Romain Courteaud's avatar
Romain Courteaud committed
2805 2806 2807 2808 2809 2810 2811
      title_list = [
        self.buildInfo(info_dict=info_dict, area='info_topleft'),
        self.buildInfo(info_dict=info_dict, area='info_topright'),
        self.buildInfo(info_dict=info_dict, area='info_center'),
        self.buildInfo(info_dict=info_dict, area='info_botleft'),
        self.buildInfo(info_dict=info_dict, area='info_botright'),
      ]
2812 2813
      self.title = " | ".join(title_list)

2814 2815 2816 2817
    if self.error != 0:
      # field has error
      # adding text_error
      self.info['info_error'] = Info(info=self.error_text, link='')
2818 2819 2820 2821 2822 2823 2824 2825 2826

  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
2827
    else:
2828
      return ''
Sebastien Robin's avatar
Sebastien Robin committed
2829

2830 2831 2832 2833 2834 2835 2836
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
2837 2838 2839
  def __init__ (self, absolute_begin=None, absolute_end=None,
                absolute_range=None, relative_begin=None, relative_end=None,
                relative_range=None):
2840 2841 2842
    # 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
2843
    self.absolute_range = absolute_range
2844
    # relative size in % of the current axis size
2845 2846
    self.relative_begin = relative_begin
    self.relative_end = relative_end
Thomas Bernard's avatar
Thomas Bernard committed
2847
    self.relative_range = relative_range
2848 2849 2850 2851


class Axis:
  """
2852
  Structure holding informations about a specified axis. Can be X or Y axis.
2853 2854 2855 2856 2857 2858
  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
2859 2860
  def __init__(self, title=None, unit=None, types=None, axis_order=None,
               name=None, axis_group=None):
2861 2862 2863 2864 2865 2866
    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.
2867
    # defined to be able to use a generic and recursive method to
2868 2869
    self.axis_group = axis_group
    # specify if axis is primary or secondary.
2870
    # - if primary axis in Planning, zoom selection is applied thanks to
2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888
    # 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.
  """

2889 2890
  def __init__ (self, name='', title='', object = None,
                axis_group_list=None, axis_group_number=0,
Thomas Bernard's avatar
Thomas Bernard committed
2891 2892 2893 2894
                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,
2895
                secondary_axis_range=None, link=None,
Thomas Bernard's avatar
Thomas Bernard committed
2896
                property_dict={}):
2897 2898
    self.name = name
    self.title = title
2899 2900 2901
    # link to fold or unfold report in report-tree mode and also 
    # special link on header columns
    self.link = link
2902
    self.info_title = Info(info=self.title, link=self.link, title=self.title)
Romain Courteaud's avatar
Romain Courteaud committed
2903 2904 2905 2906 2907 2908 2909
    # tooltip used when cursor pass over the group
    self.tooltip = ''
    # ZODB object used to validate modifications
    # XXX May generate conflict if an old version of object is saved
    self.object = object
    # ReportTree
    self.axis_group_list = axis_group_list
2910
    self.axis_group_number = axis_group_number
Romain Courteaud's avatar
Romain Courteaud committed
2911 2912
    # Multitasking
    self.axis_element_list = axis_element_list
2913
    self.axis_element_number = axis_element_number
2914 2915
    self.axis_element_start = None
    self.axis_element_stop = None
Thomas Bernard's avatar
Thomas Bernard committed
2916
    self.delimiter_type = delimiter_type
2917 2918
    # define the kind of separator used in graphic rendering
    # 0 for standard, 1 for bold, 2 for 2x bold
2919 2920 2921 2922 2923
    # 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
Romain Courteaud's avatar
Romain Courteaud committed
2924 2925
    # url to the object
    self.url = url
2926

2927 2928 2929 2930
    self.position_main = Position()
    self.position_secondary = Position()
    self.position_x = None
    self.position_y = None
2931 2932
    # secondary_axis_bounds are specified for each axis_group to handle
    # calendar view.
2933 2934
    self.secondary_axis_start = secondary_axis_start
    self.secondary_axis_stop = secondary_axis_stop
2935 2936 2937 2938 2939
    # secondary_axis_range is used in calendar mode to define range of the
    # largest axis. In case of month calendar, range is 31 so that even
    # tasks on febuary will be positioned over 31 days (and not 28) so that all
    # groups matches the same scale.
    self.secondary_axis_range = secondary_axis_range
2940
    self.property_dict = property_dict
2941 2942


2943
  security = ClassSecurityInfo()
Romain Courteaud's avatar
Romain Courteaud committed
2944

2945
  security.declarePublic('setTitle')
Romain Courteaud's avatar
Romain Courteaud committed
2946
  def setTitle(self, new_title=None):
2947 2948
    self.title = new_title

2949 2950 2951 2952 2953
  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
    """
Romain Courteaud's avatar
Romain Courteaud committed
2954
    info_title = self.info_title
2955 2956
    if self.is_open:
      # current report is unfold, action 'fold'
Romain Courteaud's avatar
Romain Courteaud committed
2957
      info_title.link = 'foldReport?report_url=' + \
Thomas Bernard's avatar
Thomas Bernard committed
2958 2959
                              '%s&form_id=%s&list_selection_name=%s' %(
                              self.url, form_id, selection_name)
Romain Courteaud's avatar
Romain Courteaud committed
2960
      info_title.info = '[-] ' + str(info_title.info)
Sebastien Robin's avatar
Sebastien Robin committed
2961
    else:
2962
      # current report is fold, action 'unfold'
Romain Courteaud's avatar
Romain Courteaud committed
2963
      info_title.link = 'unfoldReport?report_url=' + \
Thomas Bernard's avatar
Thomas Bernard committed
2964 2965
                             '%s&form_id=%s&list_selection_name=%s' %(
                              self.url, form_id, selection_name)
Romain Courteaud's avatar
Romain Courteaud committed
2966
      info_title.info = '[+] ' + str(info_title.info)
2967 2968 2969

    #for i in range(self.depth):
    #  self.title = '| ' + self.title
Romain Courteaud's avatar
Romain Courteaud committed
2970
    info_title.title = info_title.info
2971

Romain Courteaud's avatar
Romain Courteaud committed
2972
    self.tooltip = info_title.info
2973

Sebastien Robin's avatar
Sebastien Robin committed
2974

2975 2976
  def addActivity(self, activity=None, axis_element_already_insered= 0,
                  basic_structure=None):
2977
    """
2978
    Procedure that permits to add activity to the corresponding AxisElement in
2979
    an AxisGroup. This can create new Axis Element in the actual AxisGroup if
2980
    necessary. Permits representation of MULTITASKING
2981 2982 2983 2984
    """

    # declaring variable used to check if activity has already been added
    added = 0
Romain Courteaud's avatar
Romain Courteaud committed
2985 2986
    # XXX To much code inside the try: it's not possible to see
    # which part must not fails...
2987 2988 2989 2990 2991 2992 2993
    try:
      # iterating each axis_element of the axis_group
      for axis_element in self.axis_element_list:
        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:
Thomas Bernard's avatar
Thomas Bernard committed
2994
          if activity_statement.isValidPosition(activity.secondary_axis_begin,
2995
                                      activity.secondary_axis_end) != 0:
2996 2997
            # isValidPosition returned 1 or 2, this means the activity already
            # present does prevent from adding the new activity as there is
2998
            # coverage on the current axis_element.
2999
            # stop iterating actual axis_element and try with the next one
3000 3001 3002 3003
            if activity_statement.object.getUid() not in \
                            basic_structure.sec_layer_uid_list:
              can_add = 0
              break
3004

3005 3006 3007 3008 3009 3010
        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)
3011

3012 3013
          # updating activity properties
          activity.parent_axis_element = axis_element
3014

Thomas Bernard's avatar
Thomas Bernard committed
3015 3016
          # 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
3017
          break
3018

3019
      if not added:
Thomas Bernard's avatar
Thomas Bernard committed
3020 3021
        # all axis_elements of the current group have been tested and no one
        # can contain the new activity.
3022 3023
        self.axis_element_number += 1
        # Need to create a new axis_element to hold the new activity
Romain Courteaud's avatar
Romain Courteaud committed
3024
        new_axis_element=AxisElement(name='Group_%s_AxisElement_%s' % \
Thomas Bernard's avatar
Thomas Bernard committed
3025 3026 3027 3028 3029
                                          (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)
3030

3031 3032 3033
        # add new activity to this brand new axis_element
        new_axis_element.activity_list = []
        new_axis_element.activity_list.append(activity)
3034

3035 3036
        # updating activity properties
        activity.parent_axis_element = new_axis_element
3037

3038 3039 3040
        # register the axis_element to the actual group.
        self.axis_element_list.append(new_axis_element)
    except TypeError:
3041
      # in case axis_element_list is Empty (first activity to the group)
3042 3043
      # Need to create a new axis_element to hold the new activity
      self.axis_element_number += 1
Thomas Bernard's avatar
Thomas Bernard committed
3044 3045 3046 3047 3048 3049 3050 3051
      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
3052

3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
      # 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
3065
  def addStatActivities(self, basic_activity_list=None, axis_group_number=0,
3066
                        axis_element_already_present= 0, calendar_view=0,
Thomas Bernard's avatar
Thomas Bernard committed
3067
                        primary_axis_block=None, property_dict={}):
3068 3069 3070 3071 3072 3073
    """
    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
3074 3075 3076 3077 3078 3079
    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)
3080 3081 3082 3083 3084 3085 3086 3087 3088 3089
    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
3090
      activity = Activity(name= 'Group_%s_Activity_%s'
Thomas Bernard's avatar
Thomas Bernard committed
3091 3092
                               %(str(axis_group_number),
                                 str(activity_number)),
3093 3094 3095 3096
                          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
3097 3098 3099 3100 3101 3102 3103 3104
                          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,
3105 3106 3107
                          height=basic_activity_object.height,
                          primary_axis_block=primary_axis_block,
                          info=basic_activity_object.info_dict,
3108
                          calendar_view=calendar_view,
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
                          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.
Romain Courteaud's avatar
Romain Courteaud committed
3128 3129
    activity_list = self.axis_element_list[0].activity_list
    max_activity_height = max([0]+[x.height for x in activity_list])
3130 3131 3132

    # now max height is known, just need to adapt size of all the blocks
    # composing the activities
Romain Courteaud's avatar
Romain Courteaud committed
3133 3134 3135
    for activity in activity_list:
      height = activity.height
      if height in (0, None):
3136 3137
        relative_size = 1
      else:
Romain Courteaud's avatar
Romain Courteaud committed
3138
        relative_size = float(height) / max_activity_height
3139 3140
      for block in activity.block_list:
        # recovering original values
Romain Courteaud's avatar
Romain Courteaud committed
3141 3142 3143 3144
        position_main = block.position_main
        block_range = position_main.relative_range
        block_begin = position_main.relative_begin
        block_end   = position_main.relative_end
3145 3146 3147 3148 3149
        # calculating values
        final_range = relative_size * block_range
        final_loss = block_range - final_range
        final_begin = block_begin + final_loss
        # saving new values
Romain Courteaud's avatar
Romain Courteaud committed
3150 3151
        position_main.relative_begin = final_begin
        position_main.relative_range = final_range
Thomas Bernard's avatar
Thomas Bernard committed
3152
    return 1
3153

3154 3155 3156 3157 3158 3159 3160 3161 3162 3163
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.
  """
Romain Courteaud's avatar
Romain Courteaud committed
3164 3165
  def __init__ (self, name='', relative_number=0, absolute_number=0,
                activity_list=None, parent_axis_group=None):
3166
    self.name = name
Romain Courteaud's avatar
Romain Courteaud committed
3167 3168 3169 3170
    # relative number / AxisGroup
    self.relative_number = relative_number
    # id in the current rendering
    self.absolute_number = absolute_number
3171 3172 3173 3174 3175 3176 3177 3178
    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
3179 3180
  Class holding all informations to display an info text div inside of a block
  or AxisGroup or whatever
3181 3182 3183 3184 3185 3186 3187 3188 3189
  """
  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):
Romain Courteaud's avatar
Romain Courteaud committed
3190 3191 3192 3193
    """
    Special method allowing to update Info content from an external script
    """
    self.info = info
3194 3195 3196

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

Romain Courteaud's avatar
Romain Courteaud committed
3198

Sebastien Robin's avatar
Sebastien Robin committed
3199
class PlanningBox(ZMIField):
Romain Courteaud's avatar
Romain Courteaud committed
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217
  meta_type = "PlanningBox"
  widget = PlanningBoxWidgetInstance
  validator = PlanningBoxValidatorInstance
  security = ClassSecurityInfo()

  security.declareProtected('Access contents information', 'get_value')
  def get_value(self, id, render_format='html', **kw):
    """
    Surcharge get_value.
    XXX What is the purpose ?
    """
    if id == 'default' and render_format == 'list':
      return self.widget.render(self, self.generate_field_key(), None,
                                kw.get('REQUEST'),
                                render_format=render_format)
    else:
      return ZMIField.get_value(self, id, **kw)

3218 3219 3220
  def render_css(self, REQUEST=None):
    return self.widget.render_css(self, REQUEST)

3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236
# XXX Copy paste from listbox
def getContext(field, REQUEST):
  """
  Return the context of rendering this PlanningBox.
  """
  value = REQUEST.get('here')
  if value is None:
    value = getForm(field).aq_parent
  return value

# XXX Copy paste from listbox
def getForm(field):
  """Return the form which contains the PlanningBox.
  """
  return field.aq_parent

Romain Courteaud's avatar
Romain Courteaud committed
3237 3238 3239 3240 3241 3242 3243
# Allow classes in ZMI
for klass in (PlanningBoxWidget, BasicStructure, BasicGroup,
              BasicActivity, PlanningStructure, Activity,
              Bloc, Position, Axis, AxisGroup, AxisElement,
              Info):
  InitializeClass(klass)
  allow_class(klass)