OrderBuilder.py 32.6 KB
Newer Older
Romain Courteaud's avatar
Romain Courteaud committed
1 2
##############################################################################
#
3
# Copyright (c) 2005-2008 Nexedi SA and Contributors. All Rights Reserved.
Romain Courteaud's avatar
Romain Courteaud committed
4 5 6
#                    Romain Courteaud <romain@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
7
# programmers who take the whole responsibility of assessing all potential
Romain Courteaud's avatar
Romain Courteaud committed
8 9
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
10
# guarantees and support are strongly adviced to contract a Free Software
Romain Courteaud's avatar
Romain Courteaud committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# 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.
#
##############################################################################

from AccessControl import ClassSecurityInfo
30
from Products.ERP5Type import Permissions, PropertySheet
Romain Courteaud's avatar
Romain Courteaud committed
31 32 33
from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5.Document.Predicate import Predicate
from Products.ERP5.Document.Amount import Amount
34 35 36
from Products.ERP5.MovementGroup import MovementGroupNode
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
from Products.ERP5Type.CopySupport import CopyError, tryMethodCallWithTemporaryPermission
37
from DateTime import DateTime
38
from Acquisition import aq_parent, aq_inner
Romain Courteaud's avatar
Romain Courteaud committed
39

40 41 42
class CollectError(Exception): pass
class MatrixError(Exception): pass

Romain Courteaud's avatar
Romain Courteaud committed
43 44 45
class OrderBuilder(XMLObject, Amount, Predicate):
  """
    Order Builder objects allow to gather multiple Simulation Movements
46
    into a single Delivery.
Romain Courteaud's avatar
Romain Courteaud committed
47 48 49 50

    The initial quantity property of the Delivery Line is calculated by
    summing quantities of related Simulation Movements.

51
    Order Builder objects are provided with a set a parameters to achieve
Romain Courteaud's avatar
Romain Courteaud committed
52 53
    their goal:

54
    A path definition: source, destination, etc. which defines the general
Romain Courteaud's avatar
Romain Courteaud committed
55 56
    kind of movements it applies.

57 58
    simulation_select_method which defines how to query all Simulation
    Movements which meet certain criteria (including the above path path
Romain Courteaud's avatar
Romain Courteaud committed
59 60
    definition).

61
    collect_order_list which defines how to group selected movements
Romain Courteaud's avatar
Romain Courteaud committed
62 63
    according to gathering rules.

64
    delivery_select_method which defines how to select existing Delivery
Romain Courteaud's avatar
Romain Courteaud committed
65 66
    which may eventually be updated with selected simulation movements.

67
    delivery_module, delivery_type and delivery_line_type which define the
Romain Courteaud's avatar
Romain Courteaud committed
68 69
    module and portal types for newly built Deliveries and Delivery Lines.

70
    Order Builders can also be provided with optional parameters to
Romain Courteaud's avatar
Romain Courteaud committed
71
    restrict selection to a given root Applied Rule caused by a single Order
72
    or to Simulation Movements related to a limited set of existing
Romain Courteaud's avatar
Romain Courteaud committed
73 74 75 76 77 78 79 80 81
    Deliveries.
  """

  # CMF Type Definition
  meta_type = 'ERP5 Order Builder'
  portal_type = 'Order Builder'

  # Declarative security
  security = ClassSecurityInfo()
82
  security.declareObjectProtected(Permissions.AccessContentsInformation)
Romain Courteaud's avatar
Romain Courteaud committed
83 84 85 86 87 88 89 90 91 92 93

  # Default Properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Arrow
                    , PropertySheet.Amount
                    , PropertySheet.Comment
                    , PropertySheet.DeliveryBuilder
                    )
94

95
  security.declarePublic('build')
