AmortisationRule.py 63.9 KB
Newer Older
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
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#                    Guillaume MICHON <guillaume@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.
#
##############################################################################

29
import zope.interface
30 31 32
from AccessControl import ClassSecurityInfo
from DateTime import DateTime
from copy import deepcopy
33 34
from string import lower, capitalize

35
from Products.ERP5Type.DateUtils import millis, centis, getClosestDate, addToDate
36
from Products.ERP5Type.DateUtils import getDecimalNumberOfYearsBetween
37
from Products.ERP5Type import Permissions, PropertySheet, Constraint, interfaces
38 39
from Products.ERP5.Document.Rule import Rule
from Products.CMFCore.utils import getToolByName
40 41
from Products.ERP5.Document.ImmobilisationMovement import NO_CHANGE_METHOD

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

from zLOG import LOG

class AmortisationRule(Rule):
    """
      Amortisation Rule object plans an item amortisation
    """

    # CMF Type Definition
    meta_type = 'ERP5 Amortisation Rule'
    portal_type = 'Amortisation Rule'
    add_permission = Permissions.AddPortalContent
    isPortalContent = 1
    isRADContent = 1

    # Declarative security
    security = ClassSecurityInfo()
59
    security.declareObjectProtected(Permissions.AccessContentsInformation)
Jérome Perrin's avatar
Jérome Perrin committed
60
    
61
    zope.interface.implements( interfaces.IPredicate,
62
                       interfaces.IRule )
63 64 65 66 67 68

    # Default Properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
                      , PropertySheet.CategoryCore
                      , PropertySheet.DublinCore
69
                      , PropertySheet.Task
70 71
                      )

72 73 74
    movement_name_dict = { 'immobilisation':   { 'immo':  'start_immo',
                                                 'amo':   'start_amo',
                                                 'vat':   'start_vat',
75 76
                                                 'input': 'start_input',
                                                 'extra_input':'start_extra_input' },
77 78
                           'unimmobilisation': { 'immo':  'stop_immo',
                                                 'amo':   'stop_amo',
79
                                                 'output':'stop_output' },
80
                           'annuity':          { 'depr':  'annuity_depr',
81 82 83 84 85 86 87
                                                 'amo':   'annuity_amo',
                                                 'temp_amo':'annuity_temp_amo',
                                                 'temp_depr':'annuity_temp_depr' },
                           'transfer':         { 'immo':  'transfer_immo',
                                                 'amo':   'transfer_amo',
                                                 'in_out':'transfer_in_out',
                                                 'depr':  'transfer_depr'},
88 89
                           'correction':         'correction'
                         }
90

91 92 93 94 95 96 97 98 99 100 101 102

    # Simulation workflow
    security.declareProtected(Permissions.ModifyPortalContent, 'expand')
    def expand(self, applied_rule, force=0, **kw):
      """
        Expands the current movement downward.

        -> new status -> expanded

        An applied rule can be expanded only if its parent movement
        is expanded.
      """
103
      invalid_state_list = self.getPortalUpdatableAmortisationTransactionStateList()
104
      to_aggregate_movement_list = []
105 106 107 108 109 110 111 112
                                                 
      def updateSimulationMovementProperties(simulation_movement, calculated_movement, set_ratio=0):
        """
        Update the properties of the given simulation movement according
        to the given calculated_movement.
        WARNING : This method does not check if the state of the Amortisation
        Transaction corresponding to the Simulation Movement makes it uneditable
        set_ratio is used to force the delivery_ratio property update
113
        Return a list of the properties which have been modified
114
        """
115
        modified_properties = []
116
        for (key, value) in calculated_movement.items():
117 118 119 120 121 122 123 124 125 126 127
          if key not in ('name','status','id','divergent'):
            getter_name = 'get%s' % ''.join([capitalize(o) for o in key.split('_')])
            getter = getattr(simulation_movement, getter_name)
            previous_value = getter()
            # Check if this property changes
            if (previous_value is None and value is not None) or \
               (previous_value is not None and previous_value != value):
                modified_properties.append(key)
           
            if value is None and key.split('_')[-1] == 'value':
              key = '_'.join(key.split('_')[:-1])
128 129 130
            setter_name = 'set%s' % ''.join([capitalize(o) for o in key.split('_')])
            setter = getattr(simulation_movement, setter_name)
            setter(value)
131
        simulation_movement.edit(start_date=simulation_movement.getStopDate())
132 133
        if set_ratio:
          simulation_movement.setDefaultDeliveryProperties()
134
        #simulation_movement.immediateReindexObject()
135
        return modified_properties
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
     
      def updateSimulationMovement(aggregated_movement, calculated_movement,
                                   correction_number, aggregated_period_number,
                                   correction_movement_dict):
        """
        Update the Simulation Movement corresponding to aggregated_movement.
        Modify it to respect calculated_movement values.
        If the corresponding Amortisation Transaction is already validated,
        create a corrective Simulation Movement, since a validated Transaction
        must not be modified.
        If a correction movement already exists, the new movement takes care of it.
        correction_number is the id number for new movements.
        Return the number of new Simulation Movements created
        """
        def createMovement(property_dict, correction_number):
          new_id = '%s_%i_%i' % (self.movement_name_dict['correction'], aggregated_period_number, correction_number)
          simulation_movement = applied_rule.newContent(portal_type=delivery_line_type, id=new_id)
          updateSimulationMovementProperties(simulation_movement = simulation_movement,
                                             calculated_movement = property_dict)
