MovementGroup.py 32.9 KB
Newer Older
Sebastien Robin's avatar
Sebastien Robin committed
1 2
##############################################################################
#
3
# Copyright (c) 2002, 2005 Nexedi SARL and Contributors. All Rights Reserved.
Sebastien Robin's avatar
Sebastien Robin committed
4
#                    Sebastien Robin <seb@nexedi.com>
Sebastien Robin's avatar
Sebastien Robin committed
5
#                    Yoshinori Okuji <yo@nexedi.com>
6
#                    Romain Courteaud <romain@nexedi.com>
Sebastien Robin's avatar
Sebastien Robin committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#
# 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
# Service Company
#
# 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.
#
##############################################################################

"""
Define in this class all classes intended to group every kind of movement
"""

from AccessControl import ClassSecurityInfo
Sebastien Robin's avatar
Sebastien Robin committed
36 37
from Globals import InitializeClass, DTMLFile
from zLOG import LOG
38
from Products.PythonScripts.Utility import allow_class
Sebastien Robin's avatar
Sebastien Robin committed
39

40 41 42
class MovementRejected(Exception) : pass
class FakeMovementError(Exception) : pass

43
class RootMovementGroup:
Sebastien Robin's avatar
Sebastien Robin committed
44

45 46 47 48 49 50 51 52 53 54 55 56 57 58
  def __init__(self, class_list, movement=None, last_line_class_name=None,
               separate_method_name_list=[]):
    self._nested_class = None
    self.setNestedClass(class_list=class_list)
    self._movement_list = []
    self._group_list = []

    self._class_list = class_list
    self._last_line_class_name = last_line_class_name
    self._separate_method_name_list = separate_method_name_list

    if movement is not None :
      self.append(movement)

Sebastien Robin's avatar
Sebastien Robin committed
59 60 61
  def getNestedClass(self, class_list):
    if len(class_list)>0:
      return class_list[0]
Sebastien Robin's avatar
Sebastien Robin committed
62 63
    return None

64
  def setNestedClass(self,class_list):
Sebastien Robin's avatar
Sebastien Robin committed
65 66 67
    """
      This sets an appropriate nested class.
    """
68 69 70 71 72 73 74 75 76 77 78 79 80 81
    self._nested_class = self.getNestedClass(class_list)

  def _appendGroup(self, movement):
    nested_instance = self._nested_class(
                    movement=movement,
                    class_list=self._class_list[1:],
                    last_line_class_name=self._last_line_class_name,
                    separate_method_name_list=self._separate_method_name_list)
    self._group_list.append(nested_instance)

  def append(self, movement):
    is_movement_in_group = 0
    for group in self.getGroupList():
      if group.test(movement) :
82 83 84 85
        try:
          group.append(movement)
          is_movement_in_group = 1
          break
86
        except MovementRejected:
87 88 89
          if self.__class__.__name__ == self._last_line_class_name:
            pass
          else:
90
            raise MovementRejected
91 92 93 94 95 96 97 98 99 100 101
    if is_movement_in_group == 0 :
      if self._nested_class is not None:
        self._appendGroup(movement)
      else:
        # We are on a node group
        movement_list = self.getMovementList()
        if len(movement_list) > 0:
          # We have a conflict here, because it is forbidden to have 
          # 2 movements on the same node group
          tmp_result = self._separate(movement)
          self._movement_list, split_movement_list = tmp_result
102 103 104
          if split_movement_list != [None]:
            # We rejected a movement, we need to put it on another line
            # Or to create a new one
105
            raise MovementRejected
106 107 108
        else:
          # No movement on this node, we can add it
          self._movement_list.append(movement)
Sebastien Robin's avatar
Sebastien Robin committed
109

110
  def getGroupList(self):
111
    return self._group_list
Sebastien Robin's avatar
Sebastien Robin committed
112

113 114 115 116 117
  def setGroupEdit(self, **kw):
    """
      Store properties for the futur created object 
    """
    self._property_dict = kw
Sebastien Robin's avatar
Sebastien Robin committed
118

