MovementGroup.py 40.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 warnings import warn
37
from Products.PythonScripts.Utility import allow_class
Sebastien Robin's avatar
Sebastien Robin committed
38

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

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

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

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

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

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

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

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

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

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

212 213 214
allow_class(RootMovementGroup)

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

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

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

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

262 263 264 265 266
class CausalityAssignmentMovementGroup(RootMovementGroup):
  """ 
  This movement group is used in order to define the causality
  on lines and cells.
  """
267 268

  def addCausalityToEdit(self, movement):
269 270 271 272 273
    parent = movement
    # Go upper into the simulation tree in order to find an order link
    while parent.getOrderValue() is None and not(parent.isRootAppliedRule()):
      parent = parent.getParentValue()
    order_movement = parent.getOrderValue()
274
    if order_movement is not None:
Sebastien Robin's avatar
Sebastien Robin committed
275
      causality = self.getGroupEditDict().get('causality_list', [])
276 277 278
      order_movement_url = order_movement.getRelativeUrl()
      if order_movement_url not in causality:
        causality.append(order_movement_url)
279
        self.setGroupEdit(causality_list=causality)
280

281 282 283
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    self.addCausalityToEdit(movement)
284

285 286 287
  def test(self, movement):
    self.addCausalityToEdit(movement)
    return 1
288

289
allow_class(CausalityAssignmentMovementGroup)
290

291
class CausalityMovementGroup(RootMovementGroup):
292
  """ TODO: docstring """
