OrderBuilder.py 23.1 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 39 40 41 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 81 82 83 84 85 86 87 88 89
from zLOG import LOG

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()
  security.declareObjectProtected(Permissions.View)

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

127
  def callBeforeBuildingScript(self):
Romain Courteaud's avatar
Romain Courteaud committed
128
    """
129 130 131 132 133 134 135 136 137 138 139 140 141
      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]:
      delivery_module = getattr(self, self.getDeliveryModule())
      getattr(delivery_module, delivery_module_before_building_script_id)()
Romain Courteaud's avatar
Romain Courteaud committed
142

143
  def searchMovementList(self, applied_rule_uid=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
144
    """
145 146 147 148 149 150 151 152
      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
153
    movement_list = []
154 155 156 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
    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(
203
            start_date=DateTime(((stop_date-max_delay).Date())),
204
            stop_date=DateTime(stop_date.Date()),
205 206 207 208 209 210
            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
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    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,...]
    """
233 234 235
    class_list = [getattr(MovementGroup, x) \
                  for x in self.getCollectOrderList()]
    last_line_class_name = self.getDeliveryCollectOrderList()[-1]
Romain Courteaud's avatar
Romain Courteaud committed
236 237 238 239 240 241 242 243 244
    separate_method_name_list = self.getDeliveryCellSeparateOrderList()
    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

245
  def testObjectProperties(self, instance, property_dict):
Romain Courteaud's avatar
Romain Courteaud committed
246
    """
247
      Test instance properties.
Romain Courteaud's avatar
Romain Courteaud committed
248 249 250 251
    """
    result = 1
    for key in property_dict:
      getter_name = 'get%s' % convertToUpperCase(key)
252 253
      if hasattr(instance, getter_name):
        value = getattr(instance, getter_name)()
Romain Courteaud's avatar
Romain Courteaud committed
254 255 256 257 258 259 260 261
        if value != property_dict[key]:
          result = 0
          break
      else:
        result = 0
        break
    return result

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

  def _deliveryGroupProcessing(self, delivery_module, movement_group, 
                               collect_order_list, property_dict,
292
                               delivery_to_update_list=None):
Romain Courteaud's avatar
Romain Courteaud committed
293 294 295
    """
      Build empty delivery from a list of movement
    """
296 297 298
    # Parameter initialization
    if delivery_to_update_list is None:
      delivery_to_update_list = []
Romain Courteaud's avatar
Romain Courteaud committed
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    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(),
                              delivery_to_update_list=delivery_to_update_list)
        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
      if delivery == None:
        # Create delivery
        new_delivery_id = str(delivery_module.generateNewId())
        delivery = delivery_module.newContent(
                                  portal_type=self.getDeliveryPortalType(),
329 330
                                  id=new_delivery_id,
                                  bypass_init_script=1)
Romain Courteaud's avatar
Romain Courteaud committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344
        # 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:],
                                {})
      delivery_list.append(delivery)
    return delivery_list
      
  def _deliveryLineGroupProcessing(self, delivery, movement_group,
345 346
                                   collect_order_list, property_dict,
                                   update_requested=0):
Romain Courteaud's avatar
Romain Courteaud committed
347 348 349 350 351 352 353 354 355 356
    """
      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(
357 358
          delivery, group, collect_order_list[1:], property_dict.copy(),
          update_requested=update_requested)
Romain Courteaud's avatar
Romain Courteaud committed
359 360 361 362
    else:
      # Test if we can update an existing line, or if we need to create a new
      # one
      delivery_line = None
363
      update_existing_line = 0
364 365 366 367 368 369 370
      if update_requested==1:
        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
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
      if delivery_line == None:
        # Create delivery line
        new_delivery_line_id = str(delivery.generateNewId())
        delivery_line = delivery.newContent(
                                  portal_type=self.getDeliveryLinePortalType(),
                                  id=new_delivery_line_id,
                                  variation_category_list=[])
        # 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
386 387
      line_variation_category_list = dict([(variation_category, 1) \
                                          for variation_category in \
Romain Courteaud's avatar
Romain Courteaud committed
388 389 390 391
                                          line_variation_category_list]).keys()
      delivery_line.setVariationCategoryList(line_variation_category_list)
      # Then, create delivery movement (delivery cell or complete delivery
      # line)
392 393 394 395 396 397
      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
398 399 400 401 402
                                    delivery_line,
                                    group,
                                    self.getDeliveryCellCollectOrderList()[1:],
                                    {},
                                    update_existing_line=update_existing_line)
403 404 405 406 407 408 409 410
      else:
        self._deliveryCellGroupProcessing(
                                  delivery_line,
                                  movement_group,
                                  [],
                                  {},
                                  update_existing_line=update_existing_line)

Romain Courteaud's avatar
Romain Courteaud committed
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

  def _deliveryCellGroupProcessing(self, delivery_line, movement_group,
                                   collect_order_list, property_dict,
                                   update_existing_line=0):
    """
      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(),
                                    update_existing_line=update_existing_line)
    else:
      movement_list = movement_group.getMovementList()
      if len(movement_list) != 1:
        raise "CollectError", "DeliveryBuilder: %s unable to distinct those\
              movements: %s" % (self.getId(), str(movement_list))
      else:
        # XXX Hardcoded value
        base_id = 'movement'
        object_to_update = None
        # We need to initialize the cell
441
        update_existing_movement = 0
Romain Courteaud's avatar
Romain Courteaud committed
442 443 444 445 446 447 448 449 450 451 452
        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
453
              update_existing_movement = 1
Romain Courteaud's avatar
Romain Courteaud committed
454 455 456 457 458 459 460 461
        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.
462
                update_existing_movement = 1
Romain Courteaud's avatar
Romain Courteaud committed
463 464 465 466
                object_to_update = cell
                break
        if object_to_update is None:
          # create a new cell
467 468
          cell_key = movement.getVariationCategoryList(
                                                   omit_option_base_category=1)
Romain Courteaud's avatar
Romain Courteaud committed
469
          if not delivery_line.hasCell(base_id=base_id, *cell_key):
470
            cell = delivery_line.newCell(base_id=base_id, \
Romain Courteaud's avatar
Romain Courteaud committed
471
                       portal_type=self.getDeliveryCellPortalType(), *cell_key)
472 473
            vcl = movement.getVariationCategoryList()
            cell._edit(category_list=vcl,
Romain Courteaud's avatar
Romain Courteaud committed
474 475
                      # XXX hardcoded value
                      mapped_value_property_list=['quantity', 'price'],
476
                      membership_criterion_category_list=vcl,
Romain Courteaud's avatar
Romain Courteaud committed
477 478 479 480
                      membership_criterion_base_category_list=movement.\
                                             getVariationBaseCategoryList())
            object_to_update = cell
          else:
481
            raise 'MatrixError', 'Cell: %s already exists on %s' % \
Romain Courteaud's avatar
Romain Courteaud committed
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
                  (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...)
      delivery_movement._edit(**property_dict)
      #simulation_movement.setDeliveryRatio(1)
      simulation_movement.edit(delivery_ratio=1)
512

513
  def callAfterBuildingScript(self, delivery_list,**kw):
514 515 516 517 518 519 520 521
    """
      Call script on each delivery built
    """
    delivery_after_generation_script_id = \
                              self.getDeliveryAfterGenerationScriptId()
    if delivery_after_generation_script_id not in ["", None]:
      for delivery in delivery_list:
        getattr(delivery, delivery_after_generation_script_id)()