155
        if aggregated_movement['status'] not in invalid_state_list:
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 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
          # The Simulation Movement corresponds to an Amortisation Transaction Line
          # whose Amortisation Transaction is in a valid state, so we cannot modify
          # the Simulation Movement. Some new Simulation Movements are so created
          # to correct the Simulation state.
          same_path = 1
          for property in ("source", "destination",
                           "source_section_value",
                           "destination_section_value",
                           "resource_value", "stop_date", "start_date"):
            if aggregated_movement[property] != calculated_movement[property]:
              same_path = 0

          # Determine the list of correction movement for this aggregated movement.
          # It is done only for a validated aggregated movement, since a non-validated
          # one should have been modified, rather than corrected by a correction movement
          path_tuple = (aggregated_movement['source'],
                        aggregated_movement['destination'],
                        aggregated_movement['source_section_value'],
                        aggregated_movement['destination_section_value'],
                        aggregated_movement['resource_value'],
                        aggregated_movement['stop_date'],
                        aggregated_movement['start_date'])
          correction_movement_list = correction_movement_dict.get(path_tuple, [])
          already_corrected_quantity = 0
          for correction_movement in correction_movement_list:
            already_corrected_quantity += correction_movement['quantity']
          if len(correction_movement_list) != 0:
            del correction_movement_dict[path_tuple]
              
          if same_path:
            # We only need to create a new Simulation Movement to correct the amount
            correction_quantity = calculated_movement['quantity'] - aggregated_movement['quantity']
            correction_quantity -= already_corrected_quantity
            property_dict = dict(aggregated_movement)
            if correction_quantity != 0:
              property_dict['quantity'] = correction_quantity
              createMovement(property_dict, correction_number)
              return 1
          else:
            # We need to create two new Simulation Movements : one to annulate the
            # aggregated amount, and one to correct the value according to the calculated movements
            property_dict = dict(aggregated_movement)
            correction_quantity = - property_dict['quantity']
            correction_quantity -= already_corrected_quantity
            if correction_quantity != 0:
              property_dict['quantity'] = correction_quantity
              createMovement(property_dict, correction_number)
              correction_number += 1
              createMovement(calculated_movement, correction_number)
              return 2
        else:
          # The Simulation Movement corresponds to an Amortisation Transaction Line
          # whose Amortisation Transaction is not in a valid state, so we can
          # modify the Simulation Movement. It introduces an inconsistency the user
          # will have to solve.
          simulation_movement = getattr(applied_rule, aggregated_movement['id'], None)
212 213 214 215 216 217
          modified_properties = updateSimulationMovementProperties(simulation_movement = simulation_movement,
                                                                   calculated_movement = calculated_movement)
          # If anything else the quantity has changed, the movement is disconnected and re-aggregated
          if ('quantity' in modified_properties and len(modified_properties)>1) or \
              ('quantity' not in modified_properties and len(modified_properties)>0):
            to_aggregate_movement_list.append(simulation_movement)
218 219
            simulation_movement.edit(delivery='', profit_quantity=0, 
                  activate_kw={'tag':'disconnect_amortisation_transaction'})
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
        return 0
   
      def updateSimulationMovementToZero(aggregated_movement,
                                         correction_number,
                                         aggregated_period_number,
                                         correction_movement_dict):
        """
        Set the quantity value of the given aggregated movement to 0.
        This method takes care of the validated aggregated movements
        Return the number of new movements created
        """
        property_list = dict(aggregated_movement)
        if aggregated_movement['quantity'] != 0:
          property_list['quantity'] = 0
          return updateSimulationMovement(aggregated_movement = aggregated_movement,
                                          calculated_movement = property_list,
                                          correction_number   = correction_number,
                                          aggregated_period_number = aggregated_period_number,
                                          correction_movement_dict = correction_movement_dict)
        return 0

                                          
      def setRemainingAggregatedMovementsToZero(aggregated_movement_dict,
                                                correction_number,
                                                aggregated_period_number,
                                                correction_movement_dict):
        """
        The remaining aggregation movements in aggregated_movement_dict
        are set to quantity 0, taking care of their validation state and
        the already made correction
        """
        method_movements_created = 0
253 254
        for (m_type, aggregated_movement_list) in aggregated_movement_dict.items():
          if m_type != self.movement_name_dict['correction']:
255 256 257 258 259 260 261 262 263 264
            for aggregated_movement in aggregated_movement_list:
              movements_created = updateSimulationMovementToZero(aggregated_movement = aggregated_movement,
                                                                 correction_number   = correction_number,
                                                                 aggregated_period_number = aggregated_period_number,
                                                                 correction_movement_dict = correction_movement_dict)
              correction_number += movements_created 
              method_movements_created += movements_created
        # Some correction movements may still be unused, we need to set them to 0
        unused_correction_list = []
        for correction_movement_list_list in correction_movement_dict.values():
265
          for correction_movement_list in correction_movement_list_list:
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
            for correction_movement in correction_movement_list:
              unused_correction_list.append(correction_movement)
        correction_movement_list = aggregated_movement_dict.get( self.movement_name_dict['correction'], [] )
        for correction_movement in correction_movement_list:
          if correction_movement in unused_correction_list:
            movements_created = updateSimulationMovementToZero(aggregated_movement = correction_movement,
                                                               correction_number   = correction_number,
                                                               aggregated_period_number = aggregated_period_number,
                                                               correction_movement_dict = {}) 
            correction_number += movements_created
            method_movements_created += movements_created

        return method_movements_created
            
          
          
      ### Start of expand() ###
        
284
      delivery_line_type = 'Simulation Movement'
285
      to_notify_delivery_list = []
286
      # Get the item we come from
287
      my_item = applied_rule.getCausalityValue()
288
      # Only expand if my_item is not None
289 290 291 292 293
      if my_item is None:
        return

      ### First, plan the theorical accounting movements
      accounting_movement_list = []
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
      immo_cache_dict = {'period':{}, 'price':{}}
      immo_period_list = my_item.getImmobilisationPeriodList(immo_cache_dict=immo_cache_dict)
      for period_number in range(len(immo_period_list)):
        immo_cache_dict['price'] = {}
        previous_period = None
        next_period = None
        immo_period = immo_period_list[period_number]
        if period_number != 0: previous_period=immo_period_list[period_number-1]
        if period_number != len(immo_period_list)-1: next_period=immo_period_list[period_number+1]
        accounting_movements = self._getAccountingMovement(immo_period=immo_period,
                                                           previous_period=previous_period,
                                                           next_period=next_period,
                                                           period_number=period_number,
                                                           item=my_item,
                                                           immo_cache_dict=immo_cache_dict)
309
        accounting_movement_list.extend(accounting_movements)
310

311 312
      ### The next step is to create the simulation movements
      # First, we delete all of the simulation movements which are children