293 294 295 296 297 298 299 300
  
  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 """
301
    if hasattr(movement, 'getParentValue'):
302
      # This is a simulation movement
303
      if movement.getParentValue() != movement.getRootAppliedRule() :
304 305
        # get the explanation of parent movement if we have not been
        # created by the root applied rule.
306
        movement = movement.getParentValue().getParentValue()
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
      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)

328
class RootAppliedRuleCausalityMovementGroup(RootMovementGroup):
329
  """ Group movement whose root apply rules have the same causality."""
330 331 332 333
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    explanation_relative_url = self._getExplanationRelativeUrl(movement)
    self.explanation = explanation_relative_url
334 335
    explanation_value = movement.getPortalObject().restrictedTraverse(
                                        explanation_relative_url)
336 337 338
    self.setGroupEdit(
      root_causality_value_list = [explanation_value]
    )
339 340

  def _getExplanationRelativeUrl(self, movement):
341
    """ TODO: docstring; method name is bad; variables names are bad """
342 343 344 345 346 347 348 349 350 351
    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
352
allow_class(RootAppliedRuleCausalityMovementGroup)
353

354 355 356 357
# 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):
358
  """ TODO: docstring """
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
  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)

376 377 378
class PathMovementGroup(RootMovementGroup):
  """ Group movements that have the same source and the same destination."""
  def __init__(self, movement, **kw):
379
    RootMovementGroup.__init__(self, movement=movement, **kw)
380 381 382 383 384 385
    source_list = movement.getSourceList()
    destination_list = movement.getDestinationList()
    source_list.sort() ; destination_list.sort()

    self.source_list = source_list
    self.destination_list = destination_list
386

387
    self.setGroupEdit(
388 389
        source_list=source_list,
        destination_list=destination_list
390
    )
Sebastien Robin's avatar
Sebastien Robin committed
391

392
  def test(self, movement):
393 394 395 396 397
    source_list = movement.getSourceList()
    destination_list = movement.getDestinationList()
    source_list.sort() ; destination_list.sort()
    return source_list == self.source_list and \
        destination_list == self.destination_list
Sebastien Robin's avatar
Sebastien Robin committed
398

399
allow_class(PathMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
400

Sebastien Robin's avatar
Sebastien Robin committed
401
class ColourMovementGroup(RootMovementGroup):
402
  """ Group movements that have the same color category."""
Sebastien Robin's avatar
Sebastien Robin committed
403 404 405 406 407 408 409 410 411
  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)

412
class SectionPathMovementGroup(RootMovementGroup):
413 414 415
  """ Groups movement that have the same source_section and
  destination_section."""
  def __init__(self, movement, **kw):
416
    RootMovementGroup.__init__(self, movement=movement, **kw)
417 418 419 420 421 422 423
    source_section_list = movement.getSourceSectionList()
    destination_section_list = movement.getDestinationSectionList()
    source_section_list.sort() ; destination_section_list.sort()

    self.source_section_list = source_section_list
    self.destination_section_list = destination_section_list

424
    self.setGroupEdit(
425 426
        source_section_list=source_section_list,
        destination_section_list=destination_section_list
427 428 429
    )

  def test(self, movement):
430 431 432 433 434
    source_section_list = movement.getSourceSectionList()
    destination_section_list = movement.getDestinationSectionList()
    source_section_list.sort() ; destination_section_list.sort()
    return source_section_list == self.source_section_list and \
        destination_section_list == self.destination_section_list
435 436 437

allow_class(SectionPathMovementGroup)

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
class PaymentPathMovementGroup(RootMovementGroup):
  """ Groups movement that have the same source_payment and
  destination_payment"""
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    source_payment_list = movement.getSourcePaymentList()
    destination_payment_list = movement.getDestinationPaymentList()
    source_payment_list.sort()
    destination_payment_list.sort()

    self.source_payment_list = source_payment_list
    self.destination_payment_list = destination_payment_list

    self.setGroupEdit(
        source_payment_list=source_payment_list,
        destination_payment_list=destination_payment_list
    )

  def test(self, movement):
    source_payment_list = movement.getSourcePaymentList()
    destination_payment_list = movement.getDestinationPaymentList()
    source_payment_list.sort()
    destination_payment_list.sort()
    return source_payment_list == self.source_payment_list and \
        destination_payment_list == self.destination_payment_list


465 466 467 468 469 470 471
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)
472 473 474 475 476 477
    source_trade_list = movement.getSourceTradeList()
    destination_trade_list = movement.getDestinationTradeList()
    source_trade_list.sort() ; destination_trade_list.sort()

    self.source_trade_list = source_trade_list
    self.destination_trade_list = destination_trade_list
478 479

    self.setGroupEdit(
480 481
        source_trade_list=source_trade_list,
        destination_trade_list=destination_trade_list
482 483 484
    )

  def test(self, movement):
485 486 487 488 489
    source_trade_list = movement.getSourceTradeList()
    destination_trade_list = movement.getDestinationTradeList()
    source_trade_list.sort() ; destination_trade_list.sort()
    return source_trade_list == self.source_trade_list and \
        destination_trade_list == self.destination_trade_list
490 491 492

allow_class(TradePathMovementGroup)

493 494 495 496 497
# XXX Naming issue ?
class QuantitySignMovementGroup(RootMovementGroup):
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    quantity = movement.getQuantity()
498
    self.sign = cmp(quantity, 0)
499 500 501 502
    self.setGroupEdit(quantity_sign=self.sign)

  def test(self, movement):
    quantity = movement.getQuantity()
503 504 505 506 507
    sign = cmp(quantity, 0)
    if sign == 0:
      return 1
    if self.sign == 0:
      self.sign = sign
508
      self.setGroupEdit(quantity_sign=self.sign)
509 510
      return 1
    return self.sign == sign
511 512 513

allow_class(QuantitySignMovementGroup)

514
class DateMovementGroup(RootMovementGroup):
515
  """ Group movements that have exactly the same dates. """
Sebastien Robin's avatar
Sebastien Robin committed
516
  def __init__(self,movement,**kw):
517
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
518 519
    self.start_date = movement.getStartDate()
    self.stop_date = movement.getStopDate()
520 521 522 523
    self.setGroupEdit(
        start_date=movement.getStartDate(),
        stop_date=movement.getStopDate()
    )
Sebastien Robin's avatar
Sebastien Robin committed
524 525 526 527 528 529 530 531

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

532
allow_class(DateMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
533

534
class CriterionMovementGroup(RootMovementGroup):
535
  
Sebastien Robin's avatar
Sebastien Robin committed
536
  def __init__(self,movement,**kw):
537
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
538 539 540 541 542 543 544 545 546 547 548 549 550
    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

551
allow_class(CriterionMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
552

553
class ResourceMovementGroup(RootMovementGroup):
554
  """ Group movements that have the same resource. """
555
  def __init__(self, movement, **kw):
556
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
557
    self.resource = movement.getResource()
558
    self.setGroupEdit(
559
        resource_value=movement.getResourceValue()
560
    )
Sebastien Robin's avatar
Sebastien Robin committed
561

562 563
  def test(self, movement):
    return movement.getResource() == self.resource
Sebastien Robin's avatar
Sebastien Robin committed
564

565
allow_class(ResourceMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
566

567 568 569 570 571 572 573 574 575 576 577
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)

578
class BaseVariantMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
579

Sebastien Robin's avatar
Sebastien Robin committed
580
  def __init__(self,movement,**kw):
581
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
    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

600
allow_class(BaseVariantMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
601

602
class VariantMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
603

Sebastien Robin's avatar
Sebastien Robin committed
604
  def __init__(self,movement,**kw):
605
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
606 607 608
    self.category_list = movement.getVariationCategoryList()
    if self.category_list is None:
      self.category_list = []
609 610 611
    self.setGroupEdit(
        variation_category_list=self.category_list
    )
Sebastien Robin's avatar
Sebastien Robin committed
612 613 614 615 616 617 618 619 620 621 622 623 624 625

  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
626

627
allow_class(VariantMovementGroup)
628

629
class CategoryMovementGroup(RootMovementGroup):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
630 631 632
  """
    This seems to be a useless class
  """
633
  def __init__(self,movement,**kw):
634
    RootMovementGroup.__init__(self, movement=movement, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
635
    self.category_list = list(movement.getCategoryList())
636 637
    if self.category_list is None:
      self.category_list = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
638
    self.category_list.sort()
639 640 641

  def test(self,movement):
    # we must have the same number of categories
Jean-Paul Smets's avatar
Jean-Paul Smets committed
642
    movement_category_list = list(movement.getCategoryList())
643 644
    if movement_category_list is None:
      movement_category_list = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
645 646 647 648
    movement_category_list.sort()
    if self.category_list == movement_category_list:
      return 1
    return 0
649 650

allow_class(CategoryMovementGroup)
651

652 653 654 655 656
class OptionMovementGroup(RootMovementGroup):

  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    option_base_category_list = movement.getPortalOptionBaseCategoryList()
657 658
    self.option_category_list = movement.getVariationCategoryList(
                                  base_category_list=option_base_category_list)
659 660 661 662 663 664 665 666 667
    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()
668 669
    movement_option_category_list = movement.getVariationCategoryList(
                              base_category_list=option_base_category_list)
670 671 672 673 674 675 676 677 678 679 680 681
    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)

682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
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
709
              self.property_dict[variation_property]:
710 711 712 713 714 715 716 717 718 719 720
            # 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)

721 722
class FakeMovement:
  """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
