DeliveryCell.py 15.6 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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 34
#
# 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 Globals import InitializeClass, PersistentMapping
from AccessControl import ClassSecurityInfo
from Acquisition import aq_base

from Products.CMFCore.WorkflowCore import WorkflowAction
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
Sebastien Robin's avatar
Sebastien Robin committed
35
from Products.ERP5Type.Base import Base
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

from Products.ERP5.Document.OrderLine import OrderLine
from Products.ERP5.Document.Movement import Movement
from Products.ERP5.Document.SetMappedValue import SetMappedValue

from zLOG import LOG

class DeliveryCell(SetMappedValue, Movement):
    """
      A DeliveryCell allows to define specific quantities
      for each variation of a resource in a delivery line.
    """

    meta_type = 'ERP5 Delivery Cell'
    portal_type = 'Delivery Cell'
51
    add_permission = Permissions.AddPortalContent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    isPortalContent = 1
    isRADContent = 1
    isCell = 1
    isMovement = 1

    # Declarative security
    security = ClassSecurityInfo()
    security.declareObjectProtected(Permissions.View)

    # Declarative interfaces
    __implements__ = ( Interface.Variated, )

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.CategoryCore
                      , PropertySheet.Arrow
                      , PropertySheet.Amount
                      , PropertySheet.Task
                      , PropertySheet.Movement
                      , PropertySheet.Price
                      , PropertySheet.Predicate
                      , PropertySheet.Domain
                      , PropertySheet.MappedValue
                      , PropertySheet.ItemAggregation
                      )

    # Factory Type Information
    factory_type_information = \
      {    'id'             : portal_type
         , 'meta_type'      : meta_type
         , 'description'    : """\
Une ligne tarifaire."""
         , 'icon'           : 'order_line_icon.gif'
         , 'product'        : 'ERP5'
         , 'factory'        : 'addDeliveryCell'
         , 'immediate_view' : 'delivery_cell_view'
         , 'allow_discussion'     : 1
         , 'allowed_content_types': ('',
                                      )
         , 'filter_content_types' : 1
         , 'global_allow'   : 1
         , 'actions'        :
        ( { 'id'            : 'view'
          , 'name'          : 'View'
          , 'category'      : 'object_view'
          , 'action'        : 'delivery_cell_view'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'list'
          , 'name'          : 'Object Contents'
          , 'category'      : 'object_action'
          , 'action'        : 'folder_contents'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'print'
          , 'name'          : 'Print'
          , 'category'      : 'object_print'
          , 'action'        : 'delivery_cell_print'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'metadata'
          , 'name'          : 'Metadata'
          , 'category'      : 'object_view'
          , 'action'        : 'metadata_edit'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'translate'
          , 'name'          : 'Translate'
          , 'category'      : 'object_action'
          , 'action'        : 'translation_template_view'
          , 'permissions'   : (
              Permissions.TranslateContent, )
          }
        )
      }

132 133 134 135 136 137 138 139 140 141
    # Explicit acquisition of aq_dynamic generated method
    security.declareProtected(Permissions.AccessContentsInformation, 'getSimulationState')
    def getSimulationState(self):
      """
        Explicitly acquire simulation_state from parent
      """
      return self.aq_parent.getSimulationState()
    
    
    # MatrixBox methods      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
142 143 144 145 146 147 148 149 150 151 152 153 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
    security.declareProtected( Permissions.ModifyPortalContent, 'hasCellContent' )
    def hasCellContent(self, base_id='movement'):
      """
          This method can be overriden
      """
      return 0

    security.declareProtected(Permissions.AccessContentsInformation, 'isAccountable')
    def isAccountable(self):
      """
        Returns 1 if this needs to be accounted
        Only account movements which are not associated to a delivery
        Whenever delivery is there, delivery has priority
      """
      return self.aq_parent.aq_parent.isAccountable()

    security.declareProtected( Permissions.AccessContentsInformation, 'getProperty' )
    def getProperty(self, key, d=None):
      """
        Generic accessor. First we check if the value
        exists. Else we call the real accessor
      """

      #try:
      if 1:
        # If mapped_value_property_list is not set
        # then it creates an exception
        if key in self.getMappedValuePropertyList([]):
          if getattr(self, key, None) is not None:
            LOG("Found Prop",0,"")
            return getattr(self, key)
          else:
            LOG("Not Found Prop",0,"")
            return self.aq_parent.getProperty(key)
      #except:
      #  LOG("WARNING: ERP5", 0, 'Could not access mapped value property %s' % key)
      #  return None
      # Standard accessor
      try:
        result = Movement.getProperty(self, key, d=d)
      except:
        result = None
      return result

Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
    security.declareProtected( Permissions.ModifyPortalContent, 'updatePrice' )
    def updatePrice(self):
      if 'price' in self.getMappedValuePropertyList([]):
        # Try to compute an average price by accessing simulation movements
        # This should always return 0 in the case of OrderCell
        total_quantity = 0.0
        total_price = 0.0
        for m in self.getDeliveryRelatedValueList(portal_type="Simulation Movement"):
          order = m.getOrderValue()
          if order is not None:
            # Price is defined in an order
            price = m.getPrice()
            quantity = m.getQuantity()
            try:
              price = float(price)
              quantity = float(quantity)
            except:
              price = 0.0
              quantity = 0.0
            total_quantity += quantity
            total_price += quantity * price
        if total_quantity:
          # Update local price
          # self._setPrice(total_price / total_quantity)
          self.setPrice( total_price / total_quantity )

