DeliveryLine.py 20.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2 3 4
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
5
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#
# 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.
#
##############################################################################

30
import zope.interface
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31 32
from AccessControl import ClassSecurityInfo

33
from Products.ERP5Type import Permissions, PropertySheet, interfaces
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34 35 36
from Products.ERP5Type.XMLMatrix import XMLMatrix

from Products.ERP5.Document.Movement import Movement
37
from Products.ERP5.Document.ImmobilisationMovement import ImmobilisationMovement
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38

39 40 41 42 43
from inspect import getargspec
from Products.ERP5Type.Base import Base
edit_args_list = getargspec(Base._edit).args

class DeliveryLine(Movement, XMLMatrix, ImmobilisationMovement):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
44 45 46 47 48 49 50 51 52 53 54 55 56
    """
      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()
57
    security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
58 59 60 61 62 63 64 65 66 67 68 69

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
                      , PropertySheet.CategoryCore
                      , PropertySheet.Amount
                      , PropertySheet.Task
                      , PropertySheet.Arrow
                      , PropertySheet.Movement
                      , PropertySheet.Price
                      , PropertySheet.VariationRange
                      , PropertySheet.ItemAggregation
70
                      , PropertySheet.SortIndex
Jean-Paul Smets's avatar
Jean-Paul Smets committed
71 72
                      )

73 74
    # Declarative interfaces
    zope.interface.implements(interfaces.IDivergenceController,)
75

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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
79
    # Force in _edit to modify variation_base_category_list first
80
    def _edit(self, edit_order=(), **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
81 82 83 84 85
      # XXX FIXME For now, special cases are handled in _edit methods in many
      # documents : DeliveryLine, DeliveryCell ... Ideally, to prevent code
      # duplication, it should be handled in a _edit method present only in
      # Amount.py

86 87
      # If variations and resources are set at the same time, resource must be
      # set before any variation.
88 89 90 91 92 93 94 95 96
      before_order = ('resource', 'resource_value',
                      'variation_base_category_list',
                      'variation_category_list')
      before_kw = {k: kw.pop(k) for k in before_order if k in kw}
      if before_kw:
        before_kw.update((k, kw[k]) for k in edit_args_list if k in kw)
        Base._edit(self, edit_order=before_order, **before_kw)
      if kw:
        Movement._edit(self, edit_order=edit_order, **kw)
Sebastien Robin's avatar
Sebastien Robin committed
97 98 99 100 101

    # 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)
102

Fabien Morin's avatar
Fabien Morin committed
103
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
104
                              'isAccountable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
105
    def isAccountable(self):
106
      """To avoid duplicate docstring. Please read movement interface."""
107
      return self.getParentValue().isAccountable() and (not self.hasCellContent())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
108

109
    security.declareProtected(Permissions.AccessContentsInformation,
110
                             'isMovingItem')
111
    def isMovingItem(self, item):
112 113 114
      type_based_script = self._getTypeBasedMethod('isMovingItem')
      if type_based_script:
        return type_based_script(item)
115 116
      return self.isAccountable()

117
    def _getTotalPrice(self, default=0.0, context=None, fast=0):
118 119 120 121 122 123
      """
        Returns the total price for this line, this line contains, or the cells it contains.

        if hasLineContent: return sum of lines total price
        if hasCellContent: return sum of cells total price
        else: return quantity * price
124
        if fast argument is true, inventory API will be used.
125
      """
126 127 128 129 130 131 132 133 134
      if fast:
        kw = {}
        kw['section_uid'] = self.getDestinationSectionUid()
        kw['stock.explanation_uid'] = self.getExplanationUid()
        kw['relative_url'] = ( '%s/%%' % (
          self.getRelativeUrl().replace('_', '\\_')),
          self.getRelativeUrl() )
        kw['only_accountable'] = False
        return self.getPortalObject().portal_simulation.getInventoryAssetPrice(**kw)
135 136 137 138 139
      if self.hasLineContent():
        meta_type = self.meta_type
        return sum(l.getTotalPrice(context=context)
                   for l in self.objectValues() if l.meta_type==meta_type)
      elif not self.hasCellContent(base_id='movement'):
140
        return Movement._getTotalPrice(self, default=default, context=context)
141 142
      return sum(cell.getTotalPrice(default=0.0, context=context)
                 for cell in self.getCellValueList())
143 144 145

    security.declareProtected( Permissions.AccessContentsInformation,
                               'getTotalQuantity')
146
    def getTotalQuantity(self, fast=0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
147 148
      """
        Returns the quantity if no cell or the total quantity if cells
