MovementGroup.py 40.8 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
#
# WARNING: This program as such is intended to be used by professional
9
# programmers who take the whole responsibility of assessing all potential
Sebastien Robin's avatar
Sebastien Robin committed
10 11
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
12
# guarantees and support are strongly adviced to contract a Free Software
Sebastien Robin's avatar
Sebastien Robin committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
# 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 warnings import warn
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
    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:
97
          # We have a conflict here, because it is forbidden to have
98 99 100
          # 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
  def setGroupEdit(self, **kw):
    """
114
      Store properties for the futur created object
115 116
    """
    self._property_dict = kw
Sebastien Robin's avatar
Sebastien Robin committed
117

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

124 125
  def getGroupEditDict(self):
    """
126
      Get property dict for the futur created object
127
    """
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
                                  added_movement=added_movement)
        if rejected_movement is None:
          added_movement = None
        else:
          break
167

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
  def __repr__(self):
    repr_str = '<%s object at 0x%x\n' % (self.__class__.__name__, id(self))
213 214
    if getattr(self, '_property_dict', None) is not None:
      repr_str += ' _property_dict = %r,\n' % self._property_dict
215 216 217 218 219 220 221 222 223 224 225
    if self._movement_list:
      repr_str += ' _movement_list = %r,\n' % self._movement_list
    if self._group_list:
      repr_str += ' _group_list = [\n%s]>' % (
        '\n'.join(['   %s' % x for x in (',\n'.join([repr(i) for i in self._group_list])).split('\n')]))
    else:
      repr_str += ' _last_line_class_name = %r,\n' % self._last_line_class_name
      repr_str += ' _separate_method_name_list = %r,\n' % self._separate_method_name_list
      repr_str += ' _group_list = []>'
    return repr_str

226 227 228
allow_class(RootMovementGroup)

class OrderMovementGroup(RootMovementGroup):
229
  """ Group movements that comes from the same Order. """