96
  def build(self, applied_rule_uid=None, movement_relative_url_list=None,
97
            delivery_relative_url_list=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
98 99 100 101 102 103 104
    """
      Build deliveries from a list of movements

      Delivery Builders can also be provided with optional parameters to
      restrict selection to a given root Applied Rule caused by a single Order
      or to Simulation Movements related to a limited set of existing
    """
105 106 107 108 109 110 111
    # Parameter initialization
    if movement_relative_url_list is None:
      movement_relative_url_list = []
    if delivery_relative_url_list is None:
      delivery_relative_url_list = []
    # Call a script before building
    self.callBeforeBuildingScript()
Romain Courteaud's avatar
Romain Courteaud committed
112 113 114
    # Select
    if movement_relative_url_list == []:
      movement_list = self.searchMovementList(
115
                                      applied_rule_uid=applied_rule_uid,**kw)
Romain Courteaud's avatar
Romain Courteaud committed
116
    else:
117
      movement_list = [self.restrictedTraverse(relative_url) for relative_url \
Romain Courteaud's avatar
Romain Courteaud committed
118 119 120 121 122 123 124
                       in movement_relative_url_list]
    # Collect
    root_group = self.collectMovement(movement_list)
    # Build
    delivery_list = self.buildDeliveryList(
                       root_group,
                       delivery_relative_url_list=delivery_relative_url_list,
125
                       movement_list=movement_list,**kw)
126
    # Call a script after building
127
    self.callAfterBuildingScript(delivery_list, movement_list, **kw)
128
    # XXX Returning the delivery list is probably not necessary
Romain Courteaud's avatar
Romain Courteaud committed
129 130
    return delivery_list

131
  def callBeforeBuildingScript(self):
Romain Courteaud's avatar
Romain Courteaud committed
132
    """
133
      Call a script on the module, for example, to remove some
134
      auto_planned Order.
135 136
      This part can only be done with a script, because user may want
      to keep existing auto_planned Order, and only update lines in
137 138 139 140 141 142 143
      them.
      No activities are used when deleting a object, so, current
      implementation should be OK.
    """
    delivery_module_before_building_script_id = \
        self.getDeliveryModuleBeforeBuildingScriptId()
    if delivery_module_before_building_script_id not in ["", None]:
144
      delivery_module = getattr(self.getPortalObject(), self.getDeliveryModule())
145
      getattr(delivery_module, delivery_module_before_building_script_id)()
Romain Courteaud's avatar
Romain Courteaud committed
146

147
  def searchMovementList(self, applied_rule_uid=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
148
    """
149 150
      Defines how to query all Simulation Movements which meet certain
      criteria (including the above path path definition).
151
      First, select movement matching to criteria define on
152
      DeliveryBuilder.
153
      Then, call script simulation_select_method to restrict
154 155 156
      movement_list.
    """
    from Products.ERP5Type.Document import newTempMovement
Romain Courteaud's avatar
Romain Courteaud committed
157
    movement_list = []
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    for attribute, method in [('node_uid', 'getDestinationUid'),
                              ('section_uid', 'getDestinationSectionUid')]:
      if getattr(self, method)() not in ("", None):
        kw[attribute] = getattr(self, method)()
    # We have to check the inventory for each stock movement date.
    # Inventory can be negative in some date, and positive in futur !!
    # This must be done by subclassing OrderBuilder with a new inventory
    # algorithm.
    sql_list = self.portal_simulation.getFutureInventoryList(
                                                   group_by_variation=1,
                                                   group_by_resource=1,
                                                   group_by_node=1,
                                                   group_by_section=0,
                                                   **kw)
    id_count = 0
    for inventory_item in sql_list:
      # XXX FIXME SQL return None inventory...
      # It may be better to return always good values
      if (inventory_item.inventory is not None):
        dumb_movement = inventory_item.getObject()
        # Create temporary movement
179
        movement = newTempMovement(self.getPortalObject(),
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
                                   str(id_count))
        id_count += 1
        movement.edit(
            resource=inventory_item.resource_relative_url,
            variation_category_list=dumb_movement.getVariationCategoryList(),
            destination_value=self.getDestinationValue(),
            destination_section_value=self.getDestinationSectionValue())
        # We can do other test on inventory here
        # XXX It is better if it can be sql parameters
        resource_portal_type = self.getResourcePortalType()
        resource = movement.getResourceValue()
        # FIXME: XXX Those properties are defined on a supply line !!
        # min_flow, max_delay
        min_flow = resource.getMinFlow(0)
        if (resource.getPortalType() == resource_portal_type) and\
           (round(inventory_item.inventory, 5) < min_flow):
          # FIXME XXX getNextNegativeInventoryDate must work
          stop_date = DateTime()+10
#         stop_date = resource.getNextNegativeInventoryDate(
#                               variation_text=movement.getVariationText(),
#                               from_date=DateTime(),
# #                             node_category=node_category,
# #                             section_category=section_category)
#                               node_uid=self.getDestinationUid(),
#                               section_uid=self.getDestinationSectionUid())
          max_delay = resource.getMaxDelay(0)
          movement.edit(
207
            start_date=DateTime(((stop_date-max_delay).Date())),
208
            stop_date=DateTime(stop_date.Date()),
209 210 211 212 213 214
            quantity=min_flow-inventory_item.inventory,
            quantity_unit=resource.getQuantityUnit()
            # XXX FIXME define on a supply line
            # quantity_unit
          )
          movement_list.append(movement)
Romain Courteaud's avatar
Romain Courteaud committed
215 216 217 218
    return movement_list

  def collectMovement(self, movement_list):
    """
219
      group movements in the way we want. Thanks to this method, we are able
Romain Courteaud's avatar
Romain Courteaud committed
220 221
      to retrieve movement classed by order, resource, criterion,....
      movement_list : the list of movement wich we want to group
222
      class_list : the list of classes used to group movements. The order
Romain Courteaud's avatar
Romain Courteaud committed
223 224 225 226 227
                   of the list is important and determines by what we will
                   group movement first
                   Typically, check_list is :
                   [DateMovementGroup,PathMovementGroup,...]
    """
228 229
    movement_group_list = self.getMovementGroupList()
    last_line_movement_group = self.getDeliveryMovementGroupList()[-1]
230
    separate_method_name_list = self.getDeliveryCellSeparateOrderList([])
231 232 233 234 235
    my_root_group = MovementGroupNode(
      separate_method_name_list=separate_method_name_list,
      movement_group_list=movement_group_list,
      last_line_movement_group=last_line_movement_group)
    my_root_group.append(movement_list)
Romain Courteaud's avatar
Romain Courteaud committed
236 237
    return my_root_group

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  def _testToUpdate(self, instance, movement_group_list,
                    divergence_list):
    result = True
    new_property_dict = {}
    for movement_group in movement_group_list:
      tmp_result, tmp_property_dict = movement_group.testToUpdate(
        instance, divergence_list)
      if tmp_result == False:
        result = tmp_result
      new_property_dict.update(tmp_property_dict)
    return result, new_property_dict

  def _findUpdatableObject(self, instance_list, movement_group_list,
                           divergence_list):
    instance = None
    property_dict = {}
    if not len(instance_list):
      for movement_group in movement_group_list:
        property_dict.update(movement_group.getGroupEditDict())
    else:
      # we want to check the original first.
      # the original is the delivery of the last (bottom) movement group.
      try:
        original = movement_group_list[-1].getMovementList()[0].getDeliveryValue()
      except AttributeError:
        original = None
      if original is not None:
        original_id = original.getId()
        instance_list.sort(lambda a,b:cmp(b.getId()==original_id,
                                          a.getId()==original_id))
      for instance_to_update in instance_list:
        result, property_dict = self._testToUpdate(
          instance_to_update, movement_group_list, divergence_list)
        if result == True:
          instance = instance_to_update
Romain Courteaud's avatar
Romain Courteaud committed
273
          break
274
    return instance, property_dict
Romain Courteaud's avatar
Romain Courteaud committed
275

276
  def buildDeliveryList(self, movement_group, delivery_relative_url_list=None,
277
                        movement_list=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
278 279 280
    """
      Build deliveries from a list of movements
    """
281 282 283
    # Parameter initialization
    if delivery_relative_url_list is None:
      delivery_relative_url_list = []
Jérome Perrin's avatar
Jérome Perrin committed
284 285
    if movement_list is None:
      movement_list = []
Romain Courteaud's avatar
Romain Courteaud committed
286
    # Module where we can create new deliveries
287 288 289
    portal = self.getPortalObject()
    delivery_module = getattr(portal, self.getDeliveryModule())
    delivery_to_update_list = [portal.restrictedTraverse(relative_url) for \
Romain Courteaud's avatar
Romain Courteaud committed
290 291 292 293
                               relative_url in delivery_relative_url_list]
    # Deliveries we are trying to update
    delivery_select_method_id = self.getDeliverySelectMethodId()
    if delivery_select_method_id not in ["", None]:
294
      to_update_delivery_sql_list = getattr(self, delivery_select_method_id) \
Romain Courteaud's avatar
Romain Courteaud committed
295
                                      (movement_list=movement_list)
296 297
      delivery_to_update_list.extend([sql_delivery.getObject() \
                                     for sql_delivery \
Romain Courteaud's avatar
Romain Courteaud committed
298
                                     in to_update_delivery_sql_list])
299 300 301
    # We do not want to update the same object more than twice in one
    # _deliveryGroupProcessing().
    self._resetUpdated()
Romain Courteaud's avatar
Romain Courteaud committed
302 303 304
    delivery_list = self._deliveryGroupProcessing(
                          delivery_module,
                          movement_group,
305
                          self.getDeliveryMovementGroupList(),
306 307
                          delivery_to_update_list=delivery_to_update_list,
                          **kw)
Romain Courteaud's avatar
Romain Courteaud committed
308 309
    return delivery_list

310
  def _deliveryGroupProcessing(self, delivery_module, movement_group,
311
                               collect_order_list, movement_group_list=None,
312
                               delivery_to_update_list=None,
313 314
                               divergence_list=None,
                               activate_kw=None, force_update=0, **kw):
Romain Courteaud's avatar
Romain Courteaud committed
315 316 317
    """
      Build empty delivery from a list of movement
    """
318 319 320 321 322 323
    if movement_group_list is None:
      movement_group_list = []
    if divergence_list is None:
      divergence_list = []
    # do not use 'append' or '+=' because they are destructive.
    movement_group_list = movement_group_list + [movement_group]
324 325 326
    # Parameter initialization
    if delivery_to_update_list is None:
      delivery_to_update_list = []
Romain Courteaud's avatar
Romain Courteaud committed
327
    delivery_list = []
328 329

    if len(collect_order_list):
Romain Courteaud's avatar
Romain Courteaud committed
330 331 332 333 334 335
      # Get sorted movement for each delivery
      for group in movement_group.getGroupList():
        new_delivery_list = self._deliveryGroupProcessing(
                              delivery_module,
                              group,
                              collect_order_list[1:],
336
                              movement_group_list=movement_group_list,
337
                              delivery_to_update_list=delivery_to_update_list,
338 339 340
                              divergence_list=divergence_list,
                              activate_kw=activate_kw,
                              force_update=force_update, **kw)
Romain Courteaud's avatar
Romain Courteaud committed
341
        delivery_list.extend(new_delivery_list)
342
        force_update = 0
Romain Courteaud's avatar
Romain Courteaud committed
343
    else:
344
      # Test if we can update a existing delivery, or if we need to create
Romain Courteaud's avatar
Romain Courteaud committed
345
      # a new one
346 347 348 349 350 351 352 353 354 355 356 357 358
      delivery_to_update_list = [
        x for x in delivery_to_update_list \
        if x.getPortalType() == self.getDeliveryPortalType() and \
        not self._isUpdated(x, 'delivery')]
      delivery, property_dict = self._findUpdatableObject(
        delivery_to_update_list, movement_group_list,
        divergence_list)

      # if all deliveries are rejected in case of update, we update the
      # first one.
      if force_update and delivery is None and len(delivery_to_update_list):
        delivery = delivery_to_update_list[0]

Romain Courteaud's avatar
Romain Courteaud committed
359
      if delivery is None:
Romain Courteaud's avatar
Romain Courteaud committed
360
        # Create delivery
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        try:
          old_delivery = movement_group.getMovementList()[0].getDeliveryValue()
        except AttributeError:
          old_delivery = None
        if old_delivery is None:
          # from scratch
          new_delivery_id = str(delivery_module.generateNewId())
          delivery = delivery_module.newContent(
            portal_type=self.getDeliveryPortalType(),
            id=new_delivery_id,
            created_by_builder=1,
            activate_kw=activate_kw,**kw)
        else:
          # from duplicated original delivery
          old_delivery = old_delivery.getExplanationValue()
          cp = tryMethodCallWithTemporaryPermission(
            delivery_module, 'Copy or Move',
            lambda parent, *ids:
            parent._duplicate(parent.manage_copyObjects(ids=ids))[0],
            (delivery_module, old_delivery.getId()), {}, CopyError)
          delivery = delivery_module[cp['new_id']]
          # delete non-split movements
          keep_id_list = [y.getDeliveryValue().getId() for y in \
                          movement_group.getMovementList()]
          delete_id_list = [x.getId() for x in delivery.contentValues() \
                           if x.getId() not in keep_id_list]
          delivery.deleteContent(delete_id_list)
      # Put properties on delivery
      self._setUpdated(delivery, 'delivery')
      if property_dict:
Romain Courteaud's avatar
Romain Courteaud committed
391 392 393 394 395 396 397
        delivery.edit(**property_dict)

      # Then, create delivery line
      for group in movement_group.getGroupList():
        self._deliveryLineGroupProcessing(
                                delivery,
                                group,
398 399 400 401
                                self.getDeliveryLineMovementGroupList()[1:],
                                divergence_list=divergence_list,
                                activate_kw=activate_kw,
                                force_update=force_update)
Romain Courteaud's avatar
Romain Courteaud committed
402 403
      delivery_list.append(delivery)
    return delivery_list
404

Romain Courteaud's avatar
Romain Courteaud committed
405
  def _deliveryLineGroupProcessing(self, delivery, movement_group,
406 407 408
                                   collect_order_list, movement_group_list=None,
                                   divergence_list=None,
                                   activate_kw=None, force_update=0, **kw):
Romain Courteaud's avatar
Romain Courteaud committed
409 410 411
    """
      Build delivery line from a list of movement on a delivery
    """
412 413 414 415 416 417 418 419
    if movement_group_list is None:
      movement_group_list = []
    if divergence_list is None:
      divergence_list = []
    # do not use 'append' or '+=' because they are destructive.
    movement_group_list = movement_group_list + [movement_group]

    if len(collect_order_list):
Romain Courteaud's avatar
Romain Courteaud committed
420 421 422
      # Get sorted movement for each delivery line
      for group in movement_group.getGroupList():
        self._deliveryLineGroupProcessing(
423 424 425 426
          delivery, group, collect_order_list[1:],
          movement_group_list=movement_group_list,
          divergence_list=divergence_list,
          activate_kw=activate_kw, force_update=force_update)
Romain Courteaud's avatar
Romain Courteaud committed
427 428 429
    else:
      # Test if we can update an existing line, or if we need to create a new
      # one
430 431 432 433 434 435 436 437 438
      delivery_line_to_update_list = [x for x in delivery.contentValues(
        portal_type=self.getDeliveryLinePortalType()) if \
                                      not self._isUpdated(x, 'line')]
      delivery_line, property_dict = self._findUpdatableObject(
        delivery_line_to_update_list, movement_group_list,
        divergence_list)
      if delivery_line is not None:
        update_existing_line = 1
      else:
Romain Courteaud's avatar
Romain Courteaud committed
439
        # Create delivery line
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 465 466 467 468 469 470 471
        update_existing_line = 0
        try:
          old_delivery_line = self._searchUpByPortalType(
            movement_group.getMovementList()[0].getDeliveryValue(),
            self.getDeliveryLinePortalType())
        except AttributeError:
          old_delivery_line = None
        if old_delivery_line is None:
          # from scratch
          new_delivery_line_id = str(delivery.generateNewId())
          delivery_line = delivery.newContent(
            portal_type=self.getDeliveryLinePortalType(),
            id=new_delivery_line_id,
            variation_category_list=[],
            activate_kw=activate_kw)
        else:
          # from duplicated original line
          cp = tryMethodCallWithTemporaryPermission(
            delivery, 'Copy or Move',
            lambda parent, *ids:
            parent._duplicate(parent.manage_copyObjects(ids=ids))[0],
            (delivery, old_delivery_line.getId()), {}, CopyError)
          delivery_line = delivery[cp['new_id']]
          # delete non-split movements
          keep_id_list = [y.getDeliveryValue().getId() for y in \
                          movement_group.getMovementList()]
          delete_id_list = [x.getId() for x in delivery_line.contentValues() \
                           if x.getId() not in keep_id_list]
          delivery_line.deleteContent(delete_id_list)
      # Put properties on delivery line
      self._setUpdated(delivery_line, 'line')
      if property_dict:
Romain Courteaud's avatar
Romain Courteaud committed
472
        delivery_line.edit(**property_dict)
473

Romain Courteaud's avatar
Romain Courteaud committed
474 475 476 477 478 479
      # Update variation category list on line
      line_variation_category_list = delivery_line.getVariationCategoryList()
      for movement in movement_group.getMovementList():
        line_variation_category_list.extend(
                                      movement.getVariationCategoryList())
      # erase double
480 481
      line_variation_category_list = dict([(variation_category, 1) \
                                          for variation_category in \
Romain Courteaud's avatar
Romain Courteaud committed
482
                                          line_variation_category_list]).keys()
483 484
      line_variation_category_list.sort()
      delivery_line.edit(variation_category_list=line_variation_category_list)
Romain Courteaud's avatar
Romain Courteaud committed
485 486
      # Then, create delivery movement (delivery cell or complete delivery
      # line)
487
      group_list = movement_group.getGroupList()
488
      # If no group is defined for cell, we need to continue, in order to
489 490 491 492
      # save the quantity value
      if list(group_list) != []:
        for group in group_list:
          self._deliveryCellGroupProcessing(
Romain Courteaud's avatar
Romain Courteaud committed
493 494
                                    delivery_line,
                                    group,
495
                                    self.getDeliveryCellMovementGroupList()[1:],
496
                                    update_existing_line=update_existing_line,
497 498 499
                                    divergence_list=divergence_list,
                                    activate_kw=activate_kw,
                                    force_update=force_update)
500 501 502 503 504
      else:
        self._deliveryCellGroupProcessing(
                                  delivery_line,
                                  movement_group,
                                  [],
505
                                  update_existing_line=update_existing_line,
506 507 508
                                  divergence_list=divergence_list,
                                  activate_kw=activate_kw,
                                  force_update=force_update)
509

Romain Courteaud's avatar
Romain Courteaud committed
510 511

  def _deliveryCellGroupProcessing(self, delivery_line, movement_group,
512 513 514 515
                                   collect_order_list, movement_group_list=None,
                                   update_existing_line=0,
                                   divergence_list=None,
                                   activate_kw=None, force_update=0):
Romain Courteaud's avatar
Romain Courteaud committed
516 517 518 519
    """
      Build delivery cell from a list of movement on a delivery line
      or complete delivery line
    """
520 521 522 523 524 525 526 527
    if movement_group_list is None:
      movement_group_list = []
    if divergence_list is None:
      divergence_list = []
    # do not use 'append' or '+=' because they are destructive.
    movement_group_list = movement_group_list + [movement_group]

    if len(collect_order_list):
Romain Courteaud's avatar
Romain Courteaud committed
528 529 530
      # Get sorted movement for each delivery line
      for group in movement_group.getGroupList():
        self._deliveryCellGroupProcessing(
531 532 533 534 535 536 537 538
          delivery_line,
          group,
          collect_order_list[1:],
          movement_group_list=movement_group_list,
          update_existing_line=update_existing_line,
          divergence_list=divergence_list,
          activate_kw=activate_kw,
          force_update=force_update)
Romain Courteaud's avatar
Romain Courteaud committed
539 540 541
    else:
      movement_list = movement_group.getMovementList()
      if len(movement_list) != 1:
542
        raise CollectError, "DeliveryBuilder: %s unable to distinct those\
Romain Courteaud's avatar
Romain Courteaud committed
543 544 545 546 547 548
              movements: %s" % (self.getId(), str(movement_list))
      else:
        # XXX Hardcoded value
        base_id = 'movement'
        object_to_update = None
        # We need to initialize the cell
549
        update_existing_movement = 0
Romain Courteaud's avatar
Romain Courteaud committed
550 551 552 553 554
        movement = movement_list[0]
        # decide if we create a cell or if we update the line
        # Decision can only be made with line matrix range:
        # because matrix range can be empty even if line variation category
        # list is not empty
555
        property_dict = {}
Romain Courteaud's avatar
Romain Courteaud committed
556 557
        if list(delivery_line.getCellKeyList(base_id=base_id)) == []:
          # update line
558 559 560 561 562 563 564 565 566 567 568 569
          if update_existing_line == 1:
            if self._isUpdated(delivery_line, 'cell'):
              object_to_update_list = []
            else:
              object_to_update_list = [delivery_line]
            object_to_update, property_dict = self._findUpdatableObject(
              object_to_update_list, movement_group_list,
              divergence_list)
          if object_to_update is not None:
            update_existing_movement = 1
          else:
            object_to_update = delivery_line
Romain Courteaud's avatar
Romain Courteaud committed
570
        else:
571 572 573 574 575 576 577 578 579 580 581 582 583
          object_to_update_list = [
            delivery_line.getCell(base_id=base_id, *cell_key) for cell_key in \
            delivery_line.getCellKeyList(base_id=base_id) \
            if delivery_line.hasCell(base_id=base_id, *cell_key)]
          object_to_update, property_dict = self._findUpdatableObject(
            object_to_update_list, movement_group_list,
            divergence_list)
          if object_to_update is not None:
            # We update a existing cell
            # delivery_ratio of new related movement to this cell
            # must be updated to 0.
            update_existing_movement = 1

Romain Courteaud's avatar
Romain Courteaud committed
584 585
        if object_to_update is None:
          # create a new cell
586
          cell_key = movement.getVariationCategoryList(
587
              omit_optional_variation=1)
Romain Courteaud's avatar
Romain Courteaud committed
588
          if not delivery_line.hasCell(base_id=base_id, *cell_key):
589 590 591 592 593 594 595
            try:
              old_cell = movement_group.getMovementList()[0].getDeliveryValue()
            except AttributeError:
              old_cell = None
            if old_cell is None:
              # from scratch
              cell = delivery_line.newCell(base_id=base_id, \
596
                       portal_type=self.getDeliveryCellPortalType(),
597
                       activate_kw=activate_kw,*cell_key)
598 599 600 601 602 603 604 605 606
            else:
              # from duplicated original line
              cp = tryMethodCallWithTemporaryPermission(
                delivery_line, 'Copy or Move',
                lambda parent, *ids:
                parent._duplicate(parent.manage_copyObjects(ids=ids))[0],
                (delivery_line, old_cell.getId()), {}, CopyError)
              cell = delivery_line[cp['new_id']]

607 608
            vcl = movement.getVariationCategoryList()
            cell._edit(category_list=vcl,
Romain Courteaud's avatar
Romain Courteaud committed
609 610
                      # XXX hardcoded value
                      mapped_value_property_list=['quantity', 'price'],
611
                      membership_criterion_category_list=vcl,
Romain Courteaud's avatar
Romain Courteaud committed
612 613 614 615
                      membership_criterion_base_category_list=movement.\
                                             getVariationBaseCategoryList())
            object_to_update = cell
          else:
616
            raise MatrixError, 'Cell: %s already exists on %s' % \
Romain Courteaud's avatar
Romain Courteaud committed
617
                  (str(cell_key), str(delivery_line))
618
        self._setUpdated(object_to_update, 'cell')
Romain Courteaud's avatar
Romain Courteaud committed
619 620
        self._setDeliveryMovementProperties(
                            object_to_update, movement, property_dict,
621 622
                            update_existing_movement=update_existing_movement,
                            force_update=force_update)
Romain Courteaud's avatar
Romain Courteaud committed
623 624 625

  def _setDeliveryMovementProperties(self, delivery_movement,
                                     simulation_movement, property_dict,
626 627
                                     update_existing_movement=0,
                                     force_update=0):
Romain Courteaud's avatar
Romain Courteaud committed
628 629 630 631
    """
      Initialize or update delivery movement properties.
      Set delivery ratio on simulation movement.
    """
632
    if update_existing_movement == 1 and not force_update:
Romain Courteaud's avatar
Romain Courteaud committed
633 634 635 636 637 638 639 640 641 642 643 644 645
      # Important.
      # Attributes of object_to_update must not be modified here.
      # Because we can not change values that user modified.
      # Delivery will probably diverge now, but this is not the job of
      # DeliveryBuilder to resolve such problem.
      # Use Solver instead.
      simulation_movement.edit(delivery_ratio=0)
    else:
      # Now, only 1 movement is possible, so copy from this movement
      # XXX hardcoded value
      property_dict['quantity'] = simulation_movement.getQuantity()
      property_dict['price'] = simulation_movement.getPrice()
      # Update properties on object (quantity, price...)
646
      delivery_movement._edit(force_update=1, **property_dict)
Romain Courteaud's avatar
Romain Courteaud committed
647
      simulation_movement.edit(delivery_ratio=1)
648

649
  def callAfterBuildingScript(self, delivery_list, movement_list=None, **kw):
650 651 652
    """
      Call script on each delivery built
    """
653 654
    if not len(delivery_list):
      return
Jérome Perrin's avatar
Jérome Perrin committed
655 656 657
    # Parameter initialization
    if movement_list is None:
      movement_list = []
658 659
    delivery_after_generation_script_id = \
                              self.getDeliveryAfterGenerationScriptId()
660 661
    related_simulation_movement_path_list = \
                              [x.getPath() for x in movement_list]
662 663
    if delivery_after_generation_script_id not in ["", None]:
      for delivery in delivery_list:
664
        script = getattr(delivery, delivery_after_generation_script_id)
665 666 667 668 669
        # BBB: Only Python Scripts were used in the past, and they might not
        # accept an arbitrary argument. So to keep compatibility,
        # check if it can take the new parameter safely, only when
        # the callable object is a Python Script.
        safe_to_pass_parameter = True
670 671 672
        meta_type = getattr(script, 'meta_type', None)
        if meta_type == 'Script (Python)':
          # check if the script accepts related_simulation_movement_path_list
673
          safe_to_pass_parameter = False
674 675
          for param in script.params().split(','):
            param = param.split('=', 1)[0].strip()
676 677 678
            if param == 'related_simulation_movement_path_list' \
                    or param.startswith('**'):
              safe_to_pass_parameter = True
679
              break
680 681

        if safe_to_pass_parameter:
682
          script(related_simulation_movement_path_list=related_simulation_movement_path_list)
683 684
        else:
          script()
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745

  security.declareProtected(Permissions.AccessContentsInformation,
                           'getMovementGroupList')
  def getMovementGroupList(self, portal_type=None, collect_order_group=None,
                            **kw):
    """
    Return a list of movement groups sorted by collect order group and index.
    """
    category_index_dict = {}
    for i in self.getPortalObject().portal_categories.collect_order_group.contentValues():
      category_index_dict[i.getId()] = i.getIntIndex()

    def sort_movement_group(a, b):
        return cmp(category_index_dict.get(a.getCollectOrderGroup()),
                   category_index_dict.get(b.getCollectOrderGroup())) or \
               cmp(a.getIntIndex(), b.getIntIndex())
    if portal_type is None:
      portal_type = self.getPortalMovementGroupTypeList()
    movement_group_list = [x for x in self.contentValues(filter={'portal_type': portal_type}) \
                           if collect_order_group is None or collect_order_group == x.getCollectOrderGroup()]
    return sorted(movement_group_list, sort_movement_group)

  # XXX category name is hardcoded.
  def getDeliveryMovementGroupList(self, **kw):
    return self.getMovementGroupList(collect_order_group='delivery')

  # XXX category name is hardcoded.
  def getDeliveryLineMovementGroupList(self, **kw):
    return self.getMovementGroupList(collect_order_group='line')

  # XXX category name is hardcoded.
  def getDeliveryCellMovementGroupList(self, **kw):
    return self.getMovementGroupList(collect_order_group='cell')

  def _searchUpByPortalType(self, obj, portal_type):
    limit_portal_type = self.getPortalObject().getPortalType()
    while obj is not None:
      obj_portal_type = obj.getPortalType()
      if obj_portal_type == portal_type:
        break
      elif obj_portal_type == limit_portal_type:
        obj = None
        break
      else:
        obj = aq_parent(aq_inner(obj))
    return obj

  def _isUpdated(self, obj, level):
    tv = getTransactionalVariable(self)
    return level in tv['builder_processed_list'].get(obj, [])

  def _setUpdated(self, obj, level):
    tv = getTransactionalVariable(self)
    if tv.get('builder_processed_list', None) is None:
      self._resetUpdated()
    tv['builder_processed_list'][obj] = \
       tv['builder_processed_list'].get(obj, []) + [level]

  def _resetUpdated(self):
    tv = getTransactionalVariable(self)
    tv['builder_processed_list'] = {}