149

150 151 152
        if hasLineContent: return sum of lines total quantity
        if hasCellContent: return sum of cells total quantity
        else: return quantity
153
        if fast argument is true, inventory API will be used.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
154
      """
155 156 157 158 159 160 161 162 163 164 165

      if fast:
        kw = {}
        kw['section_uid'] = self.getDestinationSectionUid()
        kw['stock.explanation_uid'] = self.getExplanationUid()
        kw['relative_url'] = ( '%s/%%' % (
          self.getRelativeUrl().replace('_', '\\_')),
          self.getRelativeUrl() )
        kw['only_accountable'] = False
        return self.getPortalObject().portal_simulation.getInventory(**kw)

166
      base_id = 'movement'
167 168 169 170 171
      if self.hasLineContent():
        meta_type = self.meta_type
        return sum(l.getTotalQuantity() for l in
            self.objectValues() if l.meta_type==meta_type)
      elif self.hasCellContent(base_id=base_id):
172
        return sum([cell.getQuantity() for cell in self.getCellValueList()])
173
      return self.getQuantity()
174 175 176 177 178 179 180 181 182 183 184

    security.declareProtected(Permissions.AccessContentsInformation,
                              'hasLineContent')
    def hasLineContent(self):
      """Return true if the object contains lines.

      This method only checks the first sub line because all sub
      lines should be same meta type in reality if we have line
      inside line.
      """
      return len(self) != 0 and self.objectValues()[0].meta_type == self.meta_type
Jean-Paul Smets's avatar
Jean-Paul Smets committed
185

186 187
    security.declareProtected(Permissions.AccessContentsInformation,
                              'hasCellContent')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
188
    def hasCellContent(self, base_id='movement'):
189
      """Return true if the object contains cells.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
190
      """
191 192 193 194 195 196 197 198 199 200
      # 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)
201
      # DeliveryLine can be a movement when it does not content any cell and
202
      # matrix cell range is not empty.
203 204 205 206 207
      # Better implementation is needed.
      # We want to define a line without cell, defining a variated resource.
      # If we modify the cell range, we need to move the quantity to a new
      # cell, which define the same variated resource.
#       return XMLMatrix.hasCellContent(self, base_id=base_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
208

209 210 211 212 213 214 215 216 217
    security.declareProtected( Permissions.AccessContentsInformation,
        'isMovement' )
    def isMovement(self):
      """
      returns true is the object contains no submovement (line or cell)
      """
      portal_type = self.getPortalMovementTypeList()
      return len(self.contentValues(filter={'portal_type': portal_type})) == 0

218 219 220 221 222 223 224
    security.declareProtected(Permissions.AccessContentsInformation, 'getMovedItemUidList')
    def getMovedItemUidList(self):
      """This method returns an uid list of items
      """
      return [item.getUid() for item in self.getAggregateValueList() \
          if self.isMovingItem(item)]

Jean-Paul Smets's avatar
Jean-Paul Smets committed
225 226 227 228 229 230 231
    security.declareProtected( Permissions.AccessContentsInformation, 'getCellValueList' )
    def getCellValueList(self, base_id='movement'):
      """
          This method can be overriden
      """
      return XMLMatrix.getCellValueList(self, base_id=base_id)

232
    security.declareProtected( Permissions.AccessContentsInformation, 'getCell' )
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    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
251 252 253 254 255 256 257 258 259 260 261 262 263 264

    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):
265
      """Reindex children"""
266
      self.recursiveReindexObject(*k, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
267 268 269 270 271

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

274 275 276 277 278 279
#     security.declarePrivate('_checkConsistency')
#     def _checkConsistency(self, fixit=0, mapped_value_property_list = ('quantity', 'price')):
#       """
#         Check the constitency of transformation elements
#       """
#       error_list = XMLMatrix._checkConsistency(self, fixit=fixit)
280
#
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
#       # 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',
#         mapped_value_property_list = mapped_value_property_list )
#       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)]
306
#
307
#       return error_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
308

