AmortisationRule.py 22.1 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 29 30 31 32 33 34
##############################################################################
#
# 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.
#
##############################################################################

from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5.Document.Rule import Rule
from DateTime import DateTime
from copy import deepcopy
from string import lower
Sebastien Robin's avatar
Sebastien Robin committed
35
from Products.ERP5Type.DateUtils import centis, getClosestDate, addToDate
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

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()
    security.declareObjectProtected(Permissions.View)

    # Default Properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
                      , PropertySheet.CategoryCore
                      , PropertySheet.DublinCore
                      )

    # CMF Factory Type Information
    factory_type_information = \
      {    'id'             : portal_type
         , 'meta_type'      : meta_type
         , 'description'    : """\
An ERP5 Rule..."""
         , 'icon'           : 'rule_icon.gif'
         , 'product'        : 'ERP5'
         , 'factory'        : 'addAmortisationRule'
         , 'immediate_view' : 'rule_view'
         , 'allow_discussion'     : 1
         , 'allowed_content_types': ()
         , 'filter_content_types' : 1
         , 'global_allow'   : 1
         , 'actions'        :
        ( { 'id'            : 'view'
          , 'name'          : 'View'
          , 'category'      : 'object_view'
          , 'action'        : 'rule_view'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'list'
          , 'name'          : 'Object Contents'
          , 'category'      : 'object_action'
          , 'action'        : 'folder_contents'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'print'
          , 'name'          : 'Print'
          , 'category'      : 'object_print'
          , 'action'        : 'rule_print'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'metadata'
          , 'name'          : 'Metadata'
          , 'category'      : 'object_view'
          , 'action'        : 'metadata_edit'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'translate'
          , 'name'          : 'Translate'
          , 'category'      : 'object_action'
          , 'action'        : 'translation_template_view'
          , 'permissions'   : (
              Permissions.TranslateContent, )
          }
        )
      }

    def test(self, movement):
      """
        Tests if the rule (still) applies
      """
      # An order rule never applies since it is always explicitely instanciated
      # XXX And if it is an amortisation rule ?
      return 0
122

123 124 125 126 127 128 129 130 131 132 133 134 135

    # 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.
      """
      delivery_line_type = 'Simulation Movement'
136

137 138
      # Get the item we come from
      my_item = applied_rule.getDefaultCausalityValue()
139

140 141
      # Only expand if my_item is not None
      if my_item is not None:
142

143
        ### First, plan the theorical accounting movements
144

145
        accounting_movement_list = []
Sebastien Robin's avatar
Sebastien Robin committed
146
        immobilisation_movement_list = my_item.getImmobilisationMovementValueList()
147

148 149 150 151 152 153 154 155 156
        current_immo_movement = None
        for mvt_number in range(len(immobilisation_movement_list)):
          # Get processed immobilisation movements
          prev_immo_movement = current_immo_movement
          current_immo_movement = immobilisation_movement_list[mvt_number]
          if mvt_number < len(immobilisation_movement_list) - 1:
            next_immo_movement = immobilisation_movement_list[mvt_number + 1]
          else:
            next_immo_movement = None
157

158 159 160 161
          # Calculate the accounting movements
          accounting_movements = self._getAccountingMovement(current_immo_movement=current_immo_movement,
                                                            next_immo_movement=next_immo_movement,
                                                            previous_immo_movement=prev_immo_movement)
162

163
          accounting_movement_list.extend(accounting_movements)
164 165


166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
      ### The next step is to create the simulation movements
      # First, we delete all of the simulation movements which are children
      # of the applied rule : the entire simulation for this item has been
      # re-calculated, so old values are necessary wrong
      # However, the simulation movements already used to make accounting
      # are not deleted.
      movement_id_list = []
      movement_last_id_list = {}
      for movement in applied_rule.contentValues():
        movement_id = movement.getId()
        movement_id_name = '_'.join( movement_id.split('_')[:-1] )
        movement_id_number = int(movement_id.split('_')[-1])
        if movement.getDeliveryValue() is None:
          movement_id_list.append(movement_id)
        else:
          if movement_last_id_list.get( movement_id_name, None) is None or movement_id_number > movement_last_id_list[movement_id_name]:
            movement_last_id_list[movement_id_name] = movement_id_number
183 184


185 186 187 188 189 190 191 192 193
      applied_rule.deleteContent(movement_id_list)
      ids = {}
      for accounting_movement in accounting_movement_list:
        if accounting_movement['quantity'] != 0:
          my_type = accounting_movement['type']
          if ids.get(my_type) is None:
            ids[my_type] = movement_last_id_list.get(my_type, None)
            if ids[my_type] is None:
              ids[my_type] = -1
194

195 196
          ids[my_type] = ids[my_type] + 1
          new_id = my_type + '_' + str(ids[my_type])
197

198 199 200 201 202 203
          # Round date
          stop_date = accounting_movement['stop_date']
          if stop_date.latestTime() - stop_date < 1/24.:
            stop_date = stop_date + 1
          stop_date = DateTime('%s/%s/%s' % (repr(stop_date.year()), repr(stop_date.month()), repr(stop_date.day())))
          accounting_movement['stop_date'] = stop_date
204

205 206 207 208 209 210 211 212 213 214 215 216
          simulation_movement = applied_rule.newContent(portal_type=delivery_line_type, id=new_id )
          simulation_movement.setStartDate(stop_date)
          simulation_movement.setTargetStartDate(stop_date)
          simulation_movement.setTargetStopDate(stop_date)
          for (key, value) in accounting_movement.items():
            if key != 'type' and value != None:
              setter_name = 'set'
              tokens = key.split('_')
              for i in range(len(tokens)):
                setter_name += tokens[i].capitalize()
              setter = getattr(simulation_movement, setter_name)
              setter(value)
217 218 219 220




221 222 223 224 225
    security.declareProtected(Permissions.View, '_getAccountingMovement')
    def _getAccountingMovement(self,current_immo_movement,next_immo_movement=None, previous_immo_movement=None):
      """
      Calculates the value of accounting movements during the period
      between the two given immobilisation movements.
