OrderBuilder.py 24.9 KB
Newer Older
Romain Courteaud's avatar
Romain Courteaud committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
#                    Romain Courteaud <romain@nexedi.com>
#
# 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.
#
##############################################################################

from AccessControl import ClassSecurityInfo
30
from Products.ERP5Type import Permissions, PropertySheet
Romain Courteaud's avatar
Romain Courteaud committed
31 32 33 34 35
from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5.Document.Predicate import Predicate
from Products.ERP5.Document.Amount import Amount
from Products.ERP5 import MovementGroup
from Products.ERP5Type.Utils import convertToUpperCase
36
from DateTime import DateTime
Romain Courteaud's avatar
Romain Courteaud committed
37 38
from zLOG import LOG

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

Romain Courteaud's avatar
Romain Courteaud committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
class OrderBuilder(XMLObject, Amount, Predicate):
  """
    Order Builder objects allow to gather multiple Simulation Movements
    into a single Delivery. 

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

    Order Builder objects are provided with a set a parameters to achieve 
    their goal:

    A path definition: source, destination, etc. which defines the general 
    kind of movements it applies.

    simulation_select_method which defines how to query all Simulation 
    Movements which meet certain criteria (including the above path path 
    definition).

    collect_order_list which defines how to group selected movements 
    according to gathering rules.

    delivery_select_method which defines how to select existing Delivery 
    which may eventually be updated with selected simulation movements.

    delivery_module, delivery_type and delivery_line_type which define the 
    module and portal types for newly built Deliveries and Delivery Lines.

    Order 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 
    Deliveries.
  """

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

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

  # Default Properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Arrow
                    , PropertySheet.Amount
                    , PropertySheet.Comment
                    , PropertySheet.DeliveryBuilder
                    )
93
 
94
  security.declarePublic('build')
