MovementGroup.py 35.2 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
#
# 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.
#
##############################################################################

"""
32
Define in this file all classes intended to group every kind of movement
Sebastien Robin's avatar
Sebastien Robin committed
33 34
"""

35
from zLOG import LOG, DEBUG
36
from Products.PythonScripts.Utility import allow_class
Sebastien Robin's avatar
Sebastien Robin committed
37

38 39
class MovementRejected(Exception) : pass
class FakeMovementError(Exception) : pass
Romain Courteaud's avatar
Romain Courteaud committed
40
class MovementGroupError(Exception) : pass
41

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

44 45 46 47 48 49 50 51 52 53 54 55 56 57
  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
58 59 60
  def getNestedClass(self, class_list):
    if len(class_list)>0:
      return class_list[0]
Sebastien Robin's avatar
Sebastien Robin committed
61 62
    return None

63
  def setNestedClass(self,class_list):
Sebastien Robin's avatar
Sebastien Robin committed
64 65 66
    """
      This sets an appropriate nested class.
    """
67 68 69 70 71 72 73 74 75 76 77 78 79 80
    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) :
81 82 83 84
        try:
          group.append(movement)
          is_movement_in_group = 1
          break
85
        except MovementRejected:
86 87 88
          if self.__class__.__name__ == self._last_line_class_name:
            pass
          else:
89
            raise MovementRejected
90 91 92 93 94 95 96 97 98 99 100
    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
101 102 103
          if split_movement_list != [None]:
            # We rejected a movement, we need to put it on another line
            # Or to create a new one
104
            raise MovementRejected
105 106 107
        else:
          # No movement on this node, we can add it
          self._movement_list.append(movement)
Sebastien Robin's avatar
Sebastien Robin committed
108

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

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

Romain Courteaud's avatar
Romain Courteaud committed
118 119 120 121 122 123
  def updateGroupEdit(self, **kw):
    """
      Update properties for the futur created object 
    """
    self._property_dict.update(kw)

124 125 126 127
  def getGroupEditDict(self):
    """
      Get property dict for the futur created object 
    """
128
    return getattr(self, '_property_dict', {})
129 130 131 132 133

  def getMovementList(self):
    """
      Return movement list in the current group
    """
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    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:
149
      raise ValueError, "Can separate only 2 movements"
150 151 152 153 154 155
    else:
      old_movement = self.getMovementList()[0]

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

157 158 159 160 161
      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,
162 163 164 165 166 167
                                  added_movement=added_movement)
        if rejected_movement is None:
          added_movement = None
        else:
          break
        
168 169 170 171 172 173
      return [new_stored_movement], [rejected_movement]

  ########################################################
  # Separate methods
  ########################################################
  def _genericCalculation(self, movement, added_movement=None):
174
    """ Generic creation of FakeMovement
175 176 177 178 179 180 181 182 183
    """
    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):
184
    """ Create a new movement with a average price
185
    """
186
    new_movement = self._genericCalculation(movement,
187 188 189 190
                                            added_movement=added_movement)
    new_movement.setPriceMethod("getAveragePrice")
    return new_movement, None

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

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

211 212 213
allow_class(RootMovementGroup)

class OrderMovementGroup(RootMovementGroup):
214
  """ Group movements that comes from the same Order. """
