TradeModelLine.py 18.3 KB
Newer Older
Yusei Tahara's avatar
Yusei Tahara committed
1
# -*- coding: utf-8 -*-
2 3 4 5
##############################################################################
#
# Copyright (c) 2009 Nexedi SA and Contributors. All Rights Reserved.
#                    Łukasz Nowak <luke@nexedi.com>
6
#                    Fabien Morin <fabien@nexedi.com>
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
#
# 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
32
from Products.CMFCore.utils import getToolByName
33
from Products.ERP5Type import Permissions, PropertySheet, interfaces
34
from Products.ERP5Type.XMLMatrix import XMLMatrix
35
from Products.ERP5.Document.Amount import Amount
36
from Products.ERP5.Document.Predicate import Predicate
37
from Products.ERP5.AggregatedAmountList import AggregatedAmountList
38
from Products.ERP5.Document.TradeCondition import TradeCondition
39 40
from Products.ERP5.PropertySheet.TradeModelLine import (TARGET_LEVEL_MOVEMENT,
                                                        TARGET_LEVEL_DELIVERY)
41 42
import zope.interface

43
class TradeModelLine(Predicate, XMLMatrix, Amount):
Łukasz Nowak's avatar
Łukasz Nowak committed
44 45 46 47 48 49 50 51 52 53
  """Trade Model Line is a way to represent trade transformation for movements"""
  meta_type = 'ERP5 Trade Model Line'
  portal_type = 'Trade Model Line'

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

  # Declarative interfaces
  zope.interface.implements(
54
      interfaces.IAmountGenerator,
Łukasz Nowak's avatar
Łukasz Nowak committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
      interfaces.IVariated
  )

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                  , PropertySheet.SimpleItem
                  , PropertySheet.CategoryCore
                  , PropertySheet.Amount
                  , PropertySheet.Price
                  , PropertySheet.TradeModelLine
                  , PropertySheet.Reference
                  , PropertySheet.Predicate
                  )

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPrice')
  def getPrice(self):
    return self._baseGetPrice()

  def updateAggregatedAmountList(self, context, **kw):
    raise NotImplementedError('TODO')

77 78 79 80 81 82 83 84 85 86 87
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getCalculationScript')
  def getCalculationScript(self, context):
    '''get script in this order :
          1 - model_line script
          2 - model script
    '''
    # get the model line script
    script_name = self.getCalculationScriptId()
    if script_name is None:
      # if model line script is None, get the default model script
88 89 90
      if isinstance(self.getParentValue(), TradeCondition):
        # if parent is a TradeCondition
        script_name = self.getParentValue().getCalculationScriptId()
91 92 93 94 95 96 97 98
    if script_name is None:
      return None
    script = getattr(context, script_name, None)
    if script is None:
      raise ValueError, "Unable to find `%s` calculation script" % \
                                                       script_name
    return script

99 100 101 102 103 104 105 106 107 108 109 110 111
  security.declareProtected(Permissions.AccessContentsInformation, 'test')
  def test(self, context, tested_base_category_list=None, strict_membership=0,
           **kw):
    result = TradeModelLine.inheritedAttribute('test')(
      self, context, tested_base_category_list, strict_membership, **kw)

    if result and self.getTargetLevel():
      # If Trade Model Line is set to delivery level, then do nothing
      # at movement level.
      if self.getTargetLevel()==TARGET_LEVEL_DELIVERY and not context.isDelivery():
        return False
    return result

Łukasz Nowak's avatar
Łukasz Nowak committed
112 113
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getAggregatedAmountList')
114 115 116
  def getAggregatedAmountList(self, context, movement_list=None,
      current_aggregated_amount_list=None, base_id='movement',
      rounding=False, **kw):
Łukasz Nowak's avatar
Łukasz Nowak committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130

    # test with predicate if this model line could be applied
    if not self.test(context):
      # This model_line should not be applied
      return []
    if movement_list is None:
      movement_list = []
    if current_aggregated_amount_list is None:
      current_aggregated_amount_list = []

    # if movement_list is passed as parameter, it shall be used,
    # otherwise it is needed to look up for movements
    if len(movement_list) == 0:
      # no movements passed, need to find some
131
      if context.isMovement():
Łukasz Nowak's avatar
Łukasz Nowak committed
132 133
        # create movement lists from context
        movement_list = [context]
134
      else:
Łukasz Nowak's avatar
Łukasz Nowak committed
135 136 137 138 139 140 141
        # create movement list for delivery's movements
        movement_list = []
        for movement in context.getMovementList():
          # XXX: filtering shall be in getMovementList
          # add only movement which are input (i.e. resource use category
          # is in the normal resource use preference list). Output will
          # be recalculated
