DeliveryLine.py 15.3 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
#
# 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
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31
from Acquisition import aq_base
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32 33 34 35 36

from Products.CMFCore.WorkflowCore import WorkflowAction
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5Type.XMLMatrix import XMLMatrix
from Products.ERP5Type.XMLObject import XMLObject
Sebastien Robin's avatar
Sebastien Robin committed
37
from Products.ERP5Type.Base import Base
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38 39 40

from Products.ERP5.Document.Movement import Movement
from Products.ERP5.Variated import Variated
41
from Products.CMFCategory.Renderer import Renderer
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

from zLOG import LOG

class DeliveryLine(Movement, XMLObject, XMLMatrix, Variated):
    """
      A DeliveryLine object allows to implement lines in
      Deliveries (packing list, order, invoice, etc.)

      It may include a price (for insurance, for customs, for invoices,
      for orders)
    """

    meta_type = 'ERP5 Delivery Line'
    portal_type = 'Delivery Line'

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

    # Declarative interfaces
    __implements__ = ( Interface.Variated, )

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
                      , PropertySheet.CategoryCore
                      , PropertySheet.Amount
                      , PropertySheet.Task
                      , PropertySheet.Arrow
                      , PropertySheet.Movement
                      , PropertySheet.Price
                      , PropertySheet.VariationRange
                      , PropertySheet.ItemAggregation
                      )

77 78
    # Multiple inheritance definition
    updateRelatedContent = XMLMatrix.updateRelatedContent
79

80 81 82 83 84 85
    # Explicit acquisition of aq_dynamic generated method
    security.declareProtected(Permissions.AccessContentsInformation, 'getSimulationState')
    def getSimulationState(self):
      """
        Explicitly acquire simulation_state from parent
      """
86 87 88
      if hasattr(self.getParent(),'getSimulationState'):
        return self.getParent().getSimulationState()
      return None
89
    
Jean-Paul Smets's avatar
Jean-Paul Smets committed
90 91 92 93 94 95 96 97 98 99 100 101 102
    # Force in _edit to modify variation_base_category_list first
    security.declarePrivate( '_edit' )
    def _edit(self, REQUEST=None, force_update = 0, **kw):
      # We must first prepare the variation_base_category_list before we do the edit of the rest
      #LOG('in edit', 0, str(kw))
      if kw.has_key('variation_base_category_list'):
        self._setVariationBaseCategoryList( kw['variation_base_category_list'] )
      if kw.has_key('variation_category_list'):
        self._setVariationCategoryList( kw['variation_category_list'] )
      Movement._edit(self, REQUEST=REQUEST, force_update = force_update, **kw)
      # This one must be the last
      if kw.has_key('item_id_list'):
        self._setItemIdList( kw['item_id_list'] )
103 104 105 106
      if self.isSimulated():
        self.getRootDeliveryValue().edit() # So that we make sure that automatic workflow transitions
                                           # will be activated on the delivery
        self.getRootDeliveryValue().activate().propagateResourceToSimulation()
Sebastien Robin's avatar
Sebastien Robin committed
107 108 109 110 111

    # We must check if the user has changed the resource of particular line
    security.declareProtected( Permissions.ModifyPortalContent, 'edit' )
    def edit(self, REQUEST=None, force_update = 0, reindex_object=1, **kw):
      return self._edit(REQUEST=REQUEST, force_update=force_update, reindex_object=reindex_object, **kw)
112

Jean-Paul Smets's avatar
Jean-Paul Smets committed
113 114 115 116 117 118 119 120 121 122
    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.isAccountable() and (not self.hasCellContent())

    def _getTotalPrice(self, context):
123 124
      base_id = 'movement'
      if not self.hasCellContent(base_id=base_id):
125
        quantity = self.getQuantity() or 0.0
126
        price = self.getPrice(context=context) or 0.0
127
        return quantity * price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
128 129 130
      else:
        # Use MySQL
        aggregate = self.DeliveryLine_zGetTotal()[0]
131
        return aggregate.total_price or 0.0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
132 133 134 135 136 137

    security.declareProtected(Permissions.AccessContentsInformation, 'getTotalQuantity')
    def getTotalQuantity(self):
      """
        Returns the quantity if no cell or the total quantity if cells
      """