313 314 315 316
      # of the applied rule, but which have not been aggregated.
      to_delete_id_list = []
      aggregated_period_dict = {}
      portal_workflow = getToolByName(self, 'portal_workflow')
317 318
      for movement in applied_rule.contentValues():
        movement_id = movement.getId()
319 320 321 322
        movement_id_name = '_'.join( movement_id.split('_')[:-2] )
        movement_id_period_number = int(movement_id.split('_')[-2])
        delivery_value = movement.getDeliveryValue()
        if delivery_value is None:
323 324
          # This movement is not already used by the accounting module,
          # we can add it to the list to delete
325
          to_delete_id_list.append(movement_id)
326
        else:
327
          # This movement is already used by the accounting module,
328 329 330 331 332 333 334 335 336 337 338 339
          # we store it according to the state of the corresponding
          # Amortisation Transaction. We also make a data structure
          # to make easier the future work of correspondance
          movement_dict = { 'stop_date':                movement.getStopDate(),
                            'start_date':               movement.getStartDate(),
                            'quantity':                 movement.getQuantity(),
                            'source_section_value':     movement.getSourceSectionValue(),
                            'destination_section_value':movement.getDestinationSectionValue(),
                            'source':                   movement.getSource(),
                            'destination':              movement.getDestination(),
                            'resource_value':           movement.getResourceValue(),
                            'id':                       movement.getId(),
340
                            'status':                   delivery_value.getRootDeliveryValue().getSimulationState(),
341 342 343
                            'divergent':                movement.isDivergent() }
          self._placeMovementInStructure(aggregated_period_dict, movement_dict, movement_id_period_number, movement_id_name)
          # Add the delivery to the list to be notified (since each aggregated movement will be modified)
344 345 346
          parent = delivery_value.getRootDeliveryValue()
          if parent is not None:
            to_notify_delivery_list.append(parent)
347
      # Deletion of non-aggregated movements
348
      applied_rule.manage_delObjects(to_delete_id_list)
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

      # Re-handle data of calculated movements to make easier the future
      # work of correspondance
      calculated_period_dict = {}
      for movement in accounting_movement_list:
        # Round date
        stop_date = movement['stop_date']
        if stop_date.latestTime() - stop_date < centis:
          stop_date = stop_date + 1
        stop_date = DateTime(stop_date.Date())
        movement['stop_date'] = stop_date
        movement['start_date'] = stop_date
        
        splitted_name = movement['name'].split('_')
        movement_name = '_'.join( splitted_name[:-2] )
        movement_period = int(splitted_name[-2])
        if movement['quantity'] != 0:
          self._placeMovementInStructure(calculated_period_dict, movement, movement_period, movement_name)
        
      # Then, we need to make a correspondance between aggregated movements and calculated ones
      for current_dict in (aggregated_period_dict, calculated_period_dict):
        for type_dict in current_dict.values():
          for movement_list in type_dict.values():
372
            movement_list.sort(key=lambda x: x['stop_date'])
373
      matched_dict = self._matchAmortisationPeriods(calculated_period_dict, aggregated_period_dict)
374
      
375
      # We can now apply the calculated movements on the applied rule
376
      new_period=0
377
      try:
378 379
        if aggregated_period_dict != {}:
          new_period = max(aggregated_period_dict.keys()) + 1
Yoshinori Okuji's avatar
Yoshinori Okuji committed
380
      except TypeError:
381
        pass
382 383 384 385 386 387
      for (c_period_number, calculated_dict) in calculated_period_dict.items():
        # First, look for a potential found match
        match = matched_dict.get(c_period_number, None)
        if match is None:
          # We did not find any match for this calculated period, so we
          # simply add the Simulation Movements into the Simulation
388
          for (mov_type, movement_list) in calculated_dict.items():
389 390 391
            for movement_number in range(len(movement_list)):
              movement = movement_list[movement_number]
              if movement['quantity'] != 0:
392
                new_id = '%s_%i_%i' % (mov_type, new_period, movement_number)
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
                simulation_movement = applied_rule.newContent(portal_type=delivery_line_type, id=new_id)
                # Set the properties
                updateSimulationMovementProperties(simulation_movement = simulation_movement,
                                                   calculated_movement = movement)
          new_period += 1
        else:
          # A match has been found between this calculated period, and
          # an already aggregated one. In this case, there can be orphaned
          # calculated movements, and orphaned aggregated movements.
          relocate = match['relocate']
          aggregated_period_number = match['aggregated']
          aggregated_movement_dict = aggregated_period_dict[aggregated_period_number]
          correction_data = self._getCorrectionMovementData(aggregated_movement_dict)
          correction_number = correction_data['correction_number']
          correction_movement_dict = correction_data['correction_movement_dict']
408 409
          for (mov_type, calculated_movement_list) in calculated_dict.items():
            aggregated_movement_list = aggregated_movement_dict.get(mov_type, [])
410 411 412 413 414 415
            new_aggregated_number = 0
            for aggregated_movement in aggregated_movement_list:
              movement_id = int( aggregated_movement['id'].split('_')[-1] )
              if movement_id + 1 > new_aggregated_number:
                new_aggregated_number = movement_id + 1

416
            if mov_type in self.movement_name_dict['annuity'].values():
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
              # Annuity movement
              # We use relocate to match the movements.
              to_delete_from_aggregated = []
              for i in range(len(calculated_movement_list)):
                calculated_movement = calculated_movement_list[i]
                if not (i + relocate < 0 or i + relocate > len(aggregated_movement_list) - 1):
                  # We have two annuities to match
                  aggregated_movement = aggregated_movement_list[i + relocate]
                  movements_created = updateSimulationMovement(aggregated_movement = aggregated_movement,
                                                               calculated_movement = calculated_movement,
                                                               correction_number   = correction_number,
                                                               aggregated_period_number = aggregated_period_number,
                                                               correction_movement_dict = correction_movement_dict)
                  correction_number += movements_created
                  to_delete_from_aggregated.append(aggregated_movement)
                else:
                  # No matching found. We simply create the annuity