230 231
  def __init__(self,movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
232
    order_value = self._getOrderValue(movement)
Sebastien Robin's avatar
Sebastien Robin committed
233 234 235 236 237 238 239
    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
240
    self.setGroupEdit(causality_value=order_value)
Sebastien Robin's avatar
Sebastien Robin committed
241

242
  def _getOrderValue(self, movement):
Sebastien Robin's avatar
Sebastien Robin committed
243
    if hasattr(movement, 'getRootAppliedRule'):
244
      # This is a simulation movement
Sebastien Robin's avatar
Sebastien Robin committed
245
      order_value = movement.getRootAppliedRule().getCausalityValue(
246
                        portal_type=movement.getPortalOrderTypeList())
Sebastien Robin's avatar
Sebastien Robin committed
247 248 249 250
      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(
251
                        portal_type=movement.getPortalDeliveryTypeList())
Sebastien Robin's avatar
Sebastien Robin committed
252 253 254
    else:
      # This is a temp movement
      order_value = None
255 256 257 258
    return order_value

  def test(self,movement):
    order_value = self._getOrderValue(movement)
Sebastien Robin's avatar
Sebastien Robin committed
259 260 261 262 263 264
    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()
265
    return order_relative_url == self.order
Sebastien Robin's avatar
Sebastien Robin committed
266

267
allow_class(OrderMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
268

269
class CausalityAssignmentMovementGroup(RootMovementGroup):
270
  """
271 272 273
  This movement group is used in order to define the causality
  on lines and cells.
  """
274 275

  def addCausalityToEdit(self, movement):
276 277 278 279 280
    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()
281
    if order_movement is not None:
Sebastien Robin's avatar
Sebastien Robin committed
282
      causality = self.getGroupEditDict().get('causality_list', [])
283 284 285
      order_movement_url = order_movement.getRelativeUrl()
      if order_movement_url not in causality:
        causality.append(order_movement_url)
286
        self.setGroupEdit(causality_list=causality)
287

288 289 290
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    self.addCausalityToEdit(movement)
291

292 293 294
  def test(self, movement):
    self.addCausalityToEdit(movement)
    return 1
295

296
allow_class(CausalityAssignmentMovementGroup)
297

298
class CausalityMovementGroup(RootMovementGroup):
299
  """ TODO: docstring """
300

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

327 328
      explanation_relative_url = explanation_value.getRelativeUrl()
    return explanation_relative_url
329

330 331
  def test(self,movement):
    return self._getExplanationRelativeUrl(movement) == self.explanation
332

333 334
allow_class(CausalityMovementGroup)

335
class RootAppliedRuleCausalityMovementGroup(RootMovementGroup):
336
  """ Group movement whose root apply rules have the same causality."""
337 338 339 340
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    explanation_relative_url = self._getExplanationRelativeUrl(movement)
    self.explanation = explanation_relative_url
341
    explanation_value = movement.getPortalObject().unrestrictedTraverse(
342
                                        explanation_relative_url)
343 344 345
    self.setGroupEdit(
      root_causality_value_list = [explanation_value]
    )
346 347

  def _getExplanationRelativeUrl(self, movement):
348
    """ TODO: docstring; method name is bad; variables names are bad """
349 350 351 352 353 354
    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
355

356 357
  def test(self,movement):
    return self._getExplanationRelativeUrl(movement) == self.explanation
358

Sebastien Robin's avatar
Sebastien Robin committed
359
allow_class(RootAppliedRuleCausalityMovementGroup)
360

361 362 363 364
# 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):
365
  """ TODO: docstring """
366 367 368 369 370 371 372 373 374 375 376
  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()
377

378 379
  def test(self,movement):
    return self._getParentExplanationValue(movement) == self.explanation_value
380

381 382
allow_class(ParentExplanationMovementGroup)

383 384 385
class PathMovementGroup(RootMovementGroup):
  """ Group movements that have the same source and the same destination."""
  def __init__(self, movement, **kw):
386
    RootMovementGroup.__init__(self, movement=movement, **kw)
387 388
    source_list = movement.getSourceList()
    destination_list = movement.getDestinationList()
389 390
    source_list.sort()
    destination_list.sort()
391 392 393

    self.source_list = source_list
    self.destination_list = destination_list
394

395
    self.setGroupEdit(
396 397
        source_list=source_list,
        destination_list=destination_list
398
    )
Sebastien Robin's avatar
Sebastien Robin committed
399

400
  def test(self, movement):
401 402
    source_list = movement.getSourceList()
    destination_list = movement.getDestinationList()
403 404
    source_list.sort()
    destination_list.sort()
405 406
    return source_list == self.source_list and \
        destination_list == self.destination_list
Sebastien Robin's avatar
Sebastien Robin committed
407

408
allow_class(PathMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
409

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

    self.source_section_list = source_section_list
    self.destination_section_list = destination_section_list

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

  def test(self, movement):
429 430
    source_section_list = movement.getSourceSectionList()
    destination_section_list = movement.getDestinationSectionList()
431 432
    source_section_list.sort()
    destination_section_list.sort()
433 434
    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
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

464 465 466 467 468 469 470
class AdministrationPathMovementGroup(RootMovementGroup):
  """ Groups movement that have the same source_administration and
  destination_administration."""
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    source_administration_list = movement.getSourceAdministrationList()
    destination_administration_list = movement.getDestinationAdministrationList()
471 472
    source_administration_list.sort()
    destination_administration_list.sort()
473 474 475 476 477 478 479 480 481 482 483 484

    self.source_administration_list = source_administration_list
    self.destination_administration_list = destination_administration_list

    self.setGroupEdit(
        source_administration_list=source_administration_list,
        destination_administration_list=destination_administration_list
    )

  def test(self, movement):
    source_administration_list = movement.getSourceAdministrationList()
    destination_administration_list = movement.getDestinationAdministrationList()
485 486
    source_administration_list.sort()
    destination_administration_list.sort()
487 488
    return source_administration_list == self.source_administration_list and \
        destination_administration_list == self.destination_administration_list
489

490 491 492 493 494 495 496
class DecisionPathMovementGroup(RootMovementGroup):
  """ Groups movement that have the same source_decision and
  destination_decision."""
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    source_decision_list = movement.getSourceDecisionList()
    destination_decision_list = movement.getDestinationDecisionList()
497 498
    source_decision_list.sort()
    destination_decision_list.sort()
499 500 501 502 503 504 505 506 507 508 509 510

    self.source_decision_list = source_decision_list
    self.destination_decision_list = destination_decision_list

    self.setGroupEdit(
        source_decision_list=source_decision_list,
        destination_decision_list=destination_decision_list
    )

  def test(self, movement):
    source_decision_list = movement.getSourceDecisionList()
    destination_decision_list = movement.getDestinationDecisionList()
511 512
    source_decision_list.sort()
    destination_decision_list.sort()
513 514 515 516
    return source_decision_list == self.source_decision_list and \
        destination_decision_list == self.destination_decision_list


517 518 519 520 521 522 523
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)
524 525
    source_trade_list = movement.getSourceTradeList()
    destination_trade_list = movement.getDestinationTradeList()
526 527
    source_trade_list.sort()
    destination_trade_list.sort()
528 529 530

    self.source_trade_list = source_trade_list
    self.destination_trade_list = destination_trade_list
531 532

    self.setGroupEdit(
533 534
        source_trade_list=source_trade_list,
        destination_trade_list=destination_trade_list
535 536 537
    )

  def test(self, movement):
538 539
    source_trade_list = movement.getSourceTradeList()
    destination_trade_list = movement.getDestinationTradeList()
540 541
    source_trade_list.sort()
    destination_trade_list.sort()
542 543
    return source_trade_list == self.source_trade_list and \
        destination_trade_list == self.destination_trade_list
544 545 546

allow_class(TradePathMovementGroup)

547 548 549 550 551
# XXX Naming issue ?
class QuantitySignMovementGroup(RootMovementGroup):
  def __init__(self, movement, **kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    quantity = movement.getQuantity()
552
    self.sign = cmp(quantity, 0)
553 554 555 556
    self.setGroupEdit(quantity_sign=self.sign)

  def test(self, movement):
    quantity = movement.getQuantity()
557 558 559 560 561
    sign = cmp(quantity, 0)
    if sign == 0:
      return 1
    if self.sign == 0:
      self.sign = sign
562
      self.setGroupEdit(quantity_sign=self.sign)
563 564
      return 1
    return self.sign == sign
565 566 567

allow_class(QuantitySignMovementGroup)

568
class DateMovementGroup(RootMovementGroup):
569
  """ Group movements that have exactly the same dates. """
Sebastien Robin's avatar
Sebastien Robin committed
570
  def __init__(self,movement,**kw):
571
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
572 573
    self.start_date = movement.getStartDate()
    self.stop_date = movement.getStopDate()
574 575 576 577
    self.setGroupEdit(
        start_date=movement.getStartDate(),
        stop_date=movement.getStopDate()
    )
Sebastien Robin's avatar
Sebastien Robin committed
578 579 580 581 582 583 584 585

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

586
allow_class(DateMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
587

588
class CriterionMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
589
  def __init__(self,movement,**kw):
590
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
591 592 593 594 595 596 597 598 599 600 601 602 603
    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

604
allow_class(CriterionMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
605

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

612
  def __init__(self, movement, **kw):
613
    RootMovementGroup.__init__(self, movement=movement, **kw)
614 615 616 617 618
    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 }
619
    self.setGroupEdit(
620
        **self._property_dict
621
    )
Sebastien Robin's avatar
Sebastien Robin committed
622

623 624 625 626 627 628 629
  def test(self, movement) :
    return self._property_dict[self._property] == \
            movement.getProperty(self._property)

class ResourceMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same resource. """
  _property = 'resource'
Sebastien Robin's avatar
Sebastien Robin committed
630

631
allow_class(ResourceMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
632

633 634 635 636 637 638 639 640 641 642 643
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)

644
class BaseVariantMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
645

Sebastien Robin's avatar
Sebastien Robin committed
646
  def __init__(self,movement,**kw):
647
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
648 649 650
    self.base_category_list = movement.getVariationBaseCategoryList()
    if self.base_category_list is None:
      self.base_category_list = []
651
    self.base_category_list.sort()
Sebastien Robin's avatar
Sebastien Robin committed
652 653 654 655 656

  def test(self,movement):
    movement_base_category_list = movement.getVariationBaseCategoryList()
    if movement_base_category_list is None:
      movement_base_category_list = []
657 658
    movement_base_category_list.sort()
    return movement_base_category_list == self.base_category_list
Sebastien Robin's avatar
Sebastien Robin committed
659

660
allow_class(BaseVariantMovementGroup)
Sebastien Robin's avatar
Sebastien Robin committed
661

662
class VariantMovementGroup(RootMovementGroup):
Sebastien Robin's avatar
Sebastien Robin committed
663

Sebastien Robin's avatar
Sebastien Robin committed
664
  def __init__(self,movement,**kw):
665
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
666 667 668
    self.category_list = movement.getVariationCategoryList()
    if self.category_list is None:
      self.category_list = []
669
    self.category_list.sort()
670 671 672
    self.setGroupEdit(
        variation_category_list=self.category_list
    )
Sebastien Robin's avatar
Sebastien Robin committed
673 674 675 676 677

  def test(self,movement):
    movement_category_list = movement.getVariationCategoryList()
    if movement_category_list is None:
      movement_category_list = []
678 679
    movement_category_list.sort()
    return movement_category_list == self.category_list
Sebastien Robin's avatar
Sebastien Robin committed
680

681
allow_class(VariantMovementGroup)
682

683
class CategoryMovementGroup(RootMovementGroup):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
684 685 686
  """
    This seems to be a useless class
  """
687
  def __init__(self,movement,**kw):
688
    RootMovementGroup.__init__(self, movement=movement, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
689
    self.category_list = list(movement.getCategoryList())
690 691
    if self.category_list is None:
      self.category_list = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
692
    self.category_list.sort()
693 694

  def test(self,movement):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
695
    movement_category_list = list(movement.getCategoryList())
696 697
    if movement_category_list is None:
      movement_category_list = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
698
    movement_category_list.sort()
699
    return movement_category_list == self.category_list
700 701

allow_class(CategoryMovementGroup)
702

703 704 705 706 707
class OptionMovementGroup(RootMovementGroup):

  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
    option_base_category_list = movement.getPortalOptionBaseCategoryList()
708 709
    self.option_category_list = movement.getVariationCategoryList(
                                  base_category_list=option_base_category_list)
710 711
    if self.option_category_list is None:
      self.option_category_list = []
712
    self.option_category_list.sort()
713 714 715 716 717
    # XXX This is very bad, but no choice today.
    self.setGroupEdit(industrial_phase_list = self.option_category_list)

  def test(self,movement):
    option_base_category_list = movement.getPortalOptionBaseCategoryList()
718 719
    movement_option_category_list = movement.getVariationCategoryList(
                              base_category_list=option_base_category_list)
720 721
    if movement_option_category_list is None:
      movement_option_category_list = []
722 723
    movement_option_category_list.sort()
    return movement_option_category_list == self.option_category_list
724 725 726

allow_class(OptionMovementGroup)

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
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
754
              self.property_dict[variation_property]:
755 756 757 758 759 760 761 762 763 764 765
            # 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)

766 767
class FakeMovement:
  """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
768
    A fake movement which simulates some methods on a movement needed
769
    by DeliveryBuilder.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
770
    It contains a list of real ERP5 Movements and can modify them.
771
  """
772

773 774
  def __init__(self, movement_list):
    """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
775
      Create a fake movement and store the list of real movements
776 777 778 779 780 781 782 783
    """
    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
784
      raise ValueError, "FakeMovement used where it should not."
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    # 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
802

803
    if error_raising_needed == 1:
804
      raise ValueError, "FakeMovement not well used."
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821

  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
822

823
  def setDeliveryValue(self, object):
824 825 826 827
    """
      Set Delivery value for each movement
    """
    for movement in self.__movement_list:
828 829
      movement.edit(delivery_value=object)

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
  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):
    """
846
      Only use to return a short description of one movement
847 848 849 850 851
      (if user did not configure DeliveryBuilder well...).
      Be careful.
    """
    return self.__movement_list[0].getRelativeUrl()

852 853 854 855 856 857 858 859
  def setDeliveryRatio(self, delivery_ratio):
    """
      Calculate delivery_ratio
    """
    total_quantity = 0
    for movement in self.__movement_list:
      total_quantity += movement.getQuantity()

860 861 862
    if total_quantity != 0:
      for movement in self.__movement_list:
        quantity = movement.getQuantity()
863
        movement.edit(delivery_ratio=quantity*delivery_ratio/total_quantity)
864 865 866 867
    else:
      # Distribute equally ratio to all movement
      mvt_ratio = 1 / len(self.__movement_list)
      for movement in self.__movement_list:
868
        movement.edit(delivery_ratio=mvt_ratio)
869

870 871 872 873
  def getPrice(self):
    """
      Return calculated price
    """
874 875 876 877
    if self.__price_method is not None:
      return getattr(self, self.__price_method)()
    else:
      return None
878

879 880 881 882 883 884 885 886 887 888 889
  def setPriceMethod(self, method):
    """
      Set the price method
    """
    self.__price_method = method

  def getQuantity(self):
    """
      Return calculated quantity
    """
    return getattr(self, self.__quantity_method)()
890

891 892 893 894 895 896 897 898
  def setQuantityMethod(self, method):
    """
      Set the quantity method
    """
    self.__quantity_method = method

  def getAveragePrice(self):
    """
899
      Return average price
900
    """
901 902 903
    if self.getAddQuantity()>0:
      return (self.getAddPrice() / self.getAddQuantity())
    return 0.0
904 905 906 907 908 909 910

  def getAddQuantity(self):
    """
      Return the total quantity
    """
    total_quantity = 0
    for movement in self.getMovementList():
911 912 913
      quantity = movement.getQuantity()
      if quantity != None:
        total_quantity += quantity
914 915 916 917
    return total_quantity

  def getAddPrice(self):
    """
918
      Return total price
919 920 921
    """
    total_price = 0
    for movement in self.getMovementList():
922 923 924 925
      quantity = movement.getQuantity()
      price = movement.getPrice()
      if (quantity is not None) and (price is not None):
        total_price += (quantity * price)
926 927 928 929 930 931 932 933 934
    return total_price

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

935 936 937 938 939 940 941
  def immediateReindexObject(self):
    """
      Reindex immediately all movements
    """
    for movement in self.getMovementList():
      movement.immediateReindexObject()

942 943 944 945 946 947 948 949 950
  def getPath(self):
    """
      Return the movements path list
    """
    path_list = []
    for movement in self.getMovementList():
      path_list.append(movement.getPath())
    return path_list

951 952
  def getVariationBaseCategoryList(self, omit_optional_variation=0,
      omit_option_base_category=None, **kw):
953 954 955 956
    """
      Return variation base category list
      Which must be shared by all movement
    """
957 958 959 960 961 962
    #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

963
    return self.__movement_list[0].getVariationBaseCategoryList(
964
        omit_optional_variation=omit_optional_variation, **kw)
965

966 967
  def getVariationCategoryList(self, omit_optional_variation=0,
      omit_option_base_category=None, **kw):
968 969 970 971
    """
      Return variation base category list
      Which must be shared by all movement
    """
972 973 974 975 976 977
    #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

978
    return self.__movement_list[0].getVariationCategoryList(
979
        omit_optional_variation=omit_optional_variation, **kw)
980 981 982

  def edit(self, **kw):
    """
983 984
      Written in order to call edit in delivery builder,
      as it is the generic way to modify object.
985
    """
986 987 988 989 990 991
    for key in kw.keys():
      if key == 'delivery_ratio':
        self.setDeliveryRatio(kw[key])
      elif key == 'delivery_value':
        self.setDeliveryValue(kw[key])
      else:
992
        raise FakeMovementError,\
993
              "Could not call edit on Fakemovement with parameters: %r" % key
994

Jean-Paul Smets's avatar
Jean-Paul Smets committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
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):
1016
    return self.getTitle(movement) == self.title
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1017

1018 1019 1020 1021 1022
# 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
1023 1024 1025
  def getIntIndex(self,movement):
    order_value = movement.getOrderValue()
    int_index = 0
1026
    if order_value is not None:
Sebastien Robin's avatar
Sebastien Robin committed
1027 1028 1029 1030 1031 1032
      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

1033 1034
  def __init__(self,movement,**kw):
    RootMovementGroup.__init__(self, movement=movement, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
1035 1036
    int_index = self.getIntIndex(movement)
    self.int_index = int_index
1037
    self.setGroupEdit(
Sebastien Robin's avatar
Sebastien Robin committed
1038
        int_index=int_index
1039 1040 1041
    )

  def test(self,movement):
1042
    return self.getIntIndex(movement) == self.int_index
1043 1044

allow_class(IntIndexMovementGroup)
1045 1046 1047 1048

# XXX This should not be here
# I (seb) have commited this because movement groups are not
# yet configurable through the zope web interface
1049 1050
class DecisionMovementGroup(PropertyMovementGroup):
  _property = 'decision'
1051 1052
allow_class(DecisionMovementGroup)

1053 1054 1055
# XXX This should not be here
# I (seb) have commited this because movement groups are not
# yet configurable through the zope web interface
1056 1057
class BrandMovementGroup(PropertyMovementGroup):
  _property = 'brand'
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
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)
1070
    self.aggregate_list = aggregate
1071
    self.setGroupEdit(
1072
        aggregate_list=aggregate
1073 1074 1075
    )

  def test(self,movement):
1076
    if self.getAggregateList(movement) == self.aggregate_list:
1077 1078 1079 1080
      return 1
    else :
      return 0

1081
allow_class(AggregateMovementGroup)
1082

1083 1084 1085 1086 1087 1088 1089
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
1090
allow_class(SplitMovementGroup)
Romain Courteaud's avatar
Romain Courteaud committed
1091 1092

class TransformationAppliedRuleCausalityMovementGroup(RootMovementGroup):
1093
  """
Romain Courteaud's avatar
Romain Courteaud committed
1094
  Groups movement that comes from simulation movement that shares the
1095
  same Production Applied Rule.
Romain Courteaud's avatar
Romain Courteaud committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  """
  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 """
1107
    transformation_applied_rule = movement.getParentValue()
Romain Courteaud's avatar
Romain Courteaud committed
1108 1109 1110
    transformation_rule = transformation_applied_rule.getSpecialiseValue()
    if transformation_rule.getPortalType() != 'Transformation Rule':
      raise MovementGroupError, 'movement! %s' % movement.getPath()
1111
    # XXX Dirty hardcoded
Romain Courteaud's avatar
Romain Courteaud committed
1112 1113 1114
    production_movement = transformation_applied_rule.pr
    production_packing_list = production_movement.getExplanationValue()
    return production_packing_list.getRelativeUrl()
1115

Romain Courteaud's avatar
Romain Courteaud committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
  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)
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

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)

1143 1144 1145 1146 1147
class DestinationDecisionMovementGroup(PropertyMovementGroup):
  """Group movements having the same destination decision."""
  _property = 'destination_decision'
allow_class(DestinationDecisionMovementGroup)

1148 1149 1150 1151 1152
class SourceProjectMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same source project ."""
  _property = 'source_project'
allow_class(SourceProjectMovementGroup)

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
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

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
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'

1188 1189 1190 1191
class QuantityUnitMovementGroup(PropertyMovementGroup):
  """ Group movements that have the same quantity unit."""
  _property = 'quantity_unit'
allow_class(QuantityUnitMovementGroup)
1192 1193 1194 1195 1196

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

Kazuhiko Shiozaki's avatar
typo.  
Kazuhiko Shiozaki committed
1197
class ColourMovementGroup(PropertyMovementGroup):
1198 1199
  """ Group movements that have the same colour category."""
  _property = 'colour'