142 143
          if not movement.getBaseApplication():
            movement_list.append(movement)
Łukasz Nowak's avatar
Łukasz Nowak committed
144

145 146 147 148
    if self.getTargetLevel()==TARGET_LEVEL_MOVEMENT:
      # movement level trade model is applied to each movement and
      # generate result par movement.
      result = []
149 150 151 152 153 154 155 156 157
      # If there is an amount which target level is delivery level and
      # create line is true, then treat it as a movement.
      movement_like_amount_list = []
      temporary_aggregated_amount_list = []
      for amount in current_aggregated_amount_list:
        if (amount.getProperty('target_level')==TARGET_LEVEL_DELIVERY and
            amount.getProperty('create_line')):
          movement_like_amount_list.append(amount)
        else:
Yusuke Muraoka's avatar
Yusuke Muraoka committed
158
          temporary_aggregated_amount_list.append(amount)
159
      for movement in (movement_list + movement_like_amount_list):
160
        result.extend(self._getAggregatedAmountList(
161
          context, [movement], temporary_aggregated_amount_list,
162 163 164 165 166 167 168 169 170 171 172 173
          base_id, rounding, **kw))
      return result
    else:
      return self._getAggregatedAmountList(
        context, movement_list, current_aggregated_amount_list,
        base_id, rounding, **kw)

  def _getAggregatedAmountList(self, context, movement_list=None,
                               current_aggregated_amount_list=None,
                               base_id='movement', rounding=False, **kw):
    from Products.ERP5Type.Document import newTempSimulationMovement

174 175 176 177 178 179 180 181
    # Define rounding stuff
    portal_roundings = getToolByName(self, 'portal_roundings', None)

    # ROUNDING
    if rounding:
      movement_list = [portal_roundings.getRoundingProxy(movement, context=self)
                       for movement in movement_list]

Łukasz Nowak's avatar
Łukasz Nowak committed
182 183 184
    aggregated_amount_list = AggregatedAmountList()
    base_application_list = self.getBaseApplicationList()

185
    document = self.getParentValue()
186
    self_id = '_'.join((document.getId(), self.getId(), context.getId()))
Łukasz Nowak's avatar
Łukasz Nowak committed
187

188 189 190 191 192 193 194
    # Make tmp movement list only when trade model line is not set to movement level.
    tmp_movement_list = []
    if self.getTargetLevel()!=TARGET_LEVEL_MOVEMENT:
      tmp_movement_list = [processed_movement
                           for processed_movement in current_aggregated_amount_list
                           if processed_movement.getReference() == self.getReference()]

Łukasz Nowak's avatar
Łukasz Nowak committed
195 196 197
    if len(tmp_movement_list) > 0:
      update = 1
    else:
198 199 200 201 202
      # get source and destination using Business Process
      if getattr(document, 'findSpecialiseValueList', None) is None:
        # if parent don't have findSpecialiseValueList, this mean it's on the
        # specialise_value
        document = self.getParentValue().getSpecialiseValue()
203 204 205 206 207
      try:
        business_process_list = document.findSpecialiseValueList(
            context=context, portal_type_list=['Business Process'])
      except AttributeError:
        business_process_list = []
208 209 210 211 212 213 214
      business_process = None
      property_dict = {}
      if len(business_process_list):
        # XXX currently, is too complicated to use more than
        # one Business Process, so the first (which is the nearest from the
        # delivery) is took
        business_process = business_process_list[0]
Łukasz Nowak's avatar
Łukasz Nowak committed
215
        business_path_list = business_process.getPathValueList(trade_phase=
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
            self.getTradePhase())
        if len(business_path_list) > 1:
          raise NotImplementedError, 'For now, it can not support more '\
              'than one business_path with same trade_phase. '\
              '%s have same trade_phase' % repr(business_path_list)
        if len(business_path_list) == 1:
          business_path = business_path_list[0]
          property_dict={
            'source_value_list': business_path.getSourceValueList(context=context),
            'destination_value_list':
            business_path.getDestinationValueList(context=context),
            'source_section_value_list':
            business_path.getSourceSectionValueList(context=context),
            'destination_section_value_list':
            business_path.getDestinationSectionValueList(context=context),
            'source_decision_value_list':
            business_path.getSourceDecisionValueList(context=context),
            'source_administration_value_list':
            business_path.getSourceAdministrationValueList(context=context),
            'source_payment_value_list':
            business_path.getSourcePaymentValueList(context=context),
            'destination_decision_value_list':
            business_path.getDestinationDecisionValueList(context=context),
            'destination_administration_value_list':
            business_path.getDestinationAdministrationValueList(context=context),
            'destination_payment_value_list':
            business_path.getDestinationPaymentValueList(context=context)
          }