Jean-Paul Smets's avatar
Jean-Paul Smets committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    security.declareProtected( Permissions.AccessContentsInformation, 'getPrice' )
    def getPrice(self, context=None, REQUEST=None, **kw):
      """
        Returns the price if defined on the cell
        or acquire it
      """
      # Call a script on the context
      if 'price' in self.getMappedValuePropertyList([]):
        if getattr(aq_base(self), 'price', None) is not None:
          return getattr(self, 'price') # default returns a price defined by the mapped value
        else:
          return self.aq_parent.getProperty('price') # Price is acquired
      else:
        return None

    security.declareProtected( Permissions.AccessContentsInformation, 'getQuantity' )
    def getQuantity(self):
      """
        Returns the quantity if defined on the cell
        or acquire it
      """
      # Call a script on the context
      if 'quantity' in self.getMappedValuePropertyList([]):
        if getattr(aq_base(self), 'quantity', None) is not None:
          return getattr(self, 'quantity')
        else:
          return self.aq_parent.getProperty('quantity')
      else:
        return self.getTargetQuantity() # We have acquisition here which me should mimic
        # return None

    security.declareProtected( Permissions.AccessContentsInformation, 'getTargetQuantity' )
    def getTargetQuantity(self):
      """
        Returns the target quantity if defined on the cell
        or acquire it
      """
      # Call a script on the context
      if 'target_quantity' in self.getMappedValuePropertyList([]):
        if getattr(aq_base(self), 'target_quantity', None) is not None:
          return getattr(self, 'target_quantity')
        else:
          return self.aq_parent.getProperty('target_quantity')
      else:
        return None

    def _setItemIdList(self, value):
      """
        Computes total_quantity of all given items and stores this total_quantity
        in the quantity attribute of the cell
      """
263
      previous_item_list = self.getAggregateValueList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
264 265 266 267 268 269 270 271 272 273 274 275 276
      given_item_id_list = value
      item_object_list = []
      for item in given_item_id_list :
        item_result_list = self.portal_catalog(id = item, portal_type="Piece Tissu")
        if len(item_result_list) == 1 :
          try :
            object = item_result_list[0].getObject()
          except :
            object = None
        else :
          object = None

        if object is not None :
277 278 279 280 281 282 283 284 285 286 287
          # if item was in previous_item_list keep it
          if object in previous_item_list :
            # we can add this item to the list of aggregated items
            item_object_list.append(object)
          # if new item verify if variated_resource of item == variated_resource of movement
          elif (self.getResource() == object.getResource()) and (self.getVariationCategoryList() == object.getVariationCategoryList()) :
            # now verify if item can be moved (not already done)
            last_location_title = object.getLastLocationTitle()
            if self.getDestinationTitle() != last_location_title or last_location_title == '' :
              # we can add this item to the list of aggregated items
              item_object_list.append(object)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
288 289 290 291 292 293 294 295 296

      # update item_id_list and build relation
      self.setAggregateValueList(item_object_list)

      # update quantity if needed
      if len(item_object_list)>0 :
        quantity = 0

        for object_item in item_object_list :
297 298 299 300
          if self.aq_parent.aq_parent.getPortalType() in ('Purchase Packing List', ) :
            quantity += object_item.getQuantity()
          else :
            quantity += object_item.getRemainingQuantity()