434
                  new_id = '%s_%i_%i' % (mov_type, aggregated_period_number, new_aggregated_number)
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
                  simulation_movement = applied_rule.newContent(portal_type=delivery_line_type, id=new_id)
                  updateSimulationMovementProperties(simulation_movement = simulation_movement,
                                                     calculated_movement = calculated_movement)
                  new_aggregated_number += 1
              # There is no calculated movement left. We set the remaining aggregated movements to zero
              for movement in to_delete_from_aggregated:
                aggregated_movement_list.remove(movement)
              for aggregated_movement in aggregated_movement_list:
                movements_created = updateSimulationMovementToZero(aggregated_movement = aggregated_movement,
                                                                   correction_number   = correction_number,
                                                                   aggregated_period_number = aggregated_period_number,
                                                                   correction_movement_dict = correction_movement_dict)
                correction_number += movements_created
            else:
              # Immobilisation or unimmobilisation movement
              # If there are more than one of such movements (this should
              # occur quite rarely), the matching process has found
              # the most matching ones
              non_annuity_match = match['non-annuity'].get(type, None)
              if non_annuity_match is not None:
                aggregated_movement = aggregated_movement_list[non_annuity_match[1]]
                calculated_movement = calculated_movement_list[non_annuity_match[0]]
                movements_created = updateSimulationMovement(aggregated_movement = aggregated_movement,
                                                             calculated_movement = calculated_movement,
                                                             correction_number   = correction_number,
                                                             aggregated_period_number = aggregated_period_number,
                                                             correction_movement_dict = correction_movement_dict)
                correction_number += movements_created
                aggregated_movement_list.remove(aggregated_movement)
                calculated_movement_list.remove(calculated_movement)
              # Then the remaining movements are arbitratry matched
              for calculated_movement in calculated_movement_list:
                if len(aggregated_movement_list) > 0:
                  aggregated_movement = aggregated_movement_list[0]
                  movements_created = updateSimulationMovement(aggregated_movement = aggregated_movement,
                                                               calculated_movement = calculated_movement,
                                                               correction_number   = correction_number,
                                                               aggregated_period_number = aggregated_period_number,
                                                               correction_movement_dict = correction_movement_dict)
                  correction_number += movements_created
                  aggregated_movement_list.remove(aggregated_movement)
                else:
                  # There is no aggregated movement left. We simply create the remaining calculated movements
478
                  new_id = '%s_%i_%i' % (mov_type, aggregated_period_number, new_aggregated_number)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
                  simulation_movement = applied_rule.newContent(portal_type=delivery_line_type, id=new_id)
                  updateSimulationMovementProperties(simulation_movement = simulation_movement,
                                                     calculated_movement = calculated_movement)
                  new_aggregated_number += 1
              for aggregated_movement in aggregated_movement_list:
                # There is no calculated movement left. We set the remaining aggregated movements to zero.
                movements_created = updateSimulationMovementToZero(aggregated_movement = aggregated_movement,
                                                                   correction_number   = correction_number,
                                                                   aggregated_period_number = aggregated_period_number,
                                                                   correction_movement_dict = correction_movement_dict)
                correction_number += movements_created
        
            # We delete this movement type from aggregation, in order to determine
            # the types which have not been matched later
            try:
494
              del aggregated_movement_dict[mov_type]
Yoshinori Okuji's avatar
Yoshinori Okuji committed
495
            except KeyError:
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
              pass
         
          movements_created = setRemainingAggregatedMovementsToZero(aggregated_movement_dict = aggregated_movement_dict,
                                                                    correction_number        = correction_number,
                                                                    aggregated_period_number = aggregated_period_number,
                                                                    correction_movement_dict = correction_movement_dict)
          correction_number += movements_created
          
          # This aggregated period handling is finished. We delete it from the dictionary
          # in order to determine the non-matched aggregated periods later.
          del aggregated_period_dict[aggregated_period_number]

          
      # The matching process is finished. Now we set to 0 each remaining aggregated movement
      for (aggregated_period_number, aggregated_movement_dict) in aggregated_period_dict.items():
        correction_data = self._getCorrectionMovementData(aggregated_movement_dict)
        correction_number = correction_data['correction_number']
        correction_movement_dict = correction_data['correction_movement_dict']
        movements_created = setRemainingAggregatedMovementsToZero(aggregated_movement_dict = aggregated_movement_dict,
                                                                  correction_number        = correction_number,
                                                                  aggregated_period_number = aggregated_period_number,
                                                                  correction_movement_dict = correction_movement_dict)
        correction_number += movements_created
519 520 521 522 523 524

      # Re-aggregate disconnected movements. These movements were already aggregated, but their properties
      # have been changed, and they have been disconnected so.
      if len(to_aggregate_movement_list) > 0:
        self.portal_deliveries.amortisation_transaction_builder.build(
            movement_relative_url_list = [m.getRelativeUrl() for m in to_aggregate_movement_list])
525 526 527 528 529 530 531

      # Finally notify modified deliveries in order to update causality state
      for delivery_value in to_notify_delivery_list:
        delivery_value.activate(
            after_tag='disconnect_amortisation_transaction'
            ).AmortisationTransaction_afterBuild()
        delivery_value.edit()
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582

        
    def _getCorrectionMovementData(self, aggregated_movement_dict):
      """
      Return a dictionary containing the first id number for a new correction movement,
      and a re-handled structure containing the correction movements, in order to make
      easier their search
      It is needed to reduce the number of correction movements. If we can notice that
      an aggregated movement is already corrected by a correction movement, we do not
      have to correct it again
      """
      correction_movement_list = aggregated_movement_dict.get(self.movement_name_dict['correction'], [])[:]
      correction_number = 0
      for correction_movement in correction_movement_list:
        movement_id = int( correction_movement['id'].split('_')[-1] )
        if movement_id + 1 > correction_number:
          correction_number = movement_id + 1

      correction_movement_dict = {}
      for correction_movement in correction_movement_list:
        path_tuple = (correction_movement['source'],
                      correction_movement['destination'],
                      correction_movement['source_section_value'],
                      correction_movement['destination_section_value'],
                      correction_movement['resource_value'],
                      correction_movement['stop_date'],
                      correction_movement['start_date'])
        if correction_movement_dict.get(path_tuple, None) is None:
          correction_movement_dict[path_tuple] = []
        correction_movement_dict[path_tuple].append(correction_movement)
      return { 'correction_number':correction_number, 'correction_movement_dict':correction_movement_dict }
    
        
    def _matchAmortisationPeriods(self, calculated_period_dict, aggregated_period_dict):
      """
      Try to match each period in calculated_period_dict with a period in
      aggregated_period_dict.
      It is done by using a "matching ratio" : when two movements of both dictionaries
      have a identical property (source, destination, quantity, resource, ...), the
      matching ratio is incremented for the correspondance between the both corresponding
      periods.
      Then, periods are matched in order of priority of the matching ratio.
      """
      def calculateMovementMatch(movement_a, movement_b, parameter_list = ['source_section_value',
                          'destination_section_value', 'source', 'destination', 'resource_value', 'quantity'],
                          compare_dates=0 ):
        if compare_dates:
          parameter_list.append('stop_date')
        matching = { 'max':0, 'score':0 }
        for matching_parameter in parameter_list:
          matching['max'] = matching['max'] + 1