Łukasz Nowak's avatar
Łukasz Nowak committed
245
      common_params = {
246 247
        'title':self.getTitle(),
        'description':self.getDescription(),
Łukasz Nowak's avatar
Łukasz Nowak committed
248 249
        'resource': self.getResource(),
        'reference': self.getReference(),
250
        'int_index': self.getIntIndex(),
Łukasz Nowak's avatar
Łukasz Nowak committed
251 252 253 254 255 256
        'base_application_list': base_application_list,
        'base_contribution_list': self.getBaseContributionList(),
        'start_date': context.getStartDate(),
        'stop_date': context.getStopDate(),
        'create_line': self.isCreateLine(),
        'trade_phase_list': self.getTradePhaseList(),
257
        'target_level': self.getTargetLevel(),
Łukasz Nowak's avatar
Łukasz Nowak committed
258
      }
259 260
      common_params.update(property_dict)

Łukasz Nowak's avatar
Łukasz Nowak committed
261 262
      update = 0
      base_category_list = self.getVariationBaseCategoryList()
263
      
264 265 266 267 268
      # get cells categories cartesian product
      cell_key_list = self.getCellKeyList(base_id='movement')
      if len(cell_key_list) > 0:
        # look for cells
        for cell_coordinates in cell_key_list:
Łukasz Nowak's avatar
Łukasz Nowak committed
269
          cell = self.getCell(base_id=base_id, *cell_coordinates)
270
          if cell is None:
271
            raise ValueError("Line '%s' (%s) can't find the cell corresponding"
272 273 274
                " to those cells coordinates : %s" % (self.getTitle(),
                                                      self.getRelativeUrl(),
                                                      cell_coordinates))
Łukasz Nowak's avatar
Łukasz Nowak committed
275 276
          tmp_movement = newTempSimulationMovement(self.getPortalObject(),
              self_id)
277 278 279 280 281 282 283 284 285 286 287

          # ROUNDING
          if rounding:
            # Once tmp_movement is replaced with the proxy, then the proxy
            # object returns rounded value.
            # For example, if rounding model is defined as
            # rounded_property_id='total_price', then proxied
            # tmp_movement.getTotalPrice() returns rounded result.
            # If rounded_property_id='quantity', then
            # tmp_movement.getQuantity() will be rounded.
            tmp_movement = portal_roundings.getRoundingProxy(tmp_movement, context=self)
Łukasz Nowak's avatar
Łukasz Nowak committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
          tmp_movement.edit(
              variation_base_category_list = cell.getVariationBaseCategoryList(),
              variation_category_list = cell.getVariationCategoryList(),
              price = cell.getPrice(),
              quantity = cell.getQuantity(0.0),
              **common_params
              )
          tmp_movement_list.append(tmp_movement)
      else:
        tmp_movement = newTempSimulationMovement(self.getPortalObject(),
          self_id,
          quantity = self.getQuantity(0.0),
          price = self.getPrice(),
          **common_params
        )
303 304 305 306 307 308

        # ROUNDING
        if rounding:
          # Replace temporary movement with rounding proxy so that target
          # property value will be rounded.
          tmp_movement = portal_roundings.getRoundingProxy(tmp_movement, context=self)
Łukasz Nowak's avatar
Łukasz Nowak committed
309 310
        tmp_movement_list.append(tmp_movement)
    modified = 0
311
    aggregated_movement_list = []
Łukasz Nowak's avatar
Łukasz Nowak committed
312 313 314 315 316
    for tmp_movement in tmp_movement_list:
      if len(self.getVariationCategoryList()) == 0 and \
          self.getQuantity(None) is None or \
          len(self.getVariationCategoryList()) and \
          tmp_movement.getQuantity(None) is None:
317 318 319 320 321
        for movement in movement_list + current_aggregated_amount_list:
          # here we need to look on movement_list and also on already processed
          # movements (current_aggregated_amount_list).
          # if the quantity is not defined, take it by searching all movements
          # that used this base_amount
322 323 324 325
          if (len(base_application_list) == 0 or \
              len(movement.getBaseContributionList()) == 0 or \
              set(base_application_list).intersection( \
              set(movement.getBaseContributionList()))) and \
326 327
              (len(movement.getVariationCategoryList()) == 0 or \
               len(tmp_movement.getVariationCategoryList()) == 0 or \
Łukasz Nowak's avatar
Łukasz Nowak committed
328
              set(movement.getVariationCategoryList()).intersection( \
329
              set(tmp_movement.getVariationCategoryList()))):