309 310
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getRootDeliveryValue')
Sebastien Robin's avatar
Sebastien Robin committed
311 312 313 314
    def getRootDeliveryValue(self):
      """
      Returns the root delivery responsible of this line
      """
315
      return self.getParentValue().getRootDeliveryValue()
316

317 318
    security.declareProtected(Permissions.ModifyPortalContent,
                              'updateSimulationDeliveryProperties')
319 320
    def updateSimulationDeliveryProperties(self, movement_list = None):
      """
321 322 323
      Set properties delivery_ratio and delivery_error for each
      simulation movement in movement_list (all movements by default),
      according to this delivery calculated quantity
324
      """
325
      parent = self.getParentValue()
326 327
      if parent is not None:
        parent.updateSimulationDeliveryProperties(movement_list, self)
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342

    security.declarePrivate('manage_afterAdd')
    def manage_afterAdd(self, item, container):
      "if the container is a line too, reindex it"
      if self.meta_type == container.meta_type:
        container.reindexObject()
      return Movement.manage_afterAdd(self, item, container)

    security.declarePrivate('manage_beforeDelete')
    def manage_beforeDelete(self, item, container):
      "if the container is a line too, reindex it"
      if self.meta_type == container.meta_type:
        container.reindexObject()
      return Movement.manage_beforeDelete(self, item, container)

Łukasz Nowak's avatar
Łukasz Nowak committed
343 344
# divergence support with solving

345 346 347 348 349 350 351
    security.declareProtected(Permissions.AccessContentsInformation, 'isDivergent')
    def isDivergent(self):
      """Returns true if the delivery line is divergent, or if any contained
      cell is divergent.
      """
      return bool(self.getDivergenceList())

352
    security.declareProtected(Permissions.AccessContentsInformation, 'getDivergenceList')
Łukasz Nowak's avatar
Łukasz Nowak committed
353
    def getDivergenceList(self):
354 355
      """Returns a list of messages that contains the divergences for that line
      and the cells it may contain.
Łukasz Nowak's avatar
Łukasz Nowak committed
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 385 386
      """
      divergence_list = []
      if self.hasCellContent():
        for cell in self.contentValues(filter={
                'portal_type': self.getPortalDeliveryMovementTypeList()}):
          divergence_list.extend(cell.getDivergenceList())
        return divergence_list
      else:
        return Movement.getDivergenceList(self)

    def _distributePropertyToSimulation(self, decision):
      """Distributes property from self to all related simulation movements

      AKA - accept decision"""
      for simulation_movement in self.getDeliveryRelatedValueList(
          portal_type='Simulation Movement'):
        simulation_movement.edit(**{
          decision.divergence.tested_property:
            self.getProperty(decision.divergence.tested_property)
        })

    def _updatePropertyFromSimulation(self, decision_list):
      """Update property from simulation
      'Stolen' from Products.ERP5.Document.DeliveryBuilder._solveDivergence

      Another possibility is to just simply copy properties or, in case of
      quantity, add from all simulation movements.
      """
      simulation_movement_list = self.getDeliveryRelatedValueList(
                                      portal_type="Simulation Movement")

387
      business_link = simulation_movement_list[0].getCausalityValue()
Łukasz Nowak's avatar
Łukasz Nowak committed
388 389 390 391
      delivery = self.getExplanationValue()
      delivery_portal_type = delivery.getPortalType()
      delivery_line_portal_type = self.getPortalType()
      # we need to find only one matching delivery builder
392
      for delivery_builder in business_link.getDeliveryBuilderValueList():