119 120 121 122 123 124 125 126 127 128 129 130 131
  def getGroupEditDict(self):
    """
      Get property dict for the futur created object 
    """
    if hasattr(self, '_property_dict'):
      return self._property_dict
    else:
      return {}

  def getMovementList(self):
    """
      Return movement list in the current group
    """
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    movement_list = []
    group_list = self.getGroupList()
    if len(group_list) == 0:
      return self._movement_list
    else:
      for group in group_list:
        movement_list.extend(group.getMovementList())
      return movement_list

  def _separate(self, movement):
    """
      Separate 2 movements on a node group
    """
    movement_list = self.getMovementList()
    if len(movement_list) != 1:
147
      raise ValueError, "Can separate only 2 movements"
148 149 150 151 152 153
    else:
      old_movement = self.getMovementList()[0]

      new_stored_movement = old_movement
      added_movement = movement
      rejected_movement = None
Sebastien Robin's avatar
Sebastien Robin committed
154

155 156 157 158 159
      for separate_method_name in self._separate_method_name_list:
        method = getattr(self, separate_method_name)

        new_stored_movement,\
        rejected_movement= method(new_stored_movement,
160 161 162 163 164 165
                                  added_movement=added_movement)
        if rejected_movement is None:
          added_movement = None
        else:
          break
        
166 167 168 169 170 171
      return [new_stored_movement], [rejected_movement]

  ########################################################
  # Separate methods
  ########################################################
  def _genericCalculation(self, movement, added_movement=None):
172
    """ Generic creation of FakeMovement
173 174 175 176 177 178 179 180 181
    """
    if added_movement is not None:
      # Create a fake movement
      new_movement = FakeMovement([movement, added_movement])
    else:
      new_movement = movement
    return new_movement

  def calculateAveragePrice(self, movement, added_movement=None):
182
    """ Create a new movement with a average price
183
    """
184
    new_movement = self._genericCalculation(movement,
185 186 187 188
                                            added_movement=added_movement)
    new_movement.setPriceMethod("getAveragePrice")
    return new_movement, None

189
  def calculateSeparatePrice(self, movement, added_movement=None):
190
    """ Separate movements which have different price
191
    """
192 193 194 195
    if added_movement is not None and \
            movement.getPrice() == added_movement.getPrice() :
      new_movement = self._genericCalculation(movement,
                                              added_movement=added_movement)
196 197
      new_movement.setPriceMethod('getAveragePrice')
      new_movement.setQuantityMethod("getAddQuantity")
198
      return new_movement, None
199 200
    return movement, added_movement

201
  def calculateAddQuantity(self, movement, added_movement=None):
202
    """ Create a new movement with the sum of quantity
203
    """
204
    new_movement = self._genericCalculation(movement,
205 206 207
                                            added_movement=added_movement)
    new_movement.setQuantityMethod("getAddQuantity")
    return new_movement, None
Sebastien Robin's avatar
Sebastien Robin committed
208

209 210 211
allow_class(RootMovementGroup)

class OrderMovementGroup(RootMovementGroup):
212
  """ Group movements that comes from the same Order. """