215 216
  def __init__(self,movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
217 218 219
    if hasattr(movement, 'getRootAppliedRule'):
      # This is a simulation movement
      order_value = movement.getRootAppliedRule().getCausalityValue(
220
                              portal_type=movement.getPortalOrderTypeList())
Sebastien Robin's avatar
Sebastien Robin committed
221 222 223 224
      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(
225
                        portal_type=movement.getPortalDeliveryTypeList())
Sebastien Robin's avatar
Sebastien Robin committed
226 227 228 229 230 231 232 233 234 235
    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
236
    self.setGroupEdit(causality_value=order_value)
Sebastien Robin's avatar
Sebastien Robin committed
237 238 239 240

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

      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(
247
                        portal_type=movement.getPortalDeliveryTypeList())
Sebastien Robin's avatar
Sebastien Robin committed
248 249 250 251 252 253 254 255 256
    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()
257
    return order_relative_url == self.order
Sebastien Robin's avatar
Sebastien Robin committed
258

259
allow_class(OrderMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
260

261 262 263 264 265 266 267 268 269 270 271 272
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 """
273
    if hasattr(movement, 'getParentValue'):
274
      # This is a simulation movement
275
      if movement.getParentValue() != movement.getRootAppliedRule() :
276 277
        # get the explanation of parent movement if we have not been
        # created by the root applied rule.
278
        movement = movement.getParentValue().getParentValue()
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
      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)

300 301 302 303 304 305 306 307 308
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
309 310
    explanation_value = movement.getPortalObject().restrictedTraverse(
                                        explanation_relative_url)
311 312 313
    self.setGroupEdit(
      root_causality_value_list = [explanation_value]
    )
314 315 316 317 318 319 320 321 322 323 324 325 326

  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
327
allow_class(RootAppliedRuleCausalityMovementGroup)
328

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
# 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)

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

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

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

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

Sebastien Robin's avatar
Sebastien Robin committed
372 373 374 375 376 377 378 379 380 381 382
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)

383
class SectionPathMovementGroup(RootMovementGroup):
384 385 386
  """ Groups movement that have the same source_section and
  destination_section."""
  def __init__(self, movement, **kw):
387 388 389 390 391 392 393 394 395
    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):
396 397
    return movement.getSourceSection() == self.source_section and \
       movement.getDestinationSection() == self.destination_section
398 399 400

allow_class(SectionPathMovementGroup)

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
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)

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

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

allow_class(QuantitySignMovementGroup)

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

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

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

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

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

Sebastien Robin's avatar
Sebastien Robin committed
469
  def __init__(self,movement,**kw):
470
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
471 472 473 474 475 476 477 478 479 480 481 482 483
    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

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

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

488
  def __init__(self, movement, **kw):
489
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
490
    self.resource = movement.getResource()
491
    self.setGroupEdit(
492
        resource_value=movement.getResourceValue()
493
    )
Sebastien Robin's avatar
Sebastien Robin committed
494

495 496
  def test(self, movement):
    return movement.getResource() == self.resource
Sebastien Robin's avatar
Sebastien Robin committed
497

498
allow_class(ResourceMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
499

500 501 502 503 504 505 506 507 508 509 510
class SplitResourceMovementGroup(RootMovementGroup):

  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    self.resource = movement.getResource()

  def test(self, movement):
    return movement.getResource() == self.resource

allow_class(SplitResourceMovementGroup)

511
class BaseVariantMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
512

Sebastien Robin's avatar
Sebastien Robin committed
513
  def __init__(self,movement,**kw):
514
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    self.base_category_list = movement.getVariationBaseCategoryList()
    if self.base_category_list is None:
      self.base_category_list = []

  def test(self,movement):
    # we must have the same number of categories
    categories_identity = 0
    movement_base_category_list = movement.getVariationBaseCategoryList()
    if movement_base_category_list is None:
      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

533
allow_class(BaseVariantMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
534

535
class VariantMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
536

Sebastien Robin's avatar
Sebastien Robin committed
537
  def __init__(self,movement,**kw):
538
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
539 540 541
    self.category_list = movement.getVariationCategoryList()
    if self.category_list is None:
      self.category_list = []
542 543 544
    self.setGroupEdit(
        variation_category_list=self.category_list
    )
Sebastien Robin's avatar
Sebastien Robin committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558

  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:
      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
559

560
allow_class(VariantMovementGroup)
561

562
class CategoryMovementGroup(RootMovementGroup):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
563 564 565
  """
    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
class OptionMovementGroup(RootMovementGroup):

  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    option_base_category_list = movement.getPortalOptionBaseCategoryList()
590 591
    self.option_category_list = movement.getVariationCategoryList(
                                  base_category_list=option_base_category_list)
592 593 594 595 596 597 598 599 600
    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()
601 602
    movement_option_category_list = movement.getVariationCategoryList(
                              base_category_list=option_base_category_list)
603 604 605 606 607 608 609 610 611 612 613 614
    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
class FakeMovement:
  """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
656
    A fake movement which simulates some methods on a movement needed
657
    by DeliveryBuilder.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
658
    It contains a list of real ERP5 Movements and can modify them.
659
  """
660

661 662
  def __init__(self, movement_list):
    """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
663
      Create a fake movement and store the list of real movements
664 665 666 667 668 669 670 671
    """
    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:
Alexandre Boeglin's avatar
Alexandre Boeglin committed
672
      raise ValueError, "FakeMovement used where it should not."
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
    # 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:
692
      raise ValueError, "FakeMovement not well used."
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

  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
    
711
  def setDeliveryValue(self, object):
712 713 714 715
    """
      Set Delivery value for each movement
    """
    for movement in self.__movement_list:
716 717
      movement.edit(delivery_value=object)

718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
  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()

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

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

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

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

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

823 824 825 826 827 828 829
  def immediateReindexObject(self):
    """
      Reindex immediately all movements
    """
    for movement in self.getMovementList():
      movement.immediateReindexObject()

830 831 832 833 834 835 836 837 838
  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
839
  def getVariationBaseCategoryList(self, omit_option_base_category=0,**kw):
840 841 842 843
    """
      Return variation base category list
      Which must be shared by all movement
    """
844
    return self.__movement_list[0].getVariationBaseCategoryList(
Sebastien Robin's avatar
Sebastien Robin committed
845
                      omit_option_base_category=omit_option_base_category,**kw)
846

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

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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
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):
890
    return self.getTitle(movement) == self.title
Jean-Paul Smets's avatar
Jean-Paul Smets committed
891

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):
916
    return self.getIntIndex(movement) == self.int_index