Łukasz Nowak's avatar
Łukasz Nowak committed
330 331 332
            # at least one base application is in base contributions and
            # if the movement have no variation category, it's the same as
            # if he have all variation categories
333
            quantity = tmp_movement.getQuantity(0.0)
Łukasz Nowak's avatar
Łukasz Nowak committed
334
            modified = 1
335
            tmp_movement.setQuantity(quantity + movement.getTotalPrice())
336 337 338
            aggregated_movement_list.append(movement)
        if aggregated_movement_list:
          tmp_movement.setCausalityValueList(aggregated_movement_list)
339

Łukasz Nowak's avatar
Łukasz Nowak committed
340 341
      else:
        # if the quantity is defined, use it
342 343 344 345
        #
        # Is this really good? This looks too implicit.
        # Using something like "apply this trade model line by force"
        # option would be better...(yusei)
Łukasz Nowak's avatar
Łukasz Nowak committed
346
        modified = 1
347
        if tmp_movement.getPrice() is None:
Łukasz Nowak's avatar
Łukasz Nowak committed
348 349 350
          # if price is not defined, it the same as 100 %
          tmp_movement.setPrice(1)

351 352 353
      # if a calculation script is defined, use it
      calculation_script = self.getCalculationScript(context)
      if calculation_script is not None:
354 355 356 357 358 359 360
        if (calculation_script.func_code.co_argcount==2 and
            calculation_script.func_code.co_varnames[:2]==('current_aggregated_amount_list',
                                                           'current_movement')):
          # backward compatibility
          tmp_movement = calculation_script(
              current_aggregated_amount_list=movement_list,
              current_movement=tmp_movement)
361 362
        elif calculation_script.func_code.co_argcount==3:
          # backward compatibility
363 364 365 366
          tmp_movement = calculation_script(
              current_aggregated_amount_list=movement_list,
              current_movement=tmp_movement,
              aggregated_movement_list=aggregated_movement_list)
367 368 369 370 371
        else:
          tmp_movement = calculation_script(
              current_aggregated_amount_list=movement_list,
              current_movement=tmp_movement,
              aggregated_movement_list=aggregated_movement_list,
372 373
              trade_model_line=self,
              **kw)
374 375 376 377 378 379
        if tmp_movement is None:
          # Do nothing
          return aggregated_amount_list
        if rounding:
          tmp_movement = portal_roundings.getRoundingProxy(
            tmp_movement, context=self)
380

Łukasz Nowak's avatar
Łukasz Nowak committed
381
      # check if slices are used
Łukasz Nowak's avatar
Łukasz Nowak committed
382
      salary_range_list = tmp_movement.getVariationCategoryList(
Łukasz Nowak's avatar
Łukasz Nowak committed
383 384
          base_category_list='salary_range') #XXX hardcoded values
      salary_range = len(salary_range_list) and salary_range_list[0] or None
385 386 387
      if salary_range is not None and calculation_script is None:
        # slice are used only if there is no script found, in case where a
        # script exist, slice should be handle in it
Fabien Morin's avatar
Fabien Morin committed
388 389
        model = context.getSpecialiseValue() # get the closest model from
                                             # the paysheet
Łukasz Nowak's avatar
Łukasz Nowak committed
390 391
        cell = model.getCell(salary_range)
        if cell is None:
392
          raise ValueError("Line '%s' (%s) can't find the cell corresponding"
393
              " to those cells coordinates : %s" % (self.getTitle(),
394
                                                    self.getRelativeUrl(),
395
                                                    salary_range))
Łukasz Nowak's avatar
Łukasz Nowak committed
396 397 398
        model_slice_min = cell.getQuantityRangeMin()
        model_slice_max = cell.getQuantityRangeMax()
        base_application = tmp_movement.getQuantity(0.0)
Fabien Morin's avatar
Fabien Morin committed
399
        if base_application <= model_slice_min:
400 401 402
          # if base_application is not in the slice range, quantity is 0
          tmp_movement.setQuantity(0)
        elif base_application-model_slice_min > 0:
Łukasz Nowak's avatar
Łukasz Nowak committed
403 404 405 406 407 408 409 410 411 412 413
          if base_application <= model_slice_max:
            tmp_movement.setQuantity(base_application-model_slice_min)
          elif model_slice_max:
            tmp_movement.setQuantity(model_slice_max-model_slice_min)

      if not update and modified:
        # no movements were updated, but something was modified, so new
        # movement appeared
        aggregated_amount_list.append(tmp_movement)

    return aggregated_amount_list