226
      If next_immo_movement is None, accounting movements are made at infinite.
227 228 229 230
      """
      item = current_immo_movement.getParent()
      if item is not None:
        # First we need to calculate the item value at the first immobilisation movement date
Sebastien Robin's avatar
Sebastien Robin committed
231
        begin_value = current_immo_movement.getAmortisationOrDefaultAmortisationPrice()
232
        begin_remaining = current_immo_movement.getAmortisationOrDefaultAmortisationDuration()
233

234
        # To find financial end date, we need to know the company
Sebastien Robin's avatar
Sebastien Robin committed
235 236
        section = current_immo_movement.getSectionValue()
        currency = current_immo_movement.getPriceCurrency()
237 238
        if currency is not None:
          currency = self.currency[currency.split('/')[-1]]
239

240 241 242 243 244
        start_date = current_immo_movement.getStopDate()
        if next_immo_movement is not None:
          stop_date = next_immo_movement.getStopDate()
        else:
          stop_date = None
245

246 247
        returned_list = []
        # Calculate particular accounting movements (immobilisation beginning, end, ownership change...)
Sebastien Robin's avatar
Sebastien Robin committed
248 249 250
        LOG('_getAccountingMovement start_date',0,start_date)
        LOG('_getAccountingMovement centis',0,centis)
        immobilised_before = item.isImmobilised(at_date = start_date - centis)
251 252
        immobilised_after = current_immo_movement.getImmobilisation()
        replace = 0
253

254
        if immobilised_before and previous_immo_movement is not None:
Sebastien Robin's avatar
Sebastien Robin committed
255 256
          immo_begin_value = previous_immo_movement.getAmortisationOrDefaultAmortisationPrice()
          immo_end_value = current_immo_movement.getDefaultAmortisationPrice() # We use this method in order to get the calculated value
257 258
                                                                          # of the item, and not the value entered later by the user
          if immo_end_value is not None:
Sebastien Robin's avatar
Sebastien Robin committed
259
            amortisation_price = immo_begin_value - immo_end_value
260 261 262 263 264 265 266 267
            end_vat = previous_immo_movement.getVat() * immo_end_value / immo_begin_value
            immo_end_value_vat = immo_end_value + end_vat
            returned_list.extend([{ 'stop_date'           : start_date,
                                    'type'                : 'immo',
                                    'quantity'            : -immo_begin_value,
                                    'source'              : None,
                                    'destination'         : previous_immo_movement.getImmobilisationAccount(),
                                    'source_section_value'      : None,
Sebastien Robin's avatar
Sebastien Robin committed
268
                                    'destination_section_value' : previous_immo_movement.getSectionValue(),
269 270 271 272 273 274 275
                                    'resource_value'     : currency },
                                  { 'stop_date'           : start_date,
                                    'type'                : 'vat',
                                    'quantity'            : -end_vat,
                                    'source'              : None,
                                    'destination'         : previous_immo_movement.getVatAccount(),
                                    'source_section_value'      : None,
Sebastien Robin's avatar
Sebastien Robin committed
276
                                    'destination_section_value' : previous_immo_movement.getSectionValue(),
277 278 279
                                    'resource_value'     : currency },
                                  { 'stop_date'           : start_date,
                                    'type'                : 'amo',
Sebastien Robin's avatar
Sebastien Robin committed
280
                                    'quantity'            : amortisation_price,
281 282 283
                                    'source'              : None,
                                    'destination'         : previous_immo_movement.getAmortisationAccount(),
                                    'source_section_value'      : None,
Sebastien Robin's avatar
Sebastien Robin committed
284
                                    'destination_section_value' : previous_immo_movement.getSectionValue(),
285 286 287 288 289 290 291
                                    'resource_value'     : currency },
                                  { 'stop_date'           : start_date,
                                    'type'                : 'in_out',
                                    'quantity'            : immo_end_value_vat,
                                    'source'              : None,
                                    'destination'         : previous_immo_movement.getOutputAccount(),
                                    'source_section_value'      : None,
Sebastien Robin's avatar
Sebastien Robin committed
292
                                    'destination_section_value' : previous_immo_movement.getSectionValue(),
293 294
                                    'resource_value'     : currency } ] )
            replace = 1
295 296


297 298 299 300 301 302 303 304 305 306
        if immobilised_after:
          immo_begin_value = begin_value
          begin_vat = current_immo_movement.getVat()
          if len(returned_list) > 0 and immo_begin_value == immo_end_value and round(begin_vat,2) == round(end_vat,2):
            # Gather data into a single movement
            returned_list[0]['source'] = current_immo_movement.getImmobilisationAccount()
            returned_list[1]['source'] = current_immo_movement.getVatAccount()
            returned_list[2]['source'] = current_immo_movement.getAmortisationAccount()
            returned_list[3]['source'] = current_immo_movement.getInputAccount()
            for i in range(4):
Sebastien Robin's avatar
Sebastien Robin committed
307
              returned_list[i]['source_section_value'] = section
308 309 310 311 312 313 314
            replace = 0
          else:
            returned_list.extend([{ 'stop_date'           : start_date,
                                    'type'                : 'immo',
                                    'quantity'            : - immo_begin_value,
                                    'source'              : current_immo_movement.getImmobilisationAccount(),
                                    'destination'         : None,
Sebastien Robin's avatar
Sebastien Robin committed
315
                                    'source_section_value'      : section,
316 317 318 319 320 321 322
                                    'destination_section_value' : None,
                                    'resource_value'     : currency },
                                  { 'stop_date'           : start_date,
                                    'type'                : 'vat',
                                    'quantity'            : - begin_vat,
                                    'source'              : current_immo_movement.getVatAccount(),
                                    'destination'         : None,
Sebastien Robin's avatar
Sebastien Robin committed
323
                                    'source_section_value'      : section,
324 325 326 327 328 329 330
                                    'destination_section_value' : None,
                                    'resource_value'     : currency },
                                  { 'stop_date'           : start_date,
                                    'type'                : 'amo',
                                    'quantity'            : 0,
                                    'source'              : current_immo_movement.getAmortisationAccount(),
                                    'destination'         : None,
Sebastien Robin's avatar
Sebastien Robin committed
331
                                    'source_section_value'      : section,
332 333 334 335 336 337 338
                                    'destination_section_value' : None,
                                    'resource_value'     : currency },
                                  { 'stop_date'           : start_date,
                                    'type'                : 'in_out',
                                    'quantity'            : immo_begin_value + begin_vat,
                                    'source'              : current_immo_movement.getInputAccount(),
                                    'destination'         : None,
Sebastien Robin's avatar
Sebastien Robin committed
339
                                    'source_section_value'      : section,
340 341
                                    'destination_section_value' : None,
                                    'resource_value'     : currency } ] )
342 343


344 345 346 347 348 349 350 351
        if replace:
          # Replace destination by source on the immobilisation-ending writings
          for i in range(4):
            returned_list[i]['source']               = returned_list[i]['destination']
            returned_list[i]['source_section_value'] = returned_list[i]['destination_section_value']
            returned_list[i]['destination']               = None
            returned_list[i]['destination_section_value'] = None
            returned_list[i]['quantity'] = - returned_list[i]['quantity']
352 353


354 355 356
        # Calculate the annuities
        current_value = begin_value
        if immobilised_after:
357

358
          # Search for the first financial end date after the first immobilisation movement
Sebastien Robin's avatar
Sebastien Robin committed
359
          end_date = getClosestDate(target_date=start_date, date=section.getFinancialYearStopDate(), precision='year', before=0)
360

361 362 363 364 365 366 367 368 369 370
          while (stop_date is None and current_value > 0) or (stop_date is not None and end_date - stop_date < 0):
            annuity_end_value = item.getAmortisationPrice(at_date=end_date)
            if annuity_end_value is not None:
              annuity_value = current_value - annuity_end_value
              if annuity_value != 0:
                returned_list.extend([{ 'stop_date'          : end_date,
                                        'type'               : 'annuity_depr',
                                        'quantity'           : (- annuity_value),
                                        'source'             : current_immo_movement.getDepreciationAccount(),
                                        'destination'        : None,
Sebastien Robin's avatar
Sebastien Robin committed
371
                                        'source_section_value'     : section,
372 373 374 375 376 377 378
                                        'destination_section_value': None,
                                        'resource_value'    : currency },
                                      { 'stop_date'          : end_date,
                                        'type'               : 'annuity_amo',
                                        'quantity'           : annuity_value,
                                        'source'             : current_immo_movement.getAmortisationAccount(),
                                        'destination'        : None,
Sebastien Robin's avatar
Sebastien Robin committed
379
                                        'source_section_value'     : section,
380 381
                                        'destination_section_value': None,
                                        'resource_value'    : currency } ] )
382

383
            current_value -= annuity_value
Sebastien Robin's avatar
Sebastien Robin committed
384
            end_date = addToDate(end_date, {'year':1})
385

386 387
          # Get the last period until the next immobilisation movement
          if stop_date is not None:
Sebastien Robin's avatar
Sebastien Robin committed
388
            # We use getDefaultAmortisationPrice in order to get the calculated value of the item,
389
            # and not the value entered later by the user for the next immobilisation period
Sebastien Robin's avatar
Sebastien Robin committed
390
            annuity_end_value = next_immo_movement.getDefaultAmortisationPrice()
391 392 393 394 395 396 397 398
            if annuity_end_value is not None:
              annuity_value = current_value - annuity_end_value
              if annuity_value != 0:
                returned_list.extend([{ 'stop_date'          : end_date,
                                        'type'               : 'annuity_depr',
                                        'quantity'           : (- annuity_value),
                                        'source'             : current_immo_movement.getDepreciationAccount(),
                                        'destination'        : None,
Sebastien Robin's avatar
Sebastien Robin committed
399
                                        'source_section_value'     : section,
400 401 402 403 404 405 406
                                        'destination_section_value': None,
                                        'resource_value'    : currency },
                                      { 'stop_date'          : end_date,
                                        'type'               : 'annuity_amo',
                                        'quantity'           : annuity_value,
                                        'source'             : current_immo_movement.getAmortisationAccount(),
                                        'destination'        : None,
Sebastien Robin's avatar
Sebastien Robin committed
407
                                        'source_section_value'     : section,
408 409
                                        'destination_section_value': None,
                                        'resource_value'    : currency } ] )
410

411
        return returned_list
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
    security.declareProtected(Permissions.ModifyPortalContent, 'solve')
    def solve(self, applied_rule, solution_list):
      """
        Solve inconsitency according to a certain number of solutions
        templates. This updates the

        -> new status -> solved

        This applies a solution to an applied rule. Once
        the solution is applied, the parent movement is checked.
        If it does not diverge, the rule is reexpanded. If not,
        diverge is called on the parent movement.
      """

    security.declareProtected(Permissions.ModifyPortalContent, 'diverge')
    def diverge(self, applied_rule):
      """
        -> new status -> diverged

        This basically sets the rule to "diverged"
        and blocks expansion process
      """

    # Solvers
    security.declareProtected(Permissions.View, 'isDivergent')
    def isDivergent(self, applied_rule):
      """
        Returns 1 if divergent rule
      """

    security.declareProtected(Permissions.View, 'getDivergenceList')
    def getDivergenceList(self, applied_rule):
      """
        Returns a list Divergence descriptors
      """

    security.declareProtected(Permissions.View, 'getSolverList')
    def getSolverList(self, applied_rule):
      """
        Returns a list Divergence solvers
      """

    # Deliverability / orderability
    def isOrderable(self, m):
      return 1

    def isDeliverable(self, m):
      return 1
      # XXX ?
464
      if m.getSimulationState() in self.getPortalDraftOrderStateList():
465 466
        return 0
      return 1