583
          if movement_a.get(matching_parameter) == movement_b.get(matching_parameter):
584 585 586 587 588 589 590 591 592 593
            matching['score'] = matching['score'] + 1
        return matching
            
      matching_ratio_list = []
      for (calculated_period_number,calculated_dict) in calculated_period_dict.items():
        calculated_immobilisation = calculated_dict.get(self.movement_name_dict['immobilisation']['immo'], [])
        for (aggregated_period_number, aggregated_dict) in aggregated_period_dict.items():
          # We first compare the dates of immobilisation, so we can compare the annuity suit
          # first directly, and then by relocating in time
          relocate_list = [0, 1, -1]
594
          aggregated_immobilisation = aggregated_dict.get(self.movement_name_dict['immobilisation']['immo'], [])
595 596 597 598 599 600 601 602 603 604
          if len(calculated_immobilisation) != 0 and len(aggregated_immobilisation) != 0:
            c_immobilisation_movement = calculated_immobilisation[-1]
            a_immobilisation_movement = aggregated_immobilisation[-1]
            c_date = c_immobilisation_movement['stop_date']
            a_date = a_immobilisation_movement['stop_date']
            if a_date < c_date:
              date_difference = int(getDecimalNumberOfYearsBetween(a_date, c_date))
            else:
              date_difference = int(- getDecimalNumberOfYearsBetween(c_date, a_date))
            if abs(date_difference) >= 1:
605
              relocate_list.extend([date_difference-1, date_difference, date_difference+1])
606 607 608 609 610 611 612 613 614 615 616 617
              for o in relocate_list[:]:
                while relocate_list.count(o) > 1:
                  relocate_list.remove(o)
                  
          # Then we try to effectively match some data in these two periods, by relocating in time
          # Annuities
          current_matching = {'score':0, 'max':0, 'relocate':0, 'non-annuity':{}}
          for relocate in relocate_list:
            relocate_matching = {'score':0, 'max':0, 'relocate':relocate, 'non-annuity':{}}
            a_annuity_list = aggregated_dict.get(self.movement_name_dict['annuity']['amo'], [])
            c_annuity_list = calculated_dict.get(self.movement_name_dict['annuity']['amo'], [])
            for i in range(len(a_annuity_list)):
618
              a_annuity = a_annuity_list[i]
619 620
              if not (i + relocate < 0 or i + relocate > len(c_annuity_list) - 1):
                c_annuity = c_annuity_list[i + relocate]
621 622 623 624 625 626 627
              else:
                # Simulate an empty c_annuity to take into account non-matched movements
                c_annuity = {}
              this_matching = calculateMovementMatch(a_annuity, c_annuity)
              relocate_matching['score'] = relocate_matching['score'] + this_matching['score']
              relocate_matching['max'] = relocate_matching['max'] + this_matching['max']
            
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
            # Compare the current relocated matching with the best relocated matching found until now
            if current_matching['max'] == 0:
              current_matching_ratio = 0
            else:
              current_matching_ratio = current_matching['score'] / (current_matching['max']+0.)
            if relocate_matching['max'] == 0: relocate_matching['max'] = 1
            relocate_matching_ratio = relocate_matching['score'] / (relocate_matching['max']+0.)
            if relocate_matching_ratio >= current_matching_ratio:
              if relocate_matching_ratio > current_matching_ratio or abs(relocate) < abs(current_matching['relocate']):
                current_matching = relocate_matching
              
          # Immobilisation and unimmobilisation ; normally, there should only be one or
          # two movements of each type here, so we can compare each movement with all
          # of the others without losing much time
          for movement_type in ('immobilisation', 'unimmobilisation'):
            for immobilisation_type in self.movement_name_dict['immobilisation'].values():
              a_movement_list = aggregated_dict.get(immobilisation_type, [])
              c_movement_list = calculated_dict.get(immobilisation_type, [])
              local_best_matching = {'score':0, 'max':0, 'non-annuity':{} }
              local_current_matching = {'score':0, 'max':0}
              for a_number in range(len(a_movement_list)):
                a_movement = a_movement_list[a_number]
                for c_number in range(len(c_movement_list)):
                  c_movement = c_movement_list[c_number]
                  local_current_matching = calculateMovementMatch(a_movement, c_movement, compare_dates=1)
                  if local_best_matching['max'] == 0: local_best_matching['max'] = 1
                  local_best_ratio = local_best_matching['score'] / (local_best_matching['max']+0.)
                  if local_current_matching['max'] == 0: local_current_matching['max'] = 1
                  local_current_ratio = local_current_matching['score'] / (local_current_matching['max']+0.)
                  if local_current_ratio > local_best_ratio:
                    local_best_matching = local_current_matching
                    local_best_matching['non-annuity'] = { immobilisation_type: [a_number, c_number] }
              # Add the best found matching to the current matching score
              current_matching['score'] = current_matching['score'] + local_best_matching['score']
              current_matching['max'] = current_matching['max'] + local_best_matching['max']
              current_matching['non-annuity'].update( local_best_matching['non-annuity'] )
          
          # We found a matching ratio for this aggregated-calculated periods pair, with a particular
          # relocating. We add the ratio in the list in order to be able to retrieve it later
          if current_matching['max'] == 0:
            ratio = 0
          else:
            ratio = current_matching['score'] / (current_matching['max']+0.)
          matching_ratio_list.append( { 'calculated_period' : calculated_period_number,
                                        'aggregated_period' : aggregated_period_number,
                                        'ratio'             : ratio,
674
                                        'max'               : current_matching['max'],
675 676 677 678 679 680
                                        'relocate'          : current_matching['relocate'],
                                        'non-annuity'       : current_matching['non-annuity'] } )

      # We have each matching ratio. Now we need to match each amortisation period
      # according to these ratio : the highest ratio gets the priority, then the next
      # highest is taken into account if corresponding resources are free, and so on
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
681
      matching_ratio_list.sort(key=lambda x: x['ratio'], reverse=True)
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
      calculated_to_match = calculated_period_dict.keys()
      aggregated_to_match = aggregated_period_dict.keys()
      match_dict = {}
      for matching_ratio in matching_ratio_list:
        calculated  = matching_ratio['calculated_period']
        aggregated  = matching_ratio['aggregated_period']
        relocate    = matching_ratio['relocate']
        non_annuity = matching_ratio['non-annuity']
        if calculated in calculated_to_match and aggregated in aggregated_to_match:
          match_dict[calculated] = { 'aggregated':aggregated, 'relocate':relocate, 'non-annuity':non_annuity }
          calculated_to_match.remove(calculated)
          aggregated_to_match.remove(aggregated)

      return match_dict
        
        
        
    def _placeMovementInStructure(self, structure, movement_dict, period_number, name):
      """
      Used to sort aggregated and calculated movements in a structure
      to make easier the correspondance work
      """
      period_dict = structure.get(period_number, None)
      if period_dict is None:
        structure[period_number] = {}
        period_dict = structure[period_number]
      movement_list = period_dict.get(name, None)
      if movement_list is None:
        period_dict[name] = []
        movement_list = period_dict[name]
      movement_list.append( movement_dict )