723
    A fake movement which simulates some methods on a movement needed
724
    by DeliveryBuilder.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
725
    It contains a list of real ERP5 Movements and can modify them.
726
  """
727

728 729
  def __init__(self, movement_list):
    """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
730
      Create a fake movement and store the list of real movements
731 732 733 734 735 736 737 738
    """
    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
739
      raise ValueError, "FakeMovement used where it should not."
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
    # 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:
759
      raise ValueError, "FakeMovement not well used."
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777

  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
    
778
  def setDeliveryValue(self, object):
779 780 781 782
    """
      Set Delivery value for each movement
    """
    for movement in self.__movement_list:
783 784
      movement.edit(delivery_value=object)

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
  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()

807 808 809 810 811 812 813 814
  def setDeliveryRatio(self, delivery_ratio):
    """
      Calculate delivery_ratio
    """
    total_quantity = 0
    for movement in self.__movement_list:
      total_quantity += movement.getQuantity()

815 816 817
    if total_quantity != 0:
      for movement in self.__movement_list:
        quantity = movement.getQuantity()
818
        movement.edit(delivery_ratio=quantity*delivery_ratio/total_quantity)
819 820 821 822
    else:
      # Distribute equally ratio to all movement
      mvt_ratio = 1 / len(self.__movement_list)
      for movement in self.__movement_list:
823
        movement.edit(delivery_ratio=mvt_ratio)
824 825 826 827 828
      
  def getPrice(self):
    """
      Return calculated price
    """
829 830 831 832
    if self.__price_method is not None:
      return getattr(self, self.__price_method)()
    else:
      return None
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
  
  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 
    """
856 857 858
    if self.getAddQuantity()>0:
      return (self.getAddPrice() / self.getAddQuantity())
    return 0.0
859 860 861 862 863 864 865

  def getAddQuantity(self):
    """
      Return the total quantity
    """
    total_quantity = 0
    for movement in self.getMovementList():
866 867 868
      quantity = movement.getQuantity()
      if quantity != None:
        total_quantity += quantity
869 870 871 872 873 874 875 876
    return total_quantity

  def getAddPrice(self):
    """
      Return total price 
    """
    total_price = 0
    for movement in self.getMovementList():
877 878 879 880
      quantity = movement.getQuantity()
      price = movement.getPrice()
      if (quantity is not None) and (price is not None):
        total_price += (quantity * price)
881 882 883 884 885 886 887 888 889
    return total_price

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

890 891 892 893 894 895 896
  def immediateReindexObject(self):
    """
      Reindex immediately all movements
    """
    for movement in self.getMovementList():
      movement.immediateReindexObject()

897 898 899 900 901 902 903 904 905
  def getPath(self):
    """
      Return the movements path list
    """
    path_list = []
    for movement in self.getMovementList():
      path_list.append(movement.getPath())
    return path_list

906 907
  def getVariationBaseCategoryList(self, omit_optional_variation=0,
      omit_option_base_category=None, **kw):
908 909 910 911
    """
      Return variation base category list
      Which must be shared by all movement
    """