Łukasz Nowak's avatar
Łukasz Nowak committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 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 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        if delivery_builder.getDeliveryPortalType() == \
             delivery_portal_type and \
           delivery_builder.getDeliveryLinePortalType() == \
             delivery_line_portal_type:
          break
      else:
        raise ValueError('No builder found')

      self.edit(quantity=0) # adoption have to 'rebuild' delivery line
      movement_type_list = (delivery_builder.getDeliveryLinePortalType(),
              delivery_builder.getDeliveryCellPortalType())
      # Collect
      root_group_node = delivery_builder.collectMovement(
          simulation_movement_list)

      divergence_list = [decision.divergence for decision in decision_list]

      # Build
      portal = self.getPortalObject()
      delivery_module = getattr(portal, delivery_builder.getDeliveryModule())
      delivery_to_update_list = [delivery]
      delivery_list = delivery_builder._processDeliveryGroup(
        delivery_module,
        root_group_node,
        delivery_builder.getDeliveryMovementGroupList(),
        delivery_to_update_list=delivery_to_update_list,
        divergence_list=divergence_list,
        force_update=1)

      new_delivery_list = [x for x in delivery_list if x != delivery]
      if new_delivery_list:
        raise ValueError('No new deliveries shall be created')

      # Then, we should re-apply quantity divergence according to 'Do
      # nothing' quantity divergence list because all quantity are already
      # calculated in adopt prevision phase.
      quantity_dict = {}
      for divergence in self.getDivergenceList():
        if divergence.getProperty('divergence_scope') != 'quantity' or \
               divergence in divergence_list:
          continue
        s_m = divergence.getProperty('simulation_movement')
        delivery_movement = s_m.getDeliveryValue()
        assert delivery_movement == self
        quantity_gap = divergence.getProperty('decision_value') - \
                       divergence.getProperty('prevision_value')
        delivery_movement.setQuantity(delivery_movement.getQuantity() + \
                                      quantity_gap)
        quantity_dict[s_m] = \
            divergence.getProperty('decision_value')

      # Finally, recalculate delivery_ratio
      #
      # Here, created/updated movements are not indexed yet. So we try to
      # gather delivery relations from simulation movements.
      delivery_dict = {}
      for s_m in simulation_movement_list:
        delivery_path = s_m.getDelivery()
        delivery_dict[delivery_path] = \
                                     delivery_dict.get(delivery_path, []) + \
                                     [s_m]

      for s_m_list_per_movement in delivery_dict.values():
        total_quantity = sum([quantity_dict.get(s_m, s_m.getQuantity()) \
                              for s_m in s_m_list_per_movement])
        if total_quantity != 0.0:
          for s_m in s_m_list_per_movement:
            delivery_ratio = quantity_dict.get(s_m, s_m.getQuantity()) \
                                               / total_quantity
            s_m.edit(delivery_ratio=delivery_ratio)
        else:
          for s_m in s_m_list_per_movement:
            delivery_ratio = 1.0 / len(s_m_list_per_movement)
            s_m.edit(delivery_ratio=delivery_ratio)

    def solve(self, decision_list):
      """Solves line according to decision list
      """
      simulation_tool = self.getPortalObject().portal_simulation
      solveMovement = simulation_tool.solveMovement
      solve_result_list = []
      # accept + split
      for decision in [q for q in decision_list if q.decision != 'adopt']:
        if decision.decision == 'accept':
          # accepting - in case of passed DeliverySolver use it, otherwise
          # simply copy values to simulation
          if not decision.delivery_solver_name:
            self._distributePropertyToSimulation(decision)
          solveMovement(self, decision.delivery_solver_name,
482
              decision.target_solver_name, divergence_list = [decision.divergence])
Łukasz Nowak's avatar
Łukasz Nowak committed
483 484 485 486 487 488 489 490 491 492
        elif decision.decision == 'split':
          solveMovement(self, decision.delivery_solver_name,
              decision.target_solver_name, **decision.split_kw)
        else: # aka - do nothing
          pass
      # adopt
      adopt_decision_list = [q for q in decision_list \
                             if q.decision == 'adopt']
      if adopt_decision_list:
        self._updatePropertyFromSimulation(adopt_decision_list)