713 714


715
    security.declareProtected(Permissions.View, '_getAccountingMovement')
716
    def _getAccountingMovement(self, immo_period, previous_period, next_period, period_number=0, item=None, **kw):
717
      """
718
      Calculates the value of accounting movements during the given period
719 720
      between the two given immobilisation movements.
      """
721 722 723 724 725 726 727 728 729
      # These methods are used to create dictionaries containing data to return
      def buildImmobilisationCalculatedMovementList(date, period, source_section, destination_section, 
                                                    currency, movement_list=[]):
        return buildSpecificCalculatedMovementList(date, period, 0, source_section, destination_section,
                                                   currency, movement_list, 'immobilisation')
      def buildUnimmobilisationCalculatedMovementList(date, period, source_section, destination_section,
                                                      currency, movement_list=[]):
        return buildSpecificCalculatedMovementList(date, period, 0, source_section, destination_section,
                                                   currency, movement_list, 'unimmobilisation')
730 731 732 733
      def buildTransferCalculatedMovementList(date, period, source_section, destination_section, 
                                                    currency, movement_list=[]):
        return buildSpecificCalculatedMovementList(date, period, 0, source_section, destination_section,
                                                   currency, movement_list, 'transfer')
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
      def buildAnnuityCalculatedMovementList(date, period, annuity, source_section, destination_section,
                                             currency, movement_list=[]):
        return buildSpecificCalculatedMovementList(date, period, annuity, source_section, destination_section,
                                                   currency, movement_list, 'annuity')

      def buildSpecificCalculatedMovementList(date, period, annuity, source_section, destination_section,
                                              currency, movement_list, name):
        for movement in movement_list:
          movement['name'] = self.movement_name_dict[name][movement['name']]
        return buildCalculatedMovementList(date, period, annuity, source_section, 
                                           destination_section, currency, movement_list)

      def buildCalculatedMovementList(date, period, annuity, source_section, 
                                      destination_section, currency, movement_list = []):
        return_list = []
        for movement in movement_list:
750 751
          return_list.append(dict(movement))
          return_list[-1].update(
752 753 754 755 756 757 758
                { 'stop_date'          : date,
                  'name'               : '%s_%i_%i' % (movement['name'], period, annuity),
                  'source_section_value'      : source_section,
                  'destination_section_value' : destination_section,
                  'resource_value'     : currency } )
        return return_list

759
      returned_list = [] 
760
      if item is not None:
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
        if immo_period is not None:
          # Get some variables
          start_movement =       immo_period.get('start_movement')
          start_date =           immo_period.get('start_date')
          start_method =         immo_period.get('start_method')
          initial_method =       immo_period.get('initial_method')
          initial_date =         immo_period.get('initial_date')
          initial_duration =     immo_period.get('initial_duration')
          disposal_price =       immo_period.get('initial_disposal_price')
          initial_price =        immo_period.get('initial_price')
          section =              immo_period.get('owner')
          continuous =           immo_period.get('continuous')
          new_owner = section
          currency = section.getPriceCurrency()
          if currency is not None:
          # XXX FIXME : do something if currency is None
            currency = self.currency_module[currency.split('/')[-1]]
          stop_date = immo_period.get('stop_date', addToDate(initial_date, month=initial_duration))