912 913 914 915 916 917
    #XXX backwards compatibility
    if omit_option_base_category is not None:
      warn("Please use omit_optional_variation instead of"\
          " omit_option_base_category.", DeprecationWarning)
      omit_optional_variation = omit_option_base_category

918
    return self.__movement_list[0].getVariationBaseCategoryList(
919
        omit_optional_variation=omit_optional_variation, **kw)
920

921 922
  def getVariationCategoryList(self, omit_optional_variation=0,
      omit_option_base_category=None, **kw):
923 924 925 926
    """
      Return variation base category list
      Which must be shared by all movement
    """
927 928 929 930 931 932
    #XXX backwards compatibility
    if omit_option_base_category is not None:
      warn("Please use omit_optional_variation instead of"\
          " omit_option_base_category.", DeprecationWarning)
      omit_optional_variation = omit_option_base_category

933
    return self.__movement_list[0].getVariationCategoryList(
934
        omit_optional_variation=omit_optional_variation, **kw)
935 936 937

  def edit(self, **kw):
    """
938 939
      Written in order to call edit in delivery builder,
      as it is the generic way to modify object.
940
    """
941 942 943 944 945 946
    for key in kw.keys():
      if key == 'delivery_ratio':
        self.setDeliveryRatio(kw[key])
      elif key == 'delivery_value':
        self.setDeliveryValue(kw[key])
      else:
947
        raise FakeMovementError,\
948
              "Could not call edit on Fakemovement with parameters: %r" % key
949

Jean-Paul Smets's avatar
Jean-Paul Smets committed
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
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):
971
    return self.getTitle(movement) == self.title
Jean-Paul Smets's avatar
Jean-Paul Smets committed
972

973 974 975 976 977
# 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
978 979 980
  def getIntIndex(self,movement):
    order_value = movement.getOrderValue()
    int_index = 0
981
    if order_value is not None:
Sebastien Robin's avatar
Sebastien Robin committed
982 983 984 985 986 987
      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

988 989
  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
990 991
    int_index = self.getIntIndex(movement)
    self.int_index = int_index
992
    self.setGroupEdit(
Sebastien Robin's avatar
Sebastien Robin committed
993
        int_index=int_index
994 995 996
    )

  def test(self,movement):
997
    return self.getIntIndex(movement) == self.int_index
998 999

allow_class(IntIndexMovementGroup)
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

# 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):
1018
    return self.getDecision(movement) == self.decision
1019 1020 1021

allow_class(DecisionMovementGroup)

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
# 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):
1039
    return self.getBrand(movement) == self.brand
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052

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)
1053
    self.aggregate_list = aggregate
1054
    self.setGroupEdit(
1055
        aggregate_list=aggregate
1056 1057 1058
    )

  def test(self,movement):
1059
    if self.getAggregateList(movement) == self.aggregate_list:
1060 1061 1062 1063
      return 1
    else :
      return 0

1064
allow_class(AggregateMovementGroup)
1065

1066 1067 1068 1069 1070 1071 1072
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
1073
allow_class(SplitMovementGroup)
Romain Courteaud's avatar
Romain Courteaud committed
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089

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 """
1090
    transformation_applied_rule = movement.getParentValue()
Romain Courteaud's avatar
Romain Courteaud committed
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    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)
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

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)

1147 1148 1149 1150 1151
class DestinationDecisionMovementGroup(PropertyMovementGroup):
  """Group movements having the same destination decision."""
  _property = 'destination_decision'
allow_class(DestinationDecisionMovementGroup)

1152 1153 1154 1155 1156
class SourceProjectMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same source project ."""
  _property = 'source_project'
allow_class(SourceProjectMovementGroup)

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
class RequirementMovementGroup(RootMovementGroup):
  """
  Group movements that have same Requirement.
  """
  def getRequirementList(self,movement):
    order_value = movement.getOrderValue()
    requirement_list = []
    if order_value is not None:
      if "Line" in order_value.getPortalType():
        requirement_list = order_value.getRequirementList()
    return requirement_list

  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    requirement_list = self.getRequirementList(movement)
    self.requirement_list = requirement_list
    self.setGroupEdit(
        requirement=requirement_list
    )

  def test(self,movement):
    return self.getRequirementList(movement) == self.requirement_list

1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
class BaseContributionMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same base contributions."""
  _property = 'base_contribution_list'

class BaseApplicationMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same base applications."""
  _property = 'base_application_list'

class PriceCurrencyMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same price currency."""
  _property = 'price_currency'

1192 1193 1194 1195
class QuantityUnitMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same quantity unit."""
  _property = 'quantity_unit'
allow_class(QuantityUnitMovementGroup)
1196 1197 1198 1199 1200 1201

class PaymentModeMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same payment mode."""
  _property = 'payment_mode'
allow_class(PaymentModeMovementGroup)