95
  def build(self, applied_rule_uid=None, movement_relative_url_list=None,
96
            delivery_relative_url_list=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
97 98 99 100 101 102 103
    """
      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
    """
104 105 106 107 108 109 110
    # 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
111 112 113
    # Select
    if movement_relative_url_list == []:
      movement_list = self.searchMovementList(
114
                                      applied_rule_uid=applied_rule_uid,**kw)
Romain Courteaud's avatar
Romain Courteaud committed
115
    else:
116
      movement_list = [self.restrictedTraverse(relative_url) for relative_url \
Romain Courteaud's avatar
Romain Courteaud committed
117 118 119 120 121 122 123
                       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,
124
                       movement_list=movement_list,**kw)
125
    # Call a script after building
126
    self.callAfterBuildingScript(delivery_list, movement_list, **kw)
127
    # XXX Returning the delivery list is probably not necessary
Romain Courteaud's avatar
Romain Courteaud committed
128 129
    return delivery_list

130
  def callBeforeBuildingScript(self):
Romain Courteaud's avatar
Romain Courteaud committed
131
    """
132 133 134 135 136 137 138 139 140 141 142
      Call a script on the module, for example, to remove some 
      auto_planned Order.
      This part can only be done with a script, because user may want 
      to keep existing auto_planned Order, and only update lines in 
      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]:
143
      delivery_module = getattr(self.getPortalObject(), self.getDeliveryModule())
144
      getattr(delivery_module, delivery_module_before_building_script_id)()
Romain Courteaud's avatar
Romain Courteaud committed
145

146
  def searchMovementList(self, applied_rule_uid=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
147
    """
148 149 150 151 152 153 154 155
      Defines how to query all Simulation Movements which meet certain
      criteria (including the above path path definition).
      First, select movement matching to criteria define on 
      DeliveryBuilder.
      Then, call script simulation_select_method to restrict 
      movement_list.
    """
    from Products.ERP5Type.Document import newTempMovement
Romain Courteaud's avatar
Romain Courteaud committed
156
    movement_list = []
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 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
    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
        movement = newTempMovement(self.getPortalObject(), 
                                   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(
206
            start_date=DateTime(((stop_date-max_delay).Date())),
207
            stop_date=DateTime(stop_date.Date()),
208 209 210 211 212 213
            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
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    return movement_list

  def getCollectOrderList(self):
    """
      Simply method to get the 3 collect order lists define on a
      DeliveryBuilder
    """
    return self.getDeliveryCollectOrderList()+\
           self.getDeliveryLineCollectOrderList()+\
           self.getDeliveryCellCollectOrderList()

  def collectMovement(self, movement_list):
    """
      group movements in the way we want. Thanks to this method, we are able 
      to retrieve movement classed by order, resource, criterion,....
      movement_list : the list of movement wich we want to group
      check_list : the list of classes used to group movements. The order
                   of the list is important and determines by what we will
                   group movement first
                   Typically, check_list is :
                   [DateMovementGroup,PathMovementGroup,...]
    """
236 237 238
    class_list = [getattr(MovementGroup, x) \
                  for x in self.getCollectOrderList()]
    last_line_class_name = self.getDeliveryCollectOrderList()[-1]
239
    separate_method_name_list = self.getDeliveryCellSeparateOrderList([])
Romain Courteaud's avatar
Romain Courteaud committed
240 241 242 243 244 245 246 247
    my_root_group = MovementGroup.RootMovementGroup(
                           class_list,
                           last_line_class_name=last_line_class_name,
                           separate_method_name_list=separate_method_name_list)
    for movement in movement_list:
      my_root_group.append(movement)
    return my_root_group

248
  def testObjectProperties(self, instance, property_dict):
Romain Courteaud's avatar
Romain Courteaud committed
249
    """
250
      Test instance properties.
Romain Courteaud's avatar
Romain Courteaud committed
251 252 253 254
    """
    result = 1
    for key in property_dict:
      getter_name = 'get%s' % convertToUpperCase(key)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
255 256 257
      getter = getattr(instance, getter_name, None)
      if getter is not None:
        value = getter()
Romain Courteaud's avatar
Romain Courteaud committed
258 259 260 261 262 263 264 265
        if value != property_dict[key]:
          result = 0
          break
      else:
        result = 0
        break
    return result

266
  def buildDeliveryList(self, movement_group, delivery_relative_url_list=None,
267
                        movement_list=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
268 269 270
    """
      Build deliveries from a list of movements
    """
271 272 273
    # Parameter initialization
    if delivery_relative_url_list is None:
      delivery_relative_url_list = []
Romain Courteaud's avatar
Romain Courteaud committed
274
    # Module where we can create new deliveries
275 276 277
    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
278 279 280 281
                               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]:
282
      to_update_delivery_sql_list = getattr(self, delivery_select_method_id) \
Romain Courteaud's avatar
Romain Courteaud committed
283
                                      (movement_list=movement_list)
284 285
      delivery_to_update_list.extend([sql_delivery.getObject() \
                                     for sql_delivery \
Romain Courteaud's avatar
Romain Courteaud committed
286 287 288 289 290 291
                                     in to_update_delivery_sql_list])
    delivery_list = self._deliveryGroupProcessing(
                          delivery_module,
                          movement_group,
                          self.getDeliveryCollectOrderList(),
                          {},
292 293
                          delivery_to_update_list=delivery_to_update_list,
                          **kw)
Romain Courteaud's avatar
Romain Courteaud committed
294 295 296 297
    return delivery_list

  def _deliveryGroupProcessing(self, delivery_module, movement_group, 
                               collect_order_list, property_dict,
298 299
                               delivery_to_update_list=None,
                               activate_kw=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
300 301 302
    """
      Build empty delivery from a list of movement
    """
303 304 305
    # Parameter initialization
    if delivery_to_update_list is None:
      delivery_to_update_list = []
Romain Courteaud's avatar
Romain Courteaud committed
306 307 308 309 310 311 312 313 314 315 316 317
    delivery_list = []
    # Get current properties from current movement group
    # And fill property_dict
    property_dict.update(movement_group.getGroupEditDict())
    if collect_order_list != []:
      # Get sorted movement for each delivery
      for group in movement_group.getGroupList():
        new_delivery_list = self._deliveryGroupProcessing(
                              delivery_module,
                              group,
                              collect_order_list[1:],
                              property_dict.copy(),
318 319
                              delivery_to_update_list=delivery_to_update_list,
                              activate_kw=activate_kw)
Romain Courteaud's avatar
Romain Courteaud committed
320 321 322 323 324 325 326 327 328 329 330 331
        delivery_list.extend(new_delivery_list)
    else:
      # Test if we can update a existing delivery, or if we need to create 
      # a new one
      delivery = None
      for delivery_to_update in delivery_to_update_list:
        if self.testObjectProperties(delivery_to_update, property_dict):
          # Check if delivery has the correct portal_type
          if delivery_to_update.getPortalType() ==\
                                        self.getDeliveryPortalType():
            delivery = delivery_to_update
            break
Romain Courteaud's avatar
Romain Courteaud committed
332
      if delivery is None:
Romain Courteaud's avatar
Romain Courteaud committed
333 334 335 336
        # Create delivery
        new_delivery_id = str(delivery_module.generateNewId())
        delivery = delivery_module.newContent(
                                  portal_type=self.getDeliveryPortalType(),
337
                                  id=new_delivery_id,
338
                                  created_by_builder=1,
339
                                  activate_kw=activate_kw,**kw)
Romain Courteaud's avatar
Romain Courteaud committed
340 341 342 343 344 345 346 347 348
        # Put properties on delivery
        delivery.edit(**property_dict)

      # Then, create delivery line
      for group in movement_group.getGroupList():
        self._deliveryLineGroupProcessing(
                                delivery,
                                group,
                                self.getDeliveryLineCollectOrderList()[1:],
349 350
                                {},
                                activate_kw=activate_kw,**kw)
Romain Courteaud's avatar
Romain Courteaud committed
351 352 353 354
      delivery_list.append(delivery)
    return delivery_list
      
  def _deliveryLineGroupProcessing(self, delivery, movement_group,
355
                                   collect_order_list, property_dict,
356
                                   activate_kw=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
357 358 359 360 361 362 363 364 365 366
    """
      Build delivery line from a list of movement on a delivery
    """
    # Get current properties from current movement group
    # And fill property_dict
    property_dict.update(movement_group.getGroupEditDict())
    if collect_order_list != []:
      # Get sorted movement for each delivery line
      for group in movement_group.getGroupList():
        self._deliveryLineGroupProcessing(
367
          delivery, group, collect_order_list[1:], property_dict.copy(),
368
          activate_kw=activate_kw)
Romain Courteaud's avatar
Romain Courteaud committed
369 370 371 372
    else:
      # Test if we can update an existing line, or if we need to create a new
      # one
      delivery_line = None
373
      update_existing_line = 0
374 375 376 377 378 379
      for delivery_line_to_update in delivery.contentValues(
               filter={'portal_type':self.getDeliveryLinePortalType()}):
        if self.testObjectProperties(delivery_line_to_update, property_dict):
          delivery_line = delivery_line_to_update
          update_existing_line = 1
          break
Romain Courteaud's avatar
Romain Courteaud committed
380
      if delivery_line is None:
Romain Courteaud's avatar
Romain Courteaud committed
381 382 383 384 385
        # Create delivery line
        new_delivery_line_id = str(delivery.generateNewId())
        delivery_line = delivery.newContent(
                                  portal_type=self.getDeliveryLinePortalType(),
                                  id=new_delivery_line_id,
386 387
                                  variation_category_list=[],
                                  activate_kw=activate_kw)
Romain Courteaud's avatar
Romain Courteaud committed
388 389 390 391 392 393 394 395
        # Put properties on delivery line
        delivery_line.edit(**property_dict)
      # 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
396 397
      line_variation_category_list = dict([(variation_category, 1) \
                                          for variation_category in \
Romain Courteaud's avatar
Romain Courteaud committed
398
                                          line_variation_category_list]).keys()
399 400
      line_variation_category_list.sort()
      delivery_line.edit(variation_category_list=line_variation_category_list)
Romain Courteaud's avatar
Romain Courteaud committed
401 402
      # Then, create delivery movement (delivery cell or complete delivery
      # line)
403 404 405 406 407 408
      group_list = movement_group.getGroupList()
      # If no group is defined for cell, we need to continue, in order to 
      # save the quantity value
      if list(group_list) != []:
        for group in group_list:
          self._deliveryCellGroupProcessing(
Romain Courteaud's avatar
Romain Courteaud committed
409 410 411 412
                                    delivery_line,
                                    group,
                                    self.getDeliveryCellCollectOrderList()[1:],
                                    {},
413 414
                                    update_existing_line=update_existing_line,
                                    activate_kw=activate_kw)
415 416 417 418 419 420
      else:
        self._deliveryCellGroupProcessing(
                                  delivery_line,
                                  movement_group,
                                  [],
                                  {},
421 422
                                  update_existing_line=update_existing_line,
                                  activate_kw=activate_kw)
423

Romain Courteaud's avatar
Romain Courteaud committed
424 425 426

  def _deliveryCellGroupProcessing(self, delivery_line, movement_group,
                                   collect_order_list, property_dict,
427
                                   update_existing_line=0,activate_kw=None):
Romain Courteaud's avatar
Romain Courteaud committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    """
      Build delivery cell from a list of movement on a delivery line
      or complete delivery line
    """
    # Get current properties from current movement group
    # And fill property_dict
    property_dict.update(movement_group.getGroupEditDict())
    if collect_order_list != []:
      # Get sorted movement for each delivery line
      for group in movement_group.getGroupList():
        self._deliveryCellGroupProcessing(
                                    delivery_line, 
                                    group, 
                                    collect_order_list[1:], 
                                    property_dict.copy(),
443 444
                                    update_existing_line=update_existing_line,
                                    activate_kw=activate_kw)
Romain Courteaud's avatar
Romain Courteaud committed
445 446 447
    else:
      movement_list = movement_group.getMovementList()
      if len(movement_list) != 1:
448
        raise CollectError, "DeliveryBuilder: %s unable to distinct those\
Romain Courteaud's avatar
Romain Courteaud committed
449 450 451 452 453 454
              movements: %s" % (self.getId(), str(movement_list))
      else:
        # XXX Hardcoded value
        base_id = 'movement'
        object_to_update = None
        # We need to initialize the cell
455
        update_existing_movement = 0
Romain Courteaud's avatar
Romain Courteaud committed
456 457 458 459 460 461 462 463 464 465 466
        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
        if list(delivery_line.getCellKeyList(base_id=base_id)) == []:
          # update line
          object_to_update = delivery_line
          if self.testObjectProperties(delivery_line, property_dict):
            if update_existing_line == 1:
              # We update a initialized line
467
              update_existing_movement = 1
Romain Courteaud's avatar
Romain Courteaud committed
468 469 470 471 472 473 474 475
        else:
          for cell_key in delivery_line.getCellKeyList(base_id=base_id):
            if delivery_line.hasCell(base_id=base_id, *cell_key):
              cell = delivery_line.getCell(base_id=base_id, *cell_key)
              if self.testObjectProperties(cell, property_dict):
                # We update a existing cell
                # delivery_ratio of new related movement to this cell 
                # must be updated to 0.
476
                update_existing_movement = 1
Romain Courteaud's avatar
Romain Courteaud committed
477 478 479 480
                object_to_update = cell
                break
        if object_to_update is None:
          # create a new cell
481 482
          cell_key = movement.getVariationCategoryList(
                                                   omit_option_base_category=1)
Romain Courteaud's avatar
Romain Courteaud committed
483
          if not delivery_line.hasCell(base_id=base_id, *cell_key):
484
            cell = delivery_line.newCell(base_id=base_id, \
485 486
                       portal_type=self.getDeliveryCellPortalType(), 
                       activate_kw=activate_kw,*cell_key)
487 488
            vcl = movement.getVariationCategoryList()
            cell._edit(category_list=vcl,
Romain Courteaud's avatar
Romain Courteaud committed
489 490
                      # XXX hardcoded value
                      mapped_value_property_list=['quantity', 'price'],
491
                      membership_criterion_category_list=vcl,
Romain Courteaud's avatar
Romain Courteaud committed
492 493 494 495
                      membership_criterion_base_category_list=movement.\
                                             getVariationBaseCategoryList())
            object_to_update = cell
          else:
496
            raise MatrixError, 'Cell: %s already exists on %s' % \
Romain Courteaud's avatar
Romain Courteaud committed
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
                  (str(cell_key), str(delivery_line))
        self._setDeliveryMovementProperties(
                            object_to_update, movement, property_dict,
                            update_existing_movement=update_existing_movement)

  def _setDeliveryMovementProperties(self, delivery_movement,
                                     simulation_movement, property_dict,
                                     update_existing_movement=0):
    """
      Initialize or update delivery movement properties.
      Set delivery ratio on simulation movement.
    """
    if update_existing_movement == 1:
      # 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.setDeliveryRatio(0)
      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...)
524
      delivery_movement._edit(force_update=1, **property_dict)
Romain Courteaud's avatar
Romain Courteaud committed
525 526
      #simulation_movement.setDeliveryRatio(1)
      simulation_movement.edit(delivery_ratio=1)
527

528
  def callAfterBuildingScript(self, delivery_list, movement_list=None, **kw):
529 530 531 532 533
    """
      Call script on each delivery built
    """
    delivery_after_generation_script_id = \
                              self.getDeliveryAfterGenerationScriptId()
534 535
    related_simulation_movement_path_list = \
                              [x.getPath() for x in movement_list]
536 537
    if delivery_after_generation_script_id not in ["", None]:
      for delivery in delivery_list:
538
        script = getattr(delivery, delivery_after_generation_script_id)
539 540 541 542 543
        # 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
544 545 546
        meta_type = getattr(script, 'meta_type', None)
        if meta_type == 'Script (Python)':
          # check if the script accepts related_simulation_movement_path_list
547
          safe_to_pass_parameter = False
548 549
          for param in script.params().split(','):
            param = param.split('=', 1)[0].strip()
550 551 552
            if param == 'related_simulation_movement_path_list' \
                    or param.startswith('**'):
              safe_to_pass_parameter = True
553
              break
554 555

        if safe_to_pass_parameter:
556
          script(related_simulation_movement_path_list=related_simulation_movement_path_list)
557 558
        else:
          script()