779
        
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
        # Period start and previous period stop
        # Possible cases :
        # 1) Item is unimmobilised before : start immobilisation
        # 2) Item is immobilised before :
        # ----------------------------------------------------------------------------------------------
        # |                   | Owner does not change |  Owner changes but the  | Actual owner changes |
        # |                   |                       |  actual owner does not  |                      |
        # ----------------------------------------------------------------------------------------------
        # |NO_CHANGE movement |     Nothing to do     |        Transfer         |Stop immo - start immo|
        # |Continuous movement|   Optional transfer   |        Transfer         |Stop immo - start immo|
        # |       Other       | Stop immo - start immo| Stop immo - start immo  |Stop immo - start immo|
        # ----------------------------------------------------------------------------------------------
        # "Optional Transfer" means "transfer from old accounts to new ones if they change"
        # "Transfer" means "transfer all non-solded accounts from a section to another"
        # "Continuous movement" means "same method as previous period and method is continuous"
        # Note that section can change without changing owner.
        # "Actual owner changes" means "the 'group' property of both owners differ"
        
        build_unimmo = 0
        build_immo = 0
        build_transfer = 0
        build_optional_transfer = 0
        previous_method = None
        previous_stop_date = None
        previous_owner = None
        if immo_period is None:
          if previous_period is not None:
            build_unimmo = 1
        else:
          if previous_period is not None:
            previous_method = previous_period['initial_method']
            previous_stop_date = previous_period['stop_date']
            previous_owner = previous_period['owner']
          if previous_stop_date is None or previous_stop_date != start_date:
            build_unimmo = 1
            build_immo = 1
          else:
            previous_group = previous_owner.getGroup()
            new_group = new_owner.getGroup()
            if previous_group is None or \
               new_group is None or \
               previous_group != new_group:
              build_unimmo = 1
              build_immo = 1
            else:
              if start_method not in ("",NO_CHANGE_METHOD) and (\
                   previous_method is None or \
                   start_method != previous_method or \
                   not start_movement.getAmortisationMethodParameterForItem(item, "continuous")["continuous"]):
                build_unimmo = 1
                build_immo = 1
              else:
                if previous_owner != new_owner:
                  build_transfer = 1
                else:
                  if start_movement.getAmortisationMethodParameterForItem(item, "continuous")["continuous"]:
                    build_optional_transfer = 1
                  #else nothing to do
        if previous_period is None:
          build_unimmo = 0
          build_transfer = 0
841
          build_optional_transfer = 0
842

843
        # Build previous period unimmobilisation
844 845 846 847 848 849 850 851 852 853 854 855 856
        if build_unimmo:
          previous_initial_price = previous_period['initial_price']
          previous_start_date = previous_period['start_date']
          previous_stop_date = previous_period['stop_date']
          previous_start_movement = previous_period['start_movement']
          previous_section = previous_owner
          previous_currency = previous_section.getPriceCurrency()
          if previous_currency is not None:
            # XXX FIXME : do something if currency is None
            previous_currency = self.currency_module[previous_currency.split('/')[-1]]
          previous_stop_price = item.getAmortisationPrice(at_date=previous_stop_date, **kw)
          if previous_stop_price is not None:
            previous_amortised_price = previous_initial_price - previous_stop_price
857
            returned_list.extend( 
858
                buildUnimmobilisationCalculatedMovementList(date = previous_stop_date,
859
                                                            period = period_number - 1,
860 861 862
                                                            source_section = previous_section,
                                                            destination_section = None,
                                                            currency = previous_currency,
863 864
                                                            movement_list=[
                            { 'name'               : 'immo',
865 866 867 868
                              'quantity'           : previous_initial_price,
                              'source'             : previous_period['start_immobilisation_account']
                                                  or previous_period['initial_immobilisation_account'],
                              'destination'        : None, },
869
                            { 'name'               : 'amo',
870 871 872 873 874 875 876 877 878
                              'quantity'           : -previous_amortised_price,
                              'source'             : previous_period['start_amortisation_account']
                                                  or previous_period['initial_amortisation_account'],
                              'destination'        : None, },
                            { 'name'               : 'output',
                              'quantity'           : previous_amortised_price - previous_initial_price,
                              'source'             : previous_period['start_output_account']
                                                  or previous_period['initial_output_account'],
                              'destination'        : None, }
879
                     ] ) )
880 881


882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
        # Build current period immobilisation
        if build_immo:
          initial_vat = immo_period.get("initial_vat") or 0
          returned_list.extend( 
              buildImmobilisationCalculatedMovementList(date = start_date,
                                                        period = period_number,
                                                        source_section = section,
                                                        destination_section = None,
                                                        currency = currency,
                                                        movement_list=[
                          { 'name'               : 'immo',
                            'quantity'           : - initial_price,
                            'source'             : immo_period.get('start_immobilisation_account')
                                                or immo_period.get('initial_immobilisation_account'),
                            'destination'        : None },
                          { 'name'               : 'vat',
                            'quantity'           : - initial_vat,
                            'source'             : immo_period.get('start_vat_account')
                                                or immo_period.get('initial_vat_account'),
                            'destination'        : None },
                          { 'name'               : 'amo',
                            'quantity'           : 0,
                            'source'             : immo_period.get('start_amortisation_account')
                                                or immo_period.get('initial_amortisation_account'),
                            'destination'        : None },
                          { 'name'               : 'input',
                            'quantity'           : immo_period.get('initial_main_price') + initial_vat,
                            'source'             : immo_period.get('start_input_account')
                                                or immo_period.get('initial_input_account'),
                            'destination'        : None },
                          { 'name'               : 'extra_input',
                            'quantity'           : immo_period.get('initial_extra_cost_price') or 0,
                            'source'             : immo_period.get('start_extra_cost_account')
                                                or immo_period.get('initial_extra_cost_account'),
                            'destination'        : None }
                      ] ) )
                        
        # Build accounts transfer if the owner changes
        # XXX FIXME : do something if currency != previous currency
        if build_transfer:
          transfer_line_list = []
          for name, key in (('immo','immobilisation_account'),
                            ('amo', 'amortisation_account')):
            previous_account = previous_period.get('start_'+ key) or previous_period['initial_'+key]
            new_account = immo_period.get('start_' + key) or immo_period.get('initial_'+key)
            cumulated_price = previous_period.get('cumulated_price_dict',{}).get( (previous_account,previous_owner), 0)
            if cumulated_price != 0:
              transfer_line_list.append({ 'name'               : name,
                                          'quantity'           : cumulated_price,
                                          'source'             : new_account,
                                          'destination'        : previous_account })
          returned_list.extend(
              buildTransferCalculatedMovementList(date = start_date,
                                                  period = period_number,
                                                  source_section = new_owner,
                                                  destination_section = previous_owner,
                                                  currency = currency,
                                                  movement_list = transfer_line_list))
                        
        # Build accounts transfer if they change
        # XXX FIXME : do something if currency != previous currency
        if build_optional_transfer:
          transfer_line_list = []
          for name, key in (('immo','immobilisation_account'),
                            ('amo', 'amortisation_account'),
                            ('depr', 'depreciation_account')):
            previous_account = previous_period.get('start_'+ key) or previous_period['initial_'+key]
            new_account = immo_period.get('start_' + key) or immo_period['initial_'+key]
            cumulated_price = previous_period.get('cumulated_price_dict',{}).get( (previous_account, previous_owner), 0)
            if previous_account != new_account and cumulated_price != 0:
              transfer_line_list.append({ 'name'               : name,
                                          'quantity'           : cumulated_price,
                                          'source'             : new_account,
                                          'destination'        : previous_account })
          returned_list.extend(
              buildTransferCalculatedMovementList(date = start_date,
                                                  period = period_number,
                                                  source_section = new_owner,
                                                  destination_section = previous_owner,
                                                  currency = currency,
                                                  movement_list = transfer_line_list))
