DeliveryBuilder.py 9.16 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 30 31 32 33
##############################################################################
#
# 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
from Products.CMFCore.utils import getToolByName
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Acquisition import aq_base, aq_parent, aq_inner, aq_acquire
from Products.ERP5 import MovementGroup
34
from Products.ERP5Type.Utils import convertToUpperCase
35
from Products.ERP5.Document.OrderBuilder import OrderBuilder
Romain Courteaud's avatar
Romain Courteaud committed
36 37 38

from zLOG import LOG

39
class DeliveryBuilder(OrderBuilder):
Romain Courteaud's avatar
Romain Courteaud committed
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 90 91 92 93 94 95
  """
    Delivery 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.

    Delivery Builders are called for example whenever an order is confirmed.
    They are also called globaly in order to gather any confirmed or above 
    Simulation Movement which was not associated to any Delivery Line. 
    Such movements are called orphaned Simulation Movements.

    Delivery 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.

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

  # CMF Type Definition
  meta_type = 'ERP5 Delivery Builder'
  portal_type = 'Delivery 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
                    )

96 97 98 99 100 101 102 103 104
  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.
      Create the relation between simulation movement
      and delivery movement.
    """
105 106 107 108
    OrderBuilder._setDeliveryMovementProperties(
                            self, delivery_movement, 
                            simulation_movement, property_dict,
                            update_existing_movement=update_existing_movement)
109 110 111 112 113 114
    # Check if simulation movement is not already linked to a existing
    # movement
    if simulation_movement.getDeliveryValue() is not None:
      raise "SelectMovementError",\
            "simulation_movement '%s' must not be selected !" %\
            simulation_movement.getRelativeUrl()
115
    # Update simulation movement
116
    simulation_movement.edit(delivery_value=delivery_movement)
Romain Courteaud's avatar
Romain Courteaud committed
117

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
  # Simulation consistency propagation
  security.declareProtected(Permissions.ModifyPortalContent, 
                            'updateFromSimulation')
  def updateFromSimulation(self, delivery_relative_url, create_new_delivery=1):
    """
      Update all lines of this transaction based on movements in the 
      simulation related to this transaction.
    """
    # We have to get a delivery, else, raise a Error
    delivery = self.restrictedTraverse(delivery_relative_url)

    delivery_uid = delivery.getUid()

    # Select
    simulation_movement_list = []
    for movement in delivery.getMovementList():
134
      movement.edit(quantity=0)
135 136 137 138 139 140 141 142 143 144 145 146
      for simulation_movement in movement.getDeliveryRelatedValueList(
                                            portal_type="Simulation Movement"):
        simulation_movement.setDelivery(None)
        simulation_movement_list.append(simulation_movement) 

    # Collect
    root_group = self.collectMovement(simulation_movement_list)

    # Update delivery
    rejected_movement_list = self._deliveryUpdateGroupProcessing(
                                          delivery,
                                          root_group)
147 148 149 150 151 152 153

    for sim_mvt in root_group.getMovementList():
      sim_mvt.immediateReindexObject()

    # Store the good quantity value on delivery line
    for movement in delivery.getMovementList():
      total_quantity = 0
154 155 156 157
      sim_mvt_list = movement.getDeliveryRelatedValueList(
                                             portal_type="Simulation Movement")

      for simulation_movement in sim_mvt_list:
158 159
        total_quantity += simulation_movement.getQuantity()

160 161 162
      if total_quantity != 0:
        for simulation_movement in sim_mvt_list:
          quantity = simulation_movement.getQuantity()
163 164
          #simulation_movement.setDeliveryRatio(quantity/total_quantity)
          simulation_movement.edit(delivery_ratio=quantity/total_quantity)
165
      else:
166 167 168 169
        if len(sim_mvt_list) != 0:
          # Distribute equally ratio to all movement
          mvt_ratio = 1 / len(sim_mvt_list)
          for simulation_movement in sim_mvt_list:
170 171
            #simulation_movement.setDeliveryRatio(mvt_ratio)
            simulation_movement.edit(delivery_ratio=mvt_ratio)
172 173

      movement.edit(quantity=total_quantity)
174 175
      # To update the divergence status, the simulation movements
      # must be reindexed, and then the delivery must be touched
176
      path_list = []
177
      #for simulation_movement in movement.getDeliveryRelatedValueList():
178
        #simulation_movement.immediateReindexObject()
179 180 181
      #  simulation_movement.edit()
      #  path_list.append(simulation_movement.getPath())
      #movement.activate(after_path_and_method_id = (path_list, ['immediateReindexObject', 'recursiveImmediateReindexObject'])).edit()
182

183 184 185
    # Launch delivery creation
    if (create_new_delivery == 1) and\
       (rejected_movement_list != []):
186 187 188 189 190 191 192 193
      movement_relative_url_list = []
      for movement in rejected_movement_list:
        # XXX FIXME Not very generic...
        if movement.__class__.__name__ == "FakeMovement":
          movement_relative_url_list.extend(
                    [x.getRelativeUrl() for x in movement.getMovementList()])
        else:
          movement_relative_url_list.append(movement.getRelativeUrl())
194
      self.activate(activity="SQLQueue").build(
195 196 197 198 199 200 201 202 203 204 205
                        movement_relative_url_list=movement_relative_url_list)

  def _deliveryUpdateGroupProcessing(self, delivery, movement_group):
    """
      Update delivery movement
    """
    rejected_movement_list = []
    property_dict = {}

    for collect_order in self.getDeliveryCollectOrderList():
      for group in movement_group.getGroupList()[1:]:
206
        rejected_movement_list.extend(group.getMovementList())
207 208 209 210
      movement_group = movement_group.getGroupList()[0]
      property_dict.update(movement_group.getGroupEditDict())
    
    # Put properties on delivery
211
    delivery.edit(**property_dict)
212

213
    # Then, reconnect simulation to delivery line
214 215 216 217 218 219 220
    for group in movement_group.getGroupList():
      self._deliveryLineGroupProcessing(
                                  delivery,
                                  group,
                                  self.getDeliveryLineCollectOrderList()[1:],
                                  {})
    return rejected_movement_list