917 918

allow_class(IntIndexMovementGroup)
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936

# 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):
937
    return self.getDecision(movement) == self.decision
938 939 940

allow_class(DecisionMovementGroup)

941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
# 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):
958
    return self.getBrand(movement) == self.brand
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977

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):
978
    if self.getAggregateList(movement) == self.aggregate :
979 980 981 982
      return 1
    else :
      return 0

983
allow_class(AggregateMovementGroup)
984

985 986 987 988 989 990 991
class SplitMovementGroup(RootMovementGroup):
  def __init__(self,movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)

  def test(self, movement):
    return 0

Alexandre Boeglin's avatar
Alexandre Boeglin committed
992
allow_class(SplitMovementGroup)
Romain Courteaud's avatar
Romain Courteaud committed
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008

class TransformationAppliedRuleCausalityMovementGroup(RootMovementGroup):
  """ 
  Groups movement that comes from simulation movement that shares the
  same Production Applied Rule. 
  """
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    explanation_relative_url = self._getExplanationRelativeUrl(movement)
    self.explanation = explanation_relative_url
    explanation_value = movement.getPortalObject().restrictedTraverse(
                                                    explanation_relative_url)
    self.setGroupEdit(causality_value=explanation_value)

  def _getExplanationRelativeUrl(self, movement):
    """ Get the order value for a movement """
1009
    transformation_applied_rule = movement.getParentValue()
Romain Courteaud's avatar
Romain Courteaud committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
    transformation_rule = transformation_applied_rule.getSpecialiseValue()
    if transformation_rule.getPortalType() != 'Transformation Rule':
      raise MovementGroupError, 'movement! %s' % movement.getPath()
    # XXX Dirty hardcoded 
    production_movement = transformation_applied_rule.pr
    production_packing_list = production_movement.getExplanationValue()
    return production_packing_list.getRelativeUrl()
    
  def test(self,movement):
    return self._getExplanationRelativeUrl(movement) == self.explanation

allow_class(TransformationAppliedRuleCausalityMovementGroup)

class ParentExplanationCausalityMovementGroup(ParentExplanationMovementGroup):
  """
  Like ParentExplanationMovementGroup, and set the causality.
  """
  def __init__(self, movement, **kw):
    ParentExplanationMovementGroup.__init__(self, movement=movement, **kw)
    self.updateGroupEdit(
        causality_value = self.explanation_value
    )

allow_class(ParentExplanationCausalityMovementGroup)
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

class PropertyMovementGroup(RootMovementGroup):
  """Abstract movement group for movement that share the same value for
  a property.
  """
  _property = [] # Subclasses must override this

  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    if self._property is PropertyMovementGroup._property :
      raise ValueError, 'PropertyMovementGroup: property not defined'
    assert isinstance(self._property, str)
    prop_value = movement.getProperty(self._property)
    self._property_dict = { self._property : prop_value }
    self.setGroupEdit(
        **self._property_dict
    )

  def test(self, movement) :
    return self._property_dict[self._property] == \
            movement.getProperty(self._property)

class SourceMovementGroup(PropertyMovementGroup):
  """Group movements having the same source."""
  _property = 'source'
allow_class(SourceMovementGroup)

class DestinationMovementGroup(PropertyMovementGroup):
  """Group movements having the same destination."""
  _property = 'destination'
allow_class(DestinationMovementGroup)

1066 1067 1068 1069 1070
class SourceProjectMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same source project ."""
  _property = 'source_project'
allow_class(SourceProjectMovementGroup)