963
        # Calculate the annuities
964
        def buildAnnuity(from_date, to_date, depr_account, amo_account, precision, depr_name, amo_name):
965
          # Search for the first financial end date after the first immobilisation movement
966 967 968
          end_date = getClosestDate(target_date=from_date,
              date=section.getFinancialYearStopDate(),
                                    precision=precision,
969
                                    before=0)
970 971 972
          adding_dict = {precision:1}
          if end_date == initial_date:
            end_date = addToDate(end_date, **adding_dict)
973
          annuity_number = 0
974 975 976 977 978 979 980 981 982
          if continuous:
            current_price = item.getAmortisationPrice(at_date=from_date, **kw)
            if current_price is None:
              current_price = initial_price
          else:
            current_price = initial_price
          # Proceed for each annuity
          while end_date - to_date < 0:
            annuity_price = 0
983 984 985
            annuity_end_price = item.getAmortisationPrice(at_date=end_date, **kw)
            if annuity_end_price is None:
              break
986 987
            # Count this annuity only if it is in the current period
            if end_date - from_date > 0:
988 989 990 991 992 993 994 995 996 997 998 999
              annuity_price = current_price - annuity_end_price
              if annuity_price < 0:
                break
              if annuity_price != 0:
                returned_list.extend( 
                    buildAnnuityCalculatedMovementList(date = end_date,
                                                       period = period_number,
                                                       annuity = annuity_number,
                                                       source_section = section,
                                                       destination_section = None,
                                                       currency = currency,
                                                       movement_list=[
1000
                                { 'name'               : depr_name,
1001
                                  'quantity'           : - annuity_price,
1002
                                  'source'             : depr_account,
1003
                                  'destination'        : None },
1004
                                { 'name'               : amo_name,
1005
                                  'quantity'           : annuity_price,
1006
                                  'source'             : amo_account,
1007 1008 1009
                                  'destination'        : None }
                          ] ) )
            current_price -= annuity_price
1010
            end_date = addToDate(end_date, **adding_dict)
1011
            annuity_number += 1
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
  
          # Proceed the last annuity (maybe incomplete, from financial year end date to to_date)
          annuity_end_price = item.getAmortisationPrice(at_date=to_date, **kw)
          if annuity_end_price is not None and annuity_end_price < current_price:
            annuity_price = current_price - annuity_end_price
            if annuity_price != 0:
              returned_list.extend( 
                  buildAnnuityCalculatedMovementList(date = end_date,
                                                     period = period_number,
                                                     annuity = annuity_number,
                                                     source_section = section,
                                                     destination_section = None,
                                                     currency = currency,
                                                     movement_list=[
                            { 'name'               : depr_name,
                              'quantity'           : - annuity_price,
                              'source'             : depr_account,
1029
                              'destination'        : None },
1030 1031 1032
                            { 'name'               : amo_name,
                              'quantity'           : annuity_price,
                              'source'             : amo_account,
1033
                              'destination'        : None }
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
                        ] ) )
        
       #######
        if immo_period is not None:
          monthly_account = immo_period.get('start_monthly_amortisation_account') \
                         or immo_period.get('initial_monthly_amortisation_account')
          final_depreciation_account = immo_period.get('start_depreciation_account') \
                                    or immo_period.get('initial_depreciation_account')
          amortisation_account = immo_period.get('start_amortisation_account') \
                              or immo_period.get('initial_amortisation_account')
          # Build monthly annuities
          if monthly_account is not None:
            buildAnnuity(from_date=start_date,
                         to_date=stop_date,
                         depr_account=monthly_account,
                         amo_account=amortisation_account,
                         precision='month',
                         depr_name='temp_depr',
                         amo_name='temp_amo')
            inter_depreciation_account = monthly_account
          else:
            inter_depreciation_account = amortisation_account
          
          # Build yearly annuities
          buildAnnuity(from_date=start_date,
                       to_date=stop_date,
                       depr_account=final_depreciation_account,
                       amo_account=inter_depreciation_account,
                       precision='year',
                       depr_name='depr',
                       amo_name='amo')
        
          # Accumulate quantities and add them to the period dict
          if previous_period is not None:
            cumulated_price_dict = dict(previous_period.get('cumulated_price_dict',{}))
          else:
            cumulated_price_dict = {}
          for line in returned_list:
            quantity = line['quantity']
            if quantity != 0:
              source = line['source']
              destination = line['destination']
              source_section_value = line['source_section_value']
              destination_section_value = line['destination_section_value']
              if source is not None and source_section_value is not None:
                cumulated_source = cumulated_price_dict.get( (source, source_section_value), 0)
                cumulated_source += quantity
                cumulated_price_dict[(source, source_section_value)] = cumulated_source
              if destination is not None and destination_section_value is not None:
                cumulated_destination = cumulated_price_dict.get( (destination, destination_section_value), 0)
                cumulated_destination -= quantity
                cumulated_price_dict[(destination_section_value)] = cumulated_destination
          immo_period['cumulated_price_dict'] = cumulated_price_dict
      return returned_list
1088

1089 1090 1091 1092 1093 1094 1095
    # Deliverability / orderability
    def isOrderable(self, m):
      return 1

    def isDeliverable(self, m):
      return 1
      # XXX ?
1096
      if m.getSimulationState() in self.getPortalDraftOrderStateList():
1097 1098
        return 0
      return 1