138 139
      base_id = 'movement'
      if not self.hasCellContent(base_id=base_id):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
140 141 142 143
        return self.getQuantity()
      else:
        # Use MySQL
        aggregate = self.DeliveryLine_zGetTotal()[0]
144
        return aggregate.total_quantity or 0.0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
145 146 147 148 149 150

    security.declareProtected( Permissions.ModifyPortalContent, 'hasCellContent' )
    def hasCellContent(self, base_id='movement'):
      """
          This method can be overriden
      """
151 152 153 154 155 156 157 158 159 160 161 162 163
      # DeliveryLine can be a movement when it does not content any cell and 
      # matrix cell range is not empty.
      return XMLMatrix.hasCellContent(self, base_id=base_id)
#       # Do not use XMLMatrix.hasCellContent, because it can generate
#       # inconsistency in catalog
#       # Exemple: define a line and set the matrix cell range, but do not create
#       # cell.
#       # Line was in this case consider like a movement, and was catalogued.
#       # But, getVariationText of the line was not empty.
#       # So, in ZODB, resource as without variation, but in catalog, this was
#       # the contrary...
#       cell_range = XMLMatrix.getCellRange(self, base_id=base_id)
#       return (cell_range is not None and len(cell_range) > 0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
164 165 166 167 168 169 170 171

    security.declareProtected( Permissions.AccessContentsInformation, 'getCellValueList' )
    def getCellValueList(self, base_id='movement'):
      """
          This method can be overriden
      """
      return XMLMatrix.getCellValueList(self, base_id=base_id)

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    security.declareProtected( Permissions.View, 'getCell' )
    def getCell(self, *kw , **kwd):
      """
          This method can be overriden
      """
      if 'base_id' not in kwd:
        kwd['base_id'] = 'movement'

      return XMLMatrix.getCell(self, *kw, **kwd)

    security.declareProtected( Permissions.ModifyPortalContent, 'newCell' )
    def newCell(self, *kw, **kwd):
      """
          This method creates a new cell
      """
      if 'base_id' not in kwd:
        kwd['base_id'] = 'movement'

      return XMLMatrix.newCell(self, *kw, **kwd)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

    security.declareProtected(Permissions.View, 'isDivergent')
    def isDivergent(self):
      """
        Returns 1 if the target is not met according to the current information
        After and edit, the isOutOfTarget will be checked. If it is 1,
        a message is emitted

        emit targetUnreachable !
      """
      if self.hasCellContent():
        for cell in self.contentValues(filter={'portal_type': 'Delivery Cell'}):
          if cell.isDivergent():
            return 1
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
206
         return Movement.isDivergent(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

    def applyToDeliveryLineRelatedMovement(self, portal_type='Simulation Movement', method_id = 'expand'):
      # Find related in simulation
      for my_simulation_movement in self.getDeliveryRelatedValueList(
                                              portal_type = 'Simulation Movement'):
        # And apply
        getattr(my_simulation_movement.getObject(), method_id)()
      for c in self.contentValues(filter={'portal_type': 'Delivery Cell'}):
        for my_simulation_movement in c.getDeliveryRelatedValueList(
                                              portal_type = 'Simulation Movement'):
          # And apply
          getattr(my_simulation_movement.getObject(), method_id)()

    def reindexObject(self, *k, **kw):
      """
        Reindex children and simulation
      """
      if self.isIndexable:
        # Reindex children
        self.activate().recursiveImmediateReindexObject()

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoriatedQuantity')
    def getInventoriatedQuantity(self):
      """
      """
232
      return Movement.getInventoriatedQuantity(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
233

234 235
    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoriatedStartDate')
    def getInventoriatedStartDate(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
236 237
      """
      """
238
      return Movement.getStartDate(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
239

240 241
    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoriatedStopDate')
    def getInventoriatedStopDate(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
242 243
      """
      """
244
      return Movement.getStopDate(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
245

Jean-Paul Smets's avatar
Jean-Paul Smets committed
246 247 248 249 250
    def _setItemIdList(self, value):
      """
        Computes total_quantity of all given items and stores this total_quantity
        in the quantity attribute of the cell
      """
251 252
      if value is None:
        return
Jean-Paul Smets's avatar
Jean-Paul Smets committed
253
      previous_item_list = self.getAggregateValueList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
254 255 256 257 258 259 260 261 262 263 264 265 266
      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 :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
267 268 269 270 271 272 273 274 275 276 277
          # 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
278 279 280 281 282 283 284 285 286

      # 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 :
287 288 289 290
          if self.aq_parent.getPortalType() in ('Purchase Packing List', ) :
            quantity += object_item.getQuantity()
          else :
            quantity += object_item.getRemainingQuantity()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
291 292
            # we reset the location of the item
            object_item.setLocation('')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
293 294 295 296 297

        self.setTargetQuantity(quantity)


    security.declarePrivate('_checkConsistency')
298
    def _checkConsistency(self, fixit=0, mapped_value_property_list = ('quantity', 'price')):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
299 300 301 302 303 304 305 306 307 308
      """
        Check the constitency of transformation elements
      """
      error_list = XMLMatrix._checkConsistency(self, fixit=fixit)

      # First quantity
      # We build an attribute equality and look at all cells
      q_constraint = Constraint.AttributeEquality(
        domain_base_category_list = self.getVariationBaseCategoryList(),
        predicate_operator = 'SUPERSET_OF',
309
        mapped_value_property_list = mapped_value_property_list )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
      for k in self.getCellKeys(base_id = 'movement'):
        kw={}
        kw['base_id'] = 'movement'
        c = self.getCell(*k, **kw)
        if c is not None:
          predicate_value = []
          for p in k:
            if p is not None: predicate_value += [p]
          q_constraint.edit(predicate_value_list = predicate_value)
          if fixit:
            error_list += q_constraint.fixConsistency(c)
          else:
            error_list += q_constraint.checkConsistency(c)
          if list(c.getVariationCategoryList()) != predicate_value:
            error_message =  "Variation %s but sould be %s" % (c.getVariationCategoryList(),predicate_value)
            if fixit:
              c.setVariationCategoryList(predicate_value)
              error_message += " (Fixed)"
            error_list += [(c.getRelativeUrl(), 'VariationCategoryList inconsistency', 100, error_message)]

      return error_list

    # Simulation Consistency Check
333
    def getSimulationQuantity(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
334 335 336
      """
          Computes the quantities in the simulation
      """
337 338 339 340
      if not self.hasCellContent():
        result = self.DeliveryLine_zGetRelatedQuantity(uid=self.getUid())
        if len(result) > 0:
          return result[0].quantity
Jean-Paul Smets's avatar
Jean-Paul Smets committed
341
      return None
342 343 344 345 346 347 348

    def getSimulationSourceList(self):
      """
          Computes the sources in the simulation
      """
      result = self.DeliveryLine_zGetRelatedSource(uid=self.getUid())
      return map(lambda x: x.source, result)
349

350 351 352 353 354 355
    def getSimulationDestinationList(self):
      """
          Computes the destinations in the simulation
      """
      result = self.DeliveryLine_zGetRelatedDestination(uid=self.getUid())
      return map(lambda x: x.destination, result)
356

357 358 359 360 361 362
    def getSimulationSourceSectionList(self):
      """
          Computes the source sections in the simulation
      """
      result = self.DeliveryLine_zGetRelatedSourceSection(uid=self.getUid())
      return map(lambda x: x.source_section, result)
363

364 365 366 367 368 369
    def getSimulationDestinationSectionList(self):
      """
          Computes the destination sections in the simulation
      """
      result = self.DeliveryLine_zGetRelatedDestinationSection(uid=self.getUid())
      return map(lambda x: x.destination_section, result)
Sebastien Robin's avatar
Sebastien Robin committed
370 371 372 373 374 375 376

    security.declareProtected(Permissions.AccessContentsInformation, 'getStopDate')
    def getRootDeliveryValue(self):
      """
      Returns the root delivery responsible of this line
      """
      return self.getParent().getRootDeliveryValue()
377

378 379 380 381 382 383 384 385 386
    security.declareProtected(Permissions.ModifyPortalContent, 'updateSimulationDeliveryProperties')
    def updateSimulationDeliveryProperties(self, movement_list = None):
      """
      Set properties delivery_ratio and delivery_error for each simulation movement
      in movement_list (all movements by default), according to this delivery calculated quantity
      """
      parent = self.getParent()
      if parent is not None:
        parent.updateSimulationDeliveryProperties(movement_list, self)