301 302
            # we reset the location of the item
            object_item.setLocation('')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316

        self.setTargetQuantity(quantity)

    security.declareProtected(Permissions.ModifyPortalContent, 'applyTargetSolver')
    def applyTargetSolver(self, solver):
      for my_simulation_movement in self.getDeliveryRelatedValueList(portal_type = 'Simulation Movement'):
        self.portal_simulation.applyTargetSolver(my_simulation_movement, solver)

    # Required for indexing
    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoriatedQuantity')
    def getInventoriatedQuantity(self):
      """
        Take into account efficiency in converted target quantity
      """
317
      if self.getSimulationState() in self.getPortalTargetInventoryStateList():
Jean-Paul Smets's avatar
Jean-Paul Smets committed
318 319 320 321 322 323
        # When an order is delivered, the target quantity should be considered
        # rather than the quantity
        return Movement.getNetConvertedTargetQuantity(self)
      else:
        return Movement.getInventoriatedQuantity(self)

324 325 326 327 328
    security.declareProtected(Permissions.AccessContentsInformation, 'getStartDate')
    def getStartDate(self):
      """
        Take into account efficiency in converted target quantity
      """
329
      if self.getSimulationState() in self.getPortalCurrentInventoryStateList():
330 331
        # When an order is delivered, the target quantity should be considered
        # rather than the quantity
Yoshinori Okuji's avatar
Yoshinori Okuji committed
332
        return self._baseGetTargetStartDate()
333
      else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
334
        return self._baseGetStartDate()
335 336 337 338 339 340

    security.declareProtected(Permissions.AccessContentsInformation, 'getStopDate')
    def getStopDate(self):
      """
        Take into account efficiency in converted target quantity
      """
341
      if self.getSimulationState() in self.getPortalCurrentInventoryStateList():
342 343
        # When an order is delivered, the target quantity should be considered
        # rather than the quantity
Yoshinori Okuji's avatar
Yoshinori Okuji committed
344
        return self._baseGetTargetStopDate()
345
      else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
346
        return self._baseGetStopDate()
347

Sebastien Robin's avatar
Sebastien Robin committed
348 349 350 351 352 353 354
    security.declareProtected(Permissions.AccessContentsInformation, 'getStopDate')
    def getRootDeliveryValue(self):
      """
      Returns the root delivery responsible of this cell
      """
      return self.getParent().getRootDeliveryValue()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    # Simulation Consistency Check
    def getRelatedQuantity(self):
      """
          Computes the quantities in the simulation
      """
      if isinstance(self, OrderLine):
        result = self.OrderLine_zGetRelatedQuantity(uid=self.getUid())
        if len(result) > 0:
          return result[0].target_quantity
        return None
      else:
        result = self.DeliveryLine_zGetRelatedQuantity(uid=self.getUid())
        if len(result) > 0:
          return result[0].quantity
        return None

    def getRelatedTargetQuantity(self):
      """
          Computes the target quantities in the simulation
      """
      if isinstance(self, OrderLine):
        result = self.OrderLine_zGetRelatedQuantity(uid=self.getUid())
        if len(result) > 0:
          return result[0].target_quantity
        return None
      else:
        result = self.DeliveryLine_zGetRelatedQuantity(uid=self.getUid())
        if len(result) > 0:
          return result[0].target_quantity
        return None
385 386 387 388 389 390 391 392 393 394 395

    security.declareProtected( Permissions.ModifyPortalContent, 'notifyAfterUpdateRelatedContent' )
    def notifyAfterUpdateRelatedContent(self, previous_category_url, new_category_url):
      """
          Membership Crirerions and Category List are same in DeliveryCell
          Must update it (or change implementation to remove data duplication)
      """
      update_method = self.portal_categories.updateRelatedCategory
      predicate_value = self.getPredicateValueList()
      new_predicate_value = map(lambda c: update_method(c, previous_category_url, new_category_url), predicate_value)
      self._setPredicateValueList(new_predicate_value) # No reindex needed since uid stable
Sebastien Robin's avatar
Sebastien Robin committed
396 397 398 399 400

    security.declarePrivate( '_edit' )
    def _edit(self, REQUEST=None, force_update = 0, reindex_object = 0, **kw):
      """
      """
401
      SetMappedValue._edit(self, REQUEST=REQUEST, force_update = force_update,
Sebastien Robin's avatar
Sebastien Robin committed
402
                           reindex_object=reindex_object, **kw)
403 404
      if self.isSimulated():
        self.getRootDeliveryValue().activate().propagateResourceToSimulation()
Sebastien Robin's avatar
Sebastien Robin committed
405 406 407 408
      # This one must be the last
      if kw.has_key('item_id_list'):
        self._setItemIdList( kw['item_id_list'] )

409