OrderBuilder.py 34.5 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 Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
38
from DateTime import DateTime
39
from Acquisition import aq_parent, aq_inner
Romain Courteaud's avatar
Romain Courteaud committed
40

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

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

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

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

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

58 59
    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
60 61
    definition).

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

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

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

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

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

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

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

96
  security.declarePublic('build')
97
  def build(self, applied_rule_uid=None, movement_relative_url_list=None,
98
            delivery_relative_url_list=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
99 100 101 102 103 104 105
    """
      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
    """
106 107 108 109 110 111 112
    # 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
113
    # Select
114
    if len(movement_relative_url_list) == 0:
Romain Courteaud's avatar
Romain Courteaud committed
115
      movement_list = self.searchMovementList(
116
                                      applied_rule_uid=applied_rule_uid,**kw)
Romain Courteaud's avatar
Romain Courteaud committed
117
    else:
118
      movement_list = [self.restrictedTraverse(relative_url) for relative_url \
Romain Courteaud's avatar
Romain Courteaud committed
119 120
                       in movement_relative_url_list]
    # Collect
121
    root_group_node = self.collectMovement(movement_list)
Romain Courteaud's avatar
Romain Courteaud committed
122 123
    # Build
    delivery_list = self.buildDeliveryList(
124
                       root_group_node,
Romain Courteaud's avatar
Romain Courteaud committed
125
                       delivery_relative_url_list=delivery_relative_url_list,
126
                       movement_list=movement_list,**kw)
127
    # Call a script after building
128
    self.callAfterBuildingScript(delivery_list, movement_list, **kw)
129
    # XXX Returning the delivery list is probably not necessary
Romain Courteaud's avatar
Romain Courteaud committed
130 131
    return delivery_list

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

148
  def searchMovementList(self, *args, **kw):
Romain Courteaud's avatar
Romain Courteaud committed
149
    """
150 151
      Defines how to query all Simulation Movements which meet certain
      criteria (including the above path path definition).
152
      First, select movement matching to criteria define on
153
      DeliveryBuilder.
154
      Then, call script simulation_select_method to restrict
155 156
      movement_list.
    """
157 158 159 160 161
    searchMovementList = UnrestrictedMethod(self._searchMovementList)
    return searchMovementList(*args, **kw)

  def _searchMovementList(self, applied_rule_uid=None,**kw):
    """This method is wrapped by UnrestrictedMethod."""
162
    from Products.ERP5Type.Document import newTempMovement
Romain Courteaud's avatar
Romain Courteaud committed
163
    movement_list = []
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    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
185
        movement = newTempMovement(self.getPortalObject(),
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
                                   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(
213
            start_date=DateTime(((stop_date-max_delay).Date())),
214
            stop_date=DateTime(stop_date.Date()),
215 216 217 218 219 220
            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
221 222 223 224
    return movement_list

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

244
  def _test(self, instance, movement_group_node_list,
245 246 247
                    divergence_list):
    result = True
    new_property_dict = {}
248 249
    for movement_group_node in movement_group_node_list:
      tmp_result, tmp_property_dict = movement_group_node.test(
250
        instance, divergence_list)
251
      if not tmp_result:
252 253 254 255
        result = tmp_result
      new_property_dict.update(tmp_property_dict)
    return result, new_property_dict

256
  def _findUpdatableObject(self, instance_list, movement_group_node_list,
257 258 259 260
                           divergence_list):
    instance = None
    property_dict = {}
    if not len(instance_list):
261 262
      for movement_group_node in movement_group_node_list:
        property_dict.update(movement_group_node.getGroupEditDict())
263
    else:
264 265
      # we want to check the original delivery first.
      # so sort instance_list by that current is exists or not.
266
      try:
267 268 269 270 271 272 273
        current = movement_group_node_list[-1].getMovementList()[0].getDeliveryValue()
        portal = self.getPortalObject()
        while current != portal:
          if current in instance_list:
            instance_list.sort(key=lambda x: x != current and 1 or 0)
            break
          current = current.getParentValue()
274
      except AttributeError:
275
        pass
276
      for instance_to_update in instance_list:
277
        result, property_dict = self._test(
278
          instance_to_update, movement_group_node_list, divergence_list)
279 280
        if result == True:
          instance = instance_to_update
Romain Courteaud's avatar
Romain Courteaud committed
281
          break
282
    return instance, property_dict
Romain Courteaud's avatar
Romain Courteaud committed
283

284
  def buildDeliveryList(self, *args, **kw):
Romain Courteaud's avatar
Romain Courteaud committed
285 286 287
    """
      Build deliveries from a list of movements
    """
288 289 290
    buildDeliveryList = UnrestrictedMethod(self._buildDeliveryList)
    return buildDeliveryList(*args, **kw)

291
  def _buildDeliveryList(self, movement_group_node, delivery_relative_url_list=None,
292 293
                         movement_list=None,**kw):
    """This method is wrapped by UnrestrictedMethod."""
294 295 296
    # Parameter initialization
    if delivery_relative_url_list is None:
      delivery_relative_url_list = []
Jérome Perrin's avatar
Jérome Perrin committed
297 298
    if movement_list is None:
      movement_list = []
Romain Courteaud's avatar
Romain Courteaud committed
299
    # Module where we can create new deliveries
300 301 302
    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
303 304 305 306
                               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]:
307
      to_update_delivery_sql_list = getattr(self, delivery_select_method_id) \
Romain Courteaud's avatar
Romain Courteaud committed
308
                                      (movement_list=movement_list)
309 310
      delivery_to_update_list.extend([sql_delivery.getObject() \
                                     for sql_delivery \
Romain Courteaud's avatar
Romain Courteaud committed
311
                                     in to_update_delivery_sql_list])
312 313 314
    # We do not want to update the same object more than twice in one
    # _deliveryGroupProcessing().
    self._resetUpdated()
315
    delivery_list = self._processDeliveryGroup(
Romain Courteaud's avatar
Romain Courteaud committed
316
                          delivery_module,
317
                          movement_group_node,
318
                          self.getDeliveryMovementGroupList(),
319 320
                          delivery_to_update_list=delivery_to_update_list,
                          **kw)
Romain Courteaud's avatar
Romain Courteaud committed
321 322
    return delivery_list

323 324 325 326 327
  def _processDeliveryGroup(self, delivery_module, movement_group_node,
                            collect_order_list, movement_group_node_list=None,
                            delivery_to_update_list=None,
                            divergence_list=None,
                            activate_kw=None, force_update=0, **kw):
328 329 330
    """
      Build delivery from a list of movement
    """
331 332
    if movement_group_node_list is None:
      movement_group_node_list = []
333 334 335
    if divergence_list is None:
      divergence_list = []
    # do not use 'append' or '+=' because they are destructive.
336
    movement_group_node_list = movement_group_node_list + [movement_group_node]
337 338 339
    # Parameter initialization
    if delivery_to_update_list is None:
      delivery_to_update_list = []
Romain Courteaud's avatar
Romain Courteaud committed
340
    delivery_list = []
341 342

    if len(collect_order_list):
Romain Courteaud's avatar
Romain Courteaud committed
343
      # Get sorted movement for each delivery
344 345
      for grouped_node in movement_group_node.getGroupList():
        new_delivery_list = self._processDeliveryGroup(
Romain Courteaud's avatar
Romain Courteaud committed
346
                              delivery_module,
347
                              grouped_node,
Romain Courteaud's avatar
Romain Courteaud committed
348
                              collect_order_list[1:],
349
                              movement_group_node_list=movement_group_node_list,
350
                              delivery_to_update_list=delivery_to_update_list,
351 352
                              divergence_list=divergence_list,
                              activate_kw=activate_kw,
353
                              force_update=force_update)
Romain Courteaud's avatar
Romain Courteaud committed
354
        delivery_list.extend(new_delivery_list)
355
        force_update = 0
Romain Courteaud's avatar
Romain Courteaud committed
356
    else:
357
      # Test if we can update a existing delivery, or if we need to create
Romain Courteaud's avatar
Romain Courteaud committed
358
      # a new one
359 360 361 362 363
      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(
364
        delivery_to_update_list, movement_group_node_list,
365 366 367 368 369 370 371
        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
372
      if delivery is None:
Romain Courteaud's avatar
Romain Courteaud committed
373
        # Create delivery
374
        try:
375
          old_delivery = self._searchUpByPortalType(
376
            movement_group_node.getMovementList()[0].getDeliveryValue(),
377
            self.getDeliveryPortalType())
378 379 380 381 382 383 384 385 386
        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,
387
            activate_kw=activate_kw)
388 389 390 391 392 393 394 395 396 397
        else:
          # from duplicated original delivery
          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 \
398
                          movement_group_node.getMovementList()]
399 400 401 402 403 404
          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
405 406 407
        delivery.edit(**property_dict)

      # Then, create delivery line
408 409
      for grouped_node in movement_group_node.getGroupList():
        self._processDeliveryLineGroup(
Romain Courteaud's avatar
Romain Courteaud committed
410
                                delivery,
411
                                grouped_node,
412 413 414 415
                                self.getDeliveryLineMovementGroupList()[1:],
                                divergence_list=divergence_list,
                                activate_kw=activate_kw,
                                force_update=force_update)
Romain Courteaud's avatar
Romain Courteaud committed
416 417
      delivery_list.append(delivery)
    return delivery_list
418

419 420 421 422
  def _processDeliveryLineGroup(self, delivery, movement_group_node,
                                collect_order_list, movement_group_node_list=None,
                                divergence_list=None,
                                activate_kw=None, force_update=0, **kw):
Romain Courteaud's avatar
Romain Courteaud committed
423 424 425
    """
      Build delivery line from a list of movement on a delivery
    """
426 427
    if movement_group_node_list is None:
      movement_group_node_list = []
428 429 430
    if divergence_list is None:
      divergence_list = []
    # do not use 'append' or '+=' because they are destructive.
431
    movement_group_node_list = movement_group_node_list + [movement_group_node]
432

433
    if len(collect_order_list) and not movement_group_node.getCurrentMovementGroup().isBranch():
Romain Courteaud's avatar
Romain Courteaud committed
434
      # Get sorted movement for each delivery line
435 436 437 438 439 440
      for grouped_node in movement_group_node.getGroupList():
        self._processDeliveryLineGroup(
          delivery,
          grouped_node,
          collect_order_list[1:],
          movement_group_node_list=movement_group_node_list,
441
          divergence_list=divergence_list,
442 443
          activate_kw=activate_kw,
          force_update=force_update)
Romain Courteaud's avatar
Romain Courteaud committed
444 445 446
    else:
      # Test if we can update an existing line, or if we need to create a new
      # one
447 448 449 450
      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(
451
        delivery_line_to_update_list, movement_group_node_list,
452 453 454 455
        divergence_list)
      if delivery_line is not None:
        update_existing_line = 1
      else:
Romain Courteaud's avatar
Romain Courteaud committed
456
        # Create delivery line
457 458 459
        update_existing_line = 0
        try:
          old_delivery_line = self._searchUpByPortalType(
460
            movement_group_node.getMovementList()[0].getDeliveryValue(),
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
            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']]
480 481
          # reset variation category list
          delivery_line.setVariationCategoryList([])
482 483
          # delete non-split movements
          keep_id_list = [y.getDeliveryValue().getId() for y in \
484
                          movement_group_node.getMovementList()]
485 486 487 488 489 490
          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
491
        delivery_line.edit(**property_dict)
492

493 494 495 496 497 498 499 500 501 502 503 504
      if movement_group_node.getCurrentMovementGroup().isBranch():
        for grouped_node in movement_group_node.getGroupList():
          self._processDeliveryLineGroup(
            delivery_line,
            grouped_node,
            collect_order_list[1:],
            movement_group_node_list=movement_group_node_list,
            divergence_list=divergence_list,
            activate_kw=activate_kw,
            force_update=force_update)
        return

Romain Courteaud's avatar
Romain Courteaud committed
505
      # Update variation category list on line
506 507 508
      variation_category_dict = dict([(variation_category, True) for
                                      variation_category in
                                      delivery_line.getVariationCategoryList()])
509
      for movement in movement_group_node.getMovementList():
510 511 512 513
        for category in movement.getVariationCategoryList():
          variation_category_dict[category] = True
      variation_category_list = sorted(variation_category_dict.keys())
      delivery_line.setVariationCategoryList(variation_category_list)
Romain Courteaud's avatar
Romain Courteaud committed
514 515
      # Then, create delivery movement (delivery cell or complete delivery
      # line)
516
      grouped_node_list = movement_group_node.getGroupList()
517
      # If no group is defined for cell, we need to continue, in order to
518
      # save the quantity value
519 520 521
      if len(grouped_node_list):
        for grouped_node in grouped_node_list:
          self._processDeliveryCellGroup(
Romain Courteaud's avatar
Romain Courteaud committed
522
                                    delivery_line,
523
                                    grouped_node,
524
                                    self.getDeliveryCellMovementGroupList()[1:],
525
                                    update_existing_line=update_existing_line,
526 527 528
                                    divergence_list=divergence_list,
                                    activate_kw=activate_kw,
                                    force_update=force_update)
529
      else:
530
        self._processDeliveryCellGroup(
531
                                  delivery_line,
532
                                  movement_group_node,
533
                                  [],
534
                                  update_existing_line=update_existing_line,
535 536 537
                                  divergence_list=divergence_list,
                                  activate_kw=activate_kw,
                                  force_update=force_update)
538

Romain Courteaud's avatar
Romain Courteaud committed
539

540 541 542 543 544
  def _processDeliveryCellGroup(self, delivery_line, movement_group_node,
                                collect_order_list, movement_group_node_list=None,
                                update_existing_line=0,
                                divergence_list=None,
                                activate_kw=None, force_update=0):
Romain Courteaud's avatar
Romain Courteaud committed
545 546 547 548
    """
      Build delivery cell from a list of movement on a delivery line
      or complete delivery line
    """
549 550
    if movement_group_node_list is None:
      movement_group_node_list = []
551 552 553
    if divergence_list is None:
      divergence_list = []
    # do not use 'append' or '+=' because they are destructive.
554
    movement_group_node_list = movement_group_node_list + [movement_group_node]
555 556

    if len(collect_order_list):
Romain Courteaud's avatar
Romain Courteaud committed
557
      # Get sorted movement for each delivery line
558 559
      for grouped_node in movement_group_node.getGroupList():
        self._processDeliveryCellGroup(
560
          delivery_line,
561
          grouped_node,
562
          collect_order_list[1:],
563
          movement_group_node_list=movement_group_node_list,
564 565 566 567
          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
568
    else:
569
      movement_list = movement_group_node.getMovementList()
Romain Courteaud's avatar
Romain Courteaud committed
570
      if len(movement_list) != 1:
571
        raise CollectError, "DeliveryBuilder: %s unable to distinct those\
Romain Courteaud's avatar
Romain Courteaud committed
572 573 574 575 576 577
              movements: %s" % (self.getId(), str(movement_list))
      else:
        # XXX Hardcoded value
        base_id = 'movement'
        object_to_update = None
        # We need to initialize the cell
578
        update_existing_movement = 0
Romain Courteaud's avatar
Romain Courteaud committed
579 580 581 582 583
        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
584
        property_dict = {}
585
        if len(delivery_line.getCellKeyList(base_id=base_id)) == 0:
Romain Courteaud's avatar
Romain Courteaud committed
586
          # update line
587 588 589 590 591
          if update_existing_line == 1:
            if self._isUpdated(delivery_line, 'cell'):
              object_to_update_list = []
            else:
              object_to_update_list = [delivery_line]
592 593 594
          else:
            object_to_update_list = []
          object_to_update, property_dict = self._findUpdatableObject(
595
            object_to_update_list, movement_group_node_list,
596
            divergence_list)
597 598 599 600
          if object_to_update is not None:
            update_existing_movement = 1
          else:
            object_to_update = delivery_line
Romain Courteaud's avatar
Romain Courteaud committed
601
        else:
602 603 604 605 606
          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(
607
            object_to_update_list, movement_group_node_list,
608 609 610 611 612 613 614
            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
615 616
        if object_to_update is None:
          # create a new cell
617
          cell_key = movement.getVariationCategoryList(
618
              omit_optional_variation=1)
Romain Courteaud's avatar
Romain Courteaud committed
619
          if not delivery_line.hasCell(base_id=base_id, *cell_key):
620
            try:
621
              old_cell = movement_group_node.getMovementList()[0].getDeliveryValue()
622 623 624 625 626
            except AttributeError:
              old_cell = None
            if old_cell is None:
              # from scratch
              cell = delivery_line.newCell(base_id=base_id, \
627
                       portal_type=self.getDeliveryCellPortalType(),
628
                       activate_kw=activate_kw,*cell_key)
629 630 631 632 633 634 635 636 637
            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']]

638 639
            vcl = movement.getVariationCategoryList()
            cell._edit(category_list=vcl,
Romain Courteaud's avatar
Romain Courteaud committed
640 641
                      # XXX hardcoded value
                      mapped_value_property_list=['quantity', 'price'],
642
                      membership_criterion_category_list=vcl,
Romain Courteaud's avatar
Romain Courteaud committed
643 644 645 646
                      membership_criterion_base_category_list=movement.\
                                             getVariationBaseCategoryList())
            object_to_update = cell
          else:
647
            raise MatrixError, 'Cell: %s already exists on %s' % \
Romain Courteaud's avatar
Romain Courteaud committed
648
                  (str(cell_key), str(delivery_line))
649
        self._setUpdated(object_to_update, 'cell')
Romain Courteaud's avatar
Romain Courteaud committed
650 651
        self._setDeliveryMovementProperties(
                            object_to_update, movement, property_dict,
652
                            update_existing_movement=update_existing_movement,
653
                            force_update=force_update, activate_kw=activate_kw)
Romain Courteaud's avatar
Romain Courteaud committed
654 655 656

  def _setDeliveryMovementProperties(self, delivery_movement,
                                     simulation_movement, property_dict,
657
                                     update_existing_movement=0,
658
                                     force_update=0, activate_kw=None):
Romain Courteaud's avatar
Romain Courteaud committed
659 660 661 662
    """
      Initialize or update delivery movement properties.
      Set delivery ratio on simulation movement.
    """
663
    if update_existing_movement == 1 and not force_update:
Romain Courteaud's avatar
Romain Courteaud committed
664 665 666 667 668 669 670 671 672 673 674 675 676
      # 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...)
677
      delivery_movement._edit(force_update=1, **property_dict)
Romain Courteaud's avatar
Romain Courteaud committed
678
      simulation_movement.edit(delivery_ratio=1)
679

680
  def callAfterBuildingScript(self, *args, **kw):
681
    """
682 683 684 685 686 687 688 689 690
      Call script on each delivery built.
    """
    callAfterBuildingScript = UnrestrictedMethod(self._callAfterBuildingScript)
    return callAfterBuildingScript(*args, **kw)

  def _callAfterBuildingScript(self, delivery_list, movement_list=None, **kw):
    """
      Call script on each delivery built.
      This method is wrapped by UnrestrictedMethod.
691
    """
692 693
    if not len(delivery_list):
      return
Jérome Perrin's avatar
Jérome Perrin committed
694 695 696
    # Parameter initialization
    if movement_list is None:
      movement_list = []
697 698
    delivery_after_generation_script_id = \
                              self.getDeliveryAfterGenerationScriptId()
699 700
    related_simulation_movement_path_list = \
                              [x.getPath() for x in movement_list]
701 702
    if delivery_after_generation_script_id not in ["", None]:
      for delivery in delivery_list:
703
        script = getattr(delivery, delivery_after_generation_script_id)
704 705 706 707 708
        # 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
709 710 711
        meta_type = getattr(script, 'meta_type', None)
        if meta_type == 'Script (Python)':
          # check if the script accepts related_simulation_movement_path_list
712
          safe_to_pass_parameter = False
713 714
          for param in script.params().split(','):
            param = param.split('=', 1)[0].strip()
715 716 717
            if param == 'related_simulation_movement_path_list' \
                    or param.startswith('**'):
              safe_to_pass_parameter = True
718
              break
719 720

        if safe_to_pass_parameter:
721
          script(related_simulation_movement_path_list=related_simulation_movement_path_list)
722 723
        else:
          script()
724 725 726 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 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784

  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'] = {}
785 786

  # for backward compatibilities.
787
  _deliveryGroupProcessing = _processDeliveryGroup
788 789
  _deliveryLineGroupProcessing = _processDeliveryLineGroup
  _deliveryCellGroupProcessing = _processDeliveryCellGroup