213 214
  def __init__(self,movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
215 216 217
    if hasattr(movement, 'getRootAppliedRule'):
      # This is a simulation movement
      order_value = movement.getRootAppliedRule().getCausalityValue(
218
                              portal_type=movement.getPortalOrderTypeList())
Sebastien Robin's avatar
Sebastien Robin committed
219 220 221 222
      if order_value is None:
        # In some cases (ex. DeliveryRule), there is no order
        # we may consider a PackingList as the order in the OrderGroup
        order_value = movement.getRootAppliedRule().getCausalityValue(
223
                        portal_type=movement.getPortalDeliveryTypeList())
Sebastien Robin's avatar
Sebastien Robin committed
224 225 226 227 228 229 230 231 232 233
    else:
      # This is a temp movement
      order_value = None
    if order_value is None:
      order_relative_url = None
    else:
      # get the id of the enclosing delivery
      # for this cell or line
      order_relative_url = order_value.getRelativeUrl()
    self.order = order_relative_url
234
    self.setGroupEdit(causality_value=order_value)
Sebastien Robin's avatar
Sebastien Robin committed
235 236 237 238

  def test(self,movement):
    if hasattr(movement, 'getRootAppliedRule'):
      order_value = movement.getRootAppliedRule().getCausalityValue(
239
                        portal_type=movement.getPortalOrderTypeList())
Sebastien Robin's avatar
Sebastien Robin committed
240 241 242 243 244

      if order_value is None:
        # In some cases (ex. DeliveryRule), there is no order
        # we may consider a PackingList as the order in the OrderGroup
        order_value = movement.getRootAppliedRule().getCausalityValue(
245
                        portal_type=movement.getPortalDeliveryTypeList())
Sebastien Robin's avatar
Sebastien Robin committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259
    else:
      # This is a temp movement
      order_value = None
    if order_value is None:
      order_relative_url = None
    else:
      # get the id of the enclosing delivery
      # for this cell or line
      order_relative_url = order_value.getRelativeUrl()
    if order_relative_url == self.order:
      return 1
    else :
      return 0

260
allow_class(OrderMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
261 262


263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
class CausalityMovementGroup(RootMovementGroup):
  """ Groups movement that comes from simulation movement that shares the
  same explanation relation. For example, it groups in an Invoice
  movements from the same Packing List. """
  
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    explanation_relative_url = self._getExplanationRelativeUrl(movement)
    self.explanation = explanation_relative_url

  def _getExplanationRelativeUrl(self, movement):
    """ Get the order value for a movement """
    if hasattr(movement, 'getParent'):
      # This is a simulation movement
      if movement.getParent() != movement.getRootAppliedRule() :
        # get the explanation of parent movement if we have not been
        # created by the root applied rule.
        movement = movement.getParent().getParent()
      explanation_value = movement.getExplanationValue()
      if explanation_value is None:
        raise ValueError, 'No explanation for movement %s' % movement.getPath()
    else:
      # This is a temp movement
      explanation_value = None
    if explanation_value is None:
      explanation_relative_url = None
    else:
      # get the enclosing delivery for this cell or line
      if hasattr(explanation_value, 'getExplanationValue') :
        explanation_value = explanation_value.getExplanationValue()
        
      explanation_relative_url = explanation_value.getRelativeUrl()
    return explanation_relative_url
    
  def test(self,movement):
    return self._getExplanationRelativeUrl(movement) == self.explanation
    
allow_class(CausalityMovementGroup)

302 303 304 305 306 307 308 309 310
class RootAppliedRuleCausalityMovementGroup(RootMovementGroup):
  """ Groups movement that comes from simulation movement that shares the
  same explanation relation. For example, it groups in an Invoice
  movements from the same Packing List. """
  
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    explanation_relative_url = self._getExplanationRelativeUrl(movement)
    self.explanation = explanation_relative_url
311 312 313 314
    explanation_value = movement.getPortalObject().restrictedTraverse(explanation_relative_url)
    self.setGroupEdit(
      root_causality_value_list = [explanation_value]
    )
315 316 317 318 319 320 321 322 323 324 325 326 327

  def _getExplanationRelativeUrl(self, movement):
    """ Get the order value for a movement """
    root_applied_rule = movement.getRootAppliedRule()
    explanation_value = root_applied_rule.getCausalityValue()
    explanation_relative_url = None
    if explanation_value is not None:
      explanation_relative_url = explanation_value.getRelativeUrl()
    return explanation_relative_url
    
  def test(self,movement):
    return self._getExplanationRelativeUrl(movement) == self.explanation
    
Sebastien Robin's avatar
Sebastien Robin committed
328
allow_class(RootAppliedRuleCausalityMovementGroup)
329

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
# Again add a strange movement group, it was first created for building
# Sale invoices transactions lines. We need to put accounting lines
# in the same invoices than invoice lines.
class ParentExplanationMovementGroup(RootMovementGroup):
  """ Groups movement that comes from simulation movement that shares the
  same explanation relation. For example, it groups in an Invoice
  movements from the same Packing List. """
  
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    explanation_value = self._getParentExplanationValue(movement)
    self.explanation_value = explanation_value
    self.setGroupEdit(
      parent_explanation_value = explanation_value
    )

  def _getParentExplanationValue(self, movement):
    """ Get the order value for a movement """
    return movement.getParentValue().getExplanationValue()
    
  def test(self,movement):
    return self._getParentExplanationValue(movement) == self.explanation_value
    
allow_class(ParentExplanationMovementGroup)

355 356 357
class PathMovementGroup(RootMovementGroup):
  """ Group movements that have the same source and the same destination."""
  def __init__(self, movement, **kw):
358
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
359 360
    self.source = movement.getSource()
    self.destination = movement.getDestination()
361

362 363 364 365
    self.setGroupEdit(
        source_value=movement.getSourceValue(),
        destination_value=movement.getDestinationValue(),
    )
Sebastien Robin's avatar
Sebastien Robin committed
366

367 368 369
  def test(self, movement):
    return movement.getSource() == self.source and \
      movement.getDestination() == self.destination
Sebastien Robin's avatar
Sebastien Robin committed
370

371
allow_class(PathMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
372

Sebastien Robin's avatar
Sebastien Robin committed
373 374 375 376 377 378 379 380 381 382 383
class ColourMovementGroup(RootMovementGroup):
  """ Group movements that have the same source and the same destination."""
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    self.colour = movement.getColour()

  def test(self, movement):
    return movement.getColour() == self.colour

allow_class(ColourMovementGroup)

384
class SectionPathMovementGroup(RootMovementGroup):
385 386 387
  """ Groups movement that have the same source_section and
  destination_section."""
  def __init__(self, movement, **kw):
388 389 390 391 392 393 394 395 396
    RootMovementGroup.__init__(self, movement=movement, **kw)
    self.source_section = movement.getSourceSection()
    self.destination_section = movement.getDestinationSection()
    self.setGroupEdit(
        source_section = movement.getSourceSection(),
        destination_section = movement.getDestinationSection(),
    )

  def test(self, movement):
397 398
    return movement.getSourceSection() == self.source_section and \
       movement.getDestinationSection() == self.destination_section
399 400 401

allow_class(SectionPathMovementGroup)

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
class TradePathMovementGroup(RootMovementGroup):
  """
  Group movements that have the same source_trade and the same
  destination_trade.
  """
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    self.source_trade = movement.getSourceTrade()
    self.destination_trade = movement.getDestinationTrade()

    self.setGroupEdit(
        source_trade_value=movement.getSourceTradeValue(),
        destination_trade_value=movement.getDestinationTradeValue(),
    )

  def test(self, movement):
    return movement.getSourceTrade() == self.source_trade and \
      movement.getDestinationTrade() == self.destination_trade

allow_class(TradePathMovementGroup)

423 424 425 426 427
# XXX Naming issue ?
class QuantitySignMovementGroup(RootMovementGroup):
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    quantity = movement.getQuantity()
428 429 430
    if quantity == 0:
      self.sign = 0
    elif quantity > 0:
431 432 433 434 435 436 437
      self.sign = 1
    else:
      self.sign = -1
    self.setGroupEdit(quantity_sign=self.sign)

  def test(self, movement):
    quantity = movement.getQuantity()
438 439 440
    if quantity == 0 or self.sign == 0 :
      return 1
    if quantity > 0:
441 442 443
      sign = 1
    else:
      sign = -1
444
    return self.sign == sign
445 446 447

allow_class(QuantitySignMovementGroup)

448
class DateMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
449

Sebastien Robin's avatar
Sebastien Robin committed
450
  def __init__(self,movement,**kw):
451
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
452 453
    self.start_date = movement.getStartDate()
    self.stop_date = movement.getStopDate()
454 455 456 457
    self.setGroupEdit(
        start_date=movement.getStartDate(),
        stop_date=movement.getStopDate()
    )
Sebastien Robin's avatar
Sebastien Robin committed
458 459 460 461 462 463 464 465

  def test(self,movement):
    if movement.getStartDate() == self.start_date and \
      movement.getStopDate() == self.stop_date :
      return 1
    else :
      return 0

466
allow_class(DateMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
467

468
class CriterionMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
469

Sebastien Robin's avatar
Sebastien Robin committed
470
  def __init__(self,movement,**kw):
471
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
472 473 474 475 476 477 478 479 480 481 482 483 484
    if hasattr(movement, 'getGroupCriterion'):
      self.criterion = movement.getGroupCriterion()
    else:
      self.criterion = None

  def test(self,movement):
    # we must have the same criterion
    if hasattr(movement, 'getGroupCriterion'):
      criterion = movement.getGroupCriterion()
    else:
      criterion = None
    return self.criterion == criterion

485
allow_class(CriterionMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
486

487
class ResourceMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
488

Sebastien Robin's avatar
Sebastien Robin committed
489
  def __init__(self,movement,**kw):
490
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
491
    self.resource = movement.getResource()
492
    self.setGroupEdit(
493
        resource_value=movement.getResourceValue()
494
    )
Sebastien Robin's avatar
Sebastien Robin committed
495 496 497 498 499 500 501

  def test(self,movement):
    if movement.getResource() == self.resource :
      return 1
    else :
      return 0

502
allow_class(ResourceMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
503

504
class BaseVariantMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
505

Sebastien Robin's avatar
Sebastien Robin committed
506
  def __init__(self,movement,**kw):
507
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
508 509
    self.base_category_list = movement.getVariationBaseCategoryList()
    if self.base_category_list is None:
510
      #LOG('BaseVariantGroup __init__', 0, 'movement = %s, movement.showDict() = %s' % (repr(movement), repr(movement.showDict())))
Sebastien Robin's avatar
Sebastien Robin committed
511 512 513 514 515 516 517 518
      self.base_category_list = []

  def test(self,movement):
    # we must have the same number of categories
    categories_identity = 0
    #LOG('BaseVariantGroup', 0, 'self.base_category_list = %s, movement = %s, movement.getVariationBaseCategoryList() = %s' % (repr(self.base_category_list), repr(movement), repr(movement.getVariationBaseCategoryList())))
    movement_base_category_list = movement.getVariationBaseCategoryList()
    if movement_base_category_list is None:
519
      #LOG('BaseVariantGroup test', 0, 'movement = %s, movement.showDict() = %s' % (repr(movement), repr(movement.showDict())))
Sebastien Robin's avatar
Sebastien Robin committed
520 521 522 523 524 525 526 527 528
      movement_base_category_list = []
    if len(self.base_category_list) == len(movement_base_category_list):
      for category in movement_base_category_list:
        if not category in self.base_category_list :
          break
      else :
        categories_identity = 1
    return categories_identity

529
allow_class(BaseVariantMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
530

531
class VariantMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
532

Sebastien Robin's avatar
Sebastien Robin committed
533
  def __init__(self,movement,**kw):
534
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
535 536
    self.category_list = movement.getVariationCategoryList()
    if self.category_list is None:
537
      #LOG('VariantGroup __init__', 0, 'movement = %s, movement.showDict() = %s' % (repr(movement), repr(movement.showDict())))
Sebastien Robin's avatar
Sebastien Robin committed
538
      self.category_list = []
539 540 541
    self.setGroupEdit(
        variation_category_list=self.category_list
    )
Sebastien Robin's avatar
Sebastien Robin committed
542 543 544 545 546 547

  def test(self,movement):
    # we must have the same number of categories
    categories_identity = 0
    movement_category_list = movement.getVariationCategoryList()
    if movement_category_list is None:
548
      #LOG('VariantGroup test', 0, 'movement = %s, movement.showDict() = %s' % (repr(movement), repr(movement.showDict())))
Sebastien Robin's avatar
Sebastien Robin committed
549 550 551 552 553 554 555 556
      movement_category_list = []
    if len(self.category_list) == len(movement_category_list):
      for category in movement_category_list:
        if not category in self.category_list :
          break
      else :
        categories_identity = 1
    return categories_identity
Sebastien Robin's avatar
Sebastien Robin committed
557

558
allow_class(VariantMovementGroup)
559

Jean-Paul Smets's avatar
Jean-Paul Smets committed
560
from copy import copy
561

Jean-Paul Smets's avatar
Jean-Paul Smets committed
562 563 564 565
class CategoryMovementGroup(RootMovementGroup):  
  """
    This seems to be a useless class
  """
566
  def __init__(self,movement,**kw):
567
    RootMovementGroup.__init__(self, movement=movement, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
568
    self.category_list = list(movement.getCategoryList())
569 570
    if self.category_list is None:
      self.category_list = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
571
    self.category_list.sort()
572 573 574

  def test(self,movement):
    # we must have the same number of categories
Jean-Paul Smets's avatar
Jean-Paul Smets committed
575
    movement_category_list = list(movement.getCategoryList())
576 577
    if movement_category_list is None:
      movement_category_list = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
578 579 580 581
    movement_category_list.sort()
    if self.category_list == movement_category_list:
      return 1
    return 0
582 583

allow_class(CategoryMovementGroup)
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
class OptionMovementGroup(RootMovementGroup):

  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    option_base_category_list = movement.getPortalOptionBaseCategoryList()
    self.option_category_list = movement.getVariationCategoryList(base_category_list=option_base_category_list)
    #LOG('OptionMovementGroup.__init__, option_category_list',0,self.option_category_list)
    if self.option_category_list is None:
      self.option_category_list = []
    # XXX This is very bad, but no choice today.
    self.setGroupEdit(industrial_phase_list = self.option_category_list)

  def test(self,movement):
    # we must have the same number of categories
    categories_identity = 0
    option_base_category_list = movement.getPortalOptionBaseCategoryList()
    movement_option_category_list = movement.getVariationCategoryList(base_category_list=option_base_category_list)
    #LOG('OptionMovementGroup.test, option_category_list',0,movement_option_category_list)
    if movement_option_category_list is None:
      movement_option_category_list = []
    if len(self.option_category_list) == len(movement_option_category_list):
      categories_identity = 1
      for category in movement_option_category_list:
        if not category in self.option_category_list :
          categories_identity = 0
          break
    return categories_identity

allow_class(OptionMovementGroup)

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
class VariationPropertyMovementGroup(RootMovementGroup):
  """
  Compare variation property dict of movement.
  """

  def __init__(self, movement, **kw):
    """
    Store variation property dict of the first movement.
    """
    RootMovementGroup.__init__(self, movement=movement, **kw)
    self.property_dict = movement.getVariationPropertyDict()
    self.setGroupEdit(
      variation_property_dict = self.property_dict
    )

  def test(self, movement):
    """
    Check if the movement can be inserted in the group.
    """
    identity = 0
    variation_property_dict = movement.getVariationPropertyDict()
    variation_property_list = variation_property_dict.keys()
    if len(variation_property_list) == len(self.property_dict):
      # Same number of property. Good point.
      for variation_property in variation_property_list:
        try:
          if variation_property_dict[variation_property] != \
Romain Courteaud's avatar
Romain Courteaud committed
642
              self.property_dict[variation_property]:
643 644 645 646 647 648 649 650 651 652 653
            # Value is not the same for both movements
            break
        except KeyError:
          # Key is not common to both movements
          break
      else:
        identity = 1
    return identity

allow_class(VariationPropertyMovementGroup)

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
class FakeMovement:
  """
    A fake movement which simulate some methods on a movement needed 
    by DeliveryBuilder.
    It contents a list a real ERP5 Movement and can modify them.
  """
  def __init__(self, movement_list):
    """
      Create a fake movement and store the list of real movement
    """
    self.__price_method = None
    self.__quantity_method = None
    self.__movement_list = []
    for movement in movement_list:
      self.append(movement)
    # This object must not be use when there is not 2 or more movements
    if len(movement_list) < 2:
671
      raise ValueError, "FakeMovement used where it does not."
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
    # All movements must share the same getVariationCategoryList
    # So, verify and raise a error if not
    # But, if DeliveryBuilder is well configured, this can never append ;)
    reference_variation_category_list = movement_list[0].\
                                           getVariationCategoryList()
    error_raising_needed = 0
    for movement in movement_list[1:]:
      variation_category_list = movement.getVariationCategoryList()
      if len(variation_category_list) !=\
         len(reference_variation_category_list):
        error_raising_needed = 1
        break

      for variation_category in variation_category_list:
        if variation_category not in reference_variation_category_list:
          error_raising_needed = 1
          break
    
    if error_raising_needed == 1:
691
      raise ValueError, "FakeMovement not well used."
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709

  def append(self, movement):
    """
      Append movement to the movement list
    """
    if movement.__class__.__name__ == "FakeMovement":
      self.__movement_list.extend(movement.getMovementList())
      self.__price_method = movement.__price_method
      self.__quantity_method = movement.__quantity_method
    else:
      self.__movement_list.append(movement)

  def getMovementList(self):
    """
      Return content movement list
    """
    return self.__movement_list
    
710
  def setDeliveryValue(self, object):
711 712 713 714
    """
      Set Delivery value for each movement
    """
    for movement in self.__movement_list:
715 716
      movement.edit(delivery_value=object)

717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
  def getDeliveryValue(self):
    """
      Only use to test if all movement are not linked (if user did not
      configure DeliveryBuilder well...).
      Be careful.
    """
    result = None
    for movement in self.__movement_list:
      mvt_delivery = movement.getDeliveryValue()
      if mvt_delivery is not None:
        result = mvt_delivery
        break
    return result

  def getRelativeUrl(self):
    """
      Only use to return a short description of one movement 
      (if user did not configure DeliveryBuilder well...).
      Be careful.
    """
    return self.__movement_list[0].getRelativeUrl()

739 740 741 742 743 744 745 746
  def setDeliveryRatio(self, delivery_ratio):
    """
      Calculate delivery_ratio
    """
    total_quantity = 0
    for movement in self.__movement_list:
      total_quantity += movement.getQuantity()

747 748 749
    if total_quantity != 0:
      for movement in self.__movement_list:
        quantity = movement.getQuantity()
750
        movement.edit(delivery_ratio=quantity*delivery_ratio/total_quantity)
751 752 753 754
    else:
      # Distribute equally ratio to all movement
      mvt_ratio = 1 / len(self.__movement_list)
      for movement in self.__movement_list:
755
        movement.edit(delivery_ratio=mvt_ratio)
756 757 758 759 760
      
  def getPrice(self):
    """
      Return calculated price
    """
761 762 763 764
    if self.__price_method is not None:
      return getattr(self, self.__price_method)()
    else:
      return None
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
  
  def setPriceMethod(self, method):
    """
      Set the price method
    """
    self.__price_method = method

  def getQuantity(self):
    """
      Return calculated quantity
    """
    return getattr(self, self.__quantity_method)()
 
  def setQuantityMethod(self, method):
    """
      Set the quantity method
    """
    self.__quantity_method = method

  def getAveragePrice(self):
    """
      Return average price 
    """
    return (self.getAddPrice() / self.getAddQuantity())

  def getAddQuantity(self):
    """
      Return the total quantity
    """
    total_quantity = 0
    for movement in self.getMovementList():
796 797 798
      quantity = movement.getQuantity()
      if quantity != None:
        total_quantity += quantity
799 800 801 802 803 804 805 806
    return total_quantity

  def getAddPrice(self):
    """
      Return total price 
    """
    total_price = 0
    for movement in self.getMovementList():
807 808 809 810
      quantity = movement.getQuantity()
      price = movement.getPrice()
      if (quantity is not None) and (price is not None):
        total_price += (quantity * price)
811 812 813 814 815 816 817 818 819
    return total_price

  def recursiveReindexObject(self):
    """
      Reindex all movements
    """
    for movement in self.getMovementList():
      movement.recursiveReindexObject()

820 821 822 823 824 825 826
  def immediateReindexObject(self):
    """
      Reindex immediately all movements
    """
    for movement in self.getMovementList():
      movement.immediateReindexObject()

827 828 829 830 831 832 833 834 835
  def getPath(self):
    """
      Return the movements path list
    """
    path_list = []
    for movement in self.getMovementList():
      path_list.append(movement.getPath())
    return path_list

Sebastien Robin's avatar
Sebastien Robin committed
836
  def getVariationBaseCategoryList(self, omit_option_base_category=0,**kw):
837 838 839 840
    """
      Return variation base category list
      Which must be shared by all movement
    """
841
    return self.__movement_list[0].getVariationBaseCategoryList(
Sebastien Robin's avatar
Sebastien Robin committed
842
                      omit_option_base_category=omit_option_base_category,**kw)
843

Sebastien Robin's avatar
Sebastien Robin committed
844
  def getVariationCategoryList(self, omit_option_base_category=0,**kw):
845 846 847 848
    """
      Return variation base category list
      Which must be shared by all movement
    """
849
    return self.__movement_list[0].getVariationCategoryList(
Sebastien Robin's avatar
Sebastien Robin committed
850
                      omit_option_base_category=omit_option_base_category,**kw)
851 852 853

  def edit(self, **kw):
    """
854 855
      Written in order to call edit in delivery builder,
      as it is the generic way to modify object.
856
    """
857 858 859 860 861 862
    for key in kw.keys():
      if key == 'delivery_ratio':
        self.setDeliveryRatio(kw[key])
      elif key == 'delivery_value':
        self.setDeliveryValue(kw[key])
      else:
863
        raise FakeMovementError,\
864
              "Could not call edit on Fakeovement with parameters: %r" % key
865

Jean-Paul Smets's avatar
Jean-Paul Smets committed
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
class TitleMovementGroup(RootMovementGroup):

  def getTitle(self,movement):
    order_value = movement.getOrderValue()
    title = ''
    if order_value is not None:
      if "Line" in order_value.getPortalType():
        title = order_value.getTitle()
      elif "Cell" in order_value.getPortalType():
        title = order_value.getParentValue().getTitle()
    return title

  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    title = self.getTitle(movement)
    self.title = title
    self.setGroupEdit(
        title=title
    )

  def test(self,movement):
    if self.getTitle(movement) == self.title :
      return 1
    else :
      return 0

892 893 894 895 896
# XXX This should not be here
# I (seb) have commited this because movement groups are not
# yet configurable through the zope web interface
class IntIndexMovementGroup(RootMovementGroup):

Sebastien Robin's avatar
Sebastien Robin committed
897 898 899
  def getIntIndex(self,movement):
    order_value = movement.getOrderValue()
    int_index = 0
900
    if order_value is not None:
Sebastien Robin's avatar
Sebastien Robin committed
901 902 903 904 905 906
      if "Line" in order_value.getPortalType():
        int_index = order_value.getIntIndex()
      elif "Cell" in order_value.getPortalType():
        int_index = order_value.getParentValue().getIntIndex()
    return int_index

907 908
  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
909 910
    int_index = self.getIntIndex(movement)
    self.int_index = int_index
911
    self.setGroupEdit(
Sebastien Robin's avatar
Sebastien Robin committed
912
        int_index=int_index
913 914 915
    )

  def test(self,movement):
Sebastien Robin's avatar
Sebastien Robin committed
916
    if self.getIntIndex(movement) == self.int_index :
917 918 919 920 921
      return 1
    else :
      return 0

allow_class(IntIndexMovementGroup)
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946

# XXX This should not be here
# I (seb) have commited this because movement groups are not
# yet configurable through the zope web interface
class DecisionMovementGroup(RootMovementGroup):

  def getDecision(self,movement):
    return movement.getDecision()

  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    decision = self.getDecision(movement)
    self.decision = decision
    self.setGroupEdit(
        decision=decision
    )

  def test(self,movement):
    if self.getDecision(movement) == self.decision :
      return 1
    else :
      return 0

allow_class(DecisionMovementGroup)

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
# XXX This should not be here
# I (seb) have commited this because movement groups are not
# yet configurable through the zope web interface
class BrandMovementGroup(RootMovementGroup):

  def getBrand(self,movement):
    return movement.getBrand()

  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    brand = self.getBrand(movement)
    self.brand = brand
    self.setGroupEdit(
        brand=brand
    )

  def test(self,movement):
    if self.getBrand(movement) == self.brand :
      return 1
    else :
      return 0

allow_class(BrandMovementGroup)

class AggregateMovementGroup(RootMovementGroup):

  def getAggregateList(self,movement):
    aggregate_list = movement.getAggregateList()
    aggregate_list.sort()
    return aggregate_list

  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    aggregate = self.getAggregateList(movement)
    self.aggregate = aggregate
    self.setGroupEdit(
        aggregate=aggregate
    )

  def test(self,movement):
987
    if self.getAggregateList(movement) == self.aggregate :
988 989 990 991
      return 1
    else :
      return 0

992
allow_class(AggregateMovementGroup)
993

994 995 996 997 998 999 1000 1001
class SplitMovementGroup(RootMovementGroup):
  def __init__(self,movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)

  def test(self, movement):
    return 0

allow_